repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
GunoH/intellij-community
platform/testFramework/src/com/intellij/testFramework/ktAsserts.kt
3
1801
// 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 com.intellij.testFramework import kotlinx.coroutines.delay import java.time.Duration inline fun <reified T> assertInstanceOf(o: Any?): T = UsefulTestCase.assertInstanceOf(o, T::class.java) inline fun <reified T> Any?.requireIs(): T { assertInstanceOf<T>(this) return this as T } /** See [pollAssertionsAsync]. */ fun pollAssertions(total: Duration, interval: Duration, action: () -> Unit) { val loopStartedAt = System.nanoTime() while (true) { Thread.sleep(pollAssertionsIteration(loopStartedAt, total, interval, action) ?: return) } } /** * Repeat [action] until it doesn't throw any [AssertionError], but not longer than [total] duration. * Rethrows the latest [AssertionError]. [action] is executed not oftener than every [interval] duration. */ suspend fun pollAssertionsAsync(total: Duration, interval: Duration, action: suspend () -> Unit) { val loopStartedAtNanos = System.nanoTime() while (true) { delay(pollAssertionsIteration(loopStartedAtNanos, total, interval) { action() } ?: return) } } private inline fun pollAssertionsIteration( loopStartedAtNanos: Long, total: Duration, interval: Duration, action: () -> Unit, ): Long? { val attemptStartedAtNanos = System.nanoTime() try { action() return null } catch (err: AssertionError) { val remainsNanos = loopStartedAtNanos + total.toNanos() - System.nanoTime() if (remainsNanos < 0) throw err else return Duration.ofNanos(remainsNanos).toMillis() .coerceAtMost(Duration.ofNanos(attemptStartedAtNanos + interval.toNanos() - System.nanoTime()).toMillis()) .coerceAtLeast(0) } }
apache-2.0
GunoH/intellij-community
plugins/package-search/maven/src/com/jetbrains/packagesearch/intellij/plugin/maven/MavenModuleTransformer.kt
2
4452
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * 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.jetbrains.packagesearch.intellij.plugin.maven import com.intellij.openapi.application.readAction import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.xml.XmlTag import com.intellij.psi.xml.XmlText import com.intellij.util.asSafely import com.jetbrains.packagesearch.intellij.plugin.extensibility.BuildSystemType import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyDeclarationIndexes import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.dependencyDeclarationCallback import com.jetbrains.packagesearch.intellij.plugin.maven.configuration.PackageSearchMavenConfiguration import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenUtil internal class MavenModuleTransformer : CoroutineModuleTransformer { override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> = nativeModules.parallelMap { nativeModule -> readAction { runCatching { MavenProjectsManager.getInstance(project).findProject(nativeModule) } }.onFailure { logDebug(contextName = "MavenModuleTransformer", it) { "Error finding Maven module ${nativeModule.name}" } }.getOrNull()?.let { createMavenProjectModule(project, nativeModule, it) } }.filterNotNull() private fun createMavenProjectModule( project: Project, nativeModule: Module, mavenProject: MavenProject ): ProjectModule { val buildFile = mavenProject.file return ProjectModule( name = mavenProject.name ?: nativeModule.name, nativeModule = nativeModule, parent = null, buildFile = buildFile, projectDir = mavenProject.directoryFile.toNioPath().toFile(), buildSystemType = BuildSystemType.MAVEN, moduleType = MavenProjectModuleType, availableScopes = PackageSearchMavenConfiguration.getInstance(project).getMavenScopes(), dependencyDeclarationCallback = project.dependencyDeclarationCallback { dependency -> val children: Array<PsiElement> = dependency.psiElement.asSafely<XmlTag>() ?.children ?: return@dependencyDeclarationCallback null val xmlTag = children.filterIsInstance<XmlText>() .find { it is Navigatable && it.canNavigate() } ?: return@dependencyDeclarationCallback null DependencyDeclarationIndexes( wholeDeclarationStartIndex = xmlTag.textOffset, coordinatesStartIndex = xmlTag.textOffset, versionStartIndex = children.filterIsInstance<XmlTag>() .find { it.name == "version" } ?.children ?.filterIsInstance<XmlText>() ?.firstOrNull() ?.textOffset ) } ) } } val BuildSystemType.Companion.MAVEN get() = BuildSystemType( name = "MAVEN", language = "xml", dependencyAnalyzerKey = MavenUtil.SYSTEM_ID, statisticsKey = "maven" )
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/multiModuleHighlighting/java9/exportsTo/first/firstUsage.kt
13
103
import dependency.Foo fun firstUsage(): String { val foo: Foo = Foo() return foo.toString() }
apache-2.0
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/smartStepInto/renderer.kt
4
685
fun test() { <caret>propFoo + foo() + fooWithParam(1.extFoo()) { 2 } + FooClass(1).test() + FooClass().test() + FooClass(1, 2).test() } class FooClass(i: Int) { constructor() : this(1) constructor(i: Int, s: Int) : this(1) fun test() = 1 } fun foo() = 1 fun fooWithParam(i: Int, f: () -> Int) = 1 fun Int.extFoo() = 1 val propFoo: Int get() { return 1 } // EXISTS: getter for propFoo: Int, // EXISTS: foo() // EXISTS: fooWithParam(Int\, () -> Int) // EXISTS: extFoo() // EXISTS: fooWithParam: f.invoke() // EXISTS: test() // EXISTS: constructor FooClass() // EXISTS: constructor FooClass(Int) // EXISTS: constructor FooClass(Int\, Int) // IGNORE_K2
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/copy/AbstractCopyTest.kt
1
3646
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.copy import com.google.gson.JsonObject import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.PackageWrapper import com.intellij.refactoring.copy.CopyHandler import com.intellij.refactoring.move.moveClassesOrPackages.MultipleRootsMoveDestination import org.jetbrains.kotlin.idea.core.util.toPsiDirectory import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.jsonUtils.getNullableString import org.jetbrains.kotlin.idea.jsonUtils.getString import org.jetbrains.kotlin.idea.refactoring.AbstractMultifileRefactoringTest import org.jetbrains.kotlin.idea.refactoring.copy.CopyKotlinDeclarationsHandler.Companion.newName import org.jetbrains.kotlin.idea.refactoring.runRefactoringTest import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.utils.ifEmpty private enum class CopyAction : AbstractMultifileRefactoringTest.RefactoringAction { COPY_FILES { override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) { val project = mainFile.project val elementsToCopy = config.getAsJsonArray("filesToMove").map { val virtualFile = rootDir.findFileByRelativePath(it.asString)!! if (virtualFile.isDirectory) virtualFile.toPsiDirectory(project)!! else virtualFile.toPsiFile(project)!! } val typesToCopy = if (config.getNullableString("extractClassOrObject") == "true") elementsToCopy.flatMap { PsiTreeUtil.collectElementsOfType(it, KtClassOrObject::class.java) } else elementsToCopy DEFAULT.runRefactoring(rootDir, mainFile, typesToCopy, config) } }, DEFAULT { override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) { val project = mainFile.project val elementsToCopy = elementsAtCaret.ifEmpty { listOf(mainFile) }.toTypedArray() assert(CopyHandler.canCopy(elementsToCopy)) val targetDirectory = config.getNullableString("targetDirectory")?.let { rootDir.findFileByRelativePath(it)?.toPsiDirectory(project) } ?: run { val packageWrapper = PackageWrapper(mainFile.manager, config.getString("targetPackage")) runWriteAction { MultipleRootsMoveDestination(packageWrapper).getTargetDirectory(mainFile) } } project.newName = config.getNullableString("newName") CopyHandler.doCopy(elementsToCopy, targetDirectory) } } } abstract class AbstractCopyTest : AbstractMultifileRefactoringTest() { companion object { fun runCopyRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project) { val action = config.getNullableString("type")?.let { CopyAction.valueOf(it) } ?: CopyAction.DEFAULT runRefactoringTest(path, config, rootDir, project, action) } } override fun runRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project) { runCopyRefactoring(path, config, rootDir, project) } }
apache-2.0
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt
1
4667
// 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.compiler.configuration import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.JDOMUtil import com.intellij.util.ReflectionUtil import com.intellij.util.messages.Topic import com.intellij.util.xmlb.Accessor import com.intellij.util.xmlb.SerializationFilterBase import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.idea.syncPublisherWithDisposeCheck import kotlin.reflect.KClass abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor(private val project: Project) : PersistentStateComponent<Element>, Cloneable { // Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters private object DefaultValuesFilter : SerializationFilterBase() { private val defaultBeans = HashMap<Class<*>, Any>() private fun createDefaultBean(beanClass: Class<Any>): Any { return ReflectionUtil.newInstance<Any>(beanClass).apply { if (this is K2JSCompilerArguments) { sourceMapPrefix = "" } } } private fun getDefaultValue(accessor: Accessor, bean: Any): Any? { if (bean is K2JSCompilerArguments && accessor.name == K2JSCompilerArguments::sourceMapEmbedSources.name) { return if (bean.sourceMap) K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING else null } val beanClass = bean.javaClass val defaultBean = defaultBeans.getOrPut(beanClass) { createDefaultBean(beanClass) } return accessor.read(defaultBean) } override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean { val defValue = getDefaultValue(accessor, bean) return if (defValue is Element && beanValue is Element) { !JDOMUtil.areElementsEqual(beanValue, defValue) } else { !Comparing.equal(beanValue, defValue) } } } @Suppress("LeakingThis", "UNCHECKED_CAST") private var _settings: T = createSettings().frozen() as T private set(value) { field = value.frozen() as T } var settings: T get() = _settings set(value) { validateNewSettings(value) _settings = value ApplicationManager.getApplication().invokeLater { project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(value) } } fun update(changer: T.() -> Unit) { @Suppress("UNCHECKED_CAST") settings = (settings.unfrozen() as T).apply { changer() } } protected fun validateInheritedFieldsUnchanged(settings: T) { @Suppress("UNCHECKED_CAST") val inheritedProperties = collectProperties<T>(settings::class as KClass<T>, true) val defaultInstance = createSettings() val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) } if (invalidFields.isNotEmpty()) { throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}") } } protected open fun validateNewSettings(settings: T) { } protected abstract fun createSettings(): T override fun getState() = XmlSerializer.serialize(_settings, DefaultValuesFilter) override fun loadState(state: Element) { _settings = ReflectionUtil.newInstance(_settings.javaClass).apply { if (this is CommonCompilerArguments) { freeArgs = mutableListOf() internalArguments = mutableListOf() } XmlSerializer.deserializeInto(this, state) } ApplicationManager.getApplication().invokeLater { project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(settings) } } public override fun clone(): Any = super.clone() } interface KotlinCompilerSettingsListener { fun <T> settingsChanged(newSettings: T) companion object { val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java) } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertToScope/convertToWith/withNotSimpleInitializer2.kt
8
164
// WITH_RUNTIME // IS_APPLICABLE: false class MyClass { fun foo() { val c = 2 (c.div(2) + 3)<caret> c.div(c + 2 + c) + c.div(c) } }
apache-2.0
jwren/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUContinueExpression.kt
2
1236
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiContinueStatement import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UContinueExpression import org.jetbrains.uast.UElement @ApiStatus.Internal class JavaUContinueExpression( override val sourcePsi: PsiContinueStatement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UContinueExpression { override val label: String? get() = sourcePsi.labelIdentifier?.text override val jumpTarget: UElement? by lz { sourcePsi.findContinuedStatement().takeIf { it !== sourcePsi }?.let { JavaConverter.convertStatement(it, null) } } }
apache-2.0
loxal/FreeEthereum
free-ethereum-core/src/main/java/org/ethereum/datasource/CachedSource.kt
1
2117
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.datasource /** * Source which internally caches underlying Source key-value pairs * Created by Anton Nashatyrev on 21.10.2016. */ interface CachedSource<Key, Value> : Source<Key, Value> { /** * @return The underlying Source */ val source: Source<Key, Value> /** * @return Modified entry keys if this is a write cache */ val modified: Collection<Key> /** * @return indicates the cache has modified entries */ fun hasModified(): Boolean /** * Estimates the size of cached entries in bytes. * This value shouldn't be precise size of Java objects * @return cache size in bytes */ fun estimateCacheSize(): Long /** * Just a convenient shortcut to the most popular Sources with byte[] key */ interface BytesKey<Value> : CachedSource<ByteArray, Value> }
mit
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/numberConversion/toChar/short.kt
8
105
// "Convert expression to 'Char'" "true" fun char(x: Char) {} fun test(s: Short) { char(<caret>s) }
apache-2.0
smmribeiro/intellij-community
platform/platform-api/src/com/intellij/openapi/options/BoundConfigurable.kt
3
2080
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.options import com.intellij.openapi.Disposable import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.ClearableLazyValue import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import org.jetbrains.annotations.NonNls import javax.swing.JComponent /** * @see DialogPanelConfigurableBase */ abstract class BoundConfigurable( @NlsContexts.ConfigurableName private val displayName: String, @NonNls private val helpTopic: String? = null ) : DslConfigurableBase(), Configurable { override fun getDisplayName(): String = displayName override fun getHelpTopic(): String? = helpTopic } /** * @see DialogPanelUnnamedConfigurableBase */ abstract class DslConfigurableBase : UnnamedConfigurable { protected var disposable: Disposable? = null private set private val panel = object : ClearableLazyValue<DialogPanel>() { override fun compute(): DialogPanel { if (disposable == null) { disposable = Disposer.newDisposable() } val panel = createPanel() panel.registerValidators(disposable!!) return panel } } abstract fun createPanel(): DialogPanel final override fun createComponent(): JComponent? = panel.value override fun isModified() = panel.value.isModified() override fun reset() { panel.value.reset() } override fun apply() { panel.value.apply() } override fun getPreferredFocusedComponent(): JComponent? { return panel.value.preferredFocusedComponent } override fun disposeUIResources() { disposable?.let { Disposer.dispose(it) disposable = null } panel.drop() } } abstract class BoundSearchableConfigurable(@NlsContexts.ConfigurableName displayName: String, helpTopic: String, private val _id: String = helpTopic) : BoundConfigurable(displayName, helpTopic), SearchableConfigurable { override fun getId(): String = _id }
apache-2.0
smmribeiro/intellij-community
plugins/hg4idea/src/org/zmlx/hg4idea/action/HgCommitAndPushExecutorAction.kt
8
1082
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.zmlx.hg4idea.action import com.intellij.dvcs.commit.getCommitAndPushActionName import com.intellij.dvcs.ui.DvcsBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER import com.intellij.openapi.vcs.changes.actions.BaseCommitExecutorAction import org.zmlx.hg4idea.provider.commit.HgCommitAndPushExecutor class HgCommitAndPushExecutorAction : BaseCommitExecutorAction() { init { templatePresentation.setText(DvcsBundle.messagePointer("action.commit.and.push.text")) } override fun update(e: AnActionEvent) { // update presentation before synchronizing its state with button val workflowHandler = e.getData(COMMIT_WORKFLOW_HANDLER) if (workflowHandler != null) { e.presentation.text = workflowHandler.getCommitAndPushActionName() } super.update(e) } override val executorId: String = HgCommitAndPushExecutor.ID }
apache-2.0
LouisCAD/Splitties
modules/lifecycle-coroutines/src/androidMain/kotlin/splitties/lifecycle/coroutines/LifecycleFlow.kt
1
926
/* * Copyright 2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.lifecycle.coroutines import androidx.lifecycle.Lifecycle import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import splitties.experimental.ExperimentalSplittiesApi import kotlin.time.Duration import kotlin.time.ExperimentalTime @ExperimentalSplittiesApi @OptIn(ExperimentalCoroutinesApi::class) fun <T> Flow<T>.whileStarted(lifecycle: Lifecycle): Flow<T> { return lifecycle.isStartedFlow().flatMapLatest { isStarted -> if (isStarted) this else emptyFlow() } } @ExperimentalTime @ExperimentalSplittiesApi @OptIn(ExperimentalCoroutinesApi::class) fun <T> Flow<T>.whileStarted(lifecycle: Lifecycle, timeout: Duration): Flow<T> { return lifecycle.isStartedFlow(timeout = timeout).flatMapLatest { isStarted -> if (isStarted) this else emptyFlow() } }
apache-2.0
chcat/restler
restler-integration-tests/src/main/kotlin/org/restler/integration/Controller.kt
1
1999
package org.restler.integration import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.* import org.springframework.web.context.request.async.DeferredResult import java.io.PrintWriter import java.io.StringWriter import java.util.concurrent.Callable import javax.servlet.http.HttpServletRequest import kotlin.concurrent.thread RestController public open class Controller { RequestMapping("get") open fun publicGet() = "OK" RequestMapping("secured/get") open fun securedGet() = "Secure OK" RequestMapping("forceLogout") open fun logout(): String { SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false) return "OK" } RequestMapping("getDeferred") open fun deferredGet(): DeferredResult<String> { var deferredResult = DeferredResult<String>(); thread { Thread.sleep(1000) deferredResult.setResult("Deferred OK"); } return deferredResult; } RequestMapping("getCallable") open fun callableGet(): Callable<String> { return Callable ( fun call(): String { Thread.sleep(1000) return "Callable OK" } ); } RequestMapping("getWithVariable/{title}") open fun getWithVariable(@PathVariable(value = "title") title: String, @RequestParam(value = "name") name: String): String { return name; } RequestMapping("throwException") @throws(Throwable::class) open fun throwException(@RequestParam exceptionClass: String) { throw Class.forName(exceptionClass).asSubclass(javaClass<Throwable>()).newInstance() } @ExceptionHandler(Exception::class) fun printStackTrace(req: HttpServletRequest, e: Exception): String { val stringWriter = StringWriter() e.printStackTrace(PrintWriter(stringWriter)) return stringWriter.toString() } }
apache-2.0
BenWoodworth/FastCraft
fastcraft-bukkit/bukkit-platform/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/world/FcItemOrderComparator_Bukkit.kt
1
184
package net.benwoodworth.fastcraft.bukkit.world import net.benwoodworth.fastcraft.platform.world.FcItemOrderComparator interface FcItemOrderComparator_Bukkit : FcItemOrderComparator
gpl-3.0
xmartlabs/bigbang
ui/src/androidTest/java/com/xmartlabs/bigbang/ui/recyclerview/multipleitems/MultipleItemRecyclerViewTest.kt
1
1961
package com.xmartlabs.bigbang.ui.recyclerview.multipleitems import android.support.test.espresso.Espresso.onView import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers.withId import android.support.test.espresso.matcher.ViewMatchers.withText import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import com.xmartlabs.bigbang.test.assertions.RecyclerViewAssertions import com.xmartlabs.bigbang.test.extensions.checkRecyclerViewAtPosition import com.xmartlabs.bigbang.test.extensions.checkRecyclerViewCountIs import com.xmartlabs.bigbang.ui.recyclerview.common.Brand import com.xmartlabs.bigbang.ui.recyclerview.common.Car import com.xmartlabs.bigbang.ui.test.R import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MultipleItemRecyclerViewTest { @Rule @JvmField var activityRule = ActivityTestRule(MultipleItemActivity::class.java) @Test fun testSetItems() { val brands = brands val activity = activityRule.activity activity.runOnUiThread { activity.setItems(brands) } val recyclerViewInteraction = onView(withId(R.id.recycler_view)) recyclerViewInteraction.check(matches(RecyclerViewAssertions.countIs(6))) recyclerViewInteraction.checkRecyclerViewCountIs(6) brands .flatMap { mutableListOf(it.name).apply { addAll(it.cars.map(Car::model)) } } .forEachIndexed { index, brand -> recyclerViewInteraction.checkRecyclerViewAtPosition(index, withText(brand)) } } private val brands: List<Brand> get() { val corsa = Car("Corsa") val gol = Car("Gol") val golf = Car("Golf") val saveiro = Car("Saveiro") val chevrolet = Brand("Chevrolet", listOf(corsa)) val volkswagen = Brand("Volkswagen", listOf(gol, golf, saveiro)) return listOf(chevrolet, volkswagen) } }
apache-2.0
guiseco/Tower
Android/src/org/droidplanner/android/fragments/widget/telemetry/MiniWidgetAttitudeSpeedInfo.kt
3
5381
package org.droidplanner.android.fragments.widget.telemetry import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.preference.PreferenceManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.o3dr.services.android.lib.drone.attribute.AttributeEvent import com.o3dr.services.android.lib.drone.attribute.AttributeType import com.o3dr.services.android.lib.drone.property.Attitude import com.o3dr.services.android.lib.drone.property.Speed import org.droidplanner.android.R import org.droidplanner.android.fragments.widget.TowerWidget import org.droidplanner.android.fragments.widget.TowerWidgets import org.droidplanner.android.view.AttitudeIndicator import java.util.* /** * Created by Fredia Huya-Kouadio on 8/27/15. */ public class MiniWidgetAttitudeSpeedInfo : TowerWidget() { companion object { private val filter = initFilter() private fun initFilter(): IntentFilter { val temp = IntentFilter() temp.addAction(AttributeEvent.ATTITUDE_UPDATED) temp.addAction(AttributeEvent.SPEED_UPDATED) temp.addAction(AttributeEvent.GPS_POSITION) temp.addAction(AttributeEvent.ALTITUDE_UPDATED) temp.addAction(AttributeEvent.HOME_UPDATED) return temp } } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { AttributeEvent.ATTITUDE_UPDATED -> onOrientationUpdate() AttributeEvent.SPEED_UPDATED, AttributeEvent.ALTITUDE_UPDATED -> onSpeedUpdate() } } } private var attitudeIndicator: AttitudeIndicator? = null private var roll: TextView? = null private var yaw: TextView? = null private var pitch: TextView? = null private var horizontalSpeed: TextView? = null private var verticalSpeed: TextView? = null private var headingModeFPV: Boolean = false private val MIN_VERTICAL_SPEED_MPS = 0.10 //Meters Per Second override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_mini_widget_attitude_speed_info, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) attitudeIndicator = view.findViewById(R.id.aiView) as AttitudeIndicator? roll = view.findViewById(R.id.rollValueText) as TextView? yaw = view.findViewById(R.id.yawValueText) as TextView? pitch = view.findViewById(R.id.pitchValueText) as TextView? horizontalSpeed = view.findViewById(R.id.horizontal_speed_telem) as TextView? verticalSpeed = view.findViewById(R.id.vertical_speed_telem) as TextView? } override fun onStart() { super.onStart() val prefs = PreferenceManager.getDefaultSharedPreferences(context) headingModeFPV = prefs.getBoolean("pref_heading_mode", false) } override fun getWidgetType() = TowerWidgets.ATTITUDE_SPEED_INFO override fun onApiConnected() { updateAllTelem() broadcastManager.registerReceiver(receiver, filter) } override fun onApiDisconnected() { broadcastManager.unregisterReceiver(receiver) } private fun updateAllTelem() { onOrientationUpdate() onSpeedUpdate() } private fun onOrientationUpdate() { if (!isAdded) return val drone = drone val attitude = drone.getAttribute<Attitude>(AttributeType.ATTITUDE) ?: return val r = attitude.roll.toFloat() val p = attitude.pitch.toFloat() var y = attitude.yaw.toFloat() if (!headingModeFPV and (y < 0)) { y += 360 } attitudeIndicator?.setAttitude(r, p, y) roll?.text = String.format(Locale.US, "%3.0f\u00B0", r) pitch?.text = String.format(Locale.US, "%3.0f\u00B0", p) yaw?.text = String.format(Locale.US, "%3.0f\u00B0", y) } private fun onSpeedUpdate() { if (!isAdded) return val drone = drone val speed = drone.getAttribute<Speed>(AttributeType.SPEED) ?: return val groundSpeedValue = speed.groundSpeed val verticalSpeedValue = speed.verticalSpeed val speedUnitProvider = speedUnitProvider horizontalSpeed?.text = getString(R.string.horizontal_speed_telem, speedUnitProvider.boxBaseValueToTarget(groundSpeedValue).toString()) verticalSpeed?.text = getString(R.string.vertical_speed_telem, speedUnitProvider.boxBaseValueToTarget(verticalSpeedValue).toString()) if (verticalSpeedValue >= MIN_VERTICAL_SPEED_MPS){ verticalSpeed?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_debug_step_up, 0, 0, 0); }else if(verticalSpeedValue <= -(MIN_VERTICAL_SPEED_MPS)){ verticalSpeed?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_debug_step_down, 0, 0, 0); }else{ verticalSpeed?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_debug_step_none, 0, 0, 0); } } }
gpl-3.0
ppamorim/ThreadExecutor
threadexecutor/src/main/kotlin/com/github/ppamorim/threadexecutor/MainThread.kt
1
1021
/* * Copyright (C) 2017 Pedro Paulo de Amorim * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ppamorim.threadexecutor /** * Interface that will use the instance of * main thread to inform the result of the * async task to the main thread. */ interface MainThread { fun post(runnable: Runnable): Boolean fun post(runnable: () -> Unit): Boolean fun sendMessage(what: Int, result: () -> Unit) fun sendMessage(what: Int, any: Any, result: () -> Unit) fun sendEmptyMessage(what: Int): Boolean }
apache-2.0
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/ui/_custom/view/LolAbilityView.kt
1
9292
/* * Copyright 2017 NIRVANA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zwq65.unity.ui._custom.view import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.graphics.Point import androidx.core.content.ContextCompat import android.util.AttributeSet import com.blankj.utilcode.util.SizeUtils import com.zwq65.unity.R import com.zwq65.unity.ui._base.BaseSubView import kotlin.math.abs import kotlin.math.sin /** * ================================================ * 仿掌上英雄联盟的对局能力分布图 * * * Created by NIRVANA on 2017/10/19 * Contact with <zwq651406441></zwq651406441>@gmail.com> * ================================================ */ class LolAbilityView @JvmOverloads constructor(mContext: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : BaseSubView(mContext, attrs, defStyleAttr) { private var mPaint: Paint? = null private var radiusPaint: Paint? = null private var textPaint: Paint? = null private var valuePaint: Paint? = null private var pathHeptagon: Path? = null private val sideNum = 7 /** * 七边形的半径长度 */ private var radius: Int = 0 /** * 七边形的内角角度 */ private var degree = (360 / sideNum + 0.5).toFloat() /** * 6个点文字的坐标数组 */ private val mPoints = arrayOfNulls<Point>(7) /** * 6种能力的名称 */ private val abilityName = arrayOf("击杀", "生存", "助攻", "物理", "魔法", "防御", "金钱") /** * 6种能力的分值 */ private val abilityValue = floatArrayOf(50f, 70f, 87f, 18f, 46f, 35f, 34f) public override fun setUp(context: Context, attrs: AttributeSet?) { mPaint = Paint(Paint.ANTI_ALIAS_FLAG) radiusPaint = Paint(Paint.ANTI_ALIAS_FLAG) textPaint = Paint(Paint.ANTI_ALIAS_FLAG) valuePaint = Paint(Paint.ANTI_ALIAS_FLAG) radiusPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_3) textPaint!!.color = ContextCompat.getColor(context, R.color.text_color_dark) valuePaint!!.color = ContextCompat.getColor(context, R.color.value_color) textPaint!!.textSize = 24f radiusPaint!!.strokeWidth = 2f radiusPaint!!.style = Paint.Style.STROKE valuePaint!!.strokeWidth = 5f valuePaint!!.style = Paint.Style.STROKE mPaint!!.style = Paint.Style.FILL mPaint!!.strokeCap = Paint.Cap.ROUND } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (pathHeptagon == null) { pathHeptagon = getPathHeptagon() } drawText(canvas) drawHeptagon(canvas) drawHeptagonRadius(canvas) drawAbilityPath(canvas) } /** * 绘制能力值分布曲线path * * @param canvas 画布 */ private fun drawAbilityPath(canvas: Canvas) { val path = Path() for (i in abilityValue.indices) { val diff = getDiffrence(mPoints[i]!!, abilityValue[i]) when (i) { 0 -> path.moveTo(centerX + diff[0], centerY - diff[1]) 1 -> path.lineTo(centerX + diff[0], centerY - diff[1]) 2, 3 -> path.lineTo(centerX + diff[0], centerY + diff[1]) 4, 5 -> path.lineTo(centerX - diff[0], centerY + diff[1]) 6 -> path.lineTo(centerX - diff[0], centerY - diff[1]) else -> { } } } path.close() canvas.drawPath(path, valuePaint!!) } private fun getDiffrence(distance: Point, value: Float): FloatArray { val xx = abs(distance.x - centerX).toFloat() val yy = abs(distance.y - centerY).toFloat() return floatArrayOf(xx * (value / 100), yy * (value / 100)) } /** * 绘制七边形的7条半径 * * @param canvas 画布 */ private fun drawHeptagonRadius(canvas: Canvas) { canvas.save() canvas.rotate(0f, centerX.toFloat(), centerY.toFloat()) for (j in 0 until sideNum + 1) { canvas.drawLine(centerX.toFloat(), centerY.toFloat(), centerX.toFloat(), (centerY - radius).toFloat(), radiusPaint!!) //旋转7次,绘制七边形的7条半径 canvas.rotate(degree, centerX.toFloat(), centerY.toFloat()) } canvas.restore() } /** * 绘制七边形Heptagon * * @param canvas 画布 */ private fun drawHeptagon(canvas: Canvas) { canvas.save() mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_4) canvas.drawPath(pathHeptagon!!, mPaint!!) //缩放canvas,绘制多个同心七边形 canvas.scale(0.75f, 0.75f, centerX.toFloat(), centerY.toFloat()) mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_3) canvas.drawPath(pathHeptagon!!, mPaint!!) canvas.restore() canvas.save() canvas.scale(0.5f, 0.5f, centerX.toFloat(), centerY.toFloat()) mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_2) canvas.drawPath(pathHeptagon!!, mPaint!!) canvas.restore() canvas.save() canvas.scale(0.25f, 0.25f, centerX.toFloat(), centerY.toFloat()) mPaint!!.color = ContextCompat.getColor(context, R.color.heptagon_1) canvas.drawPath(pathHeptagon!!, mPaint!!) canvas.restore() } /** * 绘制六个能力text * * @param canvas 画布 */ private fun drawText(canvas: Canvas) { val interval = SizeUtils.dp2px(10f).toFloat() for (i in mPoints.indices) { when (i) { 0 -> canvas.drawText(abilityName[i], (mPoints[i]!!.x - 1.5 * interval).toFloat(), mPoints[i]!!.y - interval, textPaint!!) 1 -> canvas.drawText(abilityName[i], mPoints[i]!!.x + interval, mPoints[i]!!.y.toFloat(), textPaint!!) 2 -> canvas.drawText(abilityName[i], mPoints[i]!!.x + interval, mPoints[i]!!.y + interval, textPaint!!) 3 -> canvas.drawText(abilityName[i], mPoints[i]!!.x + interval, mPoints[i]!!.y + 2 * interval, textPaint!!) 4 -> canvas.drawText(abilityName[i], mPoints[i]!!.x - 3 * interval, mPoints[i]!!.y + 2 * interval, textPaint!!) 5 -> canvas.drawText(abilityName[i], mPoints[i]!!.x - 3 * interval, mPoints[i]!!.y + interval, textPaint!!) 6 -> canvas.drawText(abilityName[i], mPoints[i]!!.x - 3 * interval, mPoints[i]!!.y.toFloat(), textPaint!!) else -> { } } } } /** * @return 七边形的边path */ private fun getPathHeptagon(): Path { val path = Path() path.moveTo(centerX.toFloat(), (centerY - radius).toFloat()) mPoints[0] = Point(centerX, centerY - radius) //根据已知角度分别计算来绘制七边形的7条边 val l1 = (sin(Math.toRadians(degree.toDouble())) * radius).toInt() val l2 = ((1 - sin(Math.toRadians((90 - degree).toDouble()))) * radius).toInt() path.rLineTo(l1.toFloat(), l2.toFloat()) mPoints[1] = Point(centerX + l1, centerY - radius + l2) val l3 = (sin(Math.toRadians(1.5 * degree)) * radius).toInt() val l4 = (sin(Math.toRadians(90 - 1.5 * degree)) * radius).toInt() path.lineTo((centerX + l3).toFloat(), (centerY + l4).toFloat()) mPoints[2] = Point(centerX + l3, centerY + l4) val l5 = (sin(Math.toRadians(0.5 * degree)) * radius).toInt() val l6 = (sin(Math.toRadians(90 - 0.5 * degree)) * radius).toInt() path.lineTo((centerX + l5).toFloat(), (centerY + l6).toFloat()) mPoints[3] = Point(centerX + l5, centerY + l6) //对称,所以另外半边将x坐标改为'-'即可 path.rLineTo((-2 * l5).toFloat(), 0f) mPoints[4] = Point(centerX - l5, centerY + l6) path.moveTo(centerX.toFloat(), (centerY - radius).toFloat()) path.rLineTo((-l1).toFloat(), l2.toFloat()) mPoints[6] = Point(centerX - l1, centerY - radius + l2) path.lineTo((centerX - l3).toFloat(), (centerY + l4).toFloat()) mPoints[5] = Point(centerX - l3, centerY + l4) path.lineTo((centerX - l5).toFloat(), (centerY + l6).toFloat()) return path } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = MeasureSpec.getSize(widthMeasureSpec) val height = MeasureSpec.getSize(heightMeasureSpec) radius = height / 5 setMeasuredDimension(width, height) } }
apache-2.0
vector-im/vector-android
vector/src/main/java/im/vector/activity/interfaces/Restorable.kt
2
860
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.activity.interfaces import android.os.Bundle /** * Implement this to let the Activity save your internal state when it is destroyed */ interface Restorable { /** * Save internal state */ fun saveState(outState: Bundle) }
apache-2.0
sksamuel/ktest
kotest-runner/kotest-runner-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/runner/junit5/WordSpecEngineKitTest.kt
1
4908
package com.sksamuel.kotest.runner.junit5 import io.kotest.core.spec.style.FunSpec import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import org.junit.platform.engine.discovery.DiscoverySelectors.selectClass import org.junit.platform.testkit.engine.EngineTestKit class WordSpecEngineKitTest : FunSpec({ test("verify engine stats") { EngineTestKit .engine("kotest") .selectors(selectClass(WordSpecSample::class.java)) .configurationParameter("allow_private", "true") .execute() .allEvents().apply { started().shouldHaveNames( "Kotest", "com.sksamuel.kotest.runner.junit5.WordSpecSample", "a container should", "fail a test", "pass a test", "error", "an empty when container should", "an empty should container should", "this when container when", "contain an empty should container should", "a when container with a failing test when", "with a should container should", "fail a test", "pass a test", "a when container when", "with a should container should", "pass a test", "a failing container should" ) aborted().shouldBeEmpty() skipped().shouldHaveNames("skip a test", "skip a test") failed().shouldHaveNames( "fail a test", "error", "fail a test", "a failing container should" ) succeeded().shouldHaveNames( "pass a test", "a container should", "an empty when container should", "an empty should container should", "contain an empty should container should", "this when container when", "pass a test", "with a should container should", "a when container with a failing test when", "pass a test", "with a should container should", "a when container when", "com.sksamuel.kotest.runner.junit5.WordSpecSample", "Kotest" ) finished().shouldHaveNames( "fail a test", "pass a test", "error", "a container should", "an empty when container should", "an empty should container should", "contain an empty should container should", "this when container when", "fail a test", "pass a test", "with a should container should", "a when container with a failing test when", "pass a test", "with a should container should", "a when container when", "a failing container should", "com.sksamuel.kotest.runner.junit5.WordSpecSample", "Kotest", ) dynamicallyRegistered().shouldHaveNames( "com.sksamuel.kotest.runner.junit5.WordSpecSample", "a container should", "skip a test", "fail a test", "pass a test", "error", "an empty when container should", "an empty should container should", "this when container when", "contain an empty should container should", "a when container with a failing test when", "with a should container should", "fail a test", "pass a test", "a when container when", "with a should container should", "pass a test", "skip a test", "a failing container should" ) } } }) private class WordSpecSample : WordSpec({ "a container" should { "skip a test".config(enabled = false) {} "fail a test" { 1 shouldBe 2 } "pass a test" { 1 shouldBe 1 } "error" { throw RuntimeException() } } "an empty when container" should { } "an empty should container" should { } "this when container" `when` { "contain an empty should container" should { } } "a when container with a failing test" `when` { "with a should container" should { "fail a test" { 1 shouldBe 2 } "pass a test" { 1 shouldBe 1 } } } "a when container" `when` { "with a should container" should { "pass a test" { 1 shouldBe 1 } "skip a test".config(enabled = false) {} } } "a failing container" should { throw RuntimeException() "not reach this test" {} } })
mit
google/dagger
java/dagger/hilt/android/plugin/main/src/main/kotlin/dagger/hilt/android/plugin/util/AggregatedPackagesTransform.kt
1
3908
/* * Copyright (C) 2021 The Dagger 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 dagger.hilt.android.plugin.util import dagger.hilt.android.plugin.root.AggregatedAnnotation import java.io.ByteArrayOutputStream import java.io.File import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream import org.gradle.api.artifacts.transform.CacheableTransform 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.Classpath /** * A transform that outputs classes and jars containing only classes in key aggregating Hilt * packages that are used to pass dependencies between compilation units. */ @CacheableTransform abstract class AggregatedPackagesTransform : TransformAction<TransformParameters.None> { // TODO(danysantiago): Make incremental by using InputChanges and try to use @CompileClasspath @get:Classpath @get:InputArtifact abstract val inputArtifactProvider: Provider<FileSystemLocation> override fun transform(outputs: TransformOutputs) { val input = inputArtifactProvider.get().asFile when { input.isFile -> transformFile(outputs, input) input.isDirectory -> input.walkInPlatformIndependentOrder().filter { it.isFile }.forEach { transformFile(outputs, it) } else -> error("File/directory does not exist: ${input.absolutePath}") } } private fun transformFile(outputs: TransformOutputs, file: File) { if (file.isJarFile()) { var atLeastOneEntry = false // TODO(danysantiago): This is an in-memory buffer stream, consider using a temp file. val tmpOutputStream = ByteArrayOutputStream() ZipOutputStream(tmpOutputStream).use { outputStream -> ZipInputStream(file.inputStream()).forEachZipEntry { inputStream, inputEntry -> if (inputEntry.isClassFile()) { val parentDirectory = inputEntry.name.substringBeforeLast('/') val match = AggregatedAnnotation.AGGREGATED_PACKAGES.any { aggregatedPackage -> parentDirectory.endsWith(aggregatedPackage) } if (match) { outputStream.putNextEntry(ZipEntry(inputEntry.name)) inputStream.copyTo(outputStream) outputStream.closeEntry() atLeastOneEntry = true } } } } if (atLeastOneEntry) { outputs.file(JAR_NAME).outputStream().use { tmpOutputStream.writeTo(it) } } } else if (file.isClassFile()) { // If transforming a file, check if the parent directory matches one of the known aggregated // packages structure. File and Path APIs are used to avoid OS-specific issues when comparing // paths. val parentDirectory: File = file.parentFile val match = AggregatedAnnotation.AGGREGATED_PACKAGES.any { aggregatedPackage -> parentDirectory.endsWith(aggregatedPackage) } if (match) { outputs.file(file) } } } companion object { // The output file name containing classes in the aggregated packages. val JAR_NAME = "hiltAggregated.jar" } }
apache-2.0
cmcpasserby/MayaCharm
src/main/kotlin/actions/SendBufferAction.kt
1
1065
package actions import MayaBundle as Loc import mayacomms.MayaCommandInterface import resources.MayaNotifications import settings.ProjectSettings import com.intellij.notification.Notifications import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.fileEditor.FileDocumentManager class SendBufferAction : BaseSendAction( Loc.message("mayacharm.action.SendDocumentText"), Loc.message("mayacharm.action.SendDocumentDescription"), null ) { override fun actionPerformed(e: AnActionEvent) { val sdk = ProjectSettings.getInstance(e.project!!).selectedSdk if (sdk == null) { Notifications.Bus.notify(MayaNotifications.NO_SDK_SELECTED) return } val docManager = FileDocumentManager.getInstance() val data = e.getData(LangDataKeys.VIRTUAL_FILE) ?: return data.let { docManager.getDocument(it) }?.also { docManager.saveDocument(it) } MayaCommandInterface(sdk.port).sendFileToMaya(data.path) } }
mit
seventhroot/elysium
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKTimedPurchaseTable.kt
1
6292
/* * Copyright 2018 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.store.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileProvider import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.purchase.RPKTimedPurchase import com.rpkit.store.bukkit.purchase.RPKTimedPurchaseImpl import com.rpkit.store.bukkit.storeitem.RPKStoreItemProvider import com.rpkit.store.bukkit.storeitem.RPKTimedStoreItem import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_PURCHASE import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_TIMED_PURCHASE import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL import org.jooq.impl.SQLDataType class RPKTimedPurchaseTable(database: Database, private val plugin: RPKStoresBukkit): Table<RPKTimedPurchase>(database, RPKTimedPurchase::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_timed_purchase.id.enabled")) { database.cacheManager.createCache("rpkit-stores-bukkit.rpkit_timed_purchase.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKTimedPurchase::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_timed_purchase.id.size"))).build()) } else { null } override fun create() { database.create.createTableIfNotExists(RPKIT_TIMED_PURCHASE) .column(RPKIT_TIMED_PURCHASE.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_TIMED_PURCHASE.PURCHASE_ID, SQLDataType.INTEGER) .constraints( DSL.constraint("pk_rpkit_timed_purchase").primaryKey(RPKIT_TIMED_PURCHASE.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "1.6.0") } } override fun insert(entity: RPKTimedPurchase): Int { val id = database.getTable(RPKPurchaseTable::class).insert(entity) database.create .insertInto( RPKIT_TIMED_PURCHASE, RPKIT_TIMED_PURCHASE.PURCHASE_ID ) .values( id ) .execute() entity.id = id cache?.put(id, entity) return id } override fun update(entity: RPKTimedPurchase) { database.getTable(RPKPurchaseTable::class).update(entity) cache?.put(entity.id, entity) } override fun get(id: Int): RPKTimedPurchase? { val result = database.create .select( RPKIT_PURCHASE.STORE_ITEM_ID, RPKIT_PURCHASE.PROFILE_ID, RPKIT_PURCHASE.PURCHASE_DATE, RPKIT_TIMED_PURCHASE.PURCHASE_ID ) .from(RPKIT_TIMED_PURCHASE) .where(RPKIT_PURCHASE.ID.eq(id)) .and(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(RPKIT_PURCHASE.ID)) .fetchOne() ?: return null val storeItemProvider = plugin.core.serviceManager.getServiceProvider(RPKStoreItemProvider::class) val storeItem = storeItemProvider.getStoreItem(result[RPKIT_PURCHASE.STORE_ITEM_ID]) as? RPKTimedStoreItem if (storeItem == null) { database.create .deleteFrom(RPKIT_PURCHASE) .where(RPKIT_PURCHASE.ID.eq(id)) .execute() database.create .deleteFrom(RPKIT_TIMED_PURCHASE) .where(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(id)) .execute() cache?.remove(id) return null } val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val profile = profileProvider.getProfile(result[RPKIT_PURCHASE.PROFILE_ID]) if (profile == null) { database.create .deleteFrom(RPKIT_PURCHASE) .where(RPKIT_PURCHASE.ID.eq(id)) .execute() database.create .deleteFrom(RPKIT_TIMED_PURCHASE) .where(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(id)) .execute() cache?.remove(id) return null } val timedPurchase = RPKTimedPurchaseImpl( id, storeItem, profile, result[RPKIT_PURCHASE.PURCHASE_DATE].toLocalDateTime() ) cache?.put(id, timedPurchase) return timedPurchase } fun get(profile: RPKProfile): List<RPKTimedPurchase> { val result = database.create .select(RPKIT_TIMED_PURCHASE.PURCHASE_ID) .from( RPKIT_PURCHASE, RPKIT_TIMED_PURCHASE ) .where(RPKIT_PURCHASE.ID.eq(RPKIT_TIMED_PURCHASE.ID)) .and(RPKIT_PURCHASE.PROFILE_ID.eq(profile.id)) .fetch() return result.mapNotNull { row -> get(row[RPKIT_TIMED_PURCHASE.PURCHASE_ID]) } } override fun delete(entity: RPKTimedPurchase) { database.getTable(RPKPurchaseTable::class).delete(entity) database.create .deleteFrom(RPKIT_TIMED_PURCHASE) .where(RPKIT_TIMED_PURCHASE.PURCHASE_ID.eq(entity.id)) .execute() cache?.remove(entity.id) } }
apache-2.0
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/WebScrollSingleAction.kt
1
7712
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.action.item import android.app.AlertDialog import android.content.Context import android.hardware.SensorManager import android.os.Parcel import android.os.Parcelable import android.view.View import android.view.ViewConfiguration import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import android.widget.Toast import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.core.utility.extensions.density import jp.hazuki.yuzubrowser.core.utility.utils.ArrayUtils import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo import jp.hazuki.yuzubrowser.webview.CustomWebView import java.io.IOException class WebScrollSingleAction : SingleAction, Parcelable { private var mType = TYPE_FLING private var mX: Int = 0 private var mY: Int = 0 val iconResourceId: Int get() = when { mX > 0 -> when { mY > 0 -> R.drawable.ic_arrow_down_right_white_24dp mY < 0 -> R.drawable.ic_arrow_up_right_white_24px else -> R.drawable.ic_arrow_forward_white_24dp } mX < 0 -> when { mY > 0 -> R.drawable.ic_arrow_down_left_24dp mY < 0 -> R.drawable.ic_arrow_up_left_white_24px else -> R.drawable.ic_arrow_back_white_24dp } else -> when { mY > 0 -> R.drawable.ic_arrow_downward_white_24dp mY < 0 -> R.drawable.ic_arrow_upward_white_24dp else -> -1 } } @Throws(IOException::class) constructor(id: Int, reader: JsonReader?) : super(id) { if (reader != null) { if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return reader.beginObject() while (reader.hasNext()) { if (reader.peek() != JsonReader.Token.NAME) return when (reader.nextName()) { FIELD_NAME_TYPE -> mType = reader.nextInt() FIELD_NAME_X -> mX = reader.nextInt() FIELD_NAME_Y -> mY = reader.nextInt() else -> reader.skipValue() } } reader.endObject() } } @Throws(IOException::class) override fun writeIdAndData(writer: JsonWriter) { writer.value(id) writer.beginObject() writer.name(FIELD_NAME_TYPE) writer.value(mType) writer.name(FIELD_NAME_X) writer.value(mX) writer.name(FIELD_NAME_Y) writer.value(mY) writer.endObject() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) dest.writeInt(mType) dest.writeInt(mX) dest.writeInt(mY) } private constructor(source: Parcel) : super(source.readInt()) { mType = source.readInt() mX = source.readInt() mY = source.readInt() } override fun showMainPreference(context: ActionActivity): StartActivityInfo? { return showSubPreference(context) } override fun showSubPreference(context: ActionActivity): StartActivityInfo? { val view = View.inflate(context, R.layout.action_web_scroll_setting, null) val typeSpinner = view.findViewById<Spinner>(R.id.typeSpinner) val editTextX = view.findViewById<EditText>(R.id.editTextX) val editTextY = view.findViewById<EditText>(R.id.editTextY) val res = context.resources val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, res.getStringArray(R.array.action_web_scroll_type_list)) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) typeSpinner.adapter = adapter val values = res.getIntArray(R.array.action_web_scroll_type_values) var current = ArrayUtils.findIndexOfValue(mType, values) if (current < 0) current = TYPE_FLING typeSpinner.setSelection(current) editTextX.setText(mX.toString()) editTextY.setText(mY.toString()) AlertDialog.Builder(context) .setTitle(R.string.action_settings) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> mType = values[typeSpinner.selectedItemPosition] var x = 0 var y = 0 try { x = Integer.parseInt(editTextX.text.toString()) } catch (e: NumberFormatException) { e.printStackTrace() } try { y = Integer.parseInt(editTextY.text.toString()) } catch (e: NumberFormatException) { e.printStackTrace() } if (x == 0 && y == 0) { Toast.makeText(context.applicationContext, R.string.action_web_scroll_x_y_zero, Toast.LENGTH_SHORT).show() showSubPreference(context) return@setPositiveButton } mX = x mY = y } .setNegativeButton(android.R.string.cancel, null) .show() return null } fun scrollWebView(context: Context, web: CustomWebView) { when (mType) { TYPE_FAST -> web.scrollBy(mX, mY) TYPE_FLING -> web.flingScroll(makeFlingValue(context, mX), makeFlingValue(context, mY)) else -> throw RuntimeException("Unknown type : " + mType) } } private fun makeFlingValue(context: Context, d: Int): Int { val decelerationLate = (Math.log(0.78) / Math.log(0.9)).toFloat() val physicalCoef = SensorManager.GRAVITY_EARTH * 39.37f * context.density * 160.0f * 0.84f val flingFliction = ViewConfiguration.getScrollFriction() return (Integer.signum(d) * Math.round(Math.exp(Math.log((Math.abs(d) / (flingFliction * physicalCoef)).toDouble()) / decelerationLate * (decelerationLate - 1.0)) / 0.35f * (flingFliction * physicalCoef))).toInt() } companion object { private const val FIELD_NAME_TYPE = "0" private const val FIELD_NAME_X = "1" private const val FIELD_NAME_Y = "2" private const val TYPE_FAST = 0 private const val TYPE_FLING = 1 @JvmField val CREATOR: Parcelable.Creator<WebScrollSingleAction> = object : Parcelable.Creator<WebScrollSingleAction> { override fun createFromParcel(source: Parcel): WebScrollSingleAction { return WebScrollSingleAction(source) } override fun newArray(size: Int): Array<WebScrollSingleAction?> { return arrayOfNulls(size) } } } }
apache-2.0
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/cpu/assembler/Assembler.kt
1
4781
package com.soywiz.kpspemu.cpu.assembler import com.soywiz.korge.util.* import com.soywiz.korio.error.* import com.soywiz.korio.stream.* import com.soywiz.kpspemu.cpu.* import kotlin.collections.set @NativeThreadLocal object Assembler : InstructionDecoder() { val mnemonicGpr get() = CpuState.gprInfosByMnemonic fun parseGpr(str: String): Int { if (str.startsWith("r")) return str.substring(1).toInt() return mnemonicGpr[str]?.index ?: invalidOp("Unknown GPR $str") } fun String.parseInt(context: Context): Int { context.labels[this]?.let { return it } val str = this.replace("_", "") if (str.startsWith("0x")) return str.substring(2).toInt(16) return str.toInt() } fun assembleSingleInt(str: String, pc: Int = 0, context: Context = Context()): Int = assembleSingle(str, pc, context).value data class ParsedInstruction(val str: String) { val parts = str.split(Regex("\\s+"), limit = 2) val nameRaw = parts.getOrElse(0) { "" } val name = nameRaw.toLowerCase() val args = parts.getOrElse(1) { "" } val argsParsed = args.trim().split(',').map { it.trim() } } fun assembleSingle(str: String, pc: Int = 0, context: Context = Context()): InstructionData { val pi = ParsedInstruction(str) val instruction = Instructions.instructionsByName[pi.name] ?: invalidOp("Unknown instruction '${pi.name}'") val out = InstructionData(instruction.vm.value, pc) val replacements = instruction.replacements val formatRegex = instruction.formatRegex val match = formatRegex.matchEntire(pi.args) ?: invalidOp("${instruction.format} -> $formatRegex doesn't match ${pi.args}") val results = replacements.zip(match.groupValues.drop(1)) //println(context.labels) for ((pat, value) in results) { when (pat) { "%s" -> out.rs = parseGpr(value) "%d" -> out.rd = parseGpr(value) "%t" -> out.rt = parseGpr(value) "%a" -> out.pos = value.parseInt(context) "%i" -> out.s_imm16 = value.parseInt(context) "%I" -> out.u_imm16 = value.parseInt(context) "%O" -> out.s_imm16 = value.parseInt(context) - pc - 4 "%j" -> out.jump_address = value.parseInt(context) else -> invalidOp("Unsupported $pat :: value=$value in instruction $str") } } return out } fun assembleTo(sstr: String, out: SyncStream, pc: Int = out.position.toInt(), context: Context = Context()): Int { val labelParts = sstr.split(":", limit = 2).reversed() val str = labelParts[0].trim() val label = labelParts.getOrNull(1)?.trim() if (label != null) { context.labels[label] = pc //println("$label -> ${pc.hex}") } //println("${pc.hex}: $str") val pi = ParsedInstruction(str) val start = out.position when (pi.name) { "" -> { // None } "nop" -> { out.write32_le(assembleSingleInt("sll zero, zero, 0", pc + 0, context)) } "li" -> { val reg = pi.argsParsed[0] val value = pi.argsParsed[1].parseInt(context) if ((value ushr 16) != 0) { out.write32_le(assembleSingleInt("lui $reg, ${value ushr 16}", pc + 0, context)) out.write32_le(assembleSingleInt("ori $reg, $reg, ${value and 0xFFFF}", pc + 4, context)) } else { out.write32_le(assembleSingleInt("ori $reg, r0, ${value and 0xFFFF}", pc + 0, context)) } } else -> { out.write32_le(assembleSingleInt(str, pc, context)) } } val end = out.position val written = (end - start).toInt() //println(" : $written (${pi.name})") return written } class Context { val labels = LinkedHashMap<String, Int>() } fun assembleTo(lines: List<String>, out: SyncStream, pc: Int = out.position.toInt(), context: Context = Context()) { var cpc = pc for (line in lines) { if (line.isEmpty()) continue cpc += assembleTo(line, out, cpc, context) } } fun assemble(lines: List<String>, pc: Int = 0, context: Context = Context()): ByteArray { return MemorySyncStreamToByteArray { assembleTo(lines, this, pc, context) } } fun assemble(vararg lines: String, pc: Int = 0, context: Context = Context()): ByteArray = assemble(lines.toList(), pc = pc, context = context) }
mit
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/versions/VersionService.kt
1
6277
package com.gmail.blueboxware.libgdxplugin.versions import com.gmail.blueboxware.libgdxplugin.utils.SkinTagsModificationTracker import com.gmail.blueboxware.libgdxplugin.utils.findClasses import com.gmail.blueboxware.libgdxplugin.utils.getLibraryInfoFromIdeaLibrary import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.psi.PsiLiteralExpression import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.Alarm import com.intellij.util.text.DateFormatUtil import org.jetbrains.kotlin.config.MavenComparableVersion /* * Copyright 2017 Blue Box Ware * * 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. */ @Service class VersionService(val project: Project) : Disposable { fun isLibGDXProject() = getUsedVersion(Libraries.LIBGDX) != null fun getUsedVersion(library: Libraries): MavenComparableVersion? = usedVersions[library] fun getLatestVersion(library: Libraries): MavenComparableVersion? = library.library.getLatestVersion(this) private val usedVersions = mutableMapOf<Libraries, MavenComparableVersion>() private val updateLatestVersionsAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this) fun projectOpened() { updateUsedVersions { if (isLibGDXProject()) { Libraries.LIBGDX.library.updateLatestVersion(this, true) updateLatestVersions() updateLatestVersionsAlarm.addRequest({ scheduleUpdateLatestVersions() }, 2 * DateFormatUtil.MINUTE) } } LibraryTablesRegistrar.getInstance().getLibraryTable(project).addListener(libraryListener) } fun projectClosed() { updateLatestVersionsAlarm.cancelAllRequests() LibraryTablesRegistrar.getInstance().getLibraryTable(project).removeListener(libraryListener) } override fun dispose() { } private fun updateLatestVersions() { var networkCount = 0 Libraries.values().sortedBy { it.library.lastUpdated }.forEach { lib -> val networkAllowed = networkCount < BATCH_SIZE && usedVersions[lib] != null if (lib.library.updateLatestVersion(this, networkAllowed)) { LOG.debug("Updated latest version of ${lib.library.name}.") networkCount++ } } } fun updateUsedVersions(doAfterUpdate: (() -> Unit)? = null) { DumbService.getInstance(project).runWhenSmart { LOG.debug("Updating used library versions") usedVersions.clear() LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraryIterator.let { libraryIterator -> for (lib in libraryIterator) { getLibraryInfoFromIdeaLibrary(lib)?.let { (libraries, version) -> usedVersions[libraries].let { registeredVersion -> if (registeredVersion == null || registeredVersion < version) { usedVersions[libraries] = version } } } } } if (usedVersions[Libraries.LIBGDX] == null) { val runnable = { project.findClasses("com.badlogic.gdx.Version").forEach { psiClass -> ((psiClass.findFieldByName( "VERSION", false )?.initializer as? PsiLiteralExpression)?.value as? String) ?.let(::MavenComparableVersion) ?.let { usedVersions[Libraries.LIBGDX] = it } } } if (ApplicationManager.getApplication().isUnitTestMode) { runInEdtAndWait(runnable) } else { ReadAction.run<Exception>(runnable) } } if (isLibGDXProject()) { SkinTagsModificationTracker.getInstance(project).incModificationCount() LOG.debug("libGDX detected") } else { LOG.debug("No libGDX detected") } doAfterUpdate?.invoke() } } private fun scheduleUpdateLatestVersions() { updateLatestVersionsAlarm.cancelAllRequests() updateLatestVersions() updateLatestVersionsAlarm.addRequest({ LOG.debug("Scheduled update of latest versions") scheduleUpdateLatestVersions() }, SCHEDULED_UPDATE_INTERVAL) } private val libraryListener = object : LibraryTable.Listener { override fun beforeLibraryRemoved(library: Library) { } override fun afterLibraryAdded(newLibrary: Library) { updateUsedVersions() updateLatestVersionsAlarm.cancelAllRequests() updateLatestVersionsAlarm.addRequest({ scheduleUpdateLatestVersions() }, LIBRARY_CHANGED_TIME_OUT) } override fun afterLibraryRemoved(library: Library) { updateUsedVersions() } } companion object { val LOG = Logger.getInstance(VersionService::class.java) var LIBRARY_CHANGED_TIME_OUT = 30 * DateFormatUtil.SECOND var BATCH_SIZE = 20 var SCHEDULED_UPDATE_INTERVAL = 15 * DateFormatUtil.MINUTE } }
apache-2.0
encodeering/conflate
modules/conflate-jvm/src/test/kotlin/com/encodeering/conflate/experimental/jvm/co/CycleDispatcherTest.kt
1
2353
package com.encodeering.conflate.experimental.jvm.co import com.encodeering.conflate.experimental.api.Action import com.encodeering.conflate.experimental.api.Dispatcher import com.encodeering.conflate.experimental.test.fixture.Act import com.encodeering.conflate.experimental.test.mock import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.junit.platform.runner.JUnitPlatform import org.junit.runner.RunWith import org.mockito.Mockito.verify import kotlin.coroutines.experimental.EmptyCoroutineContext /** * @author Michael Clausen - [email protected] */ @RunWith (JUnitPlatform::class) class CycleDispatcherTest : Spek ({ describe ("CycleDispatcher") { fun success () = mock<Dispatcher.(Unit) -> Unit> () fun failure () = mock<Dispatcher.(Throwable) -> Unit> () fun callback () = mock<(Action) -> Unit> () fun dispatcher (block : suspend (Action) -> Unit) = CycleDispatcher (EmptyCoroutineContext) { block (it) } describe ("dispatch") { it ("should dispatch an action properly") { val action = Act ("ridley") val callback = callback () dispatcher { callback (it) }.dispatch (action) verify (callback).invoke (action) } } describe ("completable") { describe ("success") { it ("should match the final state and scope") { val action = Act ("ridley") val success = success () val dispatcher = dispatcher { } dispatcher.dispatch (action).then (fail = {}, ok = success) verify (success).invoke (dispatcher, Unit) } } describe ("failure") { it ("should match the final state and scope") { val action = Act ("ridley") val failure = failure () val exception = IllegalStateException () val dispatcher = dispatcher { throw exception } dispatcher.dispatch (action).then (fail = failure) verify (failure).invoke (dispatcher, exception) } } } } })
apache-2.0
mniami/android.kotlin.benchmark
app/src/main/java/guideme/volunteers/ui/fragments/settings/SettingsPresenter.kt
2
535
package guideme.volunteers.ui.fragments.settings import guideme.volunteers.helpers.dataservices.datasource.DataSourceContainer import guideme.volunteers.ui.fragments.base.BasicPresenter import guideme.volunteers.ui.utils.AppVersionProvider class SettingsPresenter(val appVersionProvider: AppVersionProvider, val dataSourceContainer: DataSourceContainer) : BasicPresenter() { var view: ISettingsFragment? = null fun getAppVersion() : String { return appVersionProvider.getAppVersion() } }
apache-2.0
wizardofos/Protozoo
component/greeter/src/main/kotlin/org/protozoo/component/greeter/Greeter.kt
1
62
package org.protozoo.component.greeter interface Greeter { }
mit
kamgurgul/cpu-info
app/src/main/java/com/kgurgul/cpuinfo/data/provider/CpuDataNativeProvider.kt
1
493
package com.kgurgul.cpuinfo.data.provider import javax.inject.Inject import javax.inject.Singleton @Singleton class CpuDataNativeProvider @Inject constructor() { external fun initLibrary() external fun getCpuName(): String external fun hasArmNeon(): Boolean external fun getL1dCaches(): IntArray? external fun getL1iCaches(): IntArray? external fun getL2Caches(): IntArray? external fun getL3Caches(): IntArray? external fun getL4Caches(): IntArray? }
apache-2.0
duftler/orca
orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/PipelineTrigger.kt
2
1736
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.pipeline.model import com.fasterxml.jackson.annotation.JsonIgnore import com.netflix.spinnaker.kork.artifacts.model.Artifact import com.netflix.spinnaker.kork.artifacts.model.ExpectedArtifact data class PipelineTrigger @JvmOverloads constructor( override val type: String = "pipeline", override val correlationId: String? = null, override val user: String? = "[anonymous]", override val parameters: Map<String, Any> = mutableMapOf(), override val artifacts: List<Artifact> = mutableListOf(), override val notifications: List<Map<String, Any>> = mutableListOf(), override var isRebake: Boolean = false, override var isDryRun: Boolean = false, override var isStrategy: Boolean = false, val parentExecution: Execution, val parentPipelineStageId: String? = null ) : Trigger { override var other: Map<String, Any> = mutableMapOf() override var resolvedExpectedArtifacts: List<ExpectedArtifact> = mutableListOf() @JsonIgnore val parentStage: Stage? = if (parentPipelineStageId != null) { parentExecution.stageById(parentPipelineStageId) } else { null } }
apache-2.0
willowtreeapps/assertk
assertk/src/jvmTest/kotlin/test/assertk/assertions/PathTest.kt
1
4961
package test.assertk.assertions import assertk.assertThat import assertk.assertions.* import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.test.* private var regularFile: Path? = null private var directory: Path? = null private var regularFileWithText: Path? = null private var doesNotExist: Path? = null class PathTest { @BeforeTest fun beforeGroup() { regularFile = createTempFile() directory = createTempDir() regularFileWithText = createTempFileWithText() doesNotExist = Paths.get("/tmp/does_not_exist") } @AfterTest fun afterGroup() { regularFile?.let(Files::deleteIfExists) directory?.let(Files::deleteIfExists) regularFileWithText?.let(Files::deleteIfExists) } //region isRegularFile @Test fun isRegularFile_value_regularFile_passes() { assertThat(regularFile!!).isRegularFile() } @Test fun isRegularFile_value_directory_fails() { val error = assertFails { assertThat(directory!!).isRegularFile() } assertEquals("expected <$directory> to be a regular file, but it is not", error.message) } //endregion //region isDirectory @Test fun isDirectory_value_not_directory_fails() { val error = assertFails { assertThat(regularFile!!).isDirectory() } assertEquals("expected <$regularFile> to be a directory, but it is not", error.message) } @Test fun isDirectory_value_directory_passes() { assertThat(directory!!).isDirectory() } //endregion //region isHidden @Test fun isHidden_value_regular_file_not_hidden_fails() { val error = assertFails { assertThat(regularFile!!).isHidden() } assertEquals("expected <$regularFile> to be hidden, but it is not", error.message) } @Test fun isHidden_value_directory_not_hidden_fails() { val error = assertFails { assertThat(directory!!).isHidden() } assertEquals("expected <$directory> to be hidden, but it is not", error.message) } //endregion //region isReadable @Test fun isReadable_value_readable_file_passes() { assertThat(regularFile!!).isReadable() } @Test fun isReadable_value_readable_directory_passes() { assertThat(directory!!).isReadable() } //endregion //region isSymbolicLink @Test fun isSymbolicLink_value_regular_file_fails() { val error = assertFails { assertThat(regularFile!!).isSymbolicLink() } assertEquals("expected <$regularFile> to be a symbolic link, but it is not", error.message) } @Test fun isSymbolicLink_value_directory_fails() { val error = assertFails { assertThat(directory!!).isSymbolicLink() } assertEquals("expected <$directory> to be a symbolic link, but it is not", error.message) } //endregion //region isWritable @Test fun isWritable_value_writable_file_passes() { assertThat(regularFile!!).isWritable() } @Test fun isWritable_value_writable_directory_passes() { assertThat(directory!!).isWritable() } //endregion //region isSameFileAs @Test fun isSameFileAs_value_same_file_passes() { assertThat(regularFile!!).isSameFileAs(regularFile!!) } @Test fun isSameFileAs_value_same_directory_passes() { assertThat(directory!!).isSameFileAs(directory!!) } @Test fun isSameFileAs_value_same_file_different_path_passes() { assertThat(regularFile!!).isSameFileAs(regularFile!!.toAbsolutePath()) } @Test fun isSameFileAs_value_same_directory_different_path_passes() { assertThat(directory!!).isSameFileAs(directory!!.toAbsolutePath()) } //endregion //region exists @Test fun exists_value_regularFile_passes() { assertThat(regularFile!!).exists() } @Test fun exists_value_directory_passes() { assertThat(directory!!).exists() } @Test fun exists_value_not_exists_fails() { val error = assertFails { assertThat(doesNotExist!!).exists() } assertEquals("expected <$doesNotExist> to exist, but it does not", error.message) } //endregion //region lines @Test fun lines_correct_string_passes() { assertThat(regularFileWithText!!).lines().containsExactly("a", "b") } //endregion //region bytes @Test fun bytes_value_correct_byte_array_passes() { assertThat(regularFile!!).bytes().containsExactly(*ByteArray(10)) } //endregion } private fun createTempDir() = Files.createTempDirectory("tempDir") private fun createTempFile() = Files.createTempFile("tempFile", "").apply { toFile().writeBytes(ByteArray(10)) } private fun createTempFileWithText() = Files.createTempFile("tempFileWithText", "").apply { toFile().writeText("a\nb", Charsets.UTF_8) }
mit
RP-Kit/RPKit
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/UnsignCommand.kt
2
1965
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.essentials.bukkit.command import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import org.bukkit.Material import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.inventory.meta.BookMeta class UnsignCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender.hasPermission("rpkit.essentials.command.unsign")) { if (sender is Player) { if (sender.inventory.itemInMainHand.type == Material.WRITTEN_BOOK) { val meta = sender.inventory.itemInMainHand.itemMeta as BookMeta sender.inventory.itemInMainHand.type = Material.WRITABLE_BOOK sender.inventory.itemInMainHand.itemMeta = meta sender.sendMessage(plugin.messages["unsign-valid"]) } else { sender.sendMessage(plugin.messages["unsign-invalid-book"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } } else { sender.sendMessage(plugin.messages["no-permission-unsign"]) } return true } }
apache-2.0
RP-Kit/RPKit
bukkit/rpk-core-bukkit/src/main/kotlin/com/rpkit/core/bukkit/command/sender/RPKBukkitRemoteCommandSender.kt
1
1474
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.core.bukkit.command.sender import com.rpkit.core.command.sender.RPKRemoteCommandSender import net.md_5.bungee.api.chat.BaseComponent import org.bukkit.command.RemoteConsoleCommandSender class RPKBukkitRemoteCommandSender( private val commandSender: RemoteConsoleCommandSender ) : RPKBukkitCommandSender, RPKRemoteCommandSender { override val name: String get() = commandSender.name override fun sendMessage(message: String) { commandSender.sendMessage(message) } override fun sendMessage(messages: Array<String>) { commandSender.sendMessage(*messages) } override fun hasPermission(permission: String): Boolean { return commandSender.hasPermission(permission) } override fun sendMessage(vararg components: BaseComponent) { commandSender.spigot().sendMessage(*components) } }
apache-2.0
RP-Kit/RPKit
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/web/minecraft/MinecraftProfilePostRequest.kt
1
330
package com.rpkit.players.bukkit.web.minecraft import org.http4k.core.Body import org.http4k.format.Gson.auto import java.util.UUID data class MinecraftProfilePostRequest( val minecraftUUID: UUID, val profileId: Int? ) { companion object { val lens = Body.auto<MinecraftProfilePostRequest>().toLens() } }
apache-2.0
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/recentlanguages/Language.kt
5
117
package fr.free.nrw.commons.recentlanguages data class Language(val languageName: String, val languageCode: String)
apache-2.0
thetric/ilias-downloader
src/main/kotlin/com/github/thetric/iliasdownloader/connector/exception/IliasAuthenticationException.kt
1
201
package com.github.thetric.iliasdownloader.connector.exception /** * Authentication at the Ilias web service failed. */ class IliasAuthenticationException(message: String) : IliasException(message)
mit
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/upload/GpsCategoryModel.kt
5
543
package fr.free.nrw.commons.upload import fr.free.nrw.commons.category.CategoryItem import io.reactivex.subjects.BehaviorSubject import javax.inject.Inject import javax.inject.Singleton @Singleton class GpsCategoryModel @Inject constructor() { val categoriesFromLocation = BehaviorSubject.createDefault(emptyList<CategoryItem>()) fun clear() { categoriesFromLocation.onNext(emptyList()) } fun setCategoriesFromLocation(categoryList: List<CategoryItem>) { categoriesFromLocation.onNext(categoryList) } }
apache-2.0
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/generics/kotlin/test5/Test1.kt
1
1936
package com.zj.example.kotlin.shengshiyuan.helloworld.generics.kotlin.test5 /** * Created by zhengjiong * date: 2018/2/25 21:07 */ interface Producer<out T> { fun produce(): T } interface Consumer<in T> { fun consume(item: T) } open class Fruit open class Apple : Fruit() class ApplePear : Apple() class FruitProducer : Producer<Fruit> { override fun produce(): Fruit { return Fruit() } } class AppleProducer : Producer<Apple> { override fun produce(): Apple { return Apple() } } class ApplePearProducer : Producer<ApplePear> { override fun produce(): ApplePear { return ApplePear() } } private fun producerTest() { //对于"out"泛型来说, 我们可以将子类型对象赋给父类型引用 val producer1: Producer<Fruit> = FruitProducer() //success val producer2: Producer<Fruit> = AppleProducer() //success val producer3: Producer<Fruit> = ApplePearProducer() //success //这里返回的是Fruit类型的变量 val fruit = producer2.produce() //val producer4: Producer<ApplePear> = AppleProducer() //error val producer5: Producer<ApplePear> = ApplePearProducer() //success } fun main(args: Array<String>) { producerTest() consumerTest() } private fun consumerTest() { //对于"in"泛型来说, 我们可以将父类型对象赋给子类型引用 val consumer1: Consumer<ApplePear> = FruitConsumer() val consumer2: Consumer<ApplePear> = AppleConsumer() val consumer3: Consumer<ApplePear> = ApplePearConsumer() consumer2.consume(ApplePear())//这里的输入参数类型是ApplePear类型的 } class FruitConsumer : Consumer<Fruit> { override fun consume(item: Fruit) { } } class AppleConsumer : Consumer<Apple> { override fun consume(item: Apple) { } } class ApplePearConsumer : Consumer<ApplePear> { override fun consume(item: ApplePear) { } }
mit
SoulBeaver/SpriteSheetProcessor
src/main/java/com/sbg/rpg/console/Main.kt
1
3510
/* * Copyright 2016 Christian Broomfield * * 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.sbg.rpg.console import com.beust.jcommander.JCommander import com.beust.jcommander.ParameterException import com.sbg.rpg.packing.common.SpriteCutter import com.sbg.rpg.packing.common.SpriteDrawer import com.sbg.rpg.packing.common.SpriteSheetWriter import com.sbg.rpg.packing.packer.SpriteSheetPacker import com.sbg.rpg.packing.packer.metadata.JsonMetadataCreator import com.sbg.rpg.packing.packer.metadata.TextMetadataCreator import com.sbg.rpg.packing.packer.metadata.YamlMetadataCreator import com.sbg.rpg.packing.unpacker.SpriteSheetUnpacker import org.apache.logging.log4j.Level import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.core.LoggerContext fun main(args: Array<String>) { try { val commandLineArguments = CommandLineArguments() JCommander(commandLineArguments).parse(*args) if (commandLineArguments.verbose || commandLineArguments.debugMode) enableVerboseOutput() if (!commandLineArguments.debugMode) disableLoggingToFile() createProcessor(commandLineArguments).processSpriteSheets(commandLineArguments) } catch (pe: ParameterException) { println("Unable to start because of invalid input:\n\t${pe.message}") JCommander(CommandLineArguments()).usage() } catch (e: Exception) { println("Unable to recover from an exception, terminating program; exception=$e") } } private fun enableVerboseOutput() { val loggerContext = LogManager.getContext(false) as LoggerContext val configuration = loggerContext.configuration configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).level = Level.DEBUG loggerContext.updateLoggers(configuration) } private fun disableLoggingToFile() { val loggerContext = LogManager.getContext(false) as LoggerContext val configuration = loggerContext.configuration configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME)!!.removeAppender("LogFile") } private fun createProcessor(cla: CommandLineArguments): SpriteSheetProcessor { val spriteDrawer = SpriteDrawer() val spriteSheetWriter = SpriteSheetWriter() val spriteSheetUnpacker = SpriteSheetUnpacker(SpriteCutter(spriteDrawer)) return if (cla.packSpriteSheets != "none") { val metadataCreator = when (cla.packSpriteSheets.toLowerCase()) { "json" -> JsonMetadataCreator() "yaml", "yml" -> YamlMetadataCreator() "txt" -> TextMetadataCreator() else -> throw IllegalArgumentException("Expected one of {json, yaml, txt} as metadata output, but got ${cla.packSpriteSheets}") } val spriteSheetPacker = SpriteSheetPacker(spriteDrawer, metadataCreator) SpriteSheetPackingProcessor(spriteSheetUnpacker, spriteSheetWriter, spriteSheetPacker) } else { SpriteSheetUnpackingProcessor(spriteSheetUnpacker, spriteSheetWriter) } }
apache-2.0
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/10.HelloKotlin-Extend2.kt
1
868
package com.zj.example.kotlin.shengshiyuan.helloworld /** * Created by zhengjiong * date: 2017/11/12 20:23 */ //方法重写 class HelloKotlin_Extend2 { open class Fruit { //需要加open才可以被重写 open fun name() { println("fruit") } fun expirationDate() { println("1 month") } } class Apple : Fruit() { override fun name() { println("apple") } } /** * 如果有一个类又继承Orange,但是不想让其能重写name方法, * 可以在name方法前加final, 这样就不能被重写 */ open class Orange : Fruit() { final override fun name() { println("orange") } } /*class OrangeChild : Orange() { override fun name() { println("orange") } }*/ }
mit
Kotlin/anko
anko/idea-plugin/preview/src/org/jetbrains/kotlin/android/dslpreview/LayoutPsiFile.kt
2
28183
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UNREACHABLE_CODE", "OverridingDeprecatedMember", "DEPRECATION") package org.jetbrains.kotlin.android.dslpreview import com.intellij.injected.editor.DocumentWindow import com.intellij.injected.editor.VirtualFileWindow import com.intellij.lang.ASTNode import com.intellij.lang.FileASTNode import com.intellij.lang.Language import com.intellij.navigation.ItemPresentation import com.intellij.openapi.Disposable import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.Iconable.IconFlags import com.intellij.openapi.util.Key import com.intellij.openapi.util.Segment import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.PsiDocumentManagerImpl import com.intellij.psi.impl.PsiManagerEx import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiElementProcessor import com.intellij.psi.search.SearchScope import com.intellij.psi.xml.XmlFile import com.intellij.testFramework.LightVirtualFile import com.intellij.util.IncorrectOperationException import org.jetbrains.android.facet.AndroidFacet import org.jetbrains.android.resourceManagers.ModuleResourceManagers import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.psi.KtFile import java.beans.PropertyChangeListener import javax.swing.Icon /* Reason for these stubs: Android Preview checks that the xml file is placed inside "layout-*" directory. TODO: Implement some kind of stable api in Android plugin for this */ class LayoutPsiFile(private val myPsiFile: XmlFile, val originalFile: KtFile, module: Module) : XmlFile { private val myPsiDirectory: PsiDirectory = LayoutPsiDirectory(module) private val myViewProvider: FileViewProvider = object : FileViewProvider by myPsiFile.viewProvider { override fun getPsi(p0: Language): PsiFile = this@LayoutPsiFile } private val myVirtualFile: VirtualFile by lazy { LayoutLightVirtualFile(myPsiFile.name, myPsiFile.text).also { virtualFile -> (myPsiFile.manager as? PsiManagerEx)?.fileManager?.setViewProvider(virtualFile, myViewProvider) } } override fun getParent() = myPsiDirectory override fun getDocument() = myPsiFile.document override fun getRootTag() = myPsiFile.rootTag override fun getVirtualFile(): VirtualFile? = myVirtualFile override fun getContainingDirectory() = myPsiDirectory override fun getModificationStamp() = myPsiFile.modificationStamp override fun getOriginalFile() = this override fun getFileType() = myPsiFile.fileType override fun getViewProvider() = myViewProvider override fun getNode(): FileASTNode? = myPsiFile.node override fun getPsiRoots(): Array<PsiFile> = myPsiFile.psiRoots override fun subtreeChanged() = myPsiFile.subtreeChanged() override fun isDirectory() = myPsiFile.isDirectory override fun getName() = myPsiFile.name override fun checkSetName(s: String) = myPsiFile.checkSetName(s) override fun setName(s: String): PsiElement = myPsiFile.setName(s) override fun getProject() = myPsiFile.project override fun getLanguage() = myPsiFile.language override fun getManager(): PsiManager? = myPsiFile.manager override fun getChildren(): Array<PsiElement> = myPsiFile.children override fun getFirstChild(): PsiElement? = myPsiFile.firstChild override fun getLastChild(): PsiElement? = myPsiFile.lastChild override fun getNextSibling(): PsiElement? = myPsiFile.nextSibling override fun getPrevSibling(): PsiElement? = myPsiFile.prevSibling override fun getContainingFile(): PsiFile? = myPsiFile.containingFile override fun getTextRange(): TextRange? = myPsiFile.textRange override fun getStartOffsetInParent() = myPsiFile.startOffsetInParent override fun getTextLength() = myPsiFile.textLength override fun findElementAt(i: Int) = myPsiFile.findElementAt(i) override fun findReferenceAt(i: Int) = myPsiFile.findReferenceAt(i) override fun getTextOffset() = myPsiFile.textOffset override fun getText(): String? = myPsiFile.text override fun textToCharArray() = myPsiFile.textToCharArray() override fun getNavigationElement(): PsiElement? = myPsiFile.navigationElement override fun getOriginalElement(): PsiElement? = myPsiFile.originalElement override fun textMatches(charSequence: CharSequence) = myPsiFile.textMatches(charSequence) override fun textMatches(psiElement: PsiElement) = myPsiFile.textMatches(psiElement) override fun textContains(c: Char) = myPsiFile.textContains(c) override fun accept(psiElementVisitor: PsiElementVisitor) = myPsiFile.accept(psiElementVisitor) override fun acceptChildren(psiElementVisitor: PsiElementVisitor) = myPsiFile.acceptChildren(psiElementVisitor) override fun copy(): PsiElement? = myPsiFile.copy() override fun add(psiElement: PsiElement): PsiElement? = myPsiFile.add(psiElement) override fun processChildren(psiFileSystemItemPsiElementProcessor: PsiElementProcessor<PsiFileSystemItem>?): Boolean { return myPsiFile.processChildren(psiFileSystemItemPsiElementProcessor) } override fun addBefore(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? = myPsiFile.addBefore(psiElement, psiElement2) override fun addAfter(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? = myPsiFile.addAfter(psiElement, psiElement2) override fun checkAdd(psiElement: PsiElement) = myPsiFile.checkAdd(psiElement) override fun addRange(psiElement: PsiElement, psiElement2: PsiElement): PsiElement? { return myPsiFile.addRange(psiElement, psiElement2) } override fun addRangeBefore(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? { return myPsiFile.addRangeBefore(psiElement, psiElement2, psiElement3) } override fun addRangeAfter(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? { return myPsiFile.addRangeAfter(psiElement, psiElement2, psiElement3) } override fun delete() = myPsiFile.delete() override fun checkDelete() = myPsiFile.checkDelete() override fun deleteChildRange(psiElement: PsiElement, psiElement2: PsiElement) = myPsiFile.deleteChildRange(psiElement, psiElement2) override fun replace(psiElement: PsiElement): PsiElement? = myPsiFile.replace(psiElement) override fun isValid() = myPsiFile.isValid override fun isWritable() = myPsiFile.isWritable override fun getReference() = myPsiFile.reference override fun getReferences(): Array<PsiReference> = myPsiFile.references override fun <T> getCopyableUserData(tKey: Key<T>) = myPsiFile.getCopyableUserData(tKey) override fun <T> putCopyableUserData(tKey: Key<T>, t: T?) = myPsiFile.putCopyableUserData(tKey, t) override fun processDeclarations( psiScopeProcessor: PsiScopeProcessor, resolveState: ResolveState, psiElement: PsiElement?, psiElement2: PsiElement ): Boolean { return myPsiFile.processDeclarations(psiScopeProcessor, resolveState, psiElement, psiElement2) } override fun getContext() = myPsiFile.context override fun isPhysical() = myPsiFile.isPhysical override fun getResolveScope() = myPsiFile.resolveScope override fun getUseScope() = myPsiFile.useScope override fun toString() = myPsiFile.toString() override fun isEquivalentTo(psiElement: PsiElement) = myPsiFile.isEquivalentTo(psiElement) override fun <T> getUserData(tKey: Key<T>) = myPsiFile.getUserData(tKey) override fun <T> putUserData(tKey: Key<T>, t: T?) = myPsiFile.putUserData(tKey, t) override fun getIcon(i: Int): Icon = myPsiFile.getIcon(i) override fun getPresentation() = myPsiFile.presentation override fun navigate(b: Boolean) = myPsiFile.navigate(b) override fun canNavigate() = myPsiFile.canNavigate() override fun canNavigateToSource() = myPsiFile.canNavigateToSource() override fun getFileResolveScope() = myPsiFile.fileResolveScope override fun ignoreReferencedElementAccessibility() = myPsiFile.ignoreReferencedElementAccessibility() override fun processElements(psiElementProcessor: PsiElementProcessor<PsiElement>, psiElement: PsiElement): Boolean { return myPsiFile.processElements(psiElementProcessor, psiElement) } private class LayoutPsiDirectory(val module: Module) : PsiDirectory { private val parentDir by lazy { val facet = AndroidFacet.getInstance(module) ?: return@lazy null val dir = ModuleResourceManagers.getInstance(facet).localResourceManager.resourceDirs .firstOrNull() ?: return@lazy null PsiManager.getInstance(module.project).findDirectory(dir) } override fun getName(): String { return "layout" } override fun getVirtualFile(): VirtualFile { return null!! } @Throws(IncorrectOperationException::class) override fun setName(s: String): PsiElement { return null!! } override fun getParentDirectory(): PsiDirectory? = parentDir override fun getParent() = parentDir override fun getSubdirectories(): Array<PsiDirectory?> { return arrayOfNulls(0) } override fun getFiles(): Array<PsiFile?> { return arrayOfNulls(0) } override fun findSubdirectory(s: String): PsiDirectory? { return null } override fun findFile(@NonNls s: String): PsiFile? { return null } @Throws(IncorrectOperationException::class) override fun createSubdirectory(s: String): PsiDirectory { return null!! } @Throws(IncorrectOperationException::class) override fun checkCreateSubdirectory(s: String) { } @Throws(IncorrectOperationException::class) override fun createFile(@NonNls s: String): PsiFile { return null!! } @Throws(IncorrectOperationException::class) override fun copyFileFrom(s: String, psiFile: PsiFile): PsiFile { return null!! } @Throws(IncorrectOperationException::class) override fun checkCreateFile(s: String) { } override fun isDirectory(): Boolean { return true } override fun processChildren(psiFileSystemItemPsiElementProcessor: PsiElementProcessor<PsiFileSystemItem>): Boolean { return false } override fun getPresentation(): ItemPresentation? { return null } override fun navigate(b: Boolean) { } override fun canNavigate(): Boolean { return false } override fun canNavigateToSource(): Boolean { return false } @Throws(IncorrectOperationException::class) override fun checkSetName(s: String) { } @Throws(PsiInvalidElementAccessException::class) override fun getProject(): Project { return null!! } override fun getLanguage(): Language { return null!! } override fun getManager(): PsiManager? { return null } override fun getChildren(): Array<PsiElement?> { return arrayOfNulls(0) } override fun getFirstChild(): PsiElement? { return null } override fun getLastChild(): PsiElement? { return null } override fun getNextSibling(): PsiElement? { return null } override fun getPrevSibling(): PsiElement? { return null } @Throws(PsiInvalidElementAccessException::class) override fun getContainingFile(): PsiFile? { return null } override fun getTextRange(): TextRange? { return null } override fun getStartOffsetInParent(): Int { return 0 } override fun getTextLength(): Int { return 0 } override fun findElementAt(i: Int): PsiElement? { return null } override fun findReferenceAt(i: Int): PsiReference? { return null } override fun getTextOffset(): Int { return 0 } override fun getText(): String? { return null } override fun textToCharArray(): CharArray { return CharArray(0) } override fun getNavigationElement(): PsiElement? { return null } override fun getOriginalElement(): PsiElement? { return null } override fun textMatches(@NonNls charSequence: CharSequence): Boolean { return false } override fun textMatches(psiElement: PsiElement): Boolean { return false } override fun textContains(c: Char): Boolean { return false } override fun accept(psiElementVisitor: PsiElementVisitor) { } override fun acceptChildren(psiElementVisitor: PsiElementVisitor) { } override fun copy(): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun add(psiElement: PsiElement): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun addBefore(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun addAfter(psiElement: PsiElement, psiElement2: PsiElement?): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun checkAdd(psiElement: PsiElement) { } @Throws(IncorrectOperationException::class) override fun addRange(psiElement: PsiElement, psiElement2: PsiElement): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun addRangeBefore(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun addRangeAfter(psiElement: PsiElement, psiElement2: PsiElement, psiElement3: PsiElement): PsiElement? { return null } @Throws(IncorrectOperationException::class) override fun delete() { } @Throws(IncorrectOperationException::class) override fun checkDelete() { } @Throws(IncorrectOperationException::class) override fun deleteChildRange(psiElement: PsiElement, psiElement2: PsiElement) { } @Throws(IncorrectOperationException::class) override fun replace(psiElement: PsiElement): PsiElement? { return null } override fun isValid(): Boolean { return false } override fun isWritable(): Boolean { return false } override fun getReference(): PsiReference? { return null } override fun getReferences(): Array<PsiReference?> { return arrayOfNulls(0) } override fun <T> getCopyableUserData(tKey: Key<T>): T? { return null } override fun <T> putCopyableUserData(tKey: Key<T>, t: T?) { } override fun processDeclarations( psiScopeProcessor: PsiScopeProcessor, resolveState: ResolveState, psiElement: PsiElement?, psiElement2: PsiElement ): Boolean { return false } override fun getContext(): PsiElement? { return null } override fun isPhysical(): Boolean { return false } override fun getResolveScope(): GlobalSearchScope { return null!! } override fun getUseScope(): SearchScope { return null!! } override fun getNode(): ASTNode? { return null } override fun isEquivalentTo(psiElement: PsiElement): Boolean { return false } override fun getIcon(@IconFlags i: Int): Icon? { return null } override fun <T> getUserData(tKey: Key<T>): T? { return null } override fun <T> putUserData(tKey: Key<T>, t: T?) { } } inner class LayoutLightVirtualFile(name: String, text: String) : LightVirtualFile(name, text), VirtualFileWindow { /* * This hack is needed to force PsiDocumentManager return our LayoutPsiFile for LayoutLightVirtualFile */ override fun getDocumentWindow(): DocumentWindow { val documentManager = PsiDocumentManager.getInstance(project) val documentWindowStub = object : UserDataHolderBase(), DocumentWindow { override fun hostToInjectedUnescaped(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isOneLine(): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun removeDocumentListener(p0: DocumentListener) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun deleteString(p0: Int, p1: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getTextLength(): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getHostRanges(): Array<Segment> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getText(): String { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getText(p0: TextRange): String { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getLineStartOffset(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun createRangeMarker(p0: Int, p1: Int): RangeMarker { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun createRangeMarker(p0: Int, p1: Int, p2: Boolean): RangeMarker { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun createRangeMarker(p0: TextRange): RangeMarker { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun insertString(p0: Int, p1: CharSequence) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setText(p0: CharSequence) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun startGuardedBlockChecking() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getHostRange(p0: Int): TextRange? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getChars(): CharArray { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getLineCount(): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun stopGuardedBlockChecking() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun areRangesEqual(p0: DocumentWindow): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isValid(): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun removeGuardedBlock(p0: RangeMarker) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getLineSeparatorLength(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun injectedToHostLine(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addPropertyChangeListener(p0: PropertyChangeListener) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun createGuardedBlock(p0: Int, p1: Int): RangeMarker { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun replaceString(p0: Int, p1: Int, p2: CharSequence) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getModificationStamp(): Long { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setReadOnly(p0: Boolean) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun intersectWithEditable(p0: TextRange): TextRange? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun fireReadOnlyModificationAttempt() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getLineNumber(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setCyclicBufferSize(p0: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun hostToInjected(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getImmutableCharSequence(): CharSequence { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getOffsetGuard(p0: Int): RangeMarker? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun isWritable(): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getLineEndOffset(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getCharsSequence(): CharSequence { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getDelegate(): Document { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun containsRange(p0: Int, p1: Int): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addDocumentListener(p0: DocumentListener) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun addDocumentListener(p0: DocumentListener, p1: Disposable) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun removePropertyChangeListener(p0: PropertyChangeListener) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getRangeGuard(p0: Int, p1: Int): RangeMarker? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun injectedToHost(p0: Int): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun injectedToHost(p0: TextRange): TextRange { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } } (documentManager as PsiDocumentManagerImpl).associatePsi(documentWindowStub, this@LayoutPsiFile) return documentWindowStub } override fun getDelegate(): VirtualFile = [email protected] override fun getParent() = object : LightVirtualFile("layout") { override fun isDirectory() = true } } }
apache-2.0
luxons/seven-wonders
sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/data/definitions/DecksDefinition.kt
1
1199
package org.luxons.sevenwonders.engine.data.definitions import org.luxons.sevenwonders.engine.cards.Card import org.luxons.sevenwonders.engine.cards.Decks import org.luxons.sevenwonders.model.cards.CardBack import kotlin.random.Random internal class DeckDefinition( val cards: List<CardDefinition>, val backImage: String, ) { fun create(nbPlayers: Int): List<Card> = cards.flatMap { it.create(CardBack(backImage), nbPlayers) } } internal class DecksDefinition( private val age1: DeckDefinition, private val age2: DeckDefinition, private val age3: DeckDefinition, private val guildCards: List<CardDefinition>, ) { fun prepareDecks(nbPlayers: Int, random: Random) = Decks( mapOf( 1 to age1.create(nbPlayers).shuffled(random), 2 to age2.create(nbPlayers).shuffled(random), 3 to (age3.create(nbPlayers) + pickGuildCards(nbPlayers, random)).shuffled(random), ), ) private fun pickGuildCards(nbPlayers: Int, random: Random): List<Card> { val back = CardBack(age3.backImage) val guild = guildCards.map { it.create(back) }.shuffled(random) return guild.subList(0, nbPlayers + 2) } }
mit
XiaoQiWen/KRefreshLayout
app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/ui/fragment/SampleEFragment.kt
1
1225
package gorden.krefreshlayout.demo.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import gorden.krefreshlayout.demo.R import gorden.krefreshlayout.demo.header.ClassicalHeader import gorden.refresh.KRefreshLayout import kotlinx.android.synthetic.main.layout_vp_scrollview.* /** * document * Created by Gordn on 2017/6/21. */ class SampleEFragment : ISampleFragment() { override val mRefreshLayout: KRefreshLayout get() = refreshLayout override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.layout_vp_scrollview, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) refreshLayout.setHeader(ClassicalHeader(context)) viewPager.setImages(arrayListOf<Int>(R.drawable.img_pager1, R.drawable.img_pager2, R.drawable.img_pager3)) refreshLayout.setKRefreshListener { refreshLayout.postDelayed({ refreshLayout?.refreshComplete(true) }, refreshTime) } } }
apache-2.0
android/user-interface-samples
CanonicalLayouts/feed-compose/app/src/main/java/com/example/feedcompose/data/Sweets.kt
1
1035
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.feedcompose.data import androidx.annotation.StringRes import com.example.feedcompose.R enum class Category(@StringRes val labelId: Int) { Pastry(R.string.pastry), Candy(R.string.candy), Chocolate(R.string.chocolate), Misc(R.string.misc), } class Sweets( val id: Int, val imageUrl: String, @StringRes val description: Int, val category: Category = Category.Misc )
apache-2.0
android/user-interface-samples
WindowInsetsAnimation/app/src/main/java/com/google/android/samples/insetsanimation/RootViewDeferringInsetsCallback.kt
1
6016
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.samples.insetsanimation import android.view.View import androidx.core.view.OnApplyWindowInsetsListener import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsAnimationCompat import androidx.core.view.WindowInsetsCompat /** * A class which extends/implements both [WindowInsetsAnimationCompat.Callback] and * [View.OnApplyWindowInsetsListener], which should be set on the root view in your layout. * * This class enables the root view is selectively defer handling any insets which match * [deferredInsetTypes], to enable better looking [WindowInsetsAnimationCompat]s. * * An example is the following: when a [WindowInsetsAnimationCompat] is started, the system will dispatch * a [WindowInsetsCompat] instance which contains the end state of the animation. For the scenario of * the IME being animated in, that means that the insets contains the IME height. If the view's * [View.OnApplyWindowInsetsListener] simply always applied the combination of * [WindowInsetsCompat.Type.ime] and [WindowInsetsCompat.Type.systemBars] using padding, the viewport of any * child views would then be smaller. This results in us animating a smaller (padded-in) view into * a larger viewport. Visually, this results in the views looking clipped. * * This class allows us to implement a different strategy for the above scenario, by selectively * deferring the [WindowInsetsCompat.Type.ime] insets until the [WindowInsetsAnimationCompat] is ended. * For the above example, you would create a [RootViewDeferringInsetsCallback] like so: * * ``` * val callback = RootViewDeferringInsetsCallback( * persistentInsetTypes = WindowInsetsCompat.Type.systemBars(), * deferredInsetTypes = WindowInsetsCompat.Type.ime() * ) * ``` * * This class is not limited to just IME animations, and can work with any [WindowInsetsCompat.Type]s. * * @param persistentInsetTypes the bitmask of any inset types which should always be handled * through padding the attached view * @param deferredInsetTypes the bitmask of insets types which should be deferred until after * any related [WindowInsetsAnimationCompat]s have ended */ class RootViewDeferringInsetsCallback( val persistentInsetTypes: Int, val deferredInsetTypes: Int ) : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE), OnApplyWindowInsetsListener { init { require(persistentInsetTypes and deferredInsetTypes == 0) { "persistentInsetTypes and deferredInsetTypes can not contain any of " + " same WindowInsetsCompat.Type values" } } private var view: View? = null private var lastWindowInsets: WindowInsetsCompat? = null private var deferredInsets = false override fun onApplyWindowInsets( v: View, windowInsets: WindowInsetsCompat ): WindowInsetsCompat { // Store the view and insets for us in onEnd() below view = v lastWindowInsets = windowInsets val types = when { // When the deferred flag is enabled, we only use the systemBars() insets deferredInsets -> persistentInsetTypes // Otherwise we handle the combination of the the systemBars() and ime() insets else -> persistentInsetTypes or deferredInsetTypes } // Finally we apply the resolved insets by setting them as padding val typeInsets = windowInsets.getInsets(types) v.setPadding(typeInsets.left, typeInsets.top, typeInsets.right, typeInsets.bottom) // We return the new WindowInsetsCompat.CONSUMED to stop the insets being dispatched any // further into the view hierarchy. This replaces the deprecated // WindowInsetsCompat.consumeSystemWindowInsets() and related functions. return WindowInsetsCompat.CONSUMED } override fun onPrepare(animation: WindowInsetsAnimationCompat) { if (animation.typeMask and deferredInsetTypes != 0) { // We defer the WindowInsetsCompat.Type.ime() insets if the IME is currently not visible. // This results in only the WindowInsetsCompat.Type.systemBars() being applied, allowing // the scrolling view to remain at it's larger size. deferredInsets = true } } override fun onProgress( insets: WindowInsetsCompat, runningAnims: List<WindowInsetsAnimationCompat> ): WindowInsetsCompat { // This is a no-op. We don't actually want to handle any WindowInsetsAnimations return insets } override fun onEnd(animation: WindowInsetsAnimationCompat) { if (deferredInsets && (animation.typeMask and deferredInsetTypes) != 0) { // If we deferred the IME insets and an IME animation has finished, we need to reset // the flag deferredInsets = false // And finally dispatch the deferred insets to the view now. // Ideally we would just call view.requestApplyInsets() and let the normal dispatch // cycle happen, but this happens too late resulting in a visual flicker. // Instead we manually dispatch the most recent WindowInsets to the view. if (lastWindowInsets != null && view != null) { ViewCompat.dispatchApplyWindowInsets(view!!, lastWindowInsets!!) } } } }
apache-2.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/profile/profiles/StaticProfileCreator.kt
1
1024
package net.perfectdreams.loritta.morenitta.profile.profiles import dev.kord.common.entity.Snowflake import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.dao.Profile import net.perfectdreams.loritta.morenitta.profile.ProfileGuildInfoData import net.perfectdreams.loritta.morenitta.profile.ProfileUserInfoData import java.awt.image.BufferedImage abstract class StaticProfileCreator(loritta: LorittaBot, internalName: String) : ProfileCreator(loritta, internalName) { abstract suspend fun create( sender: ProfileUserInfoData, user: ProfileUserInfoData, userProfile: Profile, guild: ProfileGuildInfoData?, badges: List<BufferedImage>, locale: BaseLocale, i18nContext: I18nContext, background: BufferedImage, aboutMe: String, allowedDiscordEmojis: List<Snowflake>? ): BufferedImage }
agpl-3.0
owntracks/android
project/app/src/main/java/org/owntracks/android/support/DeviceMetricsProvider.kt
1
3504
package org.owntracks.android.support import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.BatteryManager import dagger.hilt.android.qualifiers.ApplicationContext import org.owntracks.android.model.BatteryStatus import org.owntracks.android.model.messages.MessageLocation import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class DeviceMetricsProvider @Inject internal constructor(@ApplicationContext private val context: Context) { val batteryLevel: Int get() { val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) val batteryStatus = context.registerReceiver(null, intentFilter) return batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) ?: 0 } val batteryStatus: BatteryStatus get() { val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) val batteryStatus = context.registerReceiver(null, intentFilter) return when (batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, 0)) { BatteryManager.BATTERY_STATUS_FULL -> BatteryStatus.FULL BatteryManager.BATTERY_STATUS_CHARGING -> BatteryStatus.CHARGING BatteryManager.BATTERY_STATUS_DISCHARGING -> BatteryStatus.UNPLUGGED BatteryManager.BATTERY_STATUS_NOT_CHARGING -> BatteryStatus.UNKNOWN else -> BatteryStatus.UNKNOWN } } val connectionType: String? get() { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { cm.run { try { cm.getNetworkCapabilities(cm.activeNetwork)?.run { if (!hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) { return MessageLocation.CONN_TYPE_OFFLINE } if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { return MessageLocation.CONN_TYPE_MOBILE } if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { return MessageLocation.CONN_TYPE_WIFI } } // Android bug: https://issuetracker.google.com/issues/175055271 // ConnectivityManager::getNetworkCapabilities apparently throws a SecurityException } catch (e: SecurityException) { Timber.e(e, "Exception fetching networkcapabilities") } } return null } else @Suppress("DEPRECATION") { val activeNetworkInfo = cm.activeNetworkInfo ?: return null if (!activeNetworkInfo.isConnected) { return MessageLocation.CONN_TYPE_OFFLINE } return when (activeNetworkInfo.type) { ConnectivityManager.TYPE_WIFI -> MessageLocation.CONN_TYPE_WIFI ConnectivityManager.TYPE_MOBILE -> MessageLocation.CONN_TYPE_MOBILE else -> null } } } }
epl-1.0
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/BackgroundVariations.kt
1
839
package net.perfectdreams.loritta.cinnamon.pudding.tables import net.perfectdreams.exposedpowerutils.sql.jsonb import org.jetbrains.exposed.dao.id.LongIdTable object BackgroundVariations : LongIdTable() { val background = reference("background", Backgrounds) val profileDesignGroup = optReference("profile_design_group", ProfileDesignGroups) val file = text("file") val preferredMediaType = text("preferred_media_type") val crop = jsonb("crop").nullable() init { // Combined index, we can only have a crop for a specific background + design group, not multiple // This however does NOT WORK with upsert because profileDesignGroup can be null, and that breaks things // So manual checks must be made instead of relying on upsert! uniqueIndex(background, profileDesignGroup) } }
agpl-3.0
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/Arrays.kt
1
941
/* * 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.processor.commons inline fun <T, reified R> Array<out T>.mapToArray(transform: (T) -> R): Array<R> { return Array(size, { index -> transform(this[index]) }) } inline fun <T, reified R> List<T>.mapToArray(transform: (T) -> R): Array<R> { return Array(size, { index -> transform(this[index]) }) }
apache-2.0
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/activities/EventDetailsActivity.kt
1
6291
package be.digitalia.fosdem.activities import android.content.Intent import android.nfc.NdefRecord import android.os.Bundle import android.view.View import android.widget.ImageButton import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.fragment.app.add import androidx.fragment.app.commit import androidx.lifecycle.lifecycleScope import be.digitalia.fosdem.R import be.digitalia.fosdem.fragments.EventDetailsFragment import be.digitalia.fosdem.model.Event import be.digitalia.fosdem.utils.CreateNfcAppDataCallback import be.digitalia.fosdem.utils.assistedViewModels import be.digitalia.fosdem.utils.extractNfcAppData import be.digitalia.fosdem.utils.hasNfcAppData import be.digitalia.fosdem.utils.isLightTheme import be.digitalia.fosdem.utils.setNfcAppDataPushMessageCallbackIfAvailable import be.digitalia.fosdem.utils.setTaskColorPrimary import be.digitalia.fosdem.utils.statusBarColorCompat import be.digitalia.fosdem.utils.tintBackground import be.digitalia.fosdem.utils.toEventIdString import be.digitalia.fosdem.utils.toNfcAppData import be.digitalia.fosdem.viewmodels.BookmarkStatusViewModel import be.digitalia.fosdem.viewmodels.EventViewModel import be.digitalia.fosdem.widgets.setupBookmarkStatus import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject /** * Displays a single event passed either as a complete Parcelable object in extras or as an id in data. * * @author Christophe Beyls */ @AndroidEntryPoint class EventDetailsActivity : AppCompatActivity(R.layout.single_event), CreateNfcAppDataCallback { private val bookmarkStatusViewModel: BookmarkStatusViewModel by viewModels() @Inject lateinit var viewModelFactory: EventViewModel.Factory private val viewModel: EventViewModel by assistedViewModels { // Load the event from the DB using its id val intent = intent val eventIdString = if (intent.hasNfcAppData()) { // NFC intent intent.extractNfcAppData().toEventIdString() } else { // Normal in-app intent intent.dataString!! } viewModelFactory.create(eventIdString.toLong()) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(findViewById(R.id.bottom_appbar)) findViewById<ImageButton>(R.id.fab).setupBookmarkStatus(bookmarkStatusViewModel, this) val intentEvent: Event? = intent.getParcelableExtra(EXTRA_EVENT) if (intentEvent != null) { // The event has been passed as parameter, it can be displayed immediately initEvent(intentEvent) if (savedInstanceState == null) { supportFragmentManager.commit { add<EventDetailsFragment>(R.id.content, args = EventDetailsFragment.createArguments(intentEvent)) } } } else { lifecycleScope.launchWhenStarted { val event = viewModel.event.await() if (event == null) { // Event not found, quit Toast.makeText(this@EventDetailsActivity, getString(R.string.event_not_found_error), Toast.LENGTH_LONG).show() finish() } else { initEvent(event) val fm = supportFragmentManager if (fm.findFragmentById(R.id.content) == null) { fm.commit(allowStateLoss = true) { add<EventDetailsFragment>(R.id.content, args = EventDetailsFragment.createArguments(event)) } } } } } } /** * Initialize event-related configuration after the event has been loaded. */ private fun initEvent(event: Event) { // Enable up navigation only after getting the event details val toolbar = findViewById<Toolbar>(R.id.toolbar).apply { setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material) setNavigationContentDescription(androidx.appcompat.R.string.abc_action_bar_up_description) setNavigationOnClickListener { onSupportNavigateUp() } title = event.track.name } val trackType = event.track.type if (isLightTheme) { window.statusBarColorCompat = ContextCompat.getColor(this, trackType.statusBarColorResId) val trackAppBarColor = ContextCompat.getColorStateList(this, trackType.appBarColorResId)!! setTaskColorPrimary(trackAppBarColor.defaultColor) findViewById<View>(R.id.appbar).tintBackground(trackAppBarColor) } else { val trackTextColor = ContextCompat.getColorStateList(this, trackType.textColorResId)!! toolbar.setTitleTextColor(trackTextColor) } bookmarkStatusViewModel.event = event // Enable Android Beam setNfcAppDataPushMessageCallbackIfAvailable(this) } override fun getSupportParentActivityIntent(): Intent? { val event = bookmarkStatusViewModel.event ?: return null // Navigate up to the track associated with this event return Intent(this, TrackScheduleActivity::class.java) .putExtra(TrackScheduleActivity.EXTRA_DAY, event.day) .putExtra(TrackScheduleActivity.EXTRA_TRACK, event.track) .putExtra(TrackScheduleActivity.EXTRA_FROM_EVENT_ID, event.id) } override fun supportNavigateUpTo(upIntent: Intent) { // Replicate the compatibility implementation of NavUtils.navigateUpTo() // to ensure the parent Activity is always launched // even if not present on the back stack. upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(upIntent) finish() } // CreateNfcAppDataCallback override fun createNfcAppData(): NdefRecord? { return bookmarkStatusViewModel.event?.toNfcAppData(this) } companion object { const val EXTRA_EVENT = "event" } }
apache-2.0
esafirm/android-image-picker
imagepicker/src/main/java/com/esafirm/imagepicker/view/SnackBarView.kt
1
1488
package com.esafirm.imagepicker.view import android.content.Context import android.util.AttributeSet import android.view.animation.Interpolator import android.widget.RelativeLayout import android.widget.TextView import androidx.annotation.StringRes import androidx.interpolator.view.animation.FastOutLinearInInterpolator import com.esafirm.imagepicker.R class SnackBarView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : RelativeLayout(context, attrs, defStyle) { private val txtCaption get() = findViewById<TextView>(R.id.ef_snackbar_txt_bottom_caption) private val btnAction get() = findViewById<TextView>(R.id.ef_snackbar_btn_action) init { inflate(context, R.layout.ef_imagepicker_snackbar, this) if (!isInEditMode) { val height = context.resources.getDimensionPixelSize(R.dimen.ef_height_snackbar) translationY = height.toFloat() alpha = 0f } } fun show(@StringRes textResId: Int, onClickListener: OnClickListener) { txtCaption.text = context.getString(textResId) btnAction.setOnClickListener(onClickListener) animate().translationY(0f) .setDuration(ANIM_DURATION.toLong()) .setInterpolator(INTERPOLATOR) .alpha(1f) } companion object { private const val ANIM_DURATION = 200 private val INTERPOLATOR: Interpolator = FastOutLinearInInterpolator() } }
mit
r-artworks/game-seed
core/src/com/rartworks/engine/apis/GooglePlayPreferences.kt
1
131
package com.rartworks.engine.apis interface GooglePlayPreferences { fun hasAlreadyPlayed(): Boolean fun isSignedIn(): Boolean }
mit
nebula-plugins/java-source-refactor
rewrite-java/src/test/kotlin/org/openrewrite/java/search/FindReferencesToVariableTest.kt
1
1456
/* * Copyright 2020 the original 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.openrewrite.java.search import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.openrewrite.java.JavaParser import org.openrewrite.java.tree.J class FindReferencesToVariableTest : JavaParser() { @Test fun findReferences() { val a = parse(""" public class A { int n; public void foo() { int n; n = 1; (n) = 2; n++; if((n = 4) > 1) {} this.n = 1; } } """.trimIndent()) val n = (a.classes[0]!!.methods[0]!!.body!!.statements[0] as J.VariableDecls).vars[0] val refs = FindReferencesToVariable(n.name).visit(a.classes[0]) assertEquals(4, refs.size) } }
apache-2.0
kmizu/kollection
src/main/kotlin/com/github/kmizu/kollection/KQueue.kt
1
212
package com.github.kmizu.kollection interface KQueue<T> { val isEmpty: Boolean infix fun enqueue(newElement: T): KQueue<T> fun dequeue(): KQueue<T> fun peek(): T fun toList(): KList<T> }
mit
SteffenKonrad/Term_Project_Simulation
src/main/kotlin/traffic_simulation/Network.kt
1
1076
package traffic_simulation class Network(var capacity: Int) { // function to tally the cars on the road fun neededCapacity(cars: List<Car>): Int { var requiredcapacity: Int = 0 for (car in cars) { if (car.driving) requiredcapacity = requiredcapacity + 1 } return requiredcapacity } // function compares the capacity and the demand fun enoughCapacity(requirement: Int): Boolean { if (capacity <= requirement) { return true } return false } // function asks whether the capacity is exhausted and whether or not a delay occurs fun testScenario(carList: List<Car>): List<Car> { val requirement: Int = neededCapacity(carList) val compare: Boolean = enoughCapacity(requirement) if (compare) { for (car in carList) { if (car.driving) { val delayed = true car.gettingDelayed = delayed } } } return carList } }
apache-2.0
kotlintest/kotlintest
kotest-core/src/commonMain/kotlin/io/kotest/core/extensions/RuntimeTagExtension.kt
1
578
package io.kotest.core.extensions import io.kotest.core.Tag import io.kotest.core.Tags /** * Allows including/excluding tags at runtime * * You can use the properties [included] and [excluded] to modify what behavior you should use for specific tests * at runtime. Any test tagged with tags in [included] will be included to run, and any tags in [excluded] will be excluded. */ object RuntimeTagExtension : TagExtension { val included = mutableSetOf<Tag>() val excluded = mutableSetOf<Tag>() override fun tags(): Tags { return Tags(included, excluded) } }
apache-2.0
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/GithubRepositorieslinks.kt
1
914
package org.openapitools.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import org.openapitools.model.Link import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import javax.validation.Valid import io.swagger.v3.oas.annotations.media.Schema /** * * @param self * @param propertyClass */ data class GithubRepositorieslinks( @field:Valid @Schema(example = "null", description = "") @field:JsonProperty("self") val self: Link? = null, @Schema(example = "null", description = "") @field:JsonProperty("_class") val propertyClass: kotlin.String? = null ) { }
mit
yongce/DevTools
app/src/main/java/me/ycdev/android/devtools/CommonIntentService.kt
1
637
package me.ycdev.android.devtools import android.app.IntentService import android.content.Intent import me.ycdev.android.devtools.security.unmarshall.UnmarshallScannerActivity class CommonIntentService : IntentService("CommonIntentService") { override fun onHandleIntent(intent: Intent?) { val action = intent?.action if (ACTION_UNMARSHALL_SCANNER == action) { UnmarshallScannerActivity.scanUnmarshallIssue(this) } } companion object { private const val ACTION_PREFIX = "class.action." const val ACTION_UNMARSHALL_SCANNER = ACTION_PREFIX + "UNMARSHALL_SCANNER" } }
apache-2.0
cypressious/learning-spaces
app/src/main/java/de/maxvogler/learningspaces/models/Weekday.kt
1
1635
package de.maxvogler.learningspaces.models import de.maxvogler.learningspaces.helpers.toWeekday import org.joda.time.LocalDate import org.joda.time.LocalDateTime public enum class Weekday(val weekday: Int) { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7); public fun toInt(): Int = weekday public fun equals(i: Int): Boolean = weekday == i public val next: Weekday // values() indices start by zero, so [this.weekday] returns the successor! get() = values().get(this.weekday % 7) public fun rangeTo(other: Weekday): Progression<Weekday> { val start = this return object : Progression<Weekday> { override val start: Weekday = start override val end: Weekday = other override val increment: Number = 1 override fun iterator(): Iterator<Weekday> { val iterator = if (end >= start) { IntProgressionIterator(start.toInt(), end.toInt(), 1) } else { IntProgressionIterator(start.toInt(), end.toInt() + 7, 1) } return object : Iterator<Weekday> { override fun next(): Weekday = (((iterator.next() - 1 ) % 7) + 1).toWeekday() override fun hasNext(): Boolean = iterator.hasNext() } } } } companion object { public fun today(): Weekday = LocalDate.now().toWeekday() } }
gpl-2.0
Shynixn/PetBlocks
petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/business/enumeration/MaterialType.kt
1
18792
@file:Suppress("KDocMissingDocumentation") package com.github.shynixn.petblocks.api.business.enumeration /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ enum class MaterialType( /** * Numeric internal minecraft id. */ val numericId: Int, /** * Internal minecraft name. */ val minecraftName: String ) { AIR(0, "air"), STONE(1, "stone"), GRASS(2, "grass"), DIRT(3, "dirt"), COBBLESTONE(4, "cobblestone"), WOOD(5, "planks"), SAPLING(6, "sapling"), BEDROCK(7, "bedrock"), WATER(8, "flowing_water"), STATIONARY_WATER(9, "water"), LAVA(10, "flowing_lava"), STATIONARY_LAVA(11, "lava"), SAND(12, "sand"), GRAVEL(13, "gravel"), GOLD_ORE(14, "gold_ore"), IRON_ORE(15, "iron_ore"), COAL_ORE(16, "coal_ore"), LOG(17, "log"), LEAVES(18, "leaves"), SPONGE(19, "sponge"), GLASS(20, "glass"), LAPIS_ORE(21, "lapis_ore"), LAPIS_BLOCK(22, "lapis_block"), DISPENSER(23, "dispenser"), SANDSTONE(24, "sandstone"), NOTE_BLOCK(25, "noteblock"), BED_BLOCK(26, "bed"), POWERED_RAIL(27, "golden_rail"), DETECTOR_RAIL(28, "detector_rail"), PISTON_STICKY_BASE(29, "sticky_piston"), WEB(30, "web"), LONG_GRASS(31, "tallgrass"), DEAD_BUSH(32, "deadbush"), PISTON_BASE(33, "piston"), PISTON_EXTENSION(34, "piston_head"), WOOL(35, "wool"), YELLOW_FLOWER(37, "yellow_flower"), RED_ROSE(38, "red_flower"), BROWN_MUSHROOM(39, "brown_mushroom"), RED_MUSHROOM(40, "red_mushroom"), GOLD_BLOCK(41, "gold_block"), IRON_BLOCK(42, "iron_block"), DOUBLE_STEP(43, "double_stone_slab"), STEP(44, "stone_slab"), BRICK(45, "brick_block"), TNT(46, "tnt"), BOOKSHELF(47, "bookshelf"), MOSSY_COBBLESTONE(48, "mossy_cobblestone"), OBSIDIAN(49, "obsidian"), TORCH(50, "torch"), FIRE(51, "fire"), MOB_SPAWNER(52, "mob_spawner"), WOOD_STAIRS(53, "oak_stairs"), CHEST(54, "chest"), REDSTONE_WIRE(55, "redstone_wire"), DIAMOND_ORE(56, "diamond_ore"), DIAMOND_BLOCK(57, "diamond_block"), WORKBENCH(58, "crafting_table"), CROPS(59, "wheat"), SOIL(60, "farmland"), FURNACE(61, "furnace"), BURNING_FURNACE(62, "lit_furnace"), SIGN_POST(63, "standing_sign"), WOODEN_DOOR(64, "wooden_door"), LADDER(65, "ladder"), RAILS(66, "rail"), COBBLESTONE_STAIRS(67, "stone_stairs"), WALL_SIGN(68, "wall_sign"), LEVER(69, "lever"), STONE_PLATE(70, "stone_pressure_plate"), IRON_DOOR_BLOCK(71, "iron_door"), WOOD_PLATE(72, "wooden_pressure_plate"), REDSTONE_ORE(73, "redstone_ore"), GLOWING_REDSTONE_ORE(74, "lit_redstone_ore"), REDSTONE_TORCH_OFF(75, "unlit_redstone_torch"), REDSTONE_TORCH_ON(76, "redstone_torch"), STONE_BUTTON(77, "stone_button"), SNOW(78, "snow_layer"), ICE(79, "ice"), SNOW_BLOCK(80, "snow"), CACTUS(81, "cactus"), CLAY(82, "clay"), SUGAR_CANE_BLOCK(83, "reeds"), JUKEBOX(84, "jukebox"), FENCE(85, "fence"), PUMPKIN(86, "pumpkin"), NETHERRACK(87, "netherrack"), SOUL_SAND(88, "soul_sand"), GLOWSTONE(89, "glowstone"), PORTAL(90, "portal"), JACK_O_LANTERN(91, "lit_pumpkin"), CAKE_BLOCK(92, "cake"), DIODE_BLOCK_OFF(93, "unpowered_repeater"), DIODE_BLOCK_ON(94, "powered_repeater"), STAINED_GLASS(95, "stained_glass"), TRAP_DOOR(96, "trapdoor"), MONSTER_EGGS(97, "monster_egg"), SMOOTH_BRICK(98, "stonebrick"), HUGE_MUSHROOM_1(99, "brown_mushroom_block"), HUGE_MUSHROOM_2(100, "red_mushroom_block"), IRON_FENCE(101, "iron_bars"), THIN_GLASS(102, "glass_pane"), MELON_BLOCK(103, "melon_block"), PUMPKIN_STEM(104, "pumpkin_stem"), MELON_STEM(105, "melon_stem"), VINE(106, "vine"), FENCE_GATE(107, "fence_gate"), BRICK_STAIRS(108, "brick_stairs"), SMOOTH_STAIRS(109, "stone_brick_stairs"), MYCEL(110, "mycelium"), WATER_LILY(111, "waterlily"), NETHER_BRICK(112, "nether_brick"), NETHER_FENCE(113, "nether_brick_fence"), NETHER_BRICK_STAIRS(114, "nether_brick_stairs"), NETHER_WARTS(115, "nether_wart"), ENCHANTMENT_TABLE(116, "enchanting_table"), BREWING_STAND(117, "brewing_stand"), CAULDRON(118, "cauldron"), ENDER_PORTAL(119, "end_portal"), ENDER_PORTAL_FRAME(120, "end_portal_frame"), ENDER_STONE(121, "end_stone"), DRAGON_EGG(122, "dragon_egg"), REDSTONE_LAMP_OFF(123, "redstone_lamp"), REDSTONE_LAMP_ON(124, "lit_redstone_lamp"), WOOD_DOUBLE_STEP(125, "double_wooden_slab"), WOOD_STEP(126, "wooden_slab"), COCOA(127, "cocoa"), SANDSTONE_STAIRS(128, "sandstone_stairs"), EMERALD_ORE(129, "emerald_ore"), ENDER_CHEST(130, "ender_chest"), TRIPWIRE_HOOK(131, "tripwire_hook"), TRIPWIRE(132, "tripwire_hook"), EMERALD_BLOCK(133, "emerald_block"), SPRUCE_WOOD_STAIRS(134, "spruce_stairs"), BIRCH_WOOD_STAIRS(135, "birch_stairs"), JUNGLE_WOOD_STAIRS(136, "jungle_stairs"), COMMAND(137, "command_block"), BEACON(138, "beacon"), COBBLE_WALL(139, "cobblestone_wall"), FLOWER_POT(140, "flower_pot"), CARROT(141, "carrots"), POTATO(142, "potatoes"), WOOD_BUTTON(143, "wooden_button"), SKULL(144, "skull"), ANVIL(145, "anvil"), TRAPPED_CHEST(146, "trapped_chest"), GOLD_PLATE(147, "light_weighted_pressure_plate"), IRON_PLATE(148, "heavy_weighted_pressure_plate"), REDSTONE_COMPARATOR_OFF(149, "unpowered_comparator"), REDSTONE_COMPARATOR_ON(150, "powered_comparator"), DAYLIGHT_DETECTOR(151, "daylight_detector"), REDSTONE_BLOCK(152, "redstone_block"), QUARTZ_ORE(153, "quartz_ore"), HOPPER(154, "hopper"), QUARTZ_BLOCK(155, "quartz_block"), QUARTZ_STAIRS(156, "quartz_stairs"), ACTIVATOR_RAIL(157, "activator_rail"), DROPPER(158, "dropper"), STAINED_CLAY(159, "stained_hardened_clay"), STAINED_GLASS_PANE(160, "stained_glass_pane"), LEAVES_2(161, "leaves2"), LOG_2(162, "log2"), ACACIA_STAIRS(163, "acacia_stairs"), DARK_OAK_STAIRS(164, "dark_oak_stairs"), SLIME_BLOCK(165, "slime"), BARRIER(166, "barrier"), IRON_TRAPDOOR(167, "iron_trapdoor"), PRISMARINE(168, "prismarine"), SEA_LANTERN(169, "sea_lantern"), HAY_BLOCK(170, "hay_block"), CARPET(171, "carpet"), HARD_CLAY(172, "hardened_clay"), COAL_BLOCK(173, "coal_block"), PACKED_ICE(174, "packed_ice"), DOUBLE_PLANT(175, "double_plant"), STANDING_BANNER(176, "standing_banner"), WALL_BANNER(177, "wall_banner"), DAYLIGHT_DETECTOR_INVERTED(178, "daylight_detector_inverted"), RED_SANDSTONE(179, "red_sandstone"), RED_SANDSTONE_STAIRS(180, "red_sandstone_stairs"), DOUBLE_STONE_SLAB2(181, "double_stone_slab2"), STONE_SLAB2(182, "stone_slab2"), SPRUCE_FENCE_GATE(183, "spruce_fence_gate"), BIRCH_FENCE_GATE(184, "birch_fence_gate"), JUNGLE_FENCE_GATE(185, "jungle_fence_gate"), DARK_OAK_FENCE_GATE(186, "dark_oak_fence_gate"), ACACIA_FENCE_GATE(187, "acacia_fence_gate"), SPRUCE_FENCE(188, "spruce_fence"), BIRCH_FENCE(189, "birch_fence"), JUNGLE_FENCE(190, "jungle_fence"), DARK_OAK_FENCE(191, "dark_oak_fence"), ACACIA_FENCE(192, "acacia_fence"), SPRUCE_DOOR(193, "spruce_door"), BIRCH_DOOR(194, "birch_door"), JUNGLE_DOOR(195, "jungle_door"), ACACIA_DOOR(196, "acacia_door"), DARK_OAK_DOOR(197, "dark_oak_door"), END_ROD(198, "end_rod"), CHORUS_PLANT(199, "chorus_plant"), CHORUS_FLOWER(200, "chorus_flower"), PURPUR_BLOCK(201, "purpur_block"), PURPUR_PILLAR(202, "purpur_pillar"), PURPUR_STAIRS(203, "purpur_stairs"), PURPUR_DOUBLE_SLAB(204, "purpur_double_slab"), PURPUR_SLAB(205, "purpur_slab"), END_BRICKS(206, "end_bricks"), BEETROOT_BLOCK(207, "beetroots"), GRASS_PATH(208, "grass_path"), END_GATEWAY(209, "end_gateway"), COMMAND_REPEATING(210, "repeating_command_block"), COMMAND_CHAIN(211, "chain_command_block"), FROSTED_ICE(212, "frosted_ice"), MAGMA(213, "magma"), NETHER_WART_BLOCK(214, "nether_wart_block"), RED_NETHER_BRICK(215, "red_nether_brick"), BONE_BLOCK(216, "bone_block"), STRUCTURE_VOID(217, "structure_void"), OBSERVER(218, "observer"), WHITE_SHULKER_BOX(219, "white_shulker_box"), ORANGE_SHULKER_BOX(220, "orange_shulker_box"), MAGENTA_SHULKER_BOX(221, "magenta_shulker_box"), LIGHT_BLUE_SHULKER_BOX(222, "light_blue_shulker_box"), YELLOW_SHULKER_BOX(223, "yellow_shulker_box"), LIME_SHULKER_BOX(224, "lime_shulker_box"), PINK_SHULKER_BOX(225, "pink_shulker_box"), GRAY_SHULKER_BOX(226, "gray_shulker_box"), SILVER_SHULKER_BOX(227, "silver_shulker_box"), CYAN_SHULKER_BOX(228, "cyan_shulker_box"), PURPLE_SHULKER_BOX(229, "purple_shulker_box"), BLUE_SHULKER_BOX(230, "blue_shulker_box"), BROWN_SHULKER_BOX(231, "brown_shulker_box"), GREEN_SHULKER_BOX(232, "green_shulker_box"), RED_SHULKER_BOX(233, "red_shulker_box"), BLACK_SHULKER_BOX(234, "black_shulker_box"), WHITE_GLAZED_TERRACOTTA(235, "white_glazed_terracotta"), ORANGE_GLAZED_TERRACOTTA(236, "orange_glazed_terracotta"), MAGENTA_GLAZED_TERRACOTTA(237, "magenta_glazed_terracotta"), LIGHT_BLUE_GLAZED_TERRACOTTA(238, "light_blue_glazed_terracotta"), YELLOW_GLAZED_TERRACOTTA(239, "yellow_glazed_terracotta"), LIME_GLAZED_TERRACOTTA(240, "lime_glazed_terracotta"), PINK_GLAZED_TERRACOTTA(241, "pink_glazed_terracotta"), GRAY_GLAZED_TERRACOTTA(242, "gray_glazed_terracotta"), SILVER_GLAZED_TERRACOTTA(243, "light_gray_glazed_terracotta"), CYAN_GLAZED_TERRACOTTA(244, "cyan_glazed_terracotta"), PURPLE_GLAZED_TERRACOTTA(245, "purple_glazed_terracotta"), BLUE_GLAZED_TERRACOTTA(246, "blue_glazed_terracotta"), BROWN_GLAZED_TERRACOTTA(247, "brown_glazed_terracotta"), GREEN_GLAZED_TERRACOTTA(248, "green_glazed_terracotta"), RED_GLAZED_TERRACOTTA(249, "red_glazed_terracotta"), BLACK_GLAZED_TERRACOTTA(250, "black_glazed_terracotta"), CONCRETE(251, "concrete"), CONCRETE_POWDER(252, "concrete_powder"), STRUCTURE_BLOCK(255, "structure_block"), IRON_SPADE(256, "iron_shovel"), IRON_PICKAXE(257, "iron_pickaxe"), IRON_AXE(258, "iron_axe"), FLINT_AND_STEEL(259, "flint_and_steel"), APPLE(260, "apple"), BOW(261, "bow"), ARROW(262, "arrow"), COAL(263, "coal"), DIAMOND(264, "diamond"), IRON_INGOT(265, "iron_ingot"), GOLD_INGOT(266, "gold_ingot"), IRON_SWORD(267, "iron_sword"), WOOD_SWORD(268, "wooden_sword"), WOOD_SPADE(269, "wooden_shovel"), WOOD_PICKAXE(270, "wooden_pickaxe"), WOOD_AXE(271, "wooden_axe"), STONE_SWORD(272, "stone_sword"), STONE_SPADE(273, "stone_shovel"), STONE_PICKAXE(274, "stone_pickaxe"), STONE_AXE(275, "stone_axe"), DIAMOND_SWORD(276, "diamond_sword"), DIAMOND_SPADE(277, "diamond_shovel"), DIAMOND_PICKAXE(278, "diamond_pickaxe"), DIAMOND_AXE(279, "diamond_axe"), STICK(280, "stick"), BOWL(281, "bowl"), MUSHROOM_SOUP(282, "mushroom_stew"), GOLD_SWORD(283, "golden_sword"), GOLD_SPADE(284, "golden_shovel"), GOLD_PICKAXE(285, "golden_pickaxe"), GOLD_AXE(286, "golden_axe"), STRING(287, "string"), FEATHER(288, "feather"), SULPHUR(289, "gunpowder"), WOOD_HOE(290, "wooden_hoe"), STONE_HOE(291, "stone_hoe"), IRON_HOE(292, "iron_hoe"), DIAMOND_HOE(293, "diamond_hoe"), GOLD_HOE(294, "golden_hoe"), SEEDS(295, "wheat_seeds"), WHEAT(296, "wheat"), BREAD(297, "bread"), LEATHER_HELMET(298, "leather_helmet"), LEATHER_CHESTPLATE(299, "leather_chestplate"), LEATHER_LEGGINGS(300, "leather_leggings"), LEATHER_BOOTS(301, "leather_boots"), CHAINMAIL_HELMET(302, "chainmail_helmet"), CHAINMAIL_CHESTPLATE(303, "chainmail_chestplate"), CHAINMAIL_LEGGINGS(304, "chainmail_leggings"), CHAINMAIL_BOOTS(305, "chainmail_boots"), IRON_HELMET(306, "iron_helmet"), IRON_CHESTPLATE(307, "iron_chestplate"), IRON_LEGGINGS(308, "iron_leggings"), IRON_BOOTS(309, "iron_boots"), DIAMOND_HELMET(310, "diamond_helmet"), DIAMOND_CHESTPLATE(311, "diamond_chestplate"), DIAMOND_LEGGINGS(312, "diamond_leggings"), DIAMOND_BOOTS(313, "diamond_boots"), GOLD_HELMET(314, "golden_helmet"), GOLD_CHESTPLATE(315, "golden_chestplate"), GOLD_LEGGINGS(316, "golden_leggings"), GOLD_BOOTS(317, "golden_boots"), FLINT(318, "flint"), PORK(319, "porkchop"), GRILLED_PORK(320, "cooked_porkchop"), PAINTING(321, "painting"), GOLDEN_APPLE(322, "golden_apple"), SIGN(323, "sign"), WOOD_DOOR(324, "wooden_door"), BUCKET(325, "bucket"), WATER_BUCKET(326, "water_bucket"), LAVA_BUCKET(327, "lava_bucket"), MINECART(328, "minecart"), SADDLE(329, "saddle"), IRON_DOOR(330, "iron_door"), REDSTONE(331, "redstone"), SNOW_BALL(332, "snowball"), BOAT(333, "boat"), LEATHER(334, "leather"), MILK_BUCKET(335, "milk_bucket"), CLAY_BRICK(336, "brick"), CLAY_BALL(337, "clay_ball"), SUGAR_CANE(338, "reeds"), PAPER(339, "paper"), BOOK(340, "book"), SLIME_BALL(341, "slime_ball"), STORAGE_MINECART(342, "chest_minecart"), POWERED_MINECART(343, "furnace_minecart"), EGG(344, "egg"), COMPASS(345, "compass"), FISHING_ROD(346, "fishing_rod"), WATCH(347, "clock"), GLOWSTONE_DUST(348, "glowstone_dust"), RAW_FISH(349, "fish"), COOKED_FISH(350, "cooked_fish"), INK_SACK(351, "dye"), BONE(352, "bone"), SUGAR(353, "sugar"), CAKE(354, "cake"), BED(355, "bed"), DIODE(356, "repeater"), COOKIE(357, "cookie"), MAP(358, "filled_map"), SHEARS(359, "shears"), MELON(360, "melon"), PUMPKIN_SEEDS(361, "pumpkin_seeds"), MELON_SEEDS(362, "melon_seeds"), RAW_BEEF(363, "beef"), COOKED_BEEF(364, "cooked_beef"), RAW_CHICKEN(365, "chicken"), COOKED_CHICKEN(366, "cooked_chicken"), ROTTEN_FLESH(367, "rotten_flesh"), ENDER_PEARL(368, "ender_pearl"), BLAZE_ROD(369, "blaze_rod"), GHAST_TEAR(370, "ghast_tear"), GOLD_NUGGET(371, "gold_nugget"), NETHER_STALK(372, "nether_wart"), POTION(373, "potion"), GLASS_BOTTLE(374, "glass_bottle"), SPIDER_EYE(375, "spider_eye"), FERMENTED_SPIDER_EYE(376, "fermented_spider_eye"), BLAZE_POWDER(377, "blaze_powder"), MAGMA_CREAM(378, "magma_cream"), BREWING_STAND_ITEM(379, "brewing_stand"), CAULDRON_ITEM(380, "cauldron"), EYE_OF_ENDER(381, "ender_eye"), SPECKLED_MELON(382, "speckled_melon"), EXP_BOTTLE(384, "experience_bottle"), FIREBALL(385, "fire_charge"), BOOK_AND_QUILL(386, "writable_book"), WRITTEN_BOOK(387, "written_book"), EMERALD(388, "emerald"), ITEM_FRAME(389, "item_frame"), FLOWER_POT_ITEM(390, "flower_pot"), CARROT_ITEM(391, "carrot"), POTATO_ITEM(392, "potato"), BAKED_POTATO(393, "baked_potato"), POISONOUS_POTATO(394, "poisonous_potato"), EMPTY_MAP(395, "map"), GOLDEN_CARROT(396, "golden_carrot"), SKULL_ITEM(397, "skull"), CARROT_STICK(398, "carrot_on_a_stick"), NETHER_STAR(399, "nether_star"), PUMPKIN_PIE(400, "pumpkin_pie"), FIREWORK(401, "fireworks"), FIREWORK_CHARGE(402, "firework_charge"), ENCHANTED_BOOK(403, "enchanted_book"), REDSTONE_COMPARATOR(404, "comparator"), NETHER_BRICK_ITEM(405, "netherbrick"), QUARTZ(406, "quartz"), EXPLOSIVE_MINECART(407, "tnt_minecart"), HOPPER_MINECART(408, "hopper_minecart"), PRISMARINE_SHARD(409, "prismarine_shard"), PRISMARINE_CRYSTALS(410, "prismarine_crystals"), RABBIT(411, "rabbit"), COOKED_RABBIT(412, "cooked_rabbit"), RABBIT_STEW(413, "rabbit_stew"), RABBIT_FOOT(414, "rabbit_foot"), RABBIT_HIDE(415, "rabbit_hide"), ARMOR_STAND(416, "armor_stand"), IRON_BARDING(417, "iron_horse_armor"), GOLD_BARDING(418, "golden_horse_armor"), DIAMOND_BARDING(419, "diamond_horse_armor"), LEASH(420, "lead"), NAME_TAG(421, "name_tag"), COMMAND_MINECART(422, "command_block_minecart"), MUTTON(423, "mutton"), COOKED_MUTTON(424, "cooked_mutton"), BANNER(425, "banner"), SPRUCE_DOOR_ITEM(427, "spruce_door"), BIRCH_DOOR_ITEM(428, "birch_door"), JUNGLE_DOOR_ITEM(429, "jungle_door"), ACACIA_DOOR_ITEM(430, "acacia_door"), DARK_OAK_DOOR_ITEM(431, "dark_oak_door"), CHORUS_FRUIT(432, "chorus_fruit"), CHORUS_FRUIT_POPPED(433, "popped_chorus_fruit"), BEETROOT(434, "beetroot"), BEETROOT_SEEDS(435, "beetroot_seeds"), BEETROOT_SOUP(436, "beetroot_soup"), DRAGONS_BREATH(437, "dragon_breath"), SPLASH_POTION(438, "splash_potion"), SPECTRAL_ARROW(439, "spectral_arrow"), TIPPED_ARROW(440, "tipped_arrow"), LINGERING_POTION(441, "lingering_potion"), SHIELD(442, "shield"), ELYTRA(443, "elytra"), BOAT_SPRUCE(444, "spruce_boat"), BOAT_BIRCH(445, "birch_boat"), BOAT_JUNGLE(446, "jungle_boat"), BOAT_ACACIA(447, "acacia_boat"), BOAT_DARK_OAK(448, "dark_oak_boat"), TOTEM(449, "totem_of_undying"), SHULKER_SHELL(450, "shulker_shell"), IRON_NUGGET(452, "iron_nugget"), GOLD_RECORD(2256, "record_13"), GREEN_RECORD(2257, "record_cat"), RECORD_3(2258, "record_blocks"), RECORD_4(2259, "record_chirp"), RECORD_5(2260, "record_far"), RECORD_6(2261, "record_mall"), RECORD_7(2262, "record_mellohi"), RECORD_8(2263, "record_stal"), RECORD_9(2264, "record_strad"), RECORD_10(2265, "record_ward"), RECORD_11(2266, "record_11"), RECORD_12(2267, "record_wait") }
apache-2.0
ejeinc/Meganekko
library/src/main/java/org/meganekkovr/audio_engine/SoundImpl.kt
1
2845
package org.meganekkovr.audio_engine import android.animation.ValueAnimator import android.os.Handler import android.os.Looper import com.google.vr.sdk.audio.GvrAudioEngine import java.util.* internal class SoundImpl(private val audioEngine: GvrAudioEngine, private val id: Int) : SoundObject, SoundField, StereoSound { private val timedEvents = TreeMap<Float, () -> Unit>() private var volume = 1f private var currentTime: Float = 0.toFloat() private var willBeInPlaying: Boolean = false private var onEndCallback: (() -> Unit)? = null override val isPlaying: Boolean get() = audioEngine.isSoundPlaying(id) override val isEnded: Boolean get() = willBeInPlaying && !isPlaying override fun play(loopingEnabled: Boolean) { this.willBeInPlaying = true audioEngine.playSound(id, loopingEnabled) } override fun pause() { this.willBeInPlaying = false audioEngine.pauseSound(id) } override fun resume() { this.willBeInPlaying = true audioEngine.resumeSound(id) } override fun stop() { // I don't set willBeInPlaying to false here for onEndCallback. audioEngine.stopSound(id) } override fun setPosition(x: Float, y: Float, z: Float) { audioEngine.setSoundObjectPosition(id, x, y, z) } override fun setDistanceRolloffModel(rolloffModel: Int, minDistance: Float, maxDistance: Float) { audioEngine.setSoundObjectDistanceRolloffModel(id, rolloffModel, minDistance, maxDistance) } override fun setVolume(volume: Float) { this.volume = volume audioEngine.setSoundVolume(id, volume) } override fun fadeVolume(volume: Float, time: Float) { val animator = ValueAnimator.ofFloat(this.volume, volume) .setDuration((time * 1000).toLong()) animator.addUpdateListener { animation -> val value = animation.animatedValue as Float [email protected](value) } Handler(Looper.getMainLooper()).post { animator.start() } } override fun setRotation(x: Float, y: Float, z: Float, w: Float) { audioEngine.setSoundfieldRotation(id, x, y, z, w) } override fun onEnd(callback: () -> Unit) { this.onEndCallback = callback } fun notifyOnEnd() { onEndCallback?.invoke() onEndCallback = null } override fun addTimedEvent(time: Float, event: () -> Unit) { timedEvents[time] = event } fun deltaSeconds(deltaSeconds: Float) { currentTime += deltaSeconds // Emit timed events if (!timedEvents.isEmpty()) { val firstKey = timedEvents.firstKey() if (firstKey < currentTime) { timedEvents.remove(firstKey)?.invoke() } } } }
apache-2.0
thanhnbt/kovert
vertx-jdk8/src/test/kotlin/uy/kohesive/kovert/vertx/TestVertxControllerBinding.kt
1
19997
package uy.kohesive.kovert.vertx.test import com.fasterxml.jackson.databind.SerializationFeature import io.vertx.core.Vertx import io.vertx.core.http.* import io.vertx.core.json.Json import io.vertx.ext.unit.TestContext import io.vertx.ext.unit.junit.VertxUnitRunner import io.vertx.ext.web.Router import io.vertx.ext.web.RoutingContext import nl.komponents.kovenant.Promise import nl.komponents.kovenant.async import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import uy.klutter.core.jdk8.utcNow import uy.klutter.vertx.vertx import uy.kohesive.kovert.core.* import uy.kohesive.kovert.vertx.* import java.time.Instant import java.util.concurrent.CountDownLatch import kotlin.properties.Delegates import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue @RunWith(VertxUnitRunner::class) public class TestVertxBinding { var _vertx: Vertx by Delegates.notNull() var _server: HttpServer by Delegates.notNull() var _client: HttpClient by Delegates.notNull() var _router: Router by Delegates.notNull() val _serverPort: Int = 18080 @Before public fun beforeTest(context: TestContext) { KovertConfig.reportStackTracesOnExceptions = false Json.mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false); Json.mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); Json.prettyMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false); Json.prettyMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); _vertx = vertx().get() // use Kotlin wrapper to make sure Kovenent is setup to dispatch with vert.x nicely _router = Router.router(_vertx) _server = _vertx.createHttpServer(HttpServerOptions().setPort(_serverPort).setHost("localhost")) _client = _vertx.createHttpClient(HttpClientOptions().setDefaultHost("localhost").setDefaultPort(_serverPort)) val latch = CountDownLatch(1); _server.requestHandler { _router.accept(it) }.listen { latch.countDown() } latch.await() } @After public fun afterTest() { KovertConfig.reportStackTracesOnExceptions = false _client.close() val latch = CountDownLatch(1); _server.close { latch.countDown() } latch.await() } @Test public fun testOneControllerWithAllTraits() { val controller = OneControllerWithAllTraits() _router.bindController(controller, "/one") // with context factory used _client.testServer(HttpMethod.GET, "/one", 200, "Hello") assertTrue(controller.aRequest) assertTrue(controller.aDispatch) assertNotNull(controller.aDispatchMember) assertFalse(controller.aFailure) assertTrue(controller.aContextCreated) controller.reset() // no context factory used, extends different context _client.testServer(HttpMethod.GET, "/one/two", 200, "Bye") assertTrue(controller.aRequest) assertTrue(controller.aDispatch) assertNotNull(controller.aDispatchMember) assertFalse(controller.aFailure) assertFalse(controller.aContextCreated) // one path is below another _client.testServer(HttpMethod.GET, "/one/two/three", 200, "dunno") assertTrue(controller.aRequest) assertTrue(controller.aDispatch) assertNotNull(controller.aDispatchMember) assertFalse(controller.aFailure) assertFalse(controller.aContextCreated) } @Test public fun testOneControllerWithAllTraitsFails() { val controller = OneControllerWithAllTraits() _router.bindController(controller, "/one") KovertConfig.reportStackTracesOnExceptions = true _client.testServer(HttpMethod.GET, "/one/but/fail500", 500) assertTrue(controller.aRequest) assertTrue(controller.aDispatch) assertNotNull(controller.aDispatchMember) assertTrue(controller.aFailure) assertTrue(controller.aContextCreated) controller.reset() _client.testServer(HttpMethod.GET, "/one/but/fail403", 403) assertTrue(controller.aFailure) controller.reset() _client.testServer(HttpMethod.GET, "/one/but/fail401", 401) assertTrue(controller.aFailure) controller.reset() _client.testServer(HttpMethod.GET, "/one/but/fail400", 400) assertTrue(controller.aFailure) controller.reset() _client.testServer(HttpMethod.GET, "/one/but/fail404", 404) assertTrue(controller.aFailure) } @Test public fun testRoutingContextNaturally() { _router.bindController(OneControllerWithAllTraits(), "/one") _router.bindController(ContextTestController(), "/two") _client.testServer(HttpMethod.GET, "/one/no/special/context", 200, assertResponse = "success") _client.testServer(HttpMethod.GET, "/two/no/special/context", 200, assertResponse = "success") } @Test public fun testOneControllerWithAllTraitsRedirects() { val controller = OneControllerWithAllTraits() _router.bindController(controller, "/one") _client.testServer(HttpMethod.GET, "/one/that/has/redirect", 302) assertTrue(controller.aRequest) assertTrue(controller.aDispatch) assertNotNull(controller.aDispatchMember) assertFalse(controller.aFailure) assertTrue(controller.aContextCreated) controller.reset() _client.testServer(HttpMethod.GET, "/one/nothing/and/fail", 500) assertTrue(controller.aFailure) controller.reset() _client.testServer(HttpMethod.GET, "/one/nothing/and/redirect", 302) assertFalse(controller.aFailure) _client.testServer(HttpMethod.PUT, "/one/return/nothing/is/ok", 200) } @Test public fun testOneControllerWithNullableParm() { _router.bindController(OneControllerWithAllTraits(), "/one") _client.testServer(HttpMethod.GET, "/one/missing/parameter?parm2=happy", assertResponse = "null happy") } @Test public fun testOneControllerWithAllTraitsPromisedResult() { val controller = OneControllerWithAllTraits() _router.bindController(controller, "/one") _client.testServer(HttpMethod.GET, "/one/promise/results", assertResponse = "I promised, I delivered") controller.reset() _client.testServer(HttpMethod.GET, "/one/promise/error", 403) assertTrue(controller.aFailure) } @Test public fun testJsonResponses() { val controller = JsonController() _router.bindController(controller, "/api") _client.testServer(HttpMethod.GET, "/api/people", assertResponse = """[{"name":"Fred","age":30},{"name":"Tom","age":20}]""") _client.testServer(HttpMethod.GET, "/api/people/named/Fred", assertResponse = """[{"name":"Fred","age":30}]""") _client.testServer(HttpMethod.GET, "/api/people/named/Tom", assertResponse = """[{"name":"Tom","age":20}]""") _client.testServer(HttpMethod.GET, "/api/people/named/Xyz", 404) _client.testServer(HttpMethod.GET, "/api/people/age/30", assertResponse = """[{"name":"Fred","age":30}]""") _client.testServer(HttpMethod.GET, "/api/people/age/20", assertResponse = """[{"name":"Tom","age":20}]""") _client.testServer(HttpMethod.GET, "/api/people/age/18", 404) _client.testServer(HttpMethod.GET, "/api/people/named/Fred/age/30", assertResponse = """[{"name":"Fred","age":30}]""") _client.testServer(HttpMethod.GET, "/api/people/named/Tom/age/20", assertResponse = """[{"name":"Tom","age":20}]""") _client.testServer(HttpMethod.GET, "/api/people2/named/Fred/age/30", assertResponse = """[{"name":"Fred","age":30}]""") _client.testServer(HttpMethod.GET, "/api/people2/named/Tom/age/20", assertResponse = """[{"name":"Tom","age":20}]""") } @Test public fun testVerbAlisesMore() { val controller = JsonControllerManyAliases() _router.bindController(controller, "/verby") _client.testServer(HttpMethod.GET, "verby/people1", assertResponse = """[{"name":"Fred","age":30},{"name":"Tom","age":20}]""", assertStatus = 200) _client.testServer(HttpMethod.GET, "verby/people2", assertResponse = """[{"name":"Fred","age":30},{"name":"Tom","age":20}]""", assertStatus = 200) _client.testServer(HttpMethod.GET, "verby/person1", assertStatus = 200, assertResponse = """{"name":"Fred","age":30}""") _client.testServer(HttpMethod.PUT, "verby/person1", writeJson = """{ "name": "Fred", "age": 30 }""", assertStatus = 201, assertResponse = """{"name":"Fred","age":30}""") _client.testServer(HttpMethod.POST, "verby/person1", writeJson = """{ "name": "Fred", "age": 30 }""", assertStatus = 200, assertResponse = """{"name":"Fred","age":30}""") } @Test public fun testAltContentTypeWithEncoding() { val controller = JsonControllerManyAliases() _router.bindController(controller, "/verby") _client.testServerAltContentType(HttpMethod.PUT, "verby/person1", writeJson = """{ "name": "Fred", "age": 30 }""", assertStatus = 201, assertResponse = """{"name":"Fred","age":30}""") _client.testServerAltContentType(HttpMethod.POST, "verby/person1", writeJson = """{ "name": "Fred", "age": 30 }""", assertStatus = 200, assertResponse = """{"name":"Fred","age":30}""") } @Test public fun testOtherAnnotations() { val controller = AnnotationsInsideController() _router.bindController(controller, "/api") _client.testServer(HttpMethod.GET, "/api/what/is/this/method1", assertResponse = """{"status":"OK"}""") _client.testServer(HttpMethod.GET, "/api/what/is/this/method2", assertResponse = """{"status":"OK"}""") _client.testServer(HttpMethod.GET, "/api/what/is/this/method3", assertResponse = """{"status":"OK"}""") _client.testServer(HttpMethod.GET, "/api/what/is/this/method4", assertResponse = """{"status":"OK"}""") _client.testServer(HttpMethod.GET, "/api/what/is/this/method5/MAYBE", assertResponse = """{"status":"MAYBE"}""") } @Test public fun testParameterBinding() { val controller = ParameterBindingController() _router.bindController(controller, "/api") _client.testServer(HttpMethod.GET, "/api/something/having/simple/parameters?parm1=20&parm2=Fred&parm3=true", assertResponse = """20, Fred, true""") _client.testServer(HttpMethod.GET, "/api/something/having/complex/parameter?parm1.name=Fred&parm1.age=30", assertResponse = """{"name":"Fred","age":30}""") _client.testServer(HttpMethod.GET, "/api/something/having/two/complex/parameters?parm1.name=Fred&parm1.age=30&parm2.name=Tom&parm2.age=20", assertResponse = """[{"name":"Fred","age":30},{"name":"Tom","age":20}]""") } @Test public fun testJsonBody() { val controller = ParameterBindingController() _router.bindController(controller, "/api") // json body _client.testServer(HttpMethod.PUT, "/api/something/as/json", writeJson = """{ "name": "Fred", "age": 30 }""", assertResponse = """{"name":"Fred","age":30}""") _client.testServer(HttpMethod.PUT, "/api/something/as/json/and/parameters?parm1.name=Tom&parm1.age=20", writeJson = """{ "name": "Fred", "age": 30 }""", assertResponse = """[{"name":"Fred","age":30},{"name":"Tom","age":20}]""") _client.testServer(HttpMethod.PUT, "/api/something/as/json/and/parameters?parm2.name=Fred&parm2.age=30", writeJson = """{ "name": "Tom", "age": 20 }""", assertResponse = """[{"name":"Fred","age":30},{"name":"Tom","age":20}]""") } @Test public fun testMemberVarFunctions() { val controller = MemberVarController() _router.bindController(controller, "/api") _client.testServer(HttpMethod.GET, "/api/first/test", assertResponse = "FirstTest") _client.testServer(HttpMethod.GET, "/api/second/test?parm=99", assertResponse = "SecondTest 99") _client.testServer(HttpMethod.POST, "/api/third/test?parm=dog", assertResponse = "ThirdTest dog") } @Ignore("Need to figure out why the jackson bindings for Instant sometimes go bonkers") @Test public fun testSpecialTypes() { val controller = ControllerWithSpecialTypes() _router.bindController(controller, "/api") val i = utcNow() _client.testServer(HttpMethod.GET, "/api/thing/${i.toEpochMilli()}", assertResponse = "{${i.toEpochMilli()}}") } } public class MemberVarController() { public val getFirstTest = fun TwoContext.(): String = "FirstTest" public val getSecondTest = fun TwoContext.(parm: Int): String = "SecondTest ${parm}" @Location("third/test") @Verb(HttpVerb.POST) public val getThirdyBaby = fun TwoContext.(parm: String): String = "ThirdTest ${parm}" } public class OneControllerWithAllTraits : InterceptRequest, InterceptDispatch<Any>, InterceptRequestFailure, ContextFactory<OneContext> { var aRequest: Boolean = false var aDispatch: Boolean = false var aDispatchMember: Any? = null var aFailure: Boolean = false var aFailureException: Throwable? = null var aFailureCode: Int = 0 var aContextCreated: Boolean = false public fun reset() { aRequest = false aDispatch = false aDispatchMember = null aFailure = false aFailureException = null aFailureCode = 0 aContextCreated = false } override fun interceptRequest(rawContext: RoutingContext, nextHandler: () -> Unit) { aRequest = true nextHandler() } override fun Any.interceptDispatch(member: Any, dispatcher: () -> Any?): Any? { aDispatch = true aDispatchMember = member return dispatcher() } override fun interceptFailure(rawContext: RoutingContext, nextHandler: () -> Unit) { aFailure = true aFailureException = rawContext.failure() aFailureCode = rawContext.statusCode() nextHandler() } override fun createContext(routingContext: RoutingContext): OneContext { aContextCreated = true return OneContext(routingContext) } public fun OneContext.get(): String { return "Hello" } public fun TwoContext.getTwo(): String { return "Bye" } public fun TwoContext.getTwoThree(): String { return "dunno" } public fun OneContext.getButFail500(): String { // make an error 500 throw RuntimeException("Drat") } public fun OneContext.getButFail403(): String { throw HttpErrorForbidden() } public fun OneContext.getButFail401(): String { throw HttpErrorUnauthorized() } public fun OneContext.getButFail400(): String { throw HttpErrorBadRequest() } public fun OneContext.getButFail404(): String { throw HttpErrorNotFound() } public fun OneContext.getThatHasRedirect(): String { throw HttpRedirect("/one/two") } public fun OneContext.getNothingAndFail(): Unit { // will fail, because no return type, must redirect and doesn't } public fun OneContext.getNothingAndRedirect(): Unit { throw HttpRedirect("/one/two") } public fun OneContext.putReturnNothingIsOk(): Unit { } public fun OneContext.getPromiseResults(): Promise<String, Exception> { return async { "I promised, I delivered" } } public fun OneContext.getPromiseError(): Promise<String, Exception> { return async { throw HttpErrorForbidden() } } public fun OneContext.getMissingParameter(parm1: String?, parm2: String): String { return "${parm1} ${parm2}" } public fun RoutingContext.getNoSpecialContext(): String { return "success" } } public class ContextTestController { public fun RoutingContext.getNoSpecialContext(): String { return "success" } } public data class OneContext(private val context: RoutingContext) public data class TwoContext(private val context: RoutingContext) public data class Person(val name: String, val age: Int) public data class RestResponse(val status: String = "OK") @VerbAlias("find", HttpVerb.GET) public class JsonController { public fun OneContext.listPeople(): List<Person> { return listOf(Person("Fred", 30), Person("Tom", 20)) } public fun OneContext.findPeopleNamedByName(name: String): List<Person> { val people = listOf(Person("Fred", 30), Person("Tom", 20)) val matchingPersons = people.groupBy { it.name }.map { it.key to it.value }.toMap().get(name) if (matchingPersons == null || matchingPersons.size == 0) throw HttpErrorNotFound() return matchingPersons } public fun OneContext.findPeopleWithAge(age: Int): List<Person> { val people = listOf(Person("Fred", 30), Person("Tom", 20)) val matchingPersons = people.groupBy { it.age }.map { it.key to it.value }.toMap().get(age) if (matchingPersons == null || matchingPersons.size == 0) throw HttpErrorNotFound() return matchingPersons } public fun OneContext.findPeopleNamedByNameWithAge(name: String, age: Int): List<Person> { val people = listOf(Person("Fred", 30), Person("Tom", 20)) val matchingPersons = people.groupBy { it.name }.map { it.key to it.value }.toMap().get(name)?.filter { it.age == age } if (matchingPersons == null || matchingPersons.size == 0) throw HttpErrorNotFound() return matchingPersons } public fun OneContext.findPeople2_Named_ByName_Age_ByAge(name: String, age: Int): List<Person> { return findPeopleNamedByNameWithAge(name, age) } } public class ControllerWithSpecialTypes { public fun OneContext.getThingByDate(date: Instant): Instant { return date } } @VerbAliases(VerbAlias("find", HttpVerb.GET),VerbAlias("search", HttpVerb.GET),VerbAlias("add", HttpVerb.PUT, 201)) public class JsonControllerManyAliases { public fun OneContext.findPeople1(): List<Person> { return listOf(Person("Fred", 30), Person("Tom", 20)) } public fun OneContext.searchPeople2(): List<Person> { return listOf(Person("Fred", 30), Person("Tom", 20)) } public fun OneContext.addPerson1(person: Person): Person { return person } public fun OneContext.postPerson1(person: Person): Person { return person } public fun OneContext.getPerson1(): Person { return Person("Fred", 30) } } public class AnnotationsInsideController { @Verb(HttpVerb.GET, skipPrefix = false) public fun OneContext.whatIsThisMethod1(): RestResponse = RestResponse() @Verb(HttpVerb.GET, skipPrefix = true) // already the default public fun OneContext.skipWhatIsThisMethod2(): RestResponse = RestResponse() @Location("what/is/this/method3") public fun OneContext.getMethod3(): RestResponse = RestResponse() @Verb(HttpVerb.GET) @Location("what/is/this/method4") public fun OneContext.method4(): RestResponse = RestResponse() @Location("what/is/this/method5/:status") public fun OneContext.getMethod5(status: String): RestResponse = RestResponse(status) } public class ParameterBindingController { public fun OneContext.getSomethingHavingSimpleParameters(parm1: Int, parm2: String, parm3: Boolean): String { return "$parm1, $parm2, $parm3" } public fun OneContext.getSomethingHavingComplexParameter(parm1: Person): Person = parm1 public fun OneContext.getSomethingHavingTwoComplexParameters(parm1: Person, parm2: Person): List<Person> = listOf(parm1, parm2) public fun OneContext.putSomethingAsJson(parm1: Person): Person = parm1 public fun OneContext.putSomethingAsJsonAndParameters(parm1: Person, parm2: Person): List<Person> = listOf(parm2, parm1) }
mit
Magneticraft-Team/Magneticraft
ignore/test/guide/components/Text.kt
2
5192
package com.cout970.magneticraft.guide.components import com.cout970.magneticraft.MOD_ID import com.cout970.magneticraft.gui.client.guide.FONT_HEIGHT import com.cout970.magneticraft.gui.client.guide.GuiGuideBook import com.cout970.magneticraft.guide.BookPage import com.cout970.magneticraft.guide.IPageComponent import com.cout970.magneticraft.guide.JsonIgnore import com.cout970.magneticraft.guide.LinkInfo import com.cout970.magneticraft.util.i18n import com.cout970.magneticraft.util.vector.Vec2d import com.cout970.magneticraft.util.vector.contains import net.minecraft.client.resources.I18n class Text( position: Vec2d, override val size: Vec2d, val text: String ) : PageComponent(position) { override val id: String = "text" @JsonIgnore var words: List<Pair<String, LinkInfo?>>? = parseText(text) override fun toGuiComponent(parent: BookPage.Gui): IPageComponent = TextComponentGui(parent) private inner class TextComponentGui(parent: BookPage.Gui) : Gui(parent) { lateinit var boxes: List<TextBox> override fun initGui() { super.initGui() placeBoxes() } fun placeBoxes() { var x = 0 var y = 0 val boxList = mutableListOf<TextBox>() val space = parent.gui.getCharWidth(' ') if(words == null){ words = parseText(text) } for ((word, link) in words!!) { val width = parent.gui.getStringWidth(word) if (width > size.x) { // throw IllegalStateException( // "Word $word is larger than text box. Increase text box width or change the word." // ) } if (x + width > size.x) { x = 0 y += FONT_HEIGHT + 1 if (y > size.y) { // throw IllegalStateException("Text is larger than the text box.") } } else { if (boxList.isNotEmpty() && boxList.last().link == link) { boxList.last().nextLink = true } } if (x + space > size.x) { boxList += TextBox(this, Vec2d(x, y), word, false, link) } else { boxList += TextBox(this, Vec2d(x, y), word, true, link) x += space } x += width } boxes = boxList } override fun draw(mouse: Vec2d, time: Double) { boxes.forEach { it.draw(mouse) } } override fun postDraw(mouse: Vec2d, time: Double) { boxes.forEach { it.postDraw(mouse) } } override fun onLeftClick(mouse: Vec2d): Boolean { val box = boxes.firstOrNull { it.isInside(mouse) && it.link != null } box ?: return false box.link ?: return false parent.gui.mc.displayGuiScreen(GuiGuideBook(box.link.getEntryTarget())) return true } } private class TextBox( val parent: Gui, val position: Vec2d, val text: String, val space: Boolean, val link: LinkInfo? = null ) { val page = parent.parent val size = Vec2d(page.gui.getStringWidth(text), FONT_HEIGHT) var nextLink = false val drawPos: Vec2d get() = parent.drawPos + position fun isInside(pos: Vec2d) = pos in drawPos toPoint (drawPos + size) fun draw(mouse: Vec2d) { val prefix = if (link == null) { "§r" } else { if (isInside(mouse)) { "§9§n" } else { "§r§n" } } val spaceFormat = if (space) { if (nextLink) " " else "§r " } else { "" } page.gui.drawString( pos = drawPos, text = prefix + text + spaceFormat ) } fun postDraw(mouse: Vec2d) { if (link != null && isInside(mouse)) { page.gui.drawHoveringText(listOf(I18n.format("$MOD_ID.guide.link.text", link.entry.i18n(), link.page + 1)), mouse) } } } } fun parseText(text: String): List<Pair<String, LinkInfo?>> { if (!text.contains('[')) { return text.split(' ').filter(String::isNotBlank).map { it to null } } //before first link val prefix = parseText(text.substringBefore('[')) val remText = text.substringAfter('[') //link text [<this part>](...) val linkWords = parseText(remText.substringBefore(']')) val remainder = remText.substringAfter("](") //link target [...](<this part>) val link = remainder.substringBefore(')').split(':').run { LinkInfo(get(0).trim(), get(1).trim().toInt()) } //recurse for rest of the text return prefix + linkWords.map { it.first to link } + parseText(remainder.substringAfter(')')) }
gpl-2.0
toastkidjp/Jitte
lib/src/main/java/jp/toastkid/lib/ContentScrollable.kt
1
432
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.lib /** * @author toastkidjp */ interface ContentScrollable { fun toTop() fun toBottom() }
epl-1.0
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/utils/ResourceHelper.kt
1
1795
package com.senorsen.wukong.utils /* * Copyright (C) 2014 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. */ import android.content.Context import android.content.pm.PackageManager /** * Generic reusable methods to handle resources. */ object ResourceHelper { /** * Get a color value from a theme attribute. * @param context used for getting the color. * * * @param attribute theme attribute. * * * @param defaultColor default to use. * * * @return color value */ fun getThemeColor(context: Context, attribute: Int, defaultColor: Int): Int { var themeColor = 0 val packageName = context.packageName try { val packageContext = context.createPackageContext(packageName, 0) val applicationInfo = context.packageManager.getApplicationInfo(packageName, 0) packageContext.setTheme(applicationInfo.theme) val theme = packageContext.theme val ta = theme.obtainStyledAttributes(intArrayOf(attribute)) themeColor = ta.getColor(0, defaultColor) ta.recycle() } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return themeColor } }
agpl-3.0
elpassion/android-commons
recycler/src/main/java/com/elpassion/android/commons/recycler/basic/ViewHolderBinder.kt
1
254
package com.elpassion.android.commons.recycler.basic import android.view.View import androidx.recyclerview.widget.RecyclerView open class ViewHolderBinder<in Item>(itemView: View) : RecyclerView.ViewHolder(itemView) { open fun bind(item: Item) {} }
apache-2.0
xfournet/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/GroovyElementActionsFactory.kt
1
1161
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.actions.CreateFieldRequest import com.intellij.lang.jvm.actions.JvmElementActionsFactory import com.intellij.openapi.util.text.StringUtil class GroovyElementActionsFactory : JvmElementActionsFactory() { override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> { val javaClass = targetClass.toGroovyClassOrNull() ?: return emptyList() val constantRequested = request.constant || javaClass.isInterface || request.modifiers.containsAll(constantModifiers) val result = ArrayList<IntentionAction>() if (constantRequested || StringUtil.isCapitalized(request.fieldName)) { result += CreateFieldAction(javaClass, request, true) } if (!constantRequested) { result += CreateFieldAction(javaClass, request, false) } return result } }
apache-2.0
jainaman224/Algo_Ds_Notes
Tree_Inorder_Traversal/Inorder_Traversal.kt
1
1190
//Code for printing inorder traversal in kotlin class Node { //Structure of Binary tree node int num; Node left, right; public node(int num) { key = item; left = right = null; } } class BinaryTree { Node root; BinaryTree() { root = null; } //function to print inorder traversal fun printInorder(Node: node):void { if (node == null) return; printInorder(node.left); //printing val of node println(node.num); printInorder(node.right); } fun printInorder():void { printInorder(root); } } //Main function fun main() { BinaryTree tree = new BinaryTree(); var read = Scanner(System.`in`) println("Enter the size of Array:") val arrSize = read.nextLine().toInt() var arr = IntArray(arrSize) println("Enter data of binary tree") for(i in 0 until arrSize) { arr[i] = read.nextLine().toInt() tree.root = new Node(arr[i]); } println("Inorder traversal of binary tree is"); tree.printInorder();//function call } /* Input: 10 8 3 30 5 19 4 5 1 Output:5 3 1 2 8 10 19 30 4 */
gpl-3.0
JavaEden/OrchidCore
OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/functions/AnchorFunction.kt
1
2347
package com.eden.orchid.impl.themes.functions import com.caseyjbrooks.clog.Clog import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.indexing.IndexService import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import javax.inject.Inject @Description(value = "Generate an HTML link to a page.", name = "Anchor") class AnchorFunction @Inject constructor(val context: OrchidContext) : TemplateFunction("anchor", true) { @Option @Description("The title to display in an anchor tag for the given item if found. Otherwise, the title is " + "returned directly.") lateinit var title: String @Option @Description("The Id of an item to link to.") lateinit var itemId: String @Option @Description("The type of collection the item is expected to come from.") lateinit var collectionType: String @Option @Description("The specific Id of the given collection type where the item is expected to come from.") lateinit var collectionId: String @Option @Description("Custom classes to add to the resulting anchor tag. If no matching item is found, these classes are " + "not used.") lateinit var customClasses: String override fun parameters(): Array<String?> { return arrayOf( "title", *IndexService.locateParams, "customClasses" ) } override fun apply(): String? { if (EdenUtils.isEmpty(itemId) && !EdenUtils.isEmpty(title)) { itemId = title } val page = context.findPage(collectionType, collectionId, itemId) if (page != null) { val link = page.link return if (!EdenUtils.isEmpty(title) && !EdenUtils.isEmpty(customClasses)) { Clog.format("<a href=\"#{$1}\" class=\"#{$3}\">#{$2}</a>", link, title, customClasses) } else if (!EdenUtils.isEmpty(title)) { Clog.format("<a href=\"#{$1}\">#{$2}</a>", link, title) } else { Clog.format("<a href=\"#{$1}\">#{$1}</a>", link) } } return if (!EdenUtils.isEmpty(title)) { title } else { "" } } }
mit
Ekito/koin
koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/mvp/MVPActivity.kt
1
1857
package org.koin.sample.androidx.mvp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.mvp_activity.* import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.koin.androidx.scope.activityScope import org.koin.core.parameter.parametersOf import org.koin.core.scope.KoinScopeComponent import org.koin.core.scope.Scope import org.koin.core.scope.get import org.koin.core.scope.inject import org.koin.sample.android.R import org.koin.sample.androidx.components.ID import org.koin.sample.androidx.components.mvp.FactoryPresenter import org.koin.sample.androidx.components.mvp.ScopedPresenter import org.koin.sample.androidx.mvvm.MVVMActivity import org.koin.sample.androidx.utils.navigateTo class MVPActivity : AppCompatActivity(R.layout.mvp_activity), KoinScopeComponent { override val scope: Scope by lazy { activityScope() } // Inject presenter as Factory val factoryPresenter: FactoryPresenter by inject { parametersOf(ID) } // Inject presenter from MVPActivity's scope val scopedPresenter: ScopedPresenter by inject { parametersOf(ID) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) assertEquals(factoryPresenter.id, scopedPresenter.id) assertEquals(factoryPresenter.service, scopedPresenter.service) assertNotEquals(get<FactoryPresenter> { parametersOf(ID) }, factoryPresenter) assertEquals(get<ScopedPresenter>(), scopedPresenter) title = "Android MVP" mvp_button.setOnClickListener { navigateTo<MVVMActivity>(isRoot = true) } } override fun onDestroy() { super.onDestroy() // don't forget to close current scope if not activityScope() or fragmentScope() // closeScope() } }
apache-2.0
FredJul/TaskGame
TaskGame/src/main/java/net/fred/taskgame/adapters/MultiSelectAdapter.kt
1
3621
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.adapters import android.support.v7.widget.RecyclerView import android.util.SparseBooleanArray import net.fred.taskgame.utils.recycler.ItemActionAdapter import net.fred.taskgame.utils.recycler.ItemActionListener import net.fred.taskgame.utils.recycler.ItemActionViewHolder abstract class MultiSelectAdapter<VH>(private val mListener: ItemActionListener, private val mRecyclerView: RecyclerView) : RecyclerView.Adapter<VH>(), ItemActionAdapter where VH : RecyclerView.ViewHolder, VH : ItemActionViewHolder { private val mSelectedItems = SparseBooleanArray() fun isItemSelected(position: Int): Boolean { return mSelectedItems.get(position) } fun selectAll() { for (i in 0..itemCount - 1) { if (!isItemSelected(i)) { updateView(mRecyclerView, i, false) mSelectedItems.put(i, true) } } } fun clearSelections() { for (i in 0..itemCount - 1) { updateView(mRecyclerView, i, true) } mSelectedItems.clear() } val selectedItemCount: Int get() = mSelectedItems.size() val selectedItems: IntArray get() { val itemsPos = IntArray(mSelectedItems.size()) for (i in 0..mSelectedItems.size() - 1) { itemsPos[i] = mSelectedItems.keyAt(i) } return itemsPos } override fun onBindViewHolder(holder: VH, position: Int) { if (isItemSelected(position)) { holder.onItemSelected() } else { holder.onItemClear() } } protected fun toggleSelection(select: Boolean, position: Int) { updateView(mRecyclerView, position, !select) if (!select) { mSelectedItems.delete(position) } else { mSelectedItems.put(position, true) } } private fun updateView(recyclerView: RecyclerView, position: Int, isCurrentlySelected: Boolean) { val child = mRecyclerView.layoutManager.findViewByPosition(position) if (child != null) { val viewHolder = recyclerView.getChildViewHolder(child) as ItemActionViewHolder // Let the view holder know that this item is being moved or dragged if (isCurrentlySelected) { viewHolder.onItemClear() } else { viewHolder.onItemSelected() } } } override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean { return mListener.onItemMove(fromPosition, toPosition) } override fun onItemMoveFinished() { mListener.onItemMoveFinished() } override fun onItemSwiped(position: Int) { mListener.onItemSwiped(position) } override fun onItemSelected(position: Int) { toggleSelection(true, position) mListener.onItemSelected(position) } }
gpl-3.0
vshkl/Pik
app/src/main/java/by/vshkl/android/pik/BasePagerFragment.kt
1
770
package by.vshkl.android.pik import android.content.Context import by.vshkl.android.pik.ui.imageviewer.ImageViewerActivity import com.arellomobile.mvp.MvpAppCompatFragment import java.lang.ref.WeakReference open class BasePagerFragment : MvpAppCompatFragment() { private var parentActivityRef: WeakReference<ImageViewerActivity>? = null override fun onAttach(context: Context) { super.onAttach(context) if (context is ImageViewerActivity) { parentActivityRef = WeakReference(context) } } override fun onDetach() { parentActivityRef?.clear() parentActivityRef = null super.onDetach() } fun getParentActivity(): ImageViewerActivity? { return parentActivityRef?.get() } }
apache-2.0
Doctoror/FuckOffMusicPlayer
presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/library/LibraryPermissionsProvider.kt
2
1678
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.fuckoffmusicplayer.presentation.library import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.support.annotation.MainThread import android.support.v4.content.ContextCompat import com.doctoror.fuckoffmusicplayer.RuntimePermissions import com.doctoror.fuckoffmusicplayer.presentation.rxpermissions.RxPermissionsProvider import io.reactivex.Observable class LibraryPermissionsProvider( private val context: Context, private val runtimePermissions: RuntimePermissions, private val rxPermissionsProvider: RxPermissionsProvider) { fun permissionsGranted() = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED @MainThread fun requestPermission(): Observable<Boolean> { runtimePermissions.permissionsRequested = true return rxPermissionsProvider .provideRxPermissions() .request(Manifest.permission.READ_EXTERNAL_STORAGE) } }
apache-2.0
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/gui/jfx/MainWindowController.kt
1
3836
package org.stt.gui.jfx import javafx.application.Platform import javafx.fxml.FXML import javafx.fxml.FXMLLoader import javafx.scene.Parent import javafx.scene.Scene import javafx.scene.control.Tab import javafx.scene.image.Image import javafx.scene.input.KeyCode import javafx.stage.Stage import net.engio.mbassy.bus.MBassador import net.engio.mbassy.listener.Handler import org.controlsfx.control.Notifications import org.stt.event.NotifyUser import org.stt.event.ShuttingDown import org.stt.gui.UIMain import java.io.IOException import java.io.UncheckedIOException import java.util.* import java.util.concurrent.CompletableFuture import java.util.logging.Level import java.util.logging.Logger import javax.inject.Inject class MainWindowController @Inject internal constructor(private val localization: ResourceBundle, private val activitiesController: ActivitiesController, private val reportController: ReportController, private val eventBus: MBassador<Any>, private val settingsController: SettingsController, private val infoController: InfoController) { private val rootNode: Parent @FXML private lateinit var activitiesTab: Tab @FXML private lateinit var reportTab: Tab @FXML private lateinit var settingsTab: Tab @FXML private lateinit var infoTab: Tab init { val loader = FXMLLoader(javaClass.getResource( "/org/stt/gui/jfx/MainWindow.fxml"), localization) loader.setController(this) try { rootNode = loader.load() } catch (e: IOException) { throw UncheckedIOException(e) } rootNode.stylesheets.add("org/stt/gui/jfx/STT.css") eventBus.subscribe(this) } @Handler fun onUserNotifactionRequest(event: NotifyUser) { Notifications.create().text(event.message).show() } @FXML fun initialize() { activitiesTab.content = activitiesController.node CompletableFuture.supplyAsync { reportController.panel } .thenAcceptAsync({ reportTab.content = it }, { Platform.runLater(it) }) .handle { _, t -> if (t != null) LOG.log(Level.SEVERE, "Error while building report controller", t) t!!.message } CompletableFuture.supplyAsync { settingsController.panel } .thenAcceptAsync({ settingsTab.content = it }, { Platform.runLater(it) }) .handle { _, t -> if (t != null) LOG.log(Level.SEVERE, "Error while building settings controller", t) t!!.message } CompletableFuture.supplyAsync { infoController.getPanel() } .thenAcceptAsync({ infoTab.content = it }, { Platform.runLater(it) }) .handle { _, t -> if (t != null) LOG.log(Level.SEVERE, "Error while building info controller", t) t!!.message } } fun show(stage: Stage) { val scene = Scene(rootNode) stage.setOnCloseRequest { Platform.runLater { this.shutdown() } } scene.setOnKeyPressed { event -> if (KeyCode.ESCAPE == event.code) { event.consume() shutdown() } } val applicationIcon = Image("/Logo.png", 32.0, 32.0, true, true) stage.icons.add(applicationIcon) stage.title = localization.getString("window.title") stage.scene = scene stage.sizeToScene() stage.show() } private fun shutdown() { eventBus.publish(ShuttingDown()) } companion object { private val LOG = Logger.getLogger(UIMain::class.java .name) } }
gpl-3.0
mustafa01ali/Dev-Tiles
app/src/test/kotlin/xyz/mustafaali/devqstiles/ExampleUnitTest.kt
1
398
package xyz.mustafaali.devqstiles import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * @see [Testing documentation](http://d.android.com/tools/testing) */ class ExampleUnitTest { @Test @Throws(Exception::class) fun addition_isCorrect() { assertEquals(4, (2 + 2).toLong()) } }
apache-2.0
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/database/DbFavoritePlayer.kt
1
806
package com.garpr.android.data.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.garpr.android.data.models.AbsPlayer import com.garpr.android.data.models.FavoritePlayer import com.garpr.android.data.models.Region @Entity(tableName = "favoritePlayers") class DbFavoritePlayer( @PrimaryKey val id: String, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "region") val region: Region ) { constructor(player: AbsPlayer, region: Region) : this(player.id, player.name, region) fun toFavoritePlayer(): FavoritePlayer { return FavoritePlayer( id = id, name = name, region = region ) } override fun toString(): String = name }
unlicense
quarkusio/quarkus
extensions/panache/mongodb-panache-kotlin/runtime/src/main/kotlin/io/quarkus/mongodb/panache/kotlin/reactive/ReactivePanacheMongoEntityBase.kt
1
1514
package io.quarkus.mongodb.panache.kotlin.reactive import io.quarkus.mongodb.panache.kotlin.reactive.runtime.KotlinReactiveMongoOperations.Companion.INSTANCE import io.smallrye.mutiny.Uni /** * Represents an entity. If your Mongo entities extend this class they gain auto-generated accessors * to all their public fields, as well as a lot of useful * methods. Unless you have a custom ID strategy, you should not extend this class directly but extend * [ReactivePanacheMongoEntity] instead. * * @see [ReactivePanacheMongoEntity] */ abstract class ReactivePanacheMongoEntityBase { /** * Persist this entity in the database. * This will set its ID field if not already set. * * @see [persist] */ fun <T : ReactivePanacheMongoEntityBase> persist(): Uni<T> = INSTANCE.persist(this).map { this as T } /** * Update this entity in the database. * * @see [update] */ fun <T : ReactivePanacheMongoEntityBase> update(): Uni<T> = INSTANCE.update(this).map { this as T } /** * Persist this entity in the database or update it if it already exists. * * @see [persistOrUpdate] */ fun <T : ReactivePanacheMongoEntityBase> persistOrUpdate(): Uni<T> = INSTANCE.persistOrUpdate(this).map { this as T } /** * Delete this entity from the database, if it is already persisted. * * @see [delete] * @see [ReactivePanacheMongoCompanionBase.deleteAll] */ fun delete(): Uni<Void> = INSTANCE.delete(this) }
apache-2.0
daemontus/glucose
compat/src/main/java/com/glucose/app/RootCompatActivity.kt
2
2876
package com.glucose.app import android.annotation.TargetApi import android.content.Intent import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.glucose.app.presenter.LifecycleException /** * An activity that is connected to a [PresenterDelegate] and has exactly one root [Presenter]. */ abstract class RootCompatActivity( rootPresenter: Class<out Presenter>, rootArguments: Bundle = Bundle() ) : AppCompatActivity() { @Suppress("LeakingThis") // there is no other way. If one wants to register a factory for // the root presenter, delegate has to be created before onCreate. private var _presenterHost: PresenterDelegate? = PresenterDelegate(this, rootPresenter, rootArguments) protected val presenterHost: PresenterDelegate get() { return _presenterHost ?: throw LifecycleException( "Accessing presenterHost on $this that is already destroyed." ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(presenterHost.onCreate(savedInstanceState)) } override fun onStart() { super.onStart() presenterHost.onStart() } override fun onResume() { super.onResume() presenterHost.onResume() } override fun onBackPressed() { if (!presenterHost.onBackPressed()) super.onBackPressed() } override fun onPause() { presenterHost.onPause() super.onPause() } override fun onStop() { presenterHost.onStop() super.onStop() } override fun onDestroy() { presenterHost.onDestroy() super.onDestroy() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) presenterHost.onConfigurationChanged(newConfig) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) presenterHost.onActivityResult(requestCode, resultCode, data) } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) override fun onTrimMemory(level: Int) { super.onTrimMemory(level) presenterHost.onTrimMemory(level) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) presenterHost.onSaveInstanceState(outState) } @TargetApi(Build.VERSION_CODES.M) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) presenterHost.onRequestPermissionsResult(requestCode, permissions, grantResults) } }
mit
MyDogTom/detekt
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/DetektIdeaFormatTask.kt
1
546
package io.gitlab.arturbosch.detekt import io.gitlab.arturbosch.detekt.extensions.DetektExtension import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction /** * @author Artur Bosch */ open class DetektIdeaFormatTask : DefaultTask() { init { description = "Uses an external idea installation to format your code." group = "verification" } @TaskAction fun format() { with(project.extensions.getByName("detekt") as DetektExtension) { if (debug) println("$ideaExtension") startProcess(ideaFormatArgs()) } } }
apache-2.0
froriz5/cadence
mobile/src/main/kotlin/com/feliperoriz/cadence/SettingsFragment.kt
1
503
package com.feliperoriz.cadence import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * Created by Felipe Roriz on 5/7/16. */ class SettingsFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.fragment_settings, container, false) return view } }
mit
jcgay/gradle-notifier
src/main/kotlin/fr/jcgay/gradle/notifier/extension/NotificationCenter.kt
1
545
package fr.jcgay.gradle.notifier.extension import java.util.Properties class NotificationCenter: NotifierConfiguration { var path: String? = null var activate: String? = null var sound: String? = null override fun asProperties(): Properties { val prefix = "notifier.notification-center" val result = Properties() path?.let { result["${prefix}.path"] = it } activate?.let { result["${prefix}.activate"] = it } sound?.let { result["${prefix}.sound"] = it } return result } }
mit
rei-m/android_hyakuninisshu
domain/src/main/java/me/rei_m/hyakuninisshu/domain/karuta/model/KarutaId.kt
1
800
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.domain.karuta.model import me.rei_m.hyakuninisshu.domain.EntityIdentifier /** * 歌ID. * * @param value 値 */ data class KarutaId( val value: Int ) : EntityIdentifier
apache-2.0
danfma/kodando
kodando-runtime/src/main/kotlin/kodando/runtime/fetch.kt
1
566
package kodando.runtime import org.w3c.fetch.Response import kotlin.js.Json import kotlin.js.Promise /** * Created by danfma on 28/01/2017. */ @JsName("fetch") external fun fetch(url: String): Promise<Response> @JsName("fetch") external fun fetch(url: String, request: IFetchRequestInit): Promise<Response> external interface IFetchRequestInit { val method: String val body: Any? val headers: Json? } class FetchRequestInit( override val method: String, override val body: Any? = null, override val headers: Json? = undefined) : IFetchRequestInit
mit
kotlin-es/kotlin-JFrame-standalone
09-start-async-radiobutton-application/src/main/kotlin/components/menuBar/MenuBar.kt
1
638
package components.progressBar import components.Component import java.awt.event.ActionEvent import javax.swing.JComponent import javax.swing.JMenu import javax.swing.JMenuBar /** * Created by vicboma on 05/12/16. */ interface MenuBar : Component<JMenuBar> { fun addMenu(list: MutableList<JComponent?>): MenuBar fun addMenu(name: JComponent?): MenuBar fun createSubMenu(parent: JMenu?, child: JComponent?): MenuBar fun createSubMenu(parent: JMenu?, child: MutableList<JComponent?>): MenuBar fun createMenu(map: Map<String, Map<String, (ActionEvent) -> Unit>>): JMenu ? fun addSeparator(menu: JMenu?): MenuBar }
mit
googlearchive/android-RecyclerView
kotlinApp/app/src/main/java/com/example/android/common/activities/SampleActivityBase.kt
3
1561
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.common.activities import android.os.Bundle import android.support.v4.app.FragmentActivity import com.example.android.common.logger.Log import com.example.android.common.logger.LogWrapper /** * Base launcher activity, to handle most of the common plumbing for samples. */ open class SampleActivityBase : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onStart() { super.onStart() initializeLogging() } /** Set up targets to receive log data */ open fun initializeLogging() { // Using Log, front-end to the logging chain, emulates android.util.log method signatures. // Wraps Android's native log framework val logWrapper = LogWrapper() Log.logNode = logWrapper Log.i(TAG, "Ready") } companion object { val TAG = "SampleActivityBase" } }
apache-2.0
GlimpseFramework/glimpse-framework
api/src/test/kotlin/glimpse/shaders/ProgramBuilderSpec.kt
1
3104
package glimpse.shaders import com.nhaarman.mockito_kotlin.* import glimpse.gles.GLES import glimpse.test.GlimpseSpec class ProgramBuilderSpec : GlimpseSpec() { init { "Program builder" should { "create both shaders" { val glesMock = glesMock() buildShaderProgram() verify(glesMock).createShader(ShaderType.VERTEX) verify(glesMock).createShader(ShaderType.FRAGMENT) } "compile both shaders" { val glesMock = glesMock() buildShaderProgram() verify(glesMock).compileShader(ShaderHandle(1), "vertex shader code") verify(glesMock).compileShader(ShaderHandle(2), "fragment shader code") } "cause exception if compilation fails" { glesMock { on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2) on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true on { getShaderCompileStatus(ShaderHandle(2)) } doReturn false on { getShaderLog(ShaderHandle(2)) } doReturn "Error" } shouldThrow<ShaderCompileException> { buildShaderProgram() } } "create a program" { val glesMock = glesMock() buildShaderProgram() verify(glesMock).createProgram() } "attach both shaders to program" { val glesMock = glesMock() buildShaderProgram() verify(glesMock).attachShader(ProgramHandle(3), ShaderHandle(1)) verify(glesMock).attachShader(ProgramHandle(3), ShaderHandle(2)) } "link a program" { val glesMock = glesMock() buildShaderProgram() verify(glesMock).linkProgram(ProgramHandle(3)) } "return a program with correct data" { val glesMock = glesMock() val program = buildShaderProgram() program.gles shouldBe glesMock program.handle shouldBe ProgramHandle(3) program.shaders should haveSize(2) program.shaders.map { it.gles }.filter { it != glesMock } should beEmpty() program.shaders.map { it.type } should containInAnyOrder(*ShaderType.values()) program.shaders.map { it.handle } should containInAnyOrder(ShaderHandle(1), ShaderHandle(2)) } "cause exception if linking fails" { glesMock { on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2) on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true on { getShaderCompileStatus(ShaderHandle(2)) } doReturn true on { createProgram() } doReturn ProgramHandle(3) on { getProgramLinkStatus(ProgramHandle(3)) } doReturn false on { getProgramLog(ProgramHandle(3)) } doReturn "Error" } shouldThrow<ProgramLinkException> { buildShaderProgram() } } } } private fun glesMock(): GLES = glesMock { on { createShader(any()) } doReturn ShaderHandle(1) doReturn ShaderHandle(2) on { getShaderCompileStatus(ShaderHandle(1)) } doReturn true on { getShaderCompileStatus(ShaderHandle(2)) } doReturn true on { createProgram() } doReturn ProgramHandle(3) on { getProgramLinkStatus(ProgramHandle(3)) } doReturn true } private fun buildShaderProgram(): Program = shaderProgram { vertexShader { "vertex shader code" } fragmentShader { "fragment shader code" } } }
apache-2.0
GlimpseFramework/glimpse-framework
materials/src/main/kotlin/glimpse/materials/AbstractMaterial.kt
1
1338
package glimpse.materials import glimpse.Point import glimpse.Vector import glimpse.cos import glimpse.lights.Light /** * Common superclass for materials. */ abstract class AbstractMaterial : Material { /** * Sets shader uniforms containing number and properties of the [lights]. */ protected operator fun ShaderHelper.set(name: String, lights: List<Light>) { this["${name}sCount"] = lights.size this["${name}Type"] = lights.map { light -> light.type }.toIntArray() this.setColors("${name}Color", lights.map { light -> light.color() }) this.setVectors("${name}Direction", lights.map { light -> when(light) { is Light.DirectionLight -> light.direction() is Light.Spotlight -> light.position() to light.target() else -> Vector.NULL } }) this.setPoints("${name}Position", lights.map { light -> when(light) { is Light.PointLight -> light.position() is Light.Spotlight -> light.position() else -> Point.ORIGIN } }) this["${name}Distance"] = lights.map { light -> when(light) { is Light.PointLight -> light.distance() is Light.Spotlight -> light.distance() else -> Float.MAX_VALUE } }.toFloatArray() this["${name}AngleCos"] = lights.map { light -> when(light) { is Light.Spotlight -> cos(light.angle() * .5f) else -> 0f } }.toFloatArray() } }
apache-2.0
ankidroid/Anki-Android
lint-rules/src/main/java/com/ichi2/anki/lint/rules/DirectGregorianInstantiation.kt
1
4042
/**************************************************************************************** * Copyright (c) 2020 lukstbit <[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, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ @file:Suppress("UnstableApiUsage") package com.ichi2.anki.lint.rules import com.android.tools.lint.detector.api.* import com.google.common.annotations.VisibleForTesting import com.ichi2.anki.lint.utils.Constants import com.ichi2.anki.lint.utils.LintUtils import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression import java.util.GregorianCalendar /** * This custom Lint rules will raise an error if a developer creates [GregorianCalendar] instances directly * instead of using the collection's getTime() method. */ class DirectGregorianInstantiation : Detector(), SourceCodeScanner { companion object { @VisibleForTesting const val ID = "DirectGregorianInstantiation" @VisibleForTesting const val DESCRIPTION = "Use the collection's getTime() method instead of directly creating GregorianCalendar instances" private const val EXPLANATION = "Creating GregorianCalendar instances directly is not allowed, as it " + "prevents control of time during testing. Use the collection's getTime() method instead" private val implementation = Implementation(DirectGregorianInstantiation::class.java, Scope.JAVA_FILE_SCOPE) val ISSUE: Issue = Issue.create( ID, DESCRIPTION, EXPLANATION, Constants.ANKI_TIME_CATEGORY, Constants.ANKI_TIME_PRIORITY, Constants.ANKI_TIME_SEVERITY, implementation ) } override fun getApplicableMethodNames() = mutableListOf("from") override fun getApplicableConstructorTypes() = mutableListOf("java.util.GregorianCalendar") override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { super.visitMethodCall(context, node, method) val evaluator = context.evaluator val foundClasses = context.uastFile!!.classes if (!LintUtils.isAnAllowedClass(foundClasses, "Time") && evaluator.isMemberInClass(method, "java.util.GregorianCalendar")) { context.report( ISSUE, context.getCallLocation(node, includeReceiver = true, includeArguments = true), DESCRIPTION ) } } override fun visitConstructor(context: JavaContext, node: UCallExpression, constructor: PsiMethod) { super.visitConstructor(context, node, constructor) val foundClasses = context.uastFile!!.classes if (!LintUtils.isAnAllowedClass(foundClasses, "Time")) { context.report( ISSUE, node, context.getLocation(node), DESCRIPTION ) } } }
gpl-3.0
LordAkkarin/Beacon
core/src/main/kotlin/tv/dotstart/beacon/core/upnp/error/ActionException.kt
1
999
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.core.upnp.error /** * Notifies a caller about an error during a UPnP action. * * @author [Johannes Donath](mailto:[email protected]) * @date 06/12/2020 */ abstract class ActionException(message: String? = null, cause: Throwable? = null) : Exception(message, cause)
apache-2.0
tipsy/javalin
javalin-openapi/src/main/java/io/javalin/plugin/openapi/annotations/AnnotationApi.kt
1
6133
package io.javalin.plugin.openapi.annotations import io.javalin.core.PathParser import io.javalin.core.util.JavalinLogger import kotlin.reflect.KClass /** * Provide metadata for the generation of the open api documentation to the annotated Handler. */ @Target(AnnotationTarget.FUNCTION, AnnotationTarget.FIELD) annotation class OpenApi( /** Ignore the endpoint in the open api documentation */ val ignore: Boolean = false, val summary: String = NULL_STRING, val description: String = NULL_STRING, val operationId: String = NULL_STRING, val deprecated: Boolean = false, val tags: Array<String> = [], val cookies: Array<OpenApiParam> = [], val headers: Array<OpenApiParam> = [], val pathParams: Array<OpenApiParam> = [], val queryParams: Array<OpenApiParam> = [], val formParams: Array<OpenApiFormParam> = [], val requestBody: OpenApiRequestBody = OpenApiRequestBody([]), val composedRequestBody: OpenApiComposedRequestBody = OpenApiComposedRequestBody([]), val fileUploads: Array<OpenApiFileUpload> = [], val responses: Array<OpenApiResponse> = [], val security: Array<OpenApiSecurity> = [], /** The path of the endpoint. This will if the annotation * couldn't be found via reflection. */ val path: String = NULL_STRING, /** The method of the endpoint. This will if the annotation * couldn't be found via reflection. */ val method: HttpMethod = HttpMethod.GET ) @Target() annotation class OpenApiResponse( val status: String, val content: Array<OpenApiContent> = [], val description: String = NULL_STRING ) @Target() annotation class OpenApiParam( val name: String, val type: KClass<*> = String::class, val description: String = NULL_STRING, val deprecated: Boolean = false, val required: Boolean = false, val allowEmptyValue: Boolean = false, val isRepeatable: Boolean = false ) @Target() annotation class OpenApiFormParam( val name: String, val type: KClass<*> = String::class, val required: Boolean = false ) @Target() annotation class OpenApiRequestBody( val content: Array<OpenApiContent>, val required: Boolean = false, val description: String = NULL_STRING ) @Target() annotation class OpenApiComposedRequestBody( val anyOf: Array<OpenApiContent> = [], val oneOf: Array<OpenApiContent> = [], val required: Boolean = false, val description: String = NULL_STRING, val contentType: String = ContentType.AUTODETECT ) @Target() annotation class OpenApiFileUpload( val name: String, val isArray: Boolean = false, val description: String = NULL_STRING, val required: Boolean = false ) @Target() annotation class OpenApiContent( val from: KClass<*> = NULL_CLASS::class, /** Whenever the schema should be wrapped in an array */ val isArray: Boolean = false, val type: String = ContentType.AUTODETECT ) @Target() annotation class OpenApiSecurity( val name: String, val scopes: Array<String> = [] ) /** Null string because annotations do not support null values */ const val NULL_STRING = "-- This string represents a null value and shouldn't be used --" /** Null class because annotations do not support null values */ class NULL_CLASS object ContentType { const val JSON = "application/json" const val HTML = "text/html" const val FORM_DATA_URL_ENCODED = "application/x-www-form-urlencoded" const val FORM_DATA_MULTIPART = "multipart/form-data" const val AUTODETECT = "AUTODETECT - Will be replaced later" } enum class ComposedType { NULL, ANY_OF, ONE_OF; } enum class HttpMethod { POST, GET, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE; } data class PathInfo(val path: String, val method: HttpMethod) val OpenApi.pathInfo get() = PathInfo(path, method) /** Checks if there are any potential bugs in the configuration */ fun OpenApi.warnUserAboutPotentialBugs(parentClass: Class<*>) { warnUserIfPathParameterIsMissingInPath(parentClass) } fun OpenApi.warnUserIfPathParameterIsMissingInPath(parentClass: Class<*>) { if (pathParams.isEmpty() || path == NULL_STRING) { // Nothing to check return } val detectedPathParams = PathParser(path, ignoreTrailingSlashes = true).pathParamNames.toSet() val pathParamsPlaceholderNotInPath = pathParams.map { it.name }.filter { it !in detectedPathParams } if (pathParamsPlaceholderNotInPath.isNotEmpty()) { JavalinLogger.warn( formatMissingPathParamsPlaceholderWarningMessage(parentClass, pathParamsPlaceholderNotInPath) ) } } fun OpenApi.formatMissingPathParamsPlaceholderWarningMessage(parentClass: Class<*>, pathParamsPlaceholders: List<String>): String { val methodAsString = method.name val multipleParams = pathParamsPlaceholders.size > 1 val secondSentence = if (multipleParams) { "The path params ${pathParamsPlaceholders.toFormattedString()} are documented, but couldn't be found in $methodAsString \"$path\"." } else { "The path param ${pathParamsPlaceholders.toFormattedString()} is documented, but couldn't be found in $methodAsString \"$path\"." } return "The `path` of one of the @OpenApi annotations on ${parentClass.canonicalName} is incorrect. " + secondSentence + " " + "You need to use Javalin's path parameter syntax inside the path and only use the parameter name for the name field." + " " + "Do you mean $methodAsString \"$path/${pathParamsPlaceholders.joinToString("/") { "{$it}" }}\"?" } fun List<String>.toFormattedString(): String { if (size == 1) { return "\"${this[0]}\"" } var result = "" this.forEachIndexed { index, s -> when { index == lastIndex -> result += " and " index > 0 -> result += ", " } result += "\"$s\"" } return result }
apache-2.0
envoyproxy/envoy
mobile/library/kotlin/io/envoyproxy/envoymobile/filters/FilterResumeStatus.kt
2
1142
package io.envoyproxy.envoymobile import java.nio.ByteBuffer /* * Status to be returned by filters after resuming iteration asynchronously. */ sealed class FilterResumeStatus<T : Headers, U : Trailers>( val status: Int ) { /** * Resume previously-stopped iteration, potentially forwarding headers, data, and/or trailers * that have not yet been passed along the filter chain. * * It is an error to return ResumeIteration if iteration is not currently stopped, and it is * an error to include headers if headers have already been forwarded to the next filter * (i.e. iteration was stopped during an on*Data invocation instead of on*Headers). It is also * an error to include data or trailers if `endStream` was previously set or if trailers have * already been forwarded. * * @param headers: Headers to be forwarded (if needed). * @param data: Data to be forwarded (if needed). * @param trailers: Trailers to be forwarded (if needed). */ class ResumeIteration<T : Headers, U : Trailers>( val headers: T?, val data: ByteBuffer?, val trailers: U? ) : FilterResumeStatus<T, U>(-1) }
apache-2.0
pdvrieze/ProcessManager
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/patterns/WCP9.kt
1
2204
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.patterns import nl.adaptivity.process.engine.* import nl.adaptivity.process.processModel.configurableModel.activity import nl.adaptivity.process.processModel.configurableModel.endNode import nl.adaptivity.process.processModel.configurableModel.join import nl.adaptivity.process.processModel.configurableModel.startNode import org.junit.jupiter.api.DisplayName @DisplayName("WCP9: Structured Discriminator") class WCP9 : TraceTest(Companion) { companion object : ConfigBase() { override val modelData: ModelData = run { val model = object : TestConfigurableModel("WCP9") { val start1 by startNode val start2 by startNode val ac1 by activity(start1) val ac2 by activity(start2) val join by join(ac1, ac2) { min = 1; max = 1 } val ac3 by activity(join) val end by endNode(ac3) } val validTraces = with(model) { trace { ((start1 .. ac1) or (start2 .. ac2)) .. join .. ac3 ..end } } val invalidTraces = with(model) { trace { val starts = (start1.opt % start2.opt).filter { it.elems.isNotEmpty() } ac1 or ac2 or (starts..(ac3 or end or join)) or (starts..ac1 % ac2) } } ModelData(model, validTraces, invalidTraces) } } }
lgpl-3.0
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/geometry/ElementGeometryCreator.kt
1
10030
package de.westnordost.streetcomplete.data.osm.geometry import de.westnordost.streetcomplete.data.osm.mapdata.MapData import de.westnordost.streetcomplete.data.osm.mapdata.* import de.westnordost.streetcomplete.ktx.isArea import de.westnordost.streetcomplete.util.centerPointOfPolygon import de.westnordost.streetcomplete.util.centerPointOfPolyline import de.westnordost.streetcomplete.util.isRingDefinedClockwise import javax.inject.Inject import kotlin.collections.ArrayList /** Creates an ElementGeometry from an element and a collection of positions. */ class ElementGeometryCreator @Inject constructor() { /** Create an ElementGeometry from any element, using the given MapData to find the positions * of the nodes. * * @param element the element to create the geometry for * @param mapData the MapData that contains the elements with the necessary * @param allowIncomplete whether incomplete relations should return an incomplete * ElementGeometry (otherwise: null) * * @return an ElementGeometry or null if any necessary element to create the geometry is not * in the given MapData */ fun create(element: Element, mapData: MapData, allowIncomplete: Boolean = false): ElementGeometry? { when(element) { is Node -> { return create(element) } is Way -> { val positions = mapData.getNodePositions(element) ?: return null return create(element, positions) } is Relation -> { val positionsByWayId = mapData.getWaysNodePositions(element, allowIncomplete) ?: return null return create(element, positionsByWayId) } else -> return null } } /** Create an ElementPointGeometry for a node. */ fun create(node: Node) = ElementPointGeometry(node.position) /** * Create an ElementGeometry for a way * * @param way the way to create the geometry for * @param wayGeometry the geometry of the way: A list of positions of its nodes. * * @return an ElementPolygonsGeometry if the way is an area or an ElementPolylinesGeometry * if the way is a linear feature */ fun create(way: Way, wayGeometry: List<LatLon>): ElementGeometry? { val polyline = ArrayList(wayGeometry) polyline.eliminateDuplicates() if (wayGeometry.size < 2) return null return if (way.isArea()) { /* ElementGeometry considers polygons that are defined clockwise holes, so ensure that it is defined CCW here. */ if (polyline.isRingDefinedClockwise()) polyline.reverse() ElementPolygonsGeometry(arrayListOf(polyline), polyline.centerPointOfPolygon()) } else { ElementPolylinesGeometry(arrayListOf(polyline), polyline.centerPointOfPolyline()) } } /** * Create an ElementGeometry for a relation * * @param relation the relation to create the geometry for * @param wayGeometries the geometries of the ways that are members of the relation. It is a * map of way ids to a list of positions. * * @return an ElementPolygonsGeometry if the relation describes an area or an * ElementPolylinesGeometry if it describes is a linear feature */ fun create(relation: Relation, wayGeometries: Map<Long, List<LatLon>>): ElementGeometry? { return if (relation.isArea()) { createMultipolygonGeometry(relation, wayGeometries) } else { createPolylinesGeometry(relation, wayGeometries) } } private fun createMultipolygonGeometry( relation: Relation, wayGeometries: Map<Long, List<LatLon>> ): ElementPolygonsGeometry? { val outer = createNormalizedRingGeometry(relation, "outer", false, wayGeometries) val inner = createNormalizedRingGeometry(relation, "inner", true, wayGeometries) if (outer.isEmpty()) return null val rings = ArrayList<ArrayList<LatLon>>() rings.addAll(outer) rings.addAll(inner) /* only use first ring that is not a hole if there are multiple this is the same behavior as Leaflet or Tangram */ return ElementPolygonsGeometry(rings, outer.first().centerPointOfPolygon()) } private fun createPolylinesGeometry( relation: Relation, wayGeometries: Map<Long, List<LatLon>> ): ElementPolylinesGeometry? { val waysNodePositions = getRelationMemberWaysNodePositions(relation, wayGeometries) val joined = waysNodePositions.joined() val polylines = joined.ways polylines.addAll(joined.rings) if (polylines.isEmpty()) return null /* if there are more than one polylines, these polylines are not connected to each other, so there is no way to find a reasonable "center point". In most cases however, there is only one polyline, so let's just take the first one... This is the same behavior as Leaflet or Tangram */ return ElementPolylinesGeometry(polylines, polylines.first().centerPointOfPolyline()) } private fun createNormalizedRingGeometry( relation: Relation, role: String, clockwise: Boolean, wayGeometries: Map<Long, List<LatLon>> ): ArrayList<ArrayList<LatLon>> { val waysNodePositions = getRelationMemberWaysNodePositions(relation, role, wayGeometries) val ringGeometry = waysNodePositions.joined().rings ringGeometry.setOrientation(clockwise) return ringGeometry } private fun getRelationMemberWaysNodePositions( relation: Relation, wayGeometries: Map<Long, List<LatLon>> ): List<List<LatLon>> { return relation.members .filter { it.type == ElementType.WAY } .mapNotNull { getValidNodePositions(wayGeometries[it.ref]) } } private fun getRelationMemberWaysNodePositions( relation: Relation, withRole: String, wayGeometries: Map<Long, List<LatLon>> ): List<List<LatLon>> { return relation.members .filter { it.type == ElementType.WAY && it.role == withRole } .mapNotNull { getValidNodePositions(wayGeometries[it.ref]) } } private fun getValidNodePositions(wayGeometry: List<LatLon>?): List<LatLon>? { if (wayGeometry == null) return null val nodePositions = ArrayList(wayGeometry) nodePositions.eliminateDuplicates() return if (nodePositions.size >= 2) nodePositions else null } } /** Ensures that all given rings are defined in clockwise/counter-clockwise direction */ private fun List<MutableList<LatLon>>.setOrientation(clockwise: Boolean) { for (ring in this) { if (ring.isRingDefinedClockwise() != clockwise) { ring.reverse() } } } private fun List<LatLon>.isRing() = first() == last() private class ConnectedWays(val rings: ArrayList<ArrayList<LatLon>>, val ways: ArrayList<ArrayList<LatLon>>) /** Returns a list of polylines joined together at their endpoints into rings and ways */ private fun List<List<LatLon>>.joined(): ConnectedWays { val nodeWayMap = NodeWayMap(this) val rings: ArrayList<ArrayList<LatLon>> = ArrayList() val ways: ArrayList<ArrayList<LatLon>> = ArrayList() var currentWay: ArrayList<LatLon> = ArrayList() while (nodeWayMap.hasNextNode()) { val node: LatLon = if (currentWay.isEmpty()) nodeWayMap.getNextNode() else currentWay.last() val waysAtNode = nodeWayMap.getWaysAtNode(node) if (waysAtNode == null) { ways.add(currentWay) currentWay = ArrayList() } else { val way = waysAtNode.first() currentWay.join(way) nodeWayMap.removeWay(way) // finish ring and start new one if (currentWay.isRing()) { rings.add(currentWay) currentWay = ArrayList() } } } if (currentWay.isNotEmpty()) { ways.add(currentWay) } return ConnectedWays(rings, ways) } /** Join the given adjacent polyline into this polyline */ private fun MutableList<LatLon>.join(way: List<LatLon>) { if (isEmpty()) { addAll(way) } else { when { last() == way.last() -> addAll(way.asReversed().subList(1, way.size)) last() == way.first() -> addAll(way.subList(1, way.size)) first() == way.last() -> addAll(0, way.subList(0, way.size - 1)) first() == way.first() -> addAll(0, way.asReversed().subList(0, way.size - 1)) else -> throw IllegalArgumentException("The ways are not adjacent") } } } private fun MutableList<LatLon>.eliminateDuplicates() { val it = iterator() var prev: LatLon? = null while (it.hasNext()) { val line = it.next() if (prev == null || line.latitude != prev.latitude || line.longitude != prev.longitude) { prev = line } else { it.remove() } } } private fun MapData.getNodePositions(way: Way): List<LatLon>? { return way.nodeIds.map { nodeId -> val node = getNode(nodeId) ?: return null node.position } } private fun MapData.getWaysNodePositions(relation: Relation, allowIncomplete: Boolean = false): Map<Long, List<LatLon>>? { val wayMembers = relation.members.filter { it.type == ElementType.WAY } val result = mutableMapOf<Long, List<LatLon>>() for (wayMember in wayMembers) { val way = getWay(wayMember.ref) if (way != null) { val wayPositions = getNodePositions(way) if (wayPositions != null) { result[way.id] = wayPositions } else { if (!allowIncomplete) return null } } else { if (!allowIncomplete) return null } } return result }
gpl-3.0
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/auth/LoginFragment.kt
1
9184
package org.fossasia.openevent.general.auth import android.os.Bundle import android.text.Editable import android.text.SpannableStringBuilder import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import kotlinx.android.synthetic.main.fragment_login.email import kotlinx.android.synthetic.main.fragment_login.loginButton import kotlinx.android.synthetic.main.fragment_login.password import kotlinx.android.synthetic.main.fragment_login.view.* import kotlinx.android.synthetic.main.fragment_login.view.email import kotlinx.android.synthetic.main.fragment_login.view.skipTextView import kotlinx.android.synthetic.main.fragment_login.view.toolbar import org.fossasia.openevent.general.BuildConfig import org.fossasia.openevent.general.PLAY_STORE_BUILD_FLAVOR import org.fossasia.openevent.general.R import org.fossasia.openevent.general.event.EVENT_DETAIL_FRAGMENT import org.fossasia.openevent.general.favorite.FAVORITE_FRAGMENT import org.fossasia.openevent.general.notification.NOTIFICATION_FRAGMENT import org.fossasia.openevent.general.order.ORDERS_FRAGMENT import org.fossasia.openevent.general.search.ORDER_COMPLETED_FRAGMENT import org.fossasia.openevent.general.search.SEARCH_RESULTS_FRAGMENT import org.fossasia.openevent.general.speakercall.SPEAKERS_CALL_FRAGMENT import org.fossasia.openevent.general.ticket.TICKETS_FRAGMENT import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard import org.fossasia.openevent.general.utils.Utils.progressDialog import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.Utils.showNoInternetDialog import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.extensions.setSharedElementEnterTransition import org.jetbrains.anko.design.longSnackbar import org.jetbrains.anko.design.snackbar import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class LoginFragment : Fragment() { private val loginViewModel by viewModel<LoginViewModel>() private val smartAuthViewModel by sharedViewModel<SmartAuthViewModel>() private lateinit var rootView: View private val safeArgs: LoginFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_login, container, false) val progressDialog = progressDialog(context) setToolbar(activity, show = false) rootView.toolbar.setNavigationOnClickListener { activity?.onBackPressed() } rootView.settings.setOnClickListener { findNavController(rootView).navigate(LoginFragmentDirections.actionLoginToSetting()) } if (loginViewModel.isLoggedIn()) popBackStack() rootView.loginButton.setOnClickListener { loginViewModel.login(email.text.toString(), password.text.toString()) hideSoftKeyboard(context, rootView) } rootView.skipTextView.isVisible = safeArgs.showSkipButton rootView.skipTextView.setOnClickListener { findNavController(rootView).navigate( LoginFragmentDirections.actionLoginToEventsPop() ) } if (safeArgs.email.isNotEmpty()) { setSharedElementEnterTransition() rootView.email.text = SpannableStringBuilder(safeArgs.email) rootView.email.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) { if (s.toString() != safeArgs.email) { findNavController(rootView).navigate(LoginFragmentDirections .actionLoginToAuthPop(redirectedFrom = safeArgs.redirectedFrom, email = s.toString())) rootView.email.removeTextChangedListener(this) } } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { /*Do Nothing*/ } override fun onTextChanged(email: CharSequence, start: Int, before: Int, count: Int) { /*Do Nothing*/ } }) } else if (BuildConfig.FLAVOR == PLAY_STORE_BUILD_FLAVOR) { smartAuthViewModel.requestCredentials(SmartAuthUtil.getCredentialsClient(requireActivity())) smartAuthViewModel.id .nonNull() .observe(viewLifecycleOwner, Observer { email.text = SpannableStringBuilder(it) }) smartAuthViewModel.password .nonNull() .observe(viewLifecycleOwner, Observer { password.text = SpannableStringBuilder(it) }) smartAuthViewModel.apiExceptionCodePair.nonNull().observe(viewLifecycleOwner, Observer { SmartAuthUtil.handleResolvableApiException( it.first, requireActivity(), it.second) }) smartAuthViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) } loginViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) loginViewModel.showNoInternetDialog .nonNull() .observe(viewLifecycleOwner, Observer { showNoInternetDialog(context) }) loginViewModel.error .nonNull() .observe(viewLifecycleOwner, Observer { rootView.loginCoordinatorLayout.longSnackbar(it) }) loginViewModel.loggedIn .nonNull() .observe(viewLifecycleOwner, Observer { loginViewModel.fetchProfile() }) rootView.password.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(password: CharSequence, start: Int, before: Int, count: Int) { loginButton.isEnabled = password.isNotEmpty() } }) loginViewModel.requestTokenSuccess .nonNull() .observe(viewLifecycleOwner, Observer { if (it.status) { rootView.mailSentTextView.text = it.message rootView.sentEmailLayout.isVisible = true rootView.tick.isVisible = true rootView.loginLayout.isVisible = false rootView.toolbar.isVisible = true } else { rootView.toolbar.isVisible = false } }) rootView.tick.setOnClickListener { rootView.sentEmailLayout.isVisible = false rootView.tick.isVisible = false rootView.toolbar.isVisible = true rootView.loginLayout.isVisible = true } rootView.forgotPassword.setOnClickListener { hideSoftKeyboard(context, rootView) loginViewModel.sendResetPasswordEmail(email.text.toString()) } loginViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { if (BuildConfig.FLAVOR == PLAY_STORE_BUILD_FLAVOR) { smartAuthViewModel.saveCredential( email.text.toString(), password.text.toString(), SmartAuthUtil.getCredentialsClient(requireActivity())) } popBackStack() }) return rootView } private fun popBackStack() { val destinationId = when (safeArgs.redirectedFrom) { PROFILE_FRAGMENT -> R.id.profileFragment EVENT_DETAIL_FRAGMENT -> R.id.eventDetailsFragment ORDERS_FRAGMENT -> R.id.orderUnderUserFragment TICKETS_FRAGMENT -> R.id.ticketsFragment NOTIFICATION_FRAGMENT -> R.id.notificationFragment SPEAKERS_CALL_FRAGMENT -> R.id.speakersCallFragment FAVORITE_FRAGMENT -> R.id.favoriteFragment SEARCH_RESULTS_FRAGMENT -> R.id.searchResultsFragment ORDER_COMPLETED_FRAGMENT -> R.id.orderCompletedFragment else -> R.id.eventsFragment } if (destinationId == R.id.eventsFragment) { findNavController(rootView).navigate(LoginFragmentDirections.actionLoginToEventsPop()) } else { findNavController(rootView).popBackStack(destinationId, false) } rootView.snackbar(R.string.welcome_back) } }
apache-2.0
BasinMC/Basin
faucet/src/main/kotlin/org/basinmc/faucet/network/NetDirection.kt
1
921
/* * Copyright 2016 Hex <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License&quot; * 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.basinmc.faucet.network /** * Holds the two directions in which packets can be sent. */ enum class NetDirection { /** * Client-to-server packet */ SERVERBOUND, /** * Server-to-client packet */ CLIENTBOUND }
apache-2.0
fossasia/open-event-android
app/src/test/java/org/fossasia/openevent/general/event/EventUtilsTest.kt
1
6546
package org.fossasia.openevent.general.event import java.time.ZoneId import java.util.TimeZone import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.threeten.bp.ZonedDateTime class EventUtilsTest { private var timeZone: TimeZone? = null @Before fun setUp() { // Set fixed local time zone for tests timeZone = TimeZone.getDefault() TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of("Asia/Kolkata"))) } @After fun tearDown() { TimeZone.setDefault(timeZone) } private fun getEvent( id: Long = 34, name: String = "Eva Event", identifier: String = "abcdefgh", startsAt: String = "2008-09-15T15:53:00+05:00", endsAt: String = "2008-09-19T19:25:00+05:00", timeZone: String = "Asia/Kolkata", description: String? = null, locationName: String? = "Test Location", link: String? = null ) = Event(id, name, identifier, startsAt, endsAt, timeZone, locationName = locationName, description = description, externalEventUrl = link) private fun getEventDateTime(dateTime: String, timeZone: String): ZonedDateTime = EventUtils.getEventDateTime(dateTime, timeZone) @Test fun `should get timezone name`() { val event = getEvent() val localizedDateTime = getEventDateTime(event.startsAt, event.timezone) assertEquals(""" IST """.trimIndent(), EventUtils.getFormattedTimeZone(localizedDateTime)) } @Test fun `should get formatted time`() { val event = getEvent() val localizedDateTime = getEventDateTime(event.startsAt, event.timezone) assertEquals(""" 04:23 PM """.trimIndent(), EventUtils.getFormattedTime(localizedDateTime)) } @Test fun `should get formatted date and time without year`() { val event = getEvent() val localizedDateTime = getEventDateTime(event.startsAt, event.timezone) assertEquals(""" Monday, Sep 15 """.trimIndent(), EventUtils.getFormattedDateWithoutYear(localizedDateTime)) } @Test fun `should get formatted date short`() { val event = getEvent() val localizedDateTime = getEventDateTime(event.startsAt, event.timezone) assertEquals(""" Mon, Sep 15 """.trimIndent(), EventUtils.getFormattedDateShort(localizedDateTime)) } @Test fun `should get formatted date`() { val event = getEvent() val localizedDateTime = getEventDateTime(event.startsAt, event.timezone) assertEquals(""" Monday, September 15, 2008 """.trimIndent(), EventUtils.getFormattedDate(localizedDateTime)) } @Test fun `should get formatted date range when start and end date are not same`() { val event = getEvent() val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" Mon, Sep 15, 04:23 PM """.trimIndent(), EventUtils.getFormattedEventDateTimeRange(startsAt, endsAt)) } @Test fun `should get formatted date range when start and end date are same`() { val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00") val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" Monday, Sep 15 """.trimIndent(), EventUtils.getFormattedEventDateTimeRange(startsAt, endsAt)) } @Test fun `should get formatted date range when start and end date are not same in event details`() { val event = getEvent() val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" - Fri, Sep 19, 07:55 PM IST """.trimIndent(), EventUtils.getFormattedEventDateTimeRangeSecond(startsAt, endsAt)) } @Test fun `should get formatted date range when start and end date are same in event details`() { val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00") val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" 04:23 PM - 04:23 PM IST """.trimIndent(), EventUtils.getFormattedEventDateTimeRangeSecond(startsAt, endsAt)) } @Test fun `should get formatted date range when start and end date are not same in details`() { val event = getEvent() val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" Monday, September 15, 2008 at 04:23 PM - Friday, September 19, 2008 at 07:55 PM (IST) """.trimIndent(), EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt)) } @Test fun `should get formatted date range when start and end date are same in details`() { val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00") val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" Monday, September 15, 2008 from 04:23 PM to 04:23 PM (IST) """.trimIndent(), EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt)) } @Test fun `should get formatted date range bulleted when start and end date are not same in details`() { val event = getEvent() val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" Mon, Sep 15 - Fri, Sep 19 • 04:23 PM IST """.trimIndent(), EventUtils.getFormattedDateTimeRangeBulleted(startsAt, endsAt)) } @Test fun `should get formatted date range bulleted when start and end date are same in details`() { val event = getEvent(endsAt = "2008-09-15T15:53:00+05:00") val startsAt = getEventDateTime(event.startsAt, event.timezone) val endsAt = getEventDateTime(event.endsAt, event.timezone) assertEquals(""" Mon, Sep 15 • 04:23 PM IST """.trimIndent(), EventUtils.getFormattedDateTimeRangeBulleted(startsAt, endsAt)) } }
apache-2.0
ekager/focus-android
app/src/main/java/org/mozilla/focus/fragment/CrashReporterFragment.kt
1
1567
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_crash_reporter.* import org.mozilla.focus.R import org.mozilla.focus.telemetry.TelemetryWrapper class CrashReporterFragment : Fragment() { var onCloseTabPressed: ((sendCrashReport: Boolean) -> Unit)? = null private var wantsSubmitCrashReport = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_crash_reporter, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) TelemetryWrapper.crashReporterOpened() closeTabButton.setOnClickListener { wantsSubmitCrashReport = sendCrashCheckbox.isChecked TelemetryWrapper.crashReporterClosed(wantsSubmitCrashReport) onCloseTabPressed?.invoke(wantsSubmitCrashReport) } } fun onBackPressed() { TelemetryWrapper.crashReporterClosed(false) } companion object { val FRAGMENT_TAG = "crash-reporter" fun create() = CrashReporterFragment() } }
mpl-2.0
googleapis/gapic-generator-kotlin
generator/src/main/kotlin/com/google/api/kotlin/util/FieldNamer.kt
1
6757
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin.util import com.google.api.kotlin.config.PropertyPath import com.google.api.kotlin.config.ProtobufTypeMapper import com.squareup.kotlinpoet.CodeBlock import mu.KotlinLogging private val log = KotlinLogging.logger {} /** * Utilities for creating field names, getters, setters, and accessors. */ internal object FieldNamer { /* * Create setter code based on type of field (map vs. repeated, vs. single object) using * the DSL builder for the type. */ fun getDslSetterCode( typeMap: ProtobufTypeMapper, fieldInfo: ProtoFieldInfo, value: CodeBlock ): CodeBlock = when { fieldInfo.field.isMap(typeMap) -> { val name = getDslSetterMapName(fieldInfo.field.name) CodeBlock.of( "this.$name = %L", value ) } fieldInfo.field.isRepeated() -> { if (fieldInfo.index >= 0) { log.warn { "Indexed setter operations currently ignore the specified index! (${fieldInfo.message.name}.${fieldInfo.field.name})" } CodeBlock.of( "this.${getDslSetterRepeatedNameAtIndex(fieldInfo.field.name)}(%L)", value ) } else { val name = getDslSetterRepeatedName(fieldInfo.field.name) CodeBlock.of( "this.$name = %L", value ) } } else -> { // normal fields val name = getFieldName(fieldInfo.field.name) CodeBlock.of("this.$name = %L", value) } } fun getDslSetterCode( typeMap: ProtobufTypeMapper, fieldInfo: ProtoFieldInfo, value: String ) = getDslSetterCode(typeMap, fieldInfo, CodeBlock.of("%L", value)) /** * Get the accessor field name for a Java proto message type. */ fun getJavaAccessorName(typeMap: ProtobufTypeMapper, fieldInfo: ProtoFieldInfo): String { if (fieldInfo.field.isMap(typeMap)) { return getJavaBuilderAccessorMapName(fieldInfo.field.name) } else if (fieldInfo.field.isRepeated()) { return if (fieldInfo.index >= 0) { "${getJavaBuilderAccessorRepeatedName(fieldInfo.field.name)}[${fieldInfo.index}]" } else { getJavaBuilderAccessorRepeatedName(fieldInfo.field.name) } } return getJavaBuilderAccessorName(fieldInfo.field.name) } fun getNestedFieldName(p: PropertyPath): String = p.segments.map { it.asVarName() }.joinToString(".") fun getFieldName(protoFieldName: String): String = protoFieldName.asVarName() private fun getDslSetterMapName(protoFieldName: String): String = protoFieldName.asVarName().escapeIfReserved() private fun getDslSetterRepeatedName(protoFieldName: String): String = protoFieldName.asVarName().escapeIfReserved() private fun getDslSetterRepeatedNameAtIndex(protoFieldName: String): String = protoFieldName.asVarName().escapeIfReserved() fun getJavaBuilderSetterMapName(protoFieldName: String): String = "putAll${protoFieldName.asVarName(false)}".escapeIfReserved() fun getJavaBuilderSetterRepeatedName(protoFieldName: String): String = "addAll${protoFieldName.asVarName(false)}".escapeIfReserved() fun getJavaBuilderRawSetterName(protoFieldName: String): String = "set${protoFieldName.asVarName(false)}".escapeIfReserved() fun getJavaBuilderSyntheticSetterName(protoFieldName: String): String = protoFieldName.asVarName().escapeIfReserved() fun getJavaBuilderAccessorMapName(protoFieldName: String): String = "${protoFieldName.asVarName()}Map".escapeIfReserved() fun getJavaBuilderAccessorRepeatedName(protoFieldName: String): String = "${protoFieldName.asVarName()}List".escapeIfReserved() fun getJavaBuilderAccessorName(protoFieldName: String): String = protoFieldName.asVarName().escapeIfReserved() private fun String.asVarName(isLower: Boolean = true): String = this.underscoresToCamelCase(!isLower) private val LEADING_UNDERSCORES = Regex("^(_)+") // this is taken from the protobuf utility of the same name // snapshot: https://github.com/protocolbuffers/protobuf/blob/61301f01552dd84d744a05c88af95833c600a1a7/src/google/protobuf/compiler/cpp/cpp_helpers.cc private fun String.underscoresToCamelCase(capitalize: Boolean): String { var cap = capitalize val result = StringBuffer() // addition to the protobuf rule to handle synthetic names var str = this.replace(LEADING_UNDERSCORES, "") for (char in str) { if (char.isLetter() && char.isLowerCase()) { result.append(if (cap) char.toUpperCase() else char) cap = false } else if (char.isLetter() && char.isUpperCase()) { result.append(char) cap = false } else if (char.isDigit()) { result.append(char) cap = true } else { cap = true } } str = result.toString() // addition to the protobuf rule to handle synthetic names if (!capitalize) { if (str.matches(Regex("[a-z0-9][A-Z0-9]+"))) { str = str.toLowerCase() } } return str } // TODO: can remove this when Kotlin poet releases %M support private fun String.escapeIfReserved() = if (KEYWORDS.contains(this)) "`$this`" else this private val KEYWORDS = setOf( "package", "as", "typealias", "class", "this", "super", "val", "var", "fun", "for", "null", "true", "false", "is", "in", "throw", "return", "break", "continue", "object", "if", "try", "else", "while", "do", "when", "interface", "typeof" ) }
apache-2.0