package venus.riscv.insts.dsl

import venus.assembler.AssemblerError
import venus.riscv.MachineCode
import venus.riscv.insts.dsl.formats.InstructionFormat
import venus.riscv.insts.dsl.impls.InstructionImplementation
import venus.riscv.insts.dsl.parsers.InstructionParser

open class Instruction(
        private val name: String,
        val format: InstructionFormat,
        val parser: InstructionParser,
        val impl32: InstructionImplementation,
        val impl64: InstructionImplementation
) {
    companion object {
        private val allInstructions = arrayListOf<Instruction>()

        operator fun get(mcode: MachineCode): Instruction =
                allInstructions.filter { it.format.length == mcode.length }
                        .firstOrNull { it.format.matches(mcode) }
                        ?: throw AssemblerError("instruction not found for $mcode")

        operator fun get(name: String) =
                allInstructions.firstOrNull { it.name == name }
                        ?: throw AssemblerError("instruction with name $name not found")
    }

    init {
        allInstructions.add(this)
    }
}

Add toString to see current instruction

package venus.riscv.insts.dsl

import venus.assembler.AssemblerError
import venus.riscv.MachineCode
import venus.riscv.insts.dsl.formats.InstructionFormat
import venus.riscv.insts.dsl.impls.InstructionImplementation
import venus.riscv.insts.dsl.parsers.InstructionParser

open class Instruction(
        private val name: String,
        val format: InstructionFormat,
        val parser: InstructionParser,
        val impl32: InstructionImplementation,
        val impl64: InstructionImplementation
) {
    companion object {
        private val allInstructions = arrayListOf<Instruction>()

        operator fun get(mcode: MachineCode): Instruction =
                allInstructions.filter { it.format.length == mcode.length }
                        .firstOrNull { it.format.matches(mcode) }
                        ?: throw AssemblerError("instruction not found for $mcode")

        operator fun get(name: String) =
                allInstructions.firstOrNull { it.name == name }
                        ?: throw AssemblerError("instruction with name $name not found")
    }

    init {
        allInstructions.add(this)
    }

    override fun toString() = name
}


package venus.riscv.insts.dsl

import venus.assembler.AssemblerError
import venus.riscv.MachineCode
import venus.riscv.insts.dsl.disasms.InstructionDisassembler
import venus.riscv.insts.dsl.formats.InstructionFormat
import venus.riscv.insts.dsl.impls.InstructionImplementation
import venus.riscv.insts.dsl.parsers.InstructionParser

open class Instruction(
        val name: String,
        val format: InstructionFormat,
        val parser: InstructionParser,
        val impl32: InstructionImplementation,
        val impl64: InstructionImplementation,
        val disasm: InstructionDisassembler
) {
    companion object {
        private val allInstructions = arrayListOf<Instruction>()

        operator fun get(mcode: MachineCode): Instruction =
                allInstructions.filter { it.format.length == mcode.length }
                        .firstOrNull { it.format.matches(mcode) }
                        ?: throw AssemblerError("instruction not found for $mcode")

        operator fun get(name: String) =
                allInstructions.firstOrNull { it.name == name }
                        ?: throw AssemblerError("instruction with name $name not found")
    }

    init {
        allInstructions.add(this)
    }

    override fun toString() = name
}

Change to throw SimulatorError when appropriate

package venus.riscv.insts.dsl

import venus.assembler.AssemblerError
import venus.riscv.MachineCode
import venus.riscv.insts.dsl.disasms.InstructionDisassembler
import venus.riscv.insts.dsl.formats.InstructionFormat
import venus.riscv.insts.dsl.impls.InstructionImplementation
import venus.riscv.insts.dsl.parsers.InstructionParser
import venus.simulator.SimulatorError

open class Instruction(
        val name: String,
        val format: InstructionFormat,
        val parser: InstructionParser,
        val impl32: InstructionImplementation,
        val impl64: InstructionImplementation,
        val disasm: InstructionDisassembler
) {
    companion object {
        private val allInstructions = arrayListOf<Instruction>()

        operator fun get(mcode: MachineCode): Instruction =
                allInstructions.filter { it.format.length == mcode.length }
                        .firstOrNull { it.format.matches(mcode) }
                        ?: throw SimulatorError("instruction not found for $mcode")

        operator fun get(name: String) =
                allInstructions.firstOrNull { it.name == name }
                        ?: throw AssemblerError("instruction with name $name not found")
    }

    init {
        allInstructions.add(this)
    }

    override fun toString() = name
}


plugins {
  id("io.quarkus").apply(false)
}

allprojects {

  group = "org.acme"
  version = "1.0.0-SNAPSHOT"

  repositories {
    if (System.getProperties().containsKey("maven.repo.local")) {
      maven(url = System.getProperties().get("maven.repo.local")!!)
    } else {
      mavenLocal()
    }
    mavenCentral()
  }

}

subprojects {

  apply(plugin = "java")
  apply(plugin = "jacoco")
  apply(plugin = "io.quarkus")

  val quarkusPlatformGroupId: String by project
  val quarkusPlatformArtifactId: String by project
  val quarkusPlatformVersion: String by project

  val javaVersion = "11"

  dependencies {
    "implementation"(enforcedPlatform("$quarkusPlatformGroupId:$quarkusPlatformArtifactId:$quarkusPlatformVersion"))

    "testImplementation"("io.quarkus:quarkus-junit5")
    "testImplementation"("io.rest-assured:rest-assured")
  }

  configure<JavaPluginExtension> {
    sourceCompatibility = JavaVersion.toVersion(javaVersion)
    targetCompatibility = JavaVersion.toVersion(javaVersion)
  }

  tasks {

    withType<JavaCompile>().configureEach {
      options.encoding = "UTF-8"
      options.compilerArgs.add("-parameters")
    }

    named<Test>("test") {
      systemProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager")
    }

  }

}

Fix Gradle test not using Java 8

plugins {
  id("io.quarkus").apply(false)
}

allprojects {

  group = "org.acme"
  version = "1.0.0-SNAPSHOT"

  repositories {
    if (System.getProperties().containsKey("maven.repo.local")) {
      maven(url = System.getProperties().get("maven.repo.local")!!)
    } else {
      mavenLocal()
    }
    mavenCentral()
  }

}

subprojects {

  apply(plugin = "java")
  apply(plugin = "jacoco")
  apply(plugin = "io.quarkus")

  val quarkusPlatformGroupId: String by project
  val quarkusPlatformArtifactId: String by project
  val quarkusPlatformVersion: String by project

  val javaVersion = "8"

  dependencies {
    "implementation"(enforcedPlatform("$quarkusPlatformGroupId:$quarkusPlatformArtifactId:$quarkusPlatformVersion"))

    "testImplementation"("io.quarkus:quarkus-junit5")
    "testImplementation"("io.rest-assured:rest-assured")
  }

  configure<JavaPluginExtension> {
    sourceCompatibility = JavaVersion.toVersion(javaVersion)
    targetCompatibility = JavaVersion.toVersion(javaVersion)
  }

  tasks {

    withType<JavaCompile>().configureEach {
      options.encoding = "UTF-8"
      options.compilerArgs.add("-parameters")
    }

    named<Test>("test") {
      systemProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager")
    }

  }

}


import org.gradle.api.tasks.*
import org.apache.tools.ant.filters.*

//for including in the copy task
val dataContent = copySpec {
    it.from("src/data")
    it.include("*.data")
}

task<Copy>("initConfig") {

    from("src/main/config") {
        it.include("**/*.properties")
        it.include("**/*.xml")
        it.filter<ReplaceTokens>(
            "tokens" to mapOf("version" to "2.3.1"))
    }

    from("src/main/languages") {
        it.rename("EN_US_(.*)", "$1")
    }

    into("build/target/config")
    exclude("**/*.bak")
    includeEmptyDirs = false
    with(dataContent)
}

task<Delete>("clean") {
    delete(buildDir)
}

Fix copy sample to work against latest Gradle API

import org.gradle.api.file.*
import org.gradle.api.tasks.*
import org.apache.tools.ant.filters.*

//for including in the copy task
val dataContent = copySpec {
    it.from("src/data")
    it.include("*.data")
}

task<Copy>("initConfig") {

    from("src/main/config").let { it as CopySpec }.apply {
        include("**/*.properties")
        include("**/*.xml")
        filter<ReplaceTokens>(
            "tokens" to mapOf("version" to "2.3.1"))
    }

    from("src/main/languages").let { it as CopySpec }.apply {
        rename("EN_US_(.*)", "$1")
    }

    into("build/target/config")
    exclude("**/*.bak")
    includeEmptyDirs = false
    with(dataContent)
}

task<Delete>("clean") {
    delete(buildDir)
}


package nl.rubensten.texifyidea.run

import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.KillableProcessHandler
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.process.ProcessTerminatedListener
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.roots.ProjectRootManager

/**
 * @author Sten Wessel
 */
open class BibtexCommandLineState(
        environment: ExecutionEnvironment,
        private val runConfig: BibtexRunConfiguration
) : CommandLineState(environment) {

    @Throws(ExecutionException::class)
    override fun startProcess(): ProcessHandler {
        val rootManager = ProjectRootManager.getInstance(environment.project)
        val fileIndex = rootManager.fileIndex
        val moduleRoot = fileIndex.getContentRootForFile(runConfig.mainFile!!)

        val compiler = runConfig.compiler ?: throw ExecutionException("No valid compiler specified.")
        val command: List<String> = compiler.getCommand(runConfig, environment.project) ?: throw ExecutionException("Compile command could not be created.")

        // The working directory is as specified by the user in the working directory.
        // The fallback (if null) directory is the directory of the main file.
        val commandLine = GeneralCommandLine(command).withWorkDirectory(runConfig.bibWorkingDir?.path ?: runConfig.mainFile?.parent?.path)

        val handler: ProcessHandler = KillableProcessHandler(commandLine)

        // Reports exit code to run output window when command is terminated
        ProcessTerminatedListener.attach(handler, environment.project)

        return handler
    }
}

Enable the out directory on all systems, on by default

package nl.rubensten.texifyidea.run

import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.CommandLineState
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.KillableProcessHandler
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.process.ProcessTerminatedListener
import com.intellij.execution.runners.ExecutionEnvironment

/**
 * @author Sten Wessel
 */
open class BibtexCommandLineState(
        environment: ExecutionEnvironment,
        private val runConfig: BibtexRunConfiguration
) : CommandLineState(environment) {

    @Throws(ExecutionException::class)
    override fun startProcess(): ProcessHandler {

        val compiler = runConfig.compiler ?: throw ExecutionException("No valid compiler specified.")
        val command: List<String> = compiler.getCommand(runConfig, environment.project) ?: throw ExecutionException("Compile command could not be created.")

        // The working directory is as specified by the user in the working directory.
        // The fallback (if null or empty) directory is the directory of the main file.
        val bibPath = runConfig.bibWorkingDir?.path
        val commandLine = if (!(bibPath.equals("") || bibPath == null)) {
            GeneralCommandLine(command).withWorkDirectory(bibPath)
        }
        else {
            GeneralCommandLine(command).withWorkDirectory(runConfig.mainFile?.parent?.path)
        }

        val handler: ProcessHandler = KillableProcessHandler(commandLine)

        // Reports exit code to run output window when command is terminated
        ProcessTerminatedListener.attach(handler, environment.project)

        return handler
    }
}


package org.gradle.gradlebuild

import org.gradle.api.JavaVersion
import org.gradle.internal.os.OperatingSystem

object BuildEnvironment {
    val isCiServer = "CI" in System.getenv()
    val gradleKotlinDslVersion = "0.19.4"
    val jvm = org.gradle.internal.jvm.Jvm.current()
    val javaVersion = JavaVersion.current()
    val isWindows = OperatingSystem.current().isWindows
    val agentNum: Int
        get() {
            if (System.getenv().containsKey("USERNAME")) {
                val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
                if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
                    return agentNumEnv.toInt()
                }
            }
            return 1
        }
}

Upgrade Kotlin DSL `0.19.{4 => 5}`

package org.gradle.gradlebuild

import org.gradle.api.JavaVersion
import org.gradle.internal.os.OperatingSystem

object BuildEnvironment {
    val isCiServer = "CI" in System.getenv()
    val gradleKotlinDslVersion = "0.19.5"
    val jvm = org.gradle.internal.jvm.Jvm.current()
    val javaVersion = JavaVersion.current()
    val isWindows = OperatingSystem.current().isWindows
    val agentNum: Int
        get() {
            if (System.getenv().containsKey("USERNAME")) {
                val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
                if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
                    return agentNumEnv.toInt()
                }
            }
            return 1
        }
}


package com.masahirosaito.spigot.homes

object Permission {
    val home_command = "homes.command"
    val home_command_name = home_command + ".name"
    val home_command_player = home_command + ".player"
    val home_command_player_name = home_command_player + ".name"
    val home_command_set = home_command + ".set"
    val home_command_set_name = home_command_set + ".name"
}

Add permission of list command

package com.masahirosaito.spigot.homes

object Permission {
    val home_command = "homes.command"
    val home_command_name = home_command + ".name"
    val home_command_player = home_command + ".player"
    val home_command_player_name = home_command_player + ".name"
    val home_command_set = home_command + ".set"
    val home_command_set_name = home_command_set + ".name"
    val home_command_list = home_command + ".list"
}


package org.jetbrains.dokka

import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiNameIdentifierOwner
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.resolve.BindingContext
import javax.inject.Inject

class KotlinElementSignatureProvider @Inject constructor(
        val resolutionFacade: DokkaResolutionFacade
) : ElementSignatureProvider {
    override fun signature(forPsi: PsiElement): String {

        val desc = when (forPsi) {
            is KtLightElement<*, *> -> return signature(forPsi.kotlinOrigin!!)
            is PsiMember -> forPsi.getJavaOrKotlinMemberDescriptor(resolutionFacade)
            else -> resolutionFacade.resolveSession.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, forPsi]
        }

        if (desc == null && (forPsi as? PsiNameIdentifierOwner)?.name == "remove") {
            (forPsi as? PsiMember)?.getJavaOrKotlinMemberDescriptor(resolutionFacade)
        }

        return desc?.let { signature(it) }
                ?: run { "no desc for $forPsi in ${(forPsi as? PsiMember)?.containingClass}" }
    }

    override fun signature(forDesc: DeclarationDescriptor): String = forDesc.signature()
}

Fix resolution of package links

package org.jetbrains.dokka

import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.PsiPackage
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.BindingContext
import javax.inject.Inject

class KotlinElementSignatureProvider @Inject constructor(
        val resolutionFacade: DokkaResolutionFacade
) : ElementSignatureProvider {
    override fun signature(forPsi: PsiElement): String {

        val desc = when (forPsi) {
            is KtLightElement<*, *> -> return signature(forPsi.kotlinOrigin!!)
            is PsiPackage -> resolutionFacade.moduleDescriptor.getPackage(FqName(forPsi.qualifiedName))
            is PsiMember -> forPsi.getJavaOrKotlinMemberDescriptor(resolutionFacade)
            else -> resolutionFacade.resolveSession.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, forPsi]
        }

        if (desc == null && (forPsi as? PsiNameIdentifierOwner)?.name == "remove") {
            (forPsi as? PsiMember)?.getJavaOrKotlinMemberDescriptor(resolutionFacade)
        }

        return desc?.let { signature(it) }
                ?: run { "no desc for $forPsi in ${(forPsi as? PsiMember)?.containingClass}" }
    }

    override fun signature(forDesc: DeclarationDescriptor): String = forDesc.signature()
}


/**
 * Copyright © MyCollab
 *
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http:></http:>//www.gnu.org/licenses/>.
 */
package com.mycollab.module.billing.servlet

import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * @author MyCollab Ltd
 * @since 5.5.0
 */
@Configuration
class BillingSpringServletRegistrator {

    @Bean("confirmEmailServlet")
    fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*")

    @Bean("resetPasswordServlet")
    fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*")

    @Bean("resetPasswordServlet")
    fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*")
}

Update the correct reset password servlet

/**
 * Copyright © MyCollab
 *
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http:></http:>//www.gnu.org/licenses/>.
 */
package com.mycollab.module.billing.servlet

import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * @author MyCollab Ltd
 * @since 5.5.0
 */
@Configuration
class BillingSpringServletRegistrator {

    @Bean("confirmEmailServlet")
    fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*")

    @Bean("resetPasswordServlet")
    fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*")

    @Bean("resetPasswordPageServlet")
    fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordUpdatePage(), "/user/recoverypassword/*")
}


package tv.fanart.bot

import kotlinx.coroutines.*
import org.koin.core.KoinComponent
import org.koin.core.inject
import tv.fanart.api.FanartApi
import tv.fanart.config.ConfigRepo
import java.lang.Runnable
import java.util.concurrent.TimeUnit

class FanartBot : KoinComponent {

    private val configurationClient by inject<ConfigRepo>()
    private val updateBot by inject<UpdateBot>()

    private val mainJob = SupervisorJob()
    private val mainContext = Dispatchers.Unconfined + mainJob

    suspend fun start() = coroutineScope {
        configurationClient.updateConfig?.let { updateConfig ->
            launch(mainContext) {
                while (true) {
                    updateBot.update(updateConfig.lastUpdate)?.let { updateTime ->
                        configurationClient.updateConfig(updateConfig.copy(lastUpdate = updateTime))
                    }
                    delay(TimeUnit.SECONDS.toMillis(updateConfig.delay))
                }
            }
        }

        configurationClient.translationConfig?.let {
            launch(mainContext) {
            }
        }

        Runtime.getRuntime().addShutdownHook(Thread(Runnable {
            runBlocking {
                mainJob.cancelAndJoin()
            }
        }))

        yield()
    }
}

Fix update times not changing after request

package tv.fanart.bot

import kotlinx.coroutines.*
import org.koin.core.KoinComponent
import org.koin.core.inject
import tv.fanart.api.FanartApi
import tv.fanart.config.ConfigRepo
import java.lang.Runnable
import java.util.concurrent.TimeUnit

class FanartBot : KoinComponent {

    private val configurationClient by inject<ConfigRepo>()
    private val updateBot by inject<UpdateBot>()

    private val mainJob = SupervisorJob()
    private val mainContext = Dispatchers.Unconfined + mainJob

    suspend fun start() = coroutineScope {
        configurationClient.updateConfig?.let { updateConfig ->
            launch(mainContext) {
                var lastUpdate = updateConfig.lastUpdate
                while (true) {
                    updateBot.update(lastUpdate)?.let { updateTime ->
                        configurationClient.updateConfig(updateConfig.copy(lastUpdate = updateTime))
                        lastUpdate = updateTime
                    }
                    delay(TimeUnit.SECONDS.toMillis(updateConfig.delay))
                }
            }
        }

        configurationClient.translationConfig?.let {
            launch(mainContext) {
            }
        }

        Runtime.getRuntime().addShutdownHook(Thread(Runnable {
            runBlocking {
                mainJob.cancelAndJoin()
            }
        }))

        yield()
    }
}


package enmasse.smoketest

import io.kotlintest.specs.StringSpec
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

/**
 * @author Ulf Lilleengen
 */
class StoreAndForwardTopicTest: StringSpec() {
    init {
        val dest = "mytopic"
        val client = EnMasseClient(createTopicContext(dest))

        "Messages should be delivered to multiple subscribers" {
            val msgs = listOf("foo", "bar", "baz")

            val countdownLatch = CountDownLatch(3)
            val executor = Executors.newFixedThreadPool(3)
            val results = 1.rangeTo(3).map { i -> executor.submit<Int> {
                println("Running client ${i}")
                val sz = client.recvMessages(dest, msgs.size, connectListener = { countdownLatch.countDown() }).size
                println("Client ${i} recieved ${sz} messages")
                sz
            }}

            countdownLatch.await(20, TimeUnit.SECONDS)
            client.sendMessages(dest, msgs) shouldBe msgs.size
            println("Sent ${msgs.size} messages")

            executor.shutdown()
            executor.awaitTermination(20, TimeUnit.SECONDS) shouldBe true

            results.forEach { future ->
                val result = future.get()
                result shouldBe msgs.size
            }
        }
    }
}

Check if running with 1 subscriber works

package enmasse.smoketest

import io.kotlintest.specs.StringSpec
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

/**
 * @author Ulf Lilleengen
 */
class StoreAndForwardTopicTest: StringSpec() {
    init {
        val dest = "mytopic"
        val client = EnMasseClient(createTopicContext(dest))

        "Messages should be delivered to multiple subscribers" {
            val msgs = listOf("foo", "bar", "baz")

            val countdownLatch = CountDownLatch(1)
            val executor = Executors.newFixedThreadPool(1)
            val results = 1.rangeTo(1).map { i -> executor.submit<Int> {
                println("Running client ${i}")
                val sz = client.recvMessages(dest, msgs.size, connectListener = { countdownLatch.countDown() }).size
                println("Client ${i} recieved ${sz} messages")
                sz
            }}

            countdownLatch.await(20, TimeUnit.SECONDS)
            client.sendMessages(dest, msgs) shouldBe msgs.size
            println("Sent ${msgs.size} messages")

            executor.shutdown()
            executor.awaitTermination(20, TimeUnit.SECONDS) shouldBe true

            results.forEach { future ->
                val result = future.get()
                result shouldBe msgs.size
            }
        }
    }
}


package org.wordpress.aztec.plugins.shortcodes.spans

import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.ParagraphStyle
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.spans.*
import org.xml.sax.Attributes

class CaptionShortcodeSpan(override var attributes: AztecAttributes,
                           override val TAG: String, override var nestingLevel: Int)
    : IAztecInlineBlockSpan

Make the caption span a block span and styled as italic

package org.wordpress.aztec.plugins.shortcodes.spans

import android.graphics.Typeface
import android.text.style.StyleSpan
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.spans.*

class CaptionShortcodeSpan(override var attributes: AztecAttributes,
                           override val TAG: String, override var nestingLevel: Int)
    : StyleSpan(Typeface.ITALIC), IAztecBlockSpan {

    override var endBeforeBleed: Int = -1
    override var startBeforeCollapse: Int = -1
}


import org.junit.Ignore
import org.junit.Test
import org.junit.Assert.assertEquals;

class HelloWorldTest {

    @Test
    fun helloNoName() {
        assertEquals("Hello, World!", hello())
    }

    @Test
    @Ignore
    fun helloSampleName() {
        assertEquals("Hello, Alice!", hello("Alice"))
    }

    @Test
    @Ignore
    fun helloBlankName() {
        assertEquals("Hello, World!", hello("    "))
    }

    @Test
    @Ignore
    fun helloAnotherSampleName() {
        assertEquals("Hello, Bob!", hello("Bob"))
    }
}

Rework hello-world as a directed introduction to the track.

import org.junit.Ignore
import org.junit.Test
import org.junit.Assert.assertEquals

class HelloWorldTest {

    @Test
    fun helloNoName() {
        assertEquals("Hello, World!", hello())
    }

    @Test
    @Ignore
    fun helloSampleName() {
        assertEquals("Hello, Alice!", hello("Alice"))
    }

    @Test
    @Ignore
    fun helloBlankName() {
        assertEquals("Hello, World!", hello("    "))
    }

    @Test
    @Ignore
    fun helloAnotherSampleName() {
        assertEquals("Hello, Bob!", hello("Bob"))
    }
}


Add benchmark for cold, warm & hot start

package com.example.macrobenchmark.startup

import androidx.benchmark.macro.BaselineProfileMode
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.StartupTimingMetric
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

/**
 * Run this benchmark from Studio to see startup measurements, and captured system traces
 * for investigating your app's performance from a cold state.
 */
@RunWith(AndroidJUnit4ClassRunner::class)
class ColdStartupBenchmark : AbstractStartupBenchmark(StartupMode.COLD)

/**
 * Run this benchmark from Studio to see startup measurements, and captured system traces
 * for investigating your app's performance from a warm state.
 */
@RunWith(AndroidJUnit4ClassRunner::class)
class WarmStartupBenchmark : AbstractStartupBenchmark(StartupMode.WARM)

/**
 * Run this benchmark from Studio to see startup measurements, and captured system traces
 * for investigating your app's performance from a hot state.
 */
@RunWith(AndroidJUnit4ClassRunner::class)
class HotStartupBenchmark : AbstractStartupBenchmark(StartupMode.HOT)

/**
 * Base class for benchmarks with different startup modes.
 * Enables app startups from various states of baseline profile or [CompilationMode]s.
 */
abstract class AbstractStartupBenchmark(private val startupMode: StartupMode) {
    @get:Rule
    val benchmarkRule = MacrobenchmarkRule()

    @Test
    fun startupNoCompilation() = startup(CompilationMode.None())

    @Test
    fun startupPartialCompilation() = startup(
        CompilationMode.Partial(
            baselineProfileMode = BaselineProfileMode.Disable,
            warmupIterations = 1
        )
    )

    @Test
    fun startupPartialWithBaselineProfiles() =
        startup(CompilationMode.Partial(baselineProfileMode = BaselineProfileMode.Require))

    @Test
    fun startupFullCompilation() = startup(CompilationMode.Full())

    private fun startup(compilationMode: CompilationMode) = benchmarkRule.measureRepeated(
        packageName = "com.example.macrobenchmark.target",
        metrics = listOf(StartupTimingMetric()),
        compilationMode = compilationMode,
        iterations = 10,
        startupMode = startupMode,
        setupBlock = {
            pressHome()
        }
    ) {
        startActivityAndWait()
    }
}


package org.wfanet.measurement.common

import io.grpc.BindableService
import io.grpc.Server
import io.grpc.ServerBuilder
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger

class CommonServer(private val serversEnum: CommonServerType,
                   vararg services: BindableService) {
  private var server: Server

  init {
    val builder = ServerBuilder.forPort(serversEnum.port)
    services.forEach {
      builder.addService(it)
    }
    server = builder.build()
  }

  @Throws(IOException::class)
  fun start(): CommonServer {
    server.start()
    logger.log(Level.INFO,
               "${serversEnum.nameForLogging} started, listening on ${serversEnum.port}")
    Runtime.getRuntime().addShutdownHook(object : Thread() {
      override fun run() {
        // Use stderr here since the logger may have been reset by its JVM shutdown hook.
        System.err.println("*** ${serversEnum.nameForLogging} shutting down...")
        this@CommonServer.stop()
        System.err.println("*** ${serversEnum.nameForLogging} shut down")
      }
    })
    return this
  }

  private fun stop() {
    server.shutdown()
  }

  @Throws(InterruptedException::class)
  fun blockUntilShutdown() {
    server.awaitTermination()
  }

  companion object {
    private val logger = Logger.getLogger(this::class.java.name)
  }
}

enum class CommonServerType(val nameForLogging: String, val port: Int) {
  COMPUTATION_CONTROL("ComputationControlServer", 31124),
  PUBLISHER_DATA("PublisherDataServer", 31125),
  REQUISITION("RequisitionServer", 31126)
}

Create Duchy servers for workers and work management.

package org.wfanet.measurement.common

import io.grpc.BindableService
import io.grpc.Server
import io.grpc.ServerBuilder
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger

class CommonServer(
  private val nameForLogging: String,
  private val port: Int,
  vararg services: BindableService
) {
  private var server: Server

  init {
    val builder = ServerBuilder.forPort(port)
    services.forEach {
      builder.addService(it)
    }
    server = builder.build()
  }

  @Throws(IOException::class)
  fun start(): CommonServer {
    server.start()
    logger.log(
      Level.INFO,
      "$nameForLogging started, listening on $port"
    )
    Runtime.getRuntime().addShutdownHook(object : Thread() {
      override fun run() {
        // Use stderr here since the logger may have been reset by its JVM shutdown hook.
        System.err.println("*** $nameForLogging shutting down...")
        this@CommonServer.stop()
        System.err.println("*** $nameForLogging shut down")
      }
    })
    return this
  }

  private fun stop() {
    server.shutdown()
  }

  @Throws(InterruptedException::class)
  fun blockUntilShutdown() {
    server.awaitTermination()
  }

  companion object {
    private val logger = Logger.getLogger(this::class.java.name)
  }
}


package com.example.android_test

import android.app.Activity
import android.os.Bundle
import org.jetbrains.anko.*
import android.widget.LinearLayout

public open class MyActivity() : Activity() {
    public override fun onCreate(savedInstanceState: Bundle?): Unit {
        super.onCreate(savedInstanceState)
        UI {
            linearLayout {
                textSwitcher {}
                calendarView {}
                zoomButton {}
                viewSwitcher {}
                digitalClock {}
                multiAutoCompleteTextView {}
                checkBox {}
                imageButton {}
                videoView {}
                horizontalScrollView {}
                numberPicker {}
                analogClock {}
                scrollView {}
                textView {}
                tabWidget {}
                radioButton {}
                toggleButton {}
                seekBar {}
                datePicker {}
                radioGroup {}
                timePicker {}
                zoomControls {}
                imageView {}
                searchView {}
                autoCompleteTextView {}
                switch {}
                progressBar {}
                space {}
                listView {}
                gridView {}
                spinner {}
                gallery {}
                imageSwitcher {}
                checkedTextView {}
                chronometer {}
                button {}
                editText {}
                ratingBar {}
                stackView {}
                quickContactBadge {}
                twoLineListItem {}
                dialerFilter {}
                tabHost {}
                viewAnimator {}
                expandableListView {}
                viewFlipper {}
            }
        }
    }

}

Use verticalLayout() in widget compile test

package com.example.android_test

import android.app.Activity
import android.os.Bundle
import org.jetbrains.anko.*
import android.widget.LinearLayout

public open class MyActivity() : Activity() {
    public override fun onCreate(savedInstanceState: Bundle?): Unit {
        super.onCreate(savedInstanceState)
        UI {
            verticalLayout {
                textSwitcher {}
                calendarView {}
                zoomButton {}
                viewSwitcher {}
                digitalClock {}
                multiAutoCompleteTextView {}
                checkBox {}
                imageButton {}
                videoView {}
                horizontalScrollView {}
                numberPicker {}
                analogClock {}
                scrollView {}
                textView {}
                tabWidget {}
                radioButton {}
                toggleButton {}
                seekBar {}
                datePicker {}
                radioGroup {}
                timePicker {}
                zoomControls {}
                imageView {}
                searchView {}
                autoCompleteTextView {}
                switch {}
                progressBar {}
                space {}
                listView {}
                gridView {}
                spinner {}
                gallery {}
                imageSwitcher {}
                checkedTextView {}
                chronometer {}
                button {}
                editText {}
                ratingBar {}
                stackView {}
                quickContactBadge {}
                twoLineListItem {}
                dialerFilter {}
                tabHost {}
                viewAnimator {}
                expandableListView {}
                viewFlipper {}
            }
        }
    }

}


package com.sedsoftware.yaptalker.features.navigation

import android.os.Bundle
import com.nhaarman.mockito_kotlin.verify
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations

class NavigationViewPresenterTest {

  @Mock
  lateinit var navigationView: NavigationView

  @Mock
  lateinit var navigationViewState: `NavigationView$$State`

  lateinit var savedInstanceState: Bundle
  lateinit var presenter: NavigationViewPresenter

  @Before
  fun setUp() {
    MockitoAnnotations.initMocks(this)
    savedInstanceState = Bundle()
    presenter = NavigationViewPresenter()
    presenter.attachView(navigationView)
    presenter.setViewState(navigationViewState)
  }

  @Test
  fun navigation_shouldInitDrawerAndRouter() {
    presenter.initLayout(savedInstanceState)
    verify(navigationViewState).initDrawer(savedInstanceState)
    verify(navigationViewState).initRouter(savedInstanceState)
  }

  @Test
  fun navigation_clickShouldLaunchChosenSectionTransition() {
    presenter.onNavigationClicked(1L)
    verify(navigationViewState).goToChosenSection(1L)
  }
}


package com.bmuschko.gradle.docker

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.GroovySourceSet
import org.gradle.api.tasks.testing.Test
import org.gradle.kotlin.dsl.*

class FunctionalTestPlugin : Plugin<Project> {
    override fun apply(project: Project): Unit = project.run {
        val sourceSets = project.the<JavaPluginConvention>().sourceSets
        val testRuntimeClasspath by configurations

        val functionalTestSourceSet = sourceSets.create("functionalTest") {
            withConvention(GroovySourceSet::class) {
                groovy.srcDir("src/functTest/groovy")
            }
            resources.srcDir("src/functTest/resources")
            compileClasspath += sourceSets["main"]!!.output + testRuntimeClasspath
            runtimeClasspath += output + compileClasspath
        }

        val functionalTest by tasks.creating(Test::class) {
            description = "Runs the functional tests"
            group = "verification"
            testClassesDirs = functionalTestSourceSet.output.classesDirs
            classpath = functionalTestSourceSet.runtimeClasspath
            mustRunAfter("test", "integrationTest")
            reports {
                html.destination = file("${html.destination}/functional")
                junitXml.destination = file("${junitXml.destination}/functional")
            }
            testLogging {
                showStandardStreams = true
                events("started", "passed", "failed")
            }
        }

        tasks["check"].dependsOn(functionalTest)
    }
}

Add test setup output to compile classpath

package com.bmuschko.gradle.docker

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.GroovySourceSet
import org.gradle.api.tasks.testing.Test
import org.gradle.kotlin.dsl.*

class FunctionalTestPlugin : Plugin<Project> {
    override fun apply(project: Project): Unit = project.run {
        val sourceSets = project.the<JavaPluginConvention>().sourceSets
        val testRuntimeClasspath by configurations

        val functionalTestSourceSet = sourceSets.create("functionalTest") {
            withConvention(GroovySourceSet::class) {
                groovy.srcDir("src/functTest/groovy")
            }
            resources.srcDir("src/functTest/resources")
            compileClasspath += sourceSets["main"]!!.output + sourceSets["testSetup"]!!.output + testRuntimeClasspath
            runtimeClasspath += output + compileClasspath
        }

        val functionalTest by tasks.creating(Test::class) {
            description = "Runs the functional tests"
            group = "verification"
            testClassesDirs = functionalTestSourceSet.output.classesDirs
            classpath = functionalTestSourceSet.runtimeClasspath
            mustRunAfter("test", "integrationTest")
            reports {
                html.destination = file("${html.destination}/functional")
                junitXml.destination = file("${junitXml.destination}/functional")
            }
            testLogging {
                showStandardStreams = true
                events("started", "passed", "failed")
            }
        }

        tasks["check"].dependsOn(functionalTest)
    }
}


dependencies {
    api("io.github.manamiproject:modb-core:6.0.0")
    api("io.github.manamiproject:modb-db-parser:3.0.2")
    api("org.slf4j:slf4j-api:1.7.32")

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1-native-mt")
    implementation("io.github.manamiproject:modb-anidb:3.0.3")
    implementation("io.github.manamiproject:modb-anilist:4.0.2")
    implementation("io.github.manamiproject:modb-anime-planet:3.1.3")
    implementation("io.github.manamiproject:modb-anisearch:1.0.3")
    implementation("io.github.manamiproject:modb-kitsu:3.0.2")
    implementation("io.github.manamiproject:modb-livechart:1.0.2")
    implementation("io.github.manamiproject:modb-mal:3.0.3")
    implementation("io.github.manamiproject:modb-notify:3.0.2")
    implementation("ch.qos.logback:logback-classic:1.2.5")
    implementation("org.apache.commons:commons-lang3:3.12.0")
    implementation("org.apache.commons:commons-text:1.9")

    testImplementation("io.github.manamiproject:modb-test:1.2.8")
}

Bump modb-anidb from 3.0.3 to 3.0.4

dependencies {
    api("io.github.manamiproject:modb-core:6.0.0")
    api("io.github.manamiproject:modb-db-parser:3.0.2")
    api("org.slf4j:slf4j-api:1.7.32")

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1-native-mt")
    implementation("io.github.manamiproject:modb-anidb:3.0.4")
    implementation("io.github.manamiproject:modb-anilist:4.0.2")
    implementation("io.github.manamiproject:modb-anime-planet:3.1.3")
    implementation("io.github.manamiproject:modb-anisearch:1.0.3")
    implementation("io.github.manamiproject:modb-kitsu:3.0.2")
    implementation("io.github.manamiproject:modb-livechart:1.0.2")
    implementation("io.github.manamiproject:modb-mal:3.0.3")
    implementation("io.github.manamiproject:modb-notify:3.0.2")
    implementation("ch.qos.logback:logback-classic:1.2.5")
    implementation("org.apache.commons:commons-lang3:3.12.0")
    implementation("org.apache.commons:commons-text:1.9")

    testImplementation("io.github.manamiproject:modb-test:1.2.8")
}


package org.elm.ide.search

import com.intellij.psi.PsiElement
import org.elm.lang.ElmTestBase
import org.elm.lang.core.psi.ElmNamedElement
import org.intellij.lang.annotations.Language

class ElmFindUsagesProviderTest: ElmTestBase() {

    fun `test function parameter usage`() = doTestByText(
"""
foo x =
  --^
    let
        a = x -- : foobar
    in
        x -- : foobar
""")

    fun `test binary operator usage`() = doTestByText(
"""
(**) a b = a ^ b
--^
foo = 2 ** 3 -- : foobar
bar = (**) 2 -- : foobar
""")

    private fun doTestByText(@Language("Elm") code: String) {
        InlineFile(code)
        val source = findElementInEditor<ElmNamedElement>()

        val actual = markersActual(source)
        val expected = markersFrom(code)
        assertEquals(expected.joinToString(COMPARE_SEPARATOR), actual.joinToString(COMPARE_SEPARATOR))
    }

    private fun markersActual(source: ElmNamedElement) =
            myFixture.findUsages(source)
                    .filter { it.element != null }
                    // TODO [kl] implement a UsageTypeProvider and replace "foobar" with the expected usage type
                    // both here and in the test cases themselves.
//                    .map { Pair(it.element?.line ?: -1, RsUsageTypeProvider.getUsageType(it.element).toString()) }
                    .map { Pair(it.element?.line ?: -1, "foobar") }

    private fun markersFrom(text: String) =
            text.split('\n')
                    .withIndex()
                    .filter { it.value.contains(MARKER) }
                    .map { Pair(it.index, it.value.substring(it.value.indexOf(MARKER) + MARKER.length).trim()) }

    private companion object {
        val MARKER = "-- : "
        val COMPARE_SEPARATOR = " | "
    }

    val PsiElement.line: Int? get() = containingFile.viewProvider.document?.getLineNumber(textRange.startOffset)

}


package com.doomspork.helloworld

import io.dropwizard.Configuration
import org.hibernate.validator.constraints.NotEmpty
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonCreator

data class HelloWorldConfiguration [JsonCreator] (JsonProperty("template") NotEmpty var template: String,
                                                  JsonProperty("defaultName") NotEmpty var defaultName: String) : Configuration()

Change data class to normal class as data class inheritance has been removed.

package com.doomspork.helloworld

import com.fasterxml.jackson.annotation.JsonProperty
import io.dropwizard.Configuration

public class HelloWorldConfiguration() : Configuration() {
    @JsonProperty("template")
    public var template: String=""

    @JsonProperty("defaultName")
    public var defaultName: String="Stranger"
}


package com.gitlab.artismarti.tinbo.config

import com.google.common.io.Resources
import org.junit.After
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Paths

/**
 * @author artur
 */
class TinboConfigTest {

	private val path = Paths.get("test")

	private val config: TinboConfig
		get() {
			val tinboConfig = TinboConfig.load(
					Paths.get(Resources.getResource("default-config.yaml").file))
			return tinboConfig
		}

	@After
	fun tearDown() {
		if (Files.exists(path))
			Files.delete(path)
	}

	@Test
	fun writeConfig() {
		val write = TinboConfig.write(path, config)
		assert(write)
	}

	@Test
	fun timeInterval() {
		val timeInterval = config.getTimeInterval()
		assert(timeInterval == 15L)
	}

	@Test
	fun getCategoryName() {
		val name = config.getCategoryName()
		assert(name == "Main")
	}
}

Use deleteIfExists in test case

package com.gitlab.artismarti.tinbo.config

import com.google.common.io.Resources
import org.junit.After
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Paths

/**
 * @author artur
 */
class TinboConfigTest {

	private val path = Paths.get("test")

	private val config: TinboConfig
		get() {
			val tinboConfig = TinboConfig.load(
					Paths.get(Resources.getResource("default-config.yaml").file))
			return tinboConfig
		}

	@After
	fun tearDown() {
		Files.deleteIfExists(path)
	}

	@Test
	fun writeConfig() {
		val write = TinboConfig.write(path, config)
		assert(write)
	}

	@Test
	fun timeInterval() {
		val timeInterval = config.getTimeInterval()
		assert(timeInterval == 15L)
	}

	@Test
	fun getCategoryName() {
		val name = config.getCategoryName()
		assert(name == "Main")
	}
}


package com.ridi.books.helper.view

import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

private val Context.inputMethodManager: InputMethodManager
    get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

@JvmOverloads
fun View.showSoftKeyboard(flags: Int = InputMethodManager.SHOW_IMPLICIT) =
    context.inputMethodManager.showSoftInput(this, flags)

@JvmOverloads
fun View.hideSoftKeyboard(flags: Int = 0) = context.inputMethodManager.hideSoftInputFromWindow(windowToken, flags)

@JvmOverloads
fun Context.toggleSoftKeyboard(showFlags: Int = 0, hideFlags: Int = 0) {
    inputMethodManager.toggleSoftInput(showFlags, hideFlags)
}

@JvmOverloads
fun View.focusAndShowSoftKeyboard(
    flags: Int = InputMethodManager.SHOW_IMPLICIT,
    repeatIntervalInMs: Long = 100,
    condition: () -> Boolean = { true }
) {
    if (condition().not()) {
        return
    }

    requestFocus()
    if (showSoftKeyboard(flags).not()) {
        postDelayed({ focusAndShowSoftKeyboard(flags, repeatIntervalInMs, condition) }, repeatIntervalInMs)
    }
}

Revert "뷰에 포커스를 주고 동시에 키보드를 띄우는 확장 매서드 추가"


package me.mrkirby153.KirBot.command.executors.music

import me.mrkirby153.KirBot.command.Command
import me.mrkirby153.KirBot.user.Clearance
import net.dv8tion.jda.core.entities.Message

@Command(name = "volume", description = "Change the volume of the robot", clearance = Clearance.BOT_MANAGER)
class CommandVolume : MusicCommand() {

    override fun exec(message: Message, args: Array<String>) {
        if(args.isEmpty()){
            message.send().error("Please specify a volume!").queue()
            return
        }

        val volume = Math.min(150, Math.max(args[0].toInt(), 0))

        server.musicManager.audioPlayer.volume = volume
        message.send().info("Set volume to __**$volume**__").queue()
    }
}

Add support for changing volume by an amount

package me.mrkirby153.KirBot.command.executors.music

import me.mrkirby153.KirBot.command.Command
import me.mrkirby153.KirBot.user.Clearance
import net.dv8tion.jda.core.entities.Message

@Command(name = "volume", description = "Change the volume of the robot", clearance = Clearance.BOT_MANAGER)
class CommandVolume : MusicCommand() {

    override fun exec(message: Message, args: Array<String>) {
        val audioPlayer = server.musicManager.audioPlayer
        if (args.isEmpty()) {
            message.send().info("Current Volume: **${audioPlayer.volume}**").queue()
            return
        }

        var add = false
        var sub = false

        var num = args[0]
        if (num.startsWith("+")) {
            num = num.substring(1)
            add = true
        } else if (num.startsWith("-")) {
            num = num.substring(1)
            sub = true
        }

        val volume = Math.min(150, Math.max(num.toInt(), 0))

        if (add) {
            audioPlayer.volume += volume
        } else if (sub) {
            audioPlayer.volume -= volume
        } else {

            audioPlayer.volume = volume
        }
        message.send().info("Set volume to __**${audioPlayer.volume}**__").queue()
    }
}


object Versions {
    const val KTLINT = "0.36.0"
}

object BuildPluginsVersion {
    const val AGP = "4.0.0"
    const val KOTLIN = "1.3.72"
    const val KTLINT = "9.2.1"
    const val VERSIONS_PLUGIN = "0.28.0"
}

Update Android Gradle plugin for Android Studio 4.0.1

object Versions {
    const val KTLINT = "0.36.0"
}

object BuildPluginsVersion {
    const val AGP = "4.0.1"
    const val KOTLIN = "1.3.72"
    const val KTLINT = "9.2.1"
    const val VERSIONS_PLUGIN = "0.28.0"
}


plugins {
    `java-library`
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

version = "0"

tasks {

    javadoc {
        isFailOnError = false
        (options as StandardJavadocDocletOptions).addStringOption("-module-source-path", "src/main/java")
        (options as StandardJavadocDocletOptions).addStringOption("-module", "de.sormuras.bach.doc.minimal")
    }

    val sourcesJar by creating(Jar::class) {
        dependsOn(JavaPlugin.CLASSES_TASK_NAME)
        classifier = "sources"
        from(sourceSets["main"].allJava)
    }

    val javadocJar by creating(Jar::class) {
        dependsOn(JavaPlugin.JAVADOC_TASK_NAME)
        classifier = "javadoc"
        from(javadoc)
    }

    artifacts {
        add("archives", sourcesJar)
        add("archives", javadocJar)
    }
}

Patch module for javadoc generation

plugins {
    `java-library`
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

version = "0"

tasks {

    javadoc {
        (options as StandardJavadocDocletOptions).addStringOption("-module", "de.sormuras.bach.doc.minimal")
        (options as StandardJavadocDocletOptions).addStringOption("-patch-module", "de.sormuras.bach.doc.minimal=src/main/java")
    }

    val sourcesJar by creating(Jar::class) {
        dependsOn(JavaPlugin.CLASSES_TASK_NAME)
        classifier = "sources"
        from(sourceSets["main"].allJava)
    }

    val javadocJar by creating(Jar::class) {
        dependsOn(JavaPlugin.JAVADOC_TASK_NAME)
        classifier = "javadoc"
        from(javadoc)
    }

    artifacts {
        add("archives", sourcesJar)
        add("archives", javadocJar)
    }
}


package _Self

object Constants {
  const val DEFAULT_CHANNEL = "default"
  const val EAP_CHANNEL = "eap"
  const val DEV_CHANNEL = "Dev"

  const val VERSION = "1.8.0"
  const val DEV_VERSION = "1.9.0"

  const val GITHUB_TESTS = "LATEST-EAP-SNAPSHOT"
  const val LINTING_TESTS = "LATEST-EAP-SNAPSHOT"
  const val NVIM_TESTS = "LATEST-EAP-SNAPSHOT"
  const val PROPERTY_TESTS = "LATEST-EAP-SNAPSHOT"
  const val QODANA_TESTS = "LATEST-EAP-SNAPSHOT"
  const val RELEASE = "2021.2.2"
  const val RELEASE_DEV = "LATEST-EAP-SNAPSHOT"
  const val RELEASE_EAP = "LATEST-EAP-SNAPSHOT"
}

Update release version to 1.8.1

package _Self

object Constants {
  const val DEFAULT_CHANNEL = "default"
  const val EAP_CHANNEL = "eap"
  const val DEV_CHANNEL = "Dev"

  const val VERSION = "1.8.1"
  const val DEV_VERSION = "1.9.0"

  const val GITHUB_TESTS = "LATEST-EAP-SNAPSHOT"
  const val LINTING_TESTS = "LATEST-EAP-SNAPSHOT"
  const val NVIM_TESTS = "LATEST-EAP-SNAPSHOT"
  const val PROPERTY_TESTS = "LATEST-EAP-SNAPSHOT"
  const val QODANA_TESTS = "LATEST-EAP-SNAPSHOT"
  const val RELEASE = "2021.2.2"
  const val RELEASE_DEV = "LATEST-EAP-SNAPSHOT"
  const val RELEASE_EAP = "LATEST-EAP-SNAPSHOT"
}


/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package common

enum class JvmCategory(val vendor: JvmVendor, val version: JvmVersion) {
    MIN_VERSION(JvmVendor.oracle, JvmVersion.java8),
    MAX_VERSION(JvmVendor.oracle, JvmVersion.java15),
    EXPERIMENTAL_VERSION(JvmVendor.openjdk, JvmVersion.java16)
}

Fix jdk vendor for experimental jdk16 pipeline

/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package common

enum class JvmCategory(val vendor: JvmVendor, val version: JvmVersion) {
    MIN_VERSION(JvmVendor.oracle, JvmVersion.java8),
    MAX_VERSION(JvmVendor.oracle, JvmVersion.java15),
    EXPERIMENTAL_VERSION(JvmVendor.oracle, JvmVersion.java16)
}


package lt.markmerkk.interactors

import lt.markmerkk.UserSettings

/**
 * @author mariusmerkevicius
 * @since 2016-08-13
 */
class AutoUpdateInteractorImpl(
        private val userSettings: UserSettings
) : AutoUpdateInteractor {

    override fun notifyUpdateComplete(lastUpdateMillis: Long) {
        userSettings.lastUpdate = lastUpdateMillis
    }

    override fun isAutoUpdateTimeoutHit(now: Long): Boolean {
        if (userSettings.autoUpdateMinutes == -1) return false // no update
        if (userSettings.lastUpdate < 0) return true // never updated

        val timeout = userSettings.autoUpdateMinutes * 1000 * 60
        val updateGap = now - userSettings.lastUpdate
        return updateGap >= timeout
    }

}

Add auto update logging for more debug data

package lt.markmerkk.interactors

import lt.markmerkk.UserSettings
import org.slf4j.LoggerFactory

/**
 * @author mariusmerkevicius
 * @since 2016-08-13
 */
class AutoUpdateInteractorImpl(
        private val userSettings: UserSettings
) : AutoUpdateInteractor {

    override fun notifyUpdateComplete(lastUpdateMillis: Long) {
        userSettings.lastUpdate = lastUpdateMillis
    }

    override fun isAutoUpdateTimeoutHit(now: Long): Boolean {
        logger.debug("Check if update is necessary...")
        if (userSettings.autoUpdateMinutes == -1) {
            logger.debug("Auto update disabled")
            return false
        }
        if (userSettings.lastUpdate < 0) {
            logger.debug("Update was never done, executing...")
            return true
        }

        val timeout = userSettings.autoUpdateMinutes * 1000 * 60
        val updateGap = now - userSettings.lastUpdate
        logger.debug("Timeout set to ${userSettings.autoUpdateMinutes}")
        return updateGap >= timeout
    }

    companion object {
        val logger = LoggerFactory.getLogger(AutoUpdateInteractorImpl::class.java)!!
    }

}


Add custom TestRule to be used by testing classes that are Rx-based.

package com.github.ramonrabello.kiphy.common.rx.rule

import io.reactivex.Scheduler
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.internal.schedulers.ExecutorScheduler
import io.reactivex.plugins.RxJavaPlugins
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.util.concurrent.Executor

class RxImmediateSchedulerRule : TestRule {
    private val immediate = object : Scheduler() {
        override fun createWorker(): Worker {
            return ExecutorScheduler.ExecutorWorker(Executor { it.run() }, false)
        }
    }

    override fun apply(base: Statement, description: Description): Statement {
        return object : Statement() {
            @Throws(Throwable::class)
            override fun evaluate() {
                RxJavaPlugins.setInitIoSchedulerHandler { immediate }
                RxJavaPlugins.setInitComputationSchedulerHandler { immediate }
                RxJavaPlugins.setInitNewThreadSchedulerHandler { immediate }
                RxJavaPlugins.setInitSingleSchedulerHandler { immediate }
                RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediate }

                try {
                    base.evaluate()
                } finally {
                    RxJavaPlugins.reset()
                    RxAndroidPlugins.reset()
                }
            }
        }
    }
}


// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.plugin

import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.EventDispatcher
import java.util.*

@State(name = "ChangeReminderUserStorage", storages = [Storage(file = "changeReminder.user.storage.xml")])
class UserSettings : PersistentStateComponent<UserSettings.Companion.State> {
  companion object {
    data class State(var isPluginEnabled: Boolean = true)
  }

  interface PluginStatusListener : EventListener {
    fun statusChanged(isEnabled: Boolean)
  }

  private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java)
  private var currentState = State()

  var isPluginEnabled: Boolean
    get() = currentState.isPluginEnabled
    set(value) {
      currentState.isPluginEnabled = value
      eventDispatcher.multicaster.statusChanged(value)
    }

  override fun loadState(state: State) {
    currentState = state
  }

  override fun getState(): State = currentState

  fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) {
    eventDispatcher.addListener(listener, parentDisposable)
  }
}

Use PersistentStateComponent in proper way

// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.plugin

import com.intellij.openapi.Disposable
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.SimplePersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.EventDispatcher
import java.util.*

@State(name = "ChangeReminder", storages = [Storage(file = "changeReminder.xml")])
internal class UserSettings : SimplePersistentStateComponent<UserSettingsState>(UserSettingsState()) {
  private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java)

  var isPluginEnabled: Boolean
    get() = state.isPluginEnabled
    set(value) {
      state.isPluginEnabled = value
      eventDispatcher.multicaster.statusChanged(value)
    }

  fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) {
    eventDispatcher.addListener(listener, parentDisposable)
  }

  interface PluginStatusListener : EventListener {
    fun statusChanged(isEnabled: Boolean)
  }
}

internal class UserSettingsState : BaseState() {
  var isPluginEnabled: Boolean by property(true)
}


Create a schedule handler which integrates with espresso through IdlingResource

package com.felipecosta.kotlinrxjavasample.utils

import android.support.test.espresso.IdlingResource
import android.support.test.espresso.idling.CountingIdlingResource
import io.reactivex.annotations.NonNull
import io.reactivex.functions.Function

class RxEspressoScheduleHandler : Function<Runnable, Runnable> {

    private val countingIdlingResource = CountingIdlingResource("rxJava")

    @Throws(Exception::class)
    override fun apply(@NonNull runnable: Runnable): Runnable {
        return Runnable {
            countingIdlingResource.increment()

            try {
                runnable.run()
            } finally {
                countingIdlingResource.decrement()
            }
        }
    }

    val idlingResource: IdlingResource
        get() = countingIdlingResource

}


package com.beust.kobalt

class Features {
    companion object {
        /** If true, uses timestamps to speed up the tasks */
        const val USE_TIMESTAMPS = true
    }
}

Disable timestamp feature since it's obsoleted by incremental tasks.

package com.beust.kobalt

class Features {
    companion object {
        /** If true, uses timestamps to speed up the tasks */
        const val USE_TIMESTAMPS = false
    }
}


package com.github.bumblebee.command.notification

import com.github.bumblebee.bot.consumer.UpdateHandler
import com.github.bumblebee.service.RandomPhraseService
import com.github.telegram.api.BotApi
import com.github.telegram.domain.ChatType
import com.github.telegram.domain.Update
import org.springframework.stereotype.Component

@Component
class NotifyChatCommand(private val botApi: BotApi,
                        private val randomPhraseService: RandomPhraseService) : UpdateHandler {

    override fun onUpdate(update: Update): Boolean {
        if (update.message?.chat?.type == ChatType.private) {
            botApi.sendMessage(update.senderId, randomPhraseService.surprise())
            return true
        }

        val response = botApi.getChatAdministrators(update.senderId)

        if (response.ok) {
            val members = response.result.orEmpty()
            val mentions = members.asSequence()
                    .filter { !it.user.isBot }
                    .map { it.user.userName }
                    .filter { it != null }
                    .joinToString(separator = " ") { "@$it" }

            val message = if (mentions.isNotEmpty()) mentions else randomPhraseService.no()
            botApi.sendMessage(update.senderId, message)
        }

        return true
    }
}

Use filterNotNull instead of explicit filter.

package com.github.bumblebee.command.notification

import com.github.bumblebee.bot.consumer.UpdateHandler
import com.github.bumblebee.service.RandomPhraseService
import com.github.telegram.api.BotApi
import com.github.telegram.domain.ChatType
import com.github.telegram.domain.Update
import org.springframework.stereotype.Component

@Component
class NotifyChatCommand(private val botApi: BotApi,
                        private val randomPhraseService: RandomPhraseService) : UpdateHandler {

    override fun onUpdate(update: Update): Boolean {
        if (update.message?.chat?.type == ChatType.private) {
            botApi.sendMessage(update.senderId, randomPhraseService.surprise())
            return true
        }

        val response = botApi.getChatAdministrators(update.senderId)

        if (response.ok) {
            val members = response.result.orEmpty()
            val mentions = members.asSequence()
                    .filter { !it.user.isBot }
                    .map { it.user.userName }
                    .filterNotNull()
                    .joinToString(separator = " ") { "@$it" }

            val message = if (mentions.isNotEmpty()) mentions else randomPhraseService.no()
            botApi.sendMessage(update.senderId, message)
        }

        return true
    }
}


package org.rust.lang.refactoring

import com.intellij.lang.refactoring.NamesValidator
import com.intellij.openapi.project.Project
import com.intellij.psi.tree.IElementType
import org.rust.lang.core.lexer.RsLexer
import org.rust.lang.core.psi.RS_KEYWORDS
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER

class RsNamesValidator : NamesValidator {
    override fun isKeyword(name: String, project: Project?): Boolean =
        isKeyword(name, project, true)

    fun isKeyword(name: String, @Suppress("UNUSED_PARAMETER") project: Project?, withPrimitives: Boolean): Boolean =
        getLexerType(name) in RS_KEYWORDS || (withPrimitives && name in PrimitiveTypes)

    override fun isIdentifier(name: String, project: Project?): Boolean =
        isIdentifier(name, project, true)

    fun isIdentifier(name: String, @Suppress("UNUSED_PARAMETER") project: Project?, withPrimitives: Boolean): Boolean =
        when (getLexerType(name)) {
            IDENTIFIER -> !withPrimitives || name !in PrimitiveTypes
            QUOTE_IDENTIFIER -> true
            else -> false
        }

    private fun getLexerType(text: String): IElementType? {
        val lexer = RsLexer()
        lexer.start(text)
        if (lexer.tokenEnd == text.length) {
            return lexer.tokenType
        } else {
            return null
        }
    }

    companion object {
        val PrimitiveTypes = arrayOf(
            "bool",
            "char",
            "i8",
            "i16",
            "i32",
            "i64",
            "u8",
            "u16",
            "u32",
            "u64",
            "isize",
            "usize",
            "f32",
            "f64",
            "str"
        )

        val PredefinedLifetimes = arrayOf("'static")
    }
}

Allow to use primitive type names in renaming

package org.rust.lang.refactoring

import com.intellij.lang.refactoring.NamesValidator
import com.intellij.openapi.project.Project
import com.intellij.psi.tree.IElementType
import org.rust.lang.core.lexer.RsLexer
import org.rust.lang.core.psi.RS_KEYWORDS
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER

class RsNamesValidator : NamesValidator {

    override fun isKeyword(name: String, project: Project?): Boolean = getLexerType(name) in RS_KEYWORDS

    override fun isIdentifier(name: String, project: Project?): Boolean =
        when (getLexerType(name)) {
            IDENTIFIER, QUOTE_IDENTIFIER -> true
            else -> false
        }

    private fun getLexerType(text: String): IElementType? {
        val lexer = RsLexer()
        lexer.start(text)
        return if (lexer.tokenEnd == text.length) lexer.tokenType else null
    }

    companion object {
        val PredefinedLifetimes = arrayOf("'static")
    }
}


package org.gradle.script.lang.kotlin.samples

import org.gradle.script.lang.kotlin.fixtures.AbstractIntegrationTest

import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not

import org.junit.Assume.assumeThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized

import java.io.File

@RunWith(Parameterized::class)
class SamplesSmokeTest(val sampleDir: File) : AbstractIntegrationTest() {

    companion object {
        @Parameterized.Parameters(name = "{0}")
        @JvmStatic fun testCases(): Iterable<File> =
            samplesRootDir.listFiles().filter { it.isDirectory }
    }

    @Before
    fun populateProjectRootWithSample() {
        assumeThat(sampleDir.name, not(containsString("android")))
        // TODO:pm un-ignore build-scan sample test once the breakage is fixed upstream
        assumeThat(sampleDir.name, not(containsString("build-scan")))
        copySampleProject(from = sampleDir, to = projectRoot)
    }

    @Test
    fun `tasks task succeeds on `() {
        build("tasks")
    }
}

Revert "Temporarily disable build-scan sample test until upstream breakage is fixed"

package org.gradle.script.lang.kotlin.samples

import org.gradle.script.lang.kotlin.fixtures.AbstractIntegrationTest

import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not

import org.junit.Assume.assumeThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized

import java.io.File

@RunWith(Parameterized::class)
class SamplesSmokeTest(val sampleDir: File) : AbstractIntegrationTest() {

    companion object {
        @Parameterized.Parameters(name = "{0}")
        @JvmStatic fun testCases(): Iterable<File> =
            samplesRootDir.listFiles().filter { it.isDirectory }
    }

    @Before
    fun populateProjectRootWithSample() {
        assumeThat(sampleDir.name, not(containsString("android")))
        copySampleProject(from = sampleDir, to = projectRoot)
    }

    @Test
    fun `tasks task succeeds on `() {
        build("tasks")
    }
}


package org.luxons.sevenwonders.ui.redux.sagas

import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.luxons.sevenwonders.client.SevenWondersClient
import org.luxons.sevenwonders.ui.redux.RequestChooseName
import org.luxons.sevenwonders.ui.redux.SetCurrentPlayerAction
import org.luxons.sevenwonders.ui.redux.SwState
import redux.RAction
import redux.WrapperAction

typealias SwSagaContext = SagaContext<SwState, RAction, WrapperAction>

suspend fun SwSagaContext.rootSaga() {
    val action = next<RequestChooseName>()
    val session = SevenWondersClient().connect("ws://localhost:8000")

    coroutineScope {
        launch { gameBrowserSaga(session) }

        val player = session.chooseName(action.playerName)
        dispatch(SetCurrentPlayerAction(player))
        // push /games
    }
}

Fix server URL in react frontend

package org.luxons.sevenwonders.ui.redux.sagas

import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.luxons.sevenwonders.client.SevenWondersClient
import org.luxons.sevenwonders.ui.redux.RequestChooseName
import org.luxons.sevenwonders.ui.redux.SetCurrentPlayerAction
import org.luxons.sevenwonders.ui.redux.SwState
import redux.RAction
import redux.WrapperAction

typealias SwSagaContext = SagaContext<SwState, RAction, WrapperAction>

suspend fun SwSagaContext.rootSaga() {
    val action = next<RequestChooseName>()
    val session = SevenWondersClient().connect("http://localhost:8000")

    coroutineScope {
        launch { gameBrowserSaga(session) }

        val player = session.chooseName(action.playerName)
        dispatch(SetCurrentPlayerAction(player))
        // push /games
    }
}


package nhdphuong.com.manga.data.entity.book

import com.google.gson.annotations.SerializedName
import nhdphuong.com.manga.Constants
import java.io.Serializable

/*
 * Created by nhdphuong on 3/24/18.
 */
class BookTitle(@field:SerializedName(Constants.TITLE_ENG) val englishName: String,
                @field:SerializedName(Constants.TITLE_JAPANESE) val japaneseName: String = "",
                @field:SerializedName(Constants.TITLE_PRETTY) val pretty: String) : Serializable

Fix bug crash on null Japanese name

package nhdphuong.com.manga.data.entity.book

import com.google.gson.annotations.SerializedName
import nhdphuong.com.manga.Constants
import java.io.Serializable

/*
 * Created by nhdphuong on 3/24/18.
 */
class BookTitle(@field:SerializedName(Constants.TITLE_ENG) private val mEnglishName: String?,
                @field:SerializedName(Constants.TITLE_JAPANESE) private val mJapaneseName: String?,
                @field:SerializedName(Constants.TITLE_PRETTY) private val mPretty: String?) : Serializable {
    val japaneseName: String
        get() = mJapaneseName ?: ""

    val englishName: String
        get() = mEnglishName ?: ""

    val pretty: String
        get() = mPretty ?: ""
}


/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.toml.intentions

import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.toml.tomlPluginIsAbiCompatible
import org.toml.ide.intentions.TomlElementBaseIntentionAction

abstract class RsTomlElementBaseIntentionAction<Ctx> : TomlElementBaseIntentionAction<Ctx>() {
    final override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Ctx? {
        if (!tomlPluginIsAbiCompatible()) return null
        return findApplicableContextInternal(project, editor, element)
    }

    protected abstract fun findApplicableContextInternal(project: Project, editor: Editor, element: PsiElement): Ctx?
}

Use `RsElementBaseIntentionAction` to comply with non-latest Toml plugin

/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.toml.intentions

import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.ide.intentions.RsElementBaseIntentionAction
import org.rust.toml.tomlPluginIsAbiCompatible

abstract class RsTomlElementBaseIntentionAction<Ctx> : RsElementBaseIntentionAction<Ctx>() {
    final override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Ctx? {
        if (!tomlPluginIsAbiCompatible()) return null
        return findApplicableContextInternal(project, editor, element)
    }

    protected abstract fun findApplicableContextInternal(project: Project, editor: Editor, element: PsiElement): Ctx?
}


Add integration test for java script sample

package org.gradle.kotlin.dsl.samples

import org.junit.Test
import java.io.File
import java.io.FileReader
import javax.script.ScriptEngineManager
import java.io.StringWriter
import org.junit.Assert.assertThat
import org.hamcrest.CoreMatchers.equalTo

class JavaScriptSampleTest : AbstractSampleTest("hello-js") {

    @Test
    fun `hello world`() {
        build("assemble")

        val sw = StringWriter()
        val engine = ScriptEngineManager().getEngineByName("nashorn").apply {
            // Redirect output from `print` to this writer
            context.writer = sw
        }

        // Wire `console.log` to `print`
        engine.eval("var console = {}; console.log = print;")

        // Load Kotlin JS stdlib
        val pathToKotlinJsStdLib = "$projectRoot/build/web/kotlin.js"
        val pathToBuildOutputJs = "$projectRoot/build/web/output.js"

        engine.eval(FileReader(File(pathToKotlinJsStdLib)))
        // Run build output
        engine.eval(FileReader(File(pathToBuildOutputJs)))

        assertThat(
            sw.buffer.toString(),
            equalTo("Hello, world!\n"))
    }
}


package me.mrkirby153.KirBot.command.executors.admin

import me.mrkirby153.KirBot.command.BaseCommand
import me.mrkirby153.KirBot.command.Command
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.user.Clearance
import me.mrkirby153.KirBot.utils.Context

@Command(name = "dumpSettings", clearance = Clearance.SERVER_ADMINISTRATOR)
class CommandDumpSettings : BaseCommand() {

    override fun execute(context: Context, cmdContext: CommandContext) {
        val settings = context.kirbotGuild.settings

        context.channel.sendMessage(buildString {
            append("General Settings\n")
            appendln("```")
            settings.getColumnData().forEach { k, v ->
                append(k)
                append(" = ")
                append(v.toString())
                append("\n")
            }
            append("```")
        }).queue()

        val musicSettings = context.kirbotGuild.musicManager.settings
        context.channel.sendMessage(buildString {
            append("Music Settings\n")
            appendln("```")
            musicSettings.getColumnData().forEach { k, v ->
                append(k)
                append(" = ")
                append(v.toString())
                append("\n")
            }
            append("```")
        }).queue()
    }
}


package nerd.tuxmobil.fahrplan.congress.utils

import nerd.tuxmobil.fahrplan.congress.BuildConfig
import nerd.tuxmobil.fahrplan.congress.utils.ServerBackendType.*
import nerd.tuxmobil.fahrplan.congress.models.Lecture as Event

class EventUrlComposer @JvmOverloads constructor(

        private val event: Event,
        private val eventUrlTemplate: String = BuildConfig.EVENT_URL,
        private val serverBackEndType: String = BuildConfig.SERVER_BACKEND_TYPE

) {

    fun getEventUrl(): String = when (serverBackEndType) {
        PENTABARF.name -> getComposedEventUrl(event.slug)
        FRAB.name -> event.eventUrl()
        PRETALX.name -> event.url
        else -> throw NotImplementedError("Unknown server backend type: '$serverBackEndType'")
    }

    private fun Event.eventUrl() =
            if (originatesFromPretalx()) url else getComposedEventUrl(lecture_id)

    private fun getComposedEventUrl(eventIdentifier: String) =
            String.format(eventUrlTemplate, eventIdentifier)

    private fun Event.originatesFromPretalx() =
            !url.isNullOrEmpty() && !slug.isNullOrEmpty() && url.endsWith(slug)

}

Simplify by using a property extension.

package nerd.tuxmobil.fahrplan.congress.utils

import nerd.tuxmobil.fahrplan.congress.BuildConfig
import nerd.tuxmobil.fahrplan.congress.utils.ServerBackendType.*
import nerd.tuxmobil.fahrplan.congress.models.Lecture as Event

class EventUrlComposer @JvmOverloads constructor(

        private val event: Event,
        private val eventUrlTemplate: String = BuildConfig.EVENT_URL,
        private val serverBackEndType: String = BuildConfig.SERVER_BACKEND_TYPE

) {

    fun getEventUrl(): String = when (serverBackEndType) {
        PENTABARF.name -> getComposedEventUrl(event.slug)
        FRAB.name -> event.eventUrl
        PRETALX.name -> event.url
        else -> throw NotImplementedError("Unknown server backend type: '$serverBackEndType'")
    }

    private val Event.eventUrl
        get() = if (originatesFromPretalx()) url else getComposedEventUrl(lecture_id)

    private fun getComposedEventUrl(eventIdentifier: String) =
            String.format(eventUrlTemplate, eventIdentifier)

    private fun Event.originatesFromPretalx() =
            !url.isNullOrEmpty() && !slug.isNullOrEmpty() && url.endsWith(slug)

}


package me.mrkirby153.KirBot.command.help

import me.mrkirby153.KirBot.Bot
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener

class HelpManager {

    val commands = mutableListOf<CommandHelp>()

    private val INPUT_STREAM = this.javaClass.getResourceAsStream("/commands.json")!!

    fun load() {
        Bot.LOG.info("Started loading help from \"$INPUT_STREAM\"")

        val jsonArray = JSONArray(JSONTokener(INPUT_STREAM))
        Bot.LOG.debug("There are ${jsonArray.length()} command help entries registered")

        jsonArray.map { it as JSONObject }.forEach {
            val help = CommandHelp()
            help.deserialize(it)
            Bot.LOG.debug("Loaded help for ${help.name}")
            commands.add(help)
        }
        Bot.LOG.info("Registered help for ${commands.size} commands")
    }

    fun get(command: String) = commands.firstOrNull { it.name.equals(command, true) }
}

Fix closed stream when trying to read command help

package me.mrkirby153.KirBot.command.help

import me.mrkirby153.KirBot.Bot
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener

class HelpManager {

    val commands = mutableListOf<CommandHelp>()

    fun load() {
        val INPUT_STREAM = this.javaClass.getResourceAsStream("/commands.json")!!
        Bot.LOG.info("Started loading help from \"$INPUT_STREAM\"")

        val jsonArray = JSONArray(JSONTokener(INPUT_STREAM))
        Bot.LOG.debug("There are ${jsonArray.length()} command help entries registered")

        jsonArray.map { it as JSONObject }.forEach {
            val help = CommandHelp()
            help.deserialize(it)
            Bot.LOG.debug("Loaded help for ${help.name}")
            commands.add(help)
        }
        Bot.LOG.info("Registered help for ${commands.size} commands")
    }

    fun get(command: String) = commands.firstOrNull { it.name.equals(command, true) }
}


/*
 * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
 */

@file:Suppress("PackageDirectoryMismatch", "SpellCheckingInspection")

import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.kotlin.dsl.maven

fun RepositoryHandler.setupForProject() {
    jcenter()

    mavenCentral().ensureGroupsStartingWith("com.jakewharton.", "com.squareup.")

    google().ensureGroups(
        "com.google.gms",
        "com.google.firebase",
        "io.fabric.sdk.android",
        "com.crashlytics.sdk.android",
        "org.chromium.net",
        "com.android"
    ).ensureGroupsStartingWith(
        "androidx.",
        "com.android.",
        "com.google.android.",
        "com.google.ar",
        "android.arch"
    )

    maven(url = "https://maven.fabric.io/public").ensureGroups("io.fabric.tools")

    maven(
        url = "https://dl.bintray.com/louiscad/splitties-dev"
    ).ensureGroups("com.louiscad.splitties")

    maven(
        url = "https://dl.bintray.com/kotlin/kotlin-eap"
    ).ensureGroups("org.jetbrains.kotlin")

    maven(
        url = "https://oss.sonatype.org/content/repositories/snapshots"
    ).ensureGroups("org.androidannotations")
}

Add missing group in google repo content

/*
 * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
 */

@file:Suppress("PackageDirectoryMismatch", "SpellCheckingInspection")

import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.kotlin.dsl.maven

fun RepositoryHandler.setupForProject() {
    jcenter()

    mavenCentral().ensureGroupsStartingWith("com.jakewharton.", "com.squareup.")

    google().ensureGroups(
        "com.google.gms",
        "com.google.firebase",
        "com.google.test.platform",
        "io.fabric.sdk.android",
        "com.crashlytics.sdk.android",
        "org.chromium.net",
        "com.android"
    ).ensureGroupsStartingWith(
        "androidx.",
        "com.android.",
        "com.google.android.",
        "com.google.ar",
        "android.arch"
    )

    maven(url = "https://maven.fabric.io/public").ensureGroups("io.fabric.tools")

    maven(
        url = "https://dl.bintray.com/louiscad/splitties-dev"
    ).ensureGroups("com.louiscad.splitties")

    maven(
        url = "https://dl.bintray.com/kotlin/kotlin-eap"
    ).ensureGroups("org.jetbrains.kotlin")

    maven(
        url = "https://oss.sonatype.org/content/repositories/snapshots"
    ).ensureGroups("org.androidannotations")
}


package flavor.pie.kludge

import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.item.inventory.Inventory
import org.spongepowered.api.item.inventory.type.GridInventory
import org.spongepowered.api.item.inventory.entity.Hotbar

val Player.storageInventory
    get() = inventory.query<Inventory>(GridInventory::class.java, Hotbar::class.java)!!

Add ChatTypeMessageReceiver methods to MessageReceiver

package flavor.pie.kludge

import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.item.inventory.Inventory
import org.spongepowered.api.item.inventory.type.GridInventory
import org.spongepowered.api.item.inventory.entity.Hotbar
import org.spongepowered.api.text.Text
import org.spongepowered.api.text.TextElement
import org.spongepowered.api.text.TextTemplate
import org.spongepowered.api.text.channel.ChatTypeMessageReceiver
import org.spongepowered.api.text.channel.MessageReceiver
import org.spongepowered.api.text.chat.ChatType

val Player.storageInventory
    get() = inventory.query<Inventory>(GridInventory::class.java, Hotbar::class.java)!!

fun MessageReceiver.sendMessage(type: ChatType, message: Text): Boolean =
        if (this is ChatTypeMessageReceiver) {
            sendMessage(type, message)
            true
        } else {
            sendMessage(message)
            false
        }

fun MessageReceiver.sendMessage(type: ChatType, template: TextTemplate): Boolean =
        if (this is ChatTypeMessageReceiver) {
            sendMessage(type, template)
            true
        } else {
            sendMessage(template)
            false
        }

fun MessageReceiver.sendMessage(type: ChatType, template: TextTemplate, parameters: Map<String, TextElement>): Boolean =
        if (this is ChatTypeMessageReceiver) {
            sendMessage(type, template, parameters)
            true
        } else {
            sendMessage(template, parameters)
            false
        }
fun MessageReceiver.sendMessages(type: ChatType, messages: Iterable<Text>): Boolean =
        if (this is ChatTypeMessageReceiver) {
            sendMessages(type, messages)
            true
        } else {
            sendMessages(messages)
            false
        }

fun MessageReceiver.sendMessage(type: ChatType, vararg messages: Text): Boolean =
        if (this is ChatTypeMessageReceiver) {
            sendMessages(type, *messages)
            true
        } else {
            sendMessages(*messages)
            false
        }


package io.aconite.utils

import java.lang.reflect.InvocationTargetException
import kotlin.coroutines.experimental.Continuation
import kotlin.coroutines.experimental.CoroutineContext
import kotlin.coroutines.experimental.suspendCoroutine
import kotlin.reflect.KFunction

/**
 * This object can be used as the return value of the async function to indicate
 * that function was suspended. This works only with function [asyncCall].
 */
val COROUTINE_SUSPENDED = Any()

private class MyContinuation<in R>(val c: Continuation<R>): Continuation<R> {
    override val context: CoroutineContext
        get() = c.context

    override fun resume(value: R) {
        if (value === COROUTINE_SUSPENDED) return
        c.resume(value)
    }

    override fun resumeWithException(exception: Throwable) {
        if (exception === COROUTINE_SUSPENDED) return
        c.resumeWithException(exception)
    }
}

/**
 * Extension for calling asynchronous functions by reflection.
 * @receiver the called function
 * @param[args] arguments of the called function
 * @return result of the called function
 */
suspend fun <R> KFunction<R>.asyncCall(vararg args: Any?) = suspendCoroutine<R> { c ->
    val cc = MyContinuation(c)
    try {
        val r = call(*args, cc)
        cc.resume(r)
    } catch (ex: InvocationTargetException) {
        throw ex.cause ?: ex
    }
}

Use of COROUTINE_SUSPENDED from Kotlin internals

package io.aconite.utils

import java.lang.reflect.InvocationTargetException
import kotlin.coroutines.experimental.suspendCoroutine
import kotlin.reflect.KFunction

/**
 * This object can be used as the return value of the async function to indicate
 * that function was suspended.
 * TODO: find better way to use suspend with reflection
 */
val COROUTINE_SUSPENDED: Any = {
    val cls = Class.forName("kotlin.coroutines.experimental.intrinsics.IntrinsicsKt")
    val field = cls.getDeclaredField("COROUTINE_SUSPENDED")
    field.isAccessible = true
    field.get(null)
}()

/**
 * Extension for calling asynchronous functions by reflection.
 * @receiver the called function
 * @param[args] arguments of the called function
 * @return result of the called function
 */
suspend fun <R> KFunction<R>.asyncCall(vararg args: Any?) = suspendCoroutine<R> { c ->
    try {
        val r = call(*args, c)
        if (r !== COROUTINE_SUSPENDED) c.resume(r)
    } catch (ex: InvocationTargetException) {
        throw ex.cause ?: ex
    }
}


plugins {
    id("org.asciidoctor.jvm.convert")
    id("org.ajoberstar.github-pages")
}

tasks.asciidoctor {
    sourceDirProperty.set(file("src/asciidoc"))
    baseDirFollowsSourceDir()
    attributes = mapOf("revnumber" to project.version.toString())
}

tasks.prepareGhPages {
    dependsOn(tasks.asciidoctor)
}

githubPages {
    setRepoUri("git@github.com:EvidentSolutions/apina.git")
    deleteExistingFiles = true

    pages(closureOf<CopySpec> {
        from(files("src/CNAME"))
        from(files("build/docs/asciidoc"))
    })
}

Build manual when running 'check'

plugins {
    id("org.asciidoctor.jvm.convert")
    id("org.ajoberstar.github-pages")
}

tasks.asciidoctor {
    sourceDirProperty.set(file("src/asciidoc"))
    baseDirFollowsSourceDir()
    attributes = mapOf("revnumber" to project.version.toString())
}

tasks.prepareGhPages {
    dependsOn(tasks.asciidoctor)
}

tasks.check {
    dependsOn(tasks.asciidoctor)
}

githubPages {
    setRepoUri("git@github.com:EvidentSolutions/apina.git")
    deleteExistingFiles = true

    pages(closureOf<CopySpec> {
        from(files("src/CNAME"))
        from(files("build/docs/asciidoc"))
    })
}


/*
 * Copyright 2019 PolyForest
 *
 * 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.
 */

plugins {
    kotlin("multiplatform")
    `maven-publish`
}

val KOTLIN_LANGUAGE_VERSION: String by extra
val KOTLIN_JVM_TARGET: String by extra
kotlin {
    js {
        compilations.all {
            kotlinOptions {
                moduleKind = "amd"
                sourceMap = true
                sourceMapEmbedSources = "always"
                main = "noCall"
            }
        }
    }
    jvm {
        compilations.all {
            kotlinOptions {
                jvmTarget = KOTLIN_JVM_TARGET
            }
        }
    }
    targets.all {
        compilations.all {
            kotlinOptions {
                languageVersion = KOTLIN_LANGUAGE_VERSION
                apiVersion = KOTLIN_LANGUAGE_VERSION
                verbose = true
            }
        }
    }

    sourceSets {
        commonMain {
            dependencies {
                implementation(kotlin("stdlib-common"))
                implementation(project(":acornui-core"))
                implementation(project(":acornui-utils"))
                implementation(project(":backends:acornui-lwjgl-backend"))
            }
        }
        commonTest {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
            }
        }
        named("jvmMain") {
            dependencies {
                implementation(kotlin("stdlib-jdk8"))
            }
        }
        named("jvmTest") {
            dependencies {
                implementation(kotlin("test"))
                implementation(kotlin("test-junit"))
            }
        }
        named("jsMain") {
            dependencies {
                implementation(kotlin("stdlib-js"))
            }
        }
        named("jsTest") {
            dependencies {
                implementation(kotlin("test-js"))
            }
        }
    }
}

Refactor acornui-texture-packer to use 'basic' plugin

/*
 * Copyright 2019 PolyForest
 *
 * 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.
 */

plugins {
    id("com.polyforest.acornui.basic")
    `maven-publish`
}

kotlin {
    sourceSets {
        commonMain {
            dependencies {
                implementation(project(":acornui-core"))
                implementation(project(":acornui-utils"))
                implementation(project(":backends:acornui-lwjgl-backend"))
            }
        }
    }
}


/*
 * Copyright 2019 PolyForest
 *
 * 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.
 */

plugins {
    kotlin("multiplatform")
    `maven-publish`
}

val KOTLIN_LANGUAGE_VERSION: String by extra
val KOTLIN_JVM_TARGET: String by extra
kotlin {
    js {
        compilations.all {
            kotlinOptions {
                moduleKind = "amd"
                sourceMap = true
                sourceMapEmbedSources = "always"
                main = "noCall"
            }
        }
    }
    jvm {
        compilations.all {
            kotlinOptions {
                jvmTarget = KOTLIN_JVM_TARGET
            }
        }
    }
    targets.all {
        compilations.all {
            kotlinOptions {
                languageVersion = KOTLIN_LANGUAGE_VERSION
                apiVersion = KOTLIN_LANGUAGE_VERSION
                verbose = true
            }
        }
    }
    sourceSets {
        commonMain {
            dependencies {
                implementation(kotlin("stdlib-common"))
                implementation(project(":acornui-core"))
                implementation(project(":acornui-utils"))
            }
        }
        commonTest {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
            }
        }
        named("jvmMain") {
            dependencies {
                implementation(kotlin("stdlib-jdk8"))
            }
        }
        named("jvmTest") {
            dependencies {
                implementation(kotlin("test"))
                implementation(kotlin("test-junit"))
            }
        }
        named("jsMain") {
            dependencies {
                implementation(kotlin("stdlib-js"))
            }
        }
        named("jsTest") {
            dependencies {
                implementation(kotlin("test-js"))
            }
        }
    }
}

Refactor acornui-spine to use 'basic' plugin

/*
 * Copyright 2019 PolyForest
 *
 * 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.
 */

plugins {
    id("com.polyforest.acornui.basic")
    `maven-publish`
}

kotlin {
    sourceSets {
        commonMain {
            dependencies {
                implementation(project(":acornui-core"))
                implementation(project(":acornui-utils"))
            }
        }
    }
}