plugins {
    java
}

repositories {
    mavenCentral()
}

// tag::exclude-transitive-dependencies[]
configurations {
    "implementation" {
        exclude(group = "commons-collections", module = "commons-collections")
    }
}

dependencies {
    implementation("commons-beanutils:commons-beanutils:1.9.4")
    implementation("com.opencsv:opencsv:4.6")
}
// end::exclude-transitive-dependencies[]

tasks.register("printArtifacts") {
    val runtimeClasspath: FileCollection = configurations["runtimeClasspath"]
    doLast {
        runtimeClasspath.forEach { println(it.name) }
    }
}

Adjust the snippet for configuration cache

plugins {
    java
}

repositories {
    mavenCentral()
}

// tag::exclude-transitive-dependencies[]
configurations {
    "implementation" {
        exclude(group = "commons-collections", module = "commons-collections")
    }
}

dependencies {
    implementation("commons-beanutils:commons-beanutils:1.9.4")
    implementation("com.opencsv:opencsv:4.6")
}
// end::exclude-transitive-dependencies[]

tasks.register("printArtifacts") {
    val runtimeClasspath: FileCollection = configurations.runtimeClasspath.get()
    doLast {
        runtimeClasspath.forEach { println(it.name) }
    }
}


/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines

import kotlin.coroutines.*

internal actual fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable) {
    // log exception
    println(exception)
}

Print stack trace in default exception handler in K/N

/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines

import kotlin.coroutines.*

internal actual fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable) {
    // log exception
    exception.printStackTrace()
}


package dependencies

object Versions {

    const val versionName = "2.6.0"

    const val targetSdk = 28
    const val minSdk = 9
    const val minSdkWithSupportLibrary = 14

    internal const val kotlin = "1.2.71"
    internal const val junit = "4.12"
    internal const val robolectric = "3.8"
    internal const val assertj = "3.11.1"
    internal const val gson = "2.8.5"
    internal const val liveData = "2.0.0"

    internal const val androidGradlePlugin = "3.2.1"
    internal const val bintrayGradlePlugin = "1.8.4"
    internal const val androidMavenGradlePlugin = "2.1"
    internal const val dokkaAndroidGradlePlugin = "0.9.17"

    internal const val jacoco = "0.8.2"
    internal const val mockito = "2.23.0"
    internal const val mockitoKotlin = "1.6.0"

    internal object AndroidX {
        internal const val appCompat = "1.0.0"
        internal const val preference = "1.0.0"
    }
}

Update kotlin and gradle plugin

package dependencies

object Versions {

    const val versionName = "2.6.0"

    const val targetSdk = 28
    const val minSdk = 9
    const val minSdkWithSupportLibrary = 14

    internal const val kotlin = "1.3.10"
    internal const val junit = "4.12"
    internal const val robolectric = "3.8"
    internal const val assertj = "3.11.1"
    internal const val gson = "2.8.5"
    internal const val liveData = "2.0.0"

    internal const val androidGradlePlugin = "3.3.0-beta04"
    internal const val bintrayGradlePlugin = "1.8.4"
    internal const val androidMavenGradlePlugin = "2.1"
    internal const val dokkaAndroidGradlePlugin = "0.9.17"

    internal const val jacoco = "0.8.2"
    internal const val mockito = "2.23.0"
    internal const val mockitoKotlin = "1.6.0"

    internal object AndroidX {
        internal const val appCompat = "1.0.0"
        internal const val preference = "1.0.0"
    }
}


package ee.schkola

import ee.design.gen.DesingKotlinGenerator
import ee.lang.integ.eePath

fun main(args: Array<String>) {
    val generator = DesingKotlinGenerator(model())
    generator.generate(eePath)
}

Improve deletion of src-gen folders

package ee.schkola

import ee.design.gen.DesignKotlinGenerator
import ee.lang.integ.eePath

fun main(args: Array<String>) {
    val generator = DesignKotlinGenerator(model())
    generator.generate(eePath)
}


description = "Identify hidden, unlinked parameters. Useful for finding web cache poisoning vulnerabilities."

zapAddOn {
    addOnName.set("Parameter Digger")
    zapVersion.set("2.11.1")

    manifest {
        author.set("ZAP Dev Team and Arkaprabha Chakraborty")

        dependencies {
            addOns {
                register("commonlib") {
                    version.set(">= 1.9.0 & < 2.0.0")
                }
            }
        }
    }
}

dependencies {
    compileOnly(parent!!.childProjects.get("commonlib")!!)

    testImplementation(parent!!.childProjects.get("commonlib")!!)
    testImplementation(project(":testutils"))
}

crowdin {
    configuration {
        val resourcesPath = "org/zaproxy/addon/${zapAddOn.addOnId.get()}/resources/"
        tokens.put("%messagesPath%", resourcesPath)
        tokens.put("%helpPath%", resourcesPath)
    }
}

Add help docs URL in manifest

description = "Identify hidden, unlinked parameters. Useful for finding web cache poisoning vulnerabilities."

zapAddOn {
    addOnName.set("Parameter Digger")
    zapVersion.set("2.11.1")

    manifest {
        author.set("ZAP Dev Team and Arkaprabha Chakraborty")
        url.set("https://www.zaproxy.org/docs/desktop/addons/parameter-digger/")

        dependencies {
            addOns {
                register("commonlib") {
                    version.set(">= 1.9.0 & < 2.0.0")
                }
            }
        }
    }
}

dependencies {
    compileOnly(parent!!.childProjects.get("commonlib")!!)

    testImplementation(parent!!.childProjects.get("commonlib")!!)
    testImplementation(project(":testutils"))
}

crowdin {
    configuration {
        val resourcesPath = "org/zaproxy/addon/${zapAddOn.addOnId.get()}/resources/"
        tokens.put("%messagesPath%", resourcesPath)
        tokens.put("%helpPath%", resourcesPath)
    }
}


package org.runestar.client.plugins.dev

import com.google.common.collect.Iterables
import org.runestar.client.game.api.live.LiveCanvas
import org.runestar.client.game.api.live.Npcs
import org.runestar.client.game.api.live.Players
import org.runestar.client.game.api.live.Projectiles
import org.runestar.client.plugins.spi.PluginSettings
import org.runestar.client.utils.DisposablePlugin
import java.awt.Color

class BoundingBoxTest : DisposablePlugin<PluginSettings>() {

    override val defaultSettings = PluginSettings()

    override fun start() {
        add(LiveCanvas.repaints.subscribe { g ->
            g.color = Color.WHITE

            val actors = Iterables.concat(Npcs, Players)
            actors.forEach { actor ->
                val m = actor.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            Projectiles.forEach { p ->
                val m = p.model ?: return@forEach
                m.drawBoundingBox(g)
            }
        })
    }
}


package com.github.ramonrabello.kiphy.trends

import com.github.ramonrabello.kiphy.data.model.Trending

/**
 * MVP contract for Giphy Trending API.
 */
interface TrendingContract {

    /**
     * View for Trending contract.
     */
    interface View {
        fun showProgress()
        fun hideProgress()
        fun showTrending(trending: Trending)
        fun showApikeyError()
        fun showTrendingError()
    }

    /**
     * Presenter for Trending contract.
     */
    interface Presenter {
        fun loadTrending()
        fun onTrendingClick(view:View)
    }
}

Refactor of method names for better readability.

package com.github.ramonrabello.kiphy.trends

import com.github.ramonrabello.kiphy.trends.model.TrendingResponse

/**
 * MVP contract for Giphy Trending API.
 */
interface TrendingContract {

    /**
     * View for Trending contract.
     */
    interface View {
        fun showProgress()
        fun hideProgress()
        fun showTrending(trending: TrendingResponse)
        fun showApiKeyNotSetDialog()
        fun showTrendingError()
    }

    /**
     * Presenter for Trending contract.
     */
    interface Presenter {
        fun loadTrends()
    }
}


package com.github.shiraji.breakpointsmanager.model

data class BreakpointState(var entities: MutableMap<String, List<BreakpointEntity>> = mutableMapOf())

Make list of breakpoints mutable

package com.github.shiraji.breakpointsmanager.model

data class BreakpointState(var entities: MutableMap<String, MutableList<BreakpointEntity>> = mutableMapOf())


package org.jetbrains.ktor.netty

import io.netty.channel.*
import org.jetbrains.ktor.cio.*
import java.nio.*

internal class HttpContentWriteChannel(val context: ChannelHandlerContext) : WriteChannel {
    private val allocator = context.alloc()

    override suspend fun write(src: ByteBuffer) {
        while (src.hasRemaining()) {
            val buffer = allocator.buffer(src.remaining())
            buffer.writeBytes(src)
            context.writeAndFlush(buffer).suspendAwait()
        }
    }

    suspend override fun flush() {
        context.flush() // TODO: does it really completes flush once it returns? seems to be it doesn't
    }

    override fun close() {
        context.flush()
    }
}

Use `ioBuffer` to avoid redundant data copy for sending to sockets

package org.jetbrains.ktor.netty

import io.netty.channel.*
import org.jetbrains.ktor.cio.*
import java.nio.*

internal class HttpContentWriteChannel(val context: ChannelHandlerContext) : WriteChannel {
    private val allocator = context.alloc()

    override suspend fun write(src: ByteBuffer) {
        while (src.hasRemaining()) {
            val buffer = allocator.ioBuffer(src.remaining())
            buffer.writeBytes(src)
            context.writeAndFlush(buffer).suspendAwait()
        }
    }

    suspend override fun flush() {
        context.flush() // TODO: does it really completes flush once it returns? seems to be it doesn't
    }

    override fun close() {
        context.flush()
    }
}


object BuildPluginsVersion {
    const val AGP = "4.1.0"
    const val KOTLIN = "1.4.10"
    const val KOTLINTER = "3.0.2"
    const val VERSIONS_PLUGIN = "0.33.0"
}

Update AGP for AS 4.1.1

object BuildPluginsVersion {
    const val AGP = "4.1.1"
    const val KOTLIN = "1.4.10"
    const val KOTLINTER = "3.0.2"
    const val VERSIONS_PLUGIN = "0.33.0"
}


/*
 * This is an init script for internal usage at Gradle Inc.
 */
val tasksWithBuildScansOnFailure = listOf("verifyTestFilesCleanup", "killExistingProcessesStartedByGradle", "tagBuild").map { listOf(it)}

if (!gradle.startParameter.systemPropertiesArgs.containsKey("disableScanPlugin")) {
    rootProject {
        pluginManager.withPlugin("com.gradle.build-scan") {
            extensions["buildScan"].withGroovyBuilder {
                if (gradle.startParameter.taskNames in tasksWithBuildScansOnFailure) {
                    "publishOnFailure"()
                } else {
                    "publishAlways"()
                }
                setProperty("server", "https://e.grdev.net")

                if (metaClass.hasProperty(delegate, "captureTaskInputFiles") != null) {
                    if (!System.getProperty("slow.internet.connection", "false").toBoolean()) {
                        setProperty("captureTaskInputFiles", true)
                    }
                }
            }
        }
    }
}

Use Hetzner internal build cache node

/*
 * This is an init script for internal usage at Gradle Inc.
 */
val tasksWithBuildScansOnFailure = listOf("verifyTestFilesCleanup", "killExistingProcessesStartedByGradle", "tagBuild").map { listOf(it)}

if (!gradle.startParameter.systemPropertiesArgs.containsKey("disableScanPlugin")) {
    rootProject {
        pluginManager.withPlugin("com.gradle.build-scan") {
            extensions["buildScan"].withGroovyBuilder {
                if (gradle.startParameter.taskNames in tasksWithBuildScansOnFailure) {
                    "publishOnFailure"()
                } else {
                    "publishAlways"()
                }
                setProperty("server", "https://cache-node-hetzner.grdev.net")

                if (metaClass.hasProperty(delegate, "captureTaskInputFiles") != null) {
                    if (!System.getProperty("slow.internet.connection", "false").toBoolean()) {
                        setProperty("captureTaskInputFiles", true)
                    }
                }
            }
        }
    }
}


package io.ktor.samples.gson

import io.ktor.application.*
import io.ktor.features.*
import io.ktor.gson.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*

data class Model(val name: String, val items: List<Item>)
data class Item(val key: String, val value: String)

/*
         > curl -v --compress --header "Accept: application/gson" http://localhost:8080/v1
         {"name":"root","items":[{"key":"A","value":"Apache"},{"key":"B","value":"Bing"}]}

         > curl -v --compress --header "Accept: application/gson" http://localhost:8080/v1/item/A
         {"key":"A","value":"Apache"}
     */

fun Application.main() {
    install(DefaultHeaders)
    install(Compression)
    install(CallLogging)
    install(ContentNegotiation) {
        register(ContentType.Application.Json, GsonConverter())
    }

    val model = Model("root", listOf(Item("A", "Apache"), Item("B", "Bing")))
    routing {
        get("/v1") {
            call.respond(model)
        }
        get("/v1/item/{key}") {
            val item = model.items.firstOrNull { it.key == call.parameters["key"] }
            if (item == null)
                call.respond(HttpStatusCode.NotFound)
            else
                call.respond(item)
        }
    }
}

Add DSL config to the gson-sample

package io.ktor.samples.gson

import io.ktor.application.*
import io.ktor.features.*
import io.ktor.gson.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import java.text.*

data class Model(val name: String, val items: List<Item>)
data class Item(val key: String, val value: String)

/*
         > curl -v --compress --header "Accept: application/gson" http://localhost:8080/v1
         {"name":"root","items":[{"key":"A","value":"Apache"},{"key":"B","value":"Bing"}]}
         The result is pretty printed, to show off how to configure gson, but it is
         possible to use the default gson as well

         > curl -v --compress --header "Accept: application/gson" http://localhost:8080/v1/item/A
         {"key":"A","value":"Apache"}
     */

fun Application.main() {
    install(DefaultHeaders)
    install(Compression)
    install(CallLogging)
    install(ContentNegotiation) {
        gson {
            setDateFormat(DateFormat.LONG)
            setPrettyPrinting()
        }
    }
    val model = Model("root", listOf(Item("A", "Apache"), Item("B", "Bing")))
    routing {
        get("/v1") {
            call.respond(model)
        }
        get("/v1/item/{key}") {
            val item = model.items.firstOrNull { it.key == call.parameters["key"] }
            if (item == null)
                call.respond(HttpStatusCode.NotFound)
            else
                call.respond(item)
        }
    }
}


package org.runestar.client.plugins.dev

import org.runestar.client.api.util.DisposablePlugin
import org.runestar.client.game.api.Model
import org.runestar.client.game.api.SceneObject
import org.runestar.client.game.api.live.*
import org.runestar.client.game.raw.access.XScene
import org.runestar.client.plugins.spi.PluginSettings
import java.awt.Color
import java.awt.Graphics2D

class ModelDrawTest : DisposablePlugin<PluginSettings>() {

    override val defaultSettings = PluginSettings()

    private val objs: MutableSet<SceneObject> = LinkedHashSet()

    override fun start() {
        objs.addAll(SceneObjects.all())
        add(XScene.clear.exit.subscribe { objs.clear() })
        add(SceneObjects.removals.subscribe { objs.remove(it) })
        add(SceneObjects.additions.subscribe { objs.add(it) })

        add(LiveCanvas.repaints.subscribe { g ->

            g.color = Color.CYAN
            objs.forEach {
                it.models.forEach { drawModel(g, it) }
            }

            g.color = Color.WHITE
            Players.forEach {
                it.model?.let { drawModel(g, it) }
            }

            g.color = Color.YELLOW
            Npcs.forEach {
                it.model?.let { drawModel(g, it) }
            }

            g.color = Color.GREEN
            Projectiles.forEach {
                it.model?.let { drawModel(g, it) }
            }

            // todo: ground items
        })
    }

    private fun drawModel(g: Graphics2D, model: Model) {
        val pos = model.base
        val tile = pos.sceneTile
        if (!tile.isLoaded || !Game.visibilityMap.isVisible(tile)) return
        val pt = pos.toScreen() ?: return
        if (pt !in LiveViewport.shape) return
        model.drawWireFrame(g.color)
    }
}


Add test for DetectLeaksAfterTestSuccess test rule

package leakcanary

import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement

class DetectLeaksAfterTestSuccessTest {

  object CheckAssertNoLeaksInvoked : TestRule {
    override fun apply(base: Statement, description: Description): Statement {
      return object : Statement() {
        override fun evaluate() {
          try {
            var assertNoLeaksInvoked = false
            DetectLeaksAssert.update { tag ->
              assertNoLeaksInvoked = true
            }
            base.evaluate()
            assertThat(assertNoLeaksInvoked).isTrue()
          } finally {
            DetectLeaksAssert.update(AndroidDetectLeaksAssert())
          }
        }
      }
    }
  }

  @get:Rule
  val rule = RuleChain.outerRule(CheckAssertNoLeaksInvoked).around(DetectLeaksAfterTestSuccess())

  @Test fun emptyTest() {
    // This test triggers the rules.
  }
}


package io.particle.particlemesh.meshsetup

// FIXME: REVIEW ALL THESE VALUES!

const val BLE_PROTO_REQUEST_TIMEOUT_MILLIS = 8000

Add longer timeouts due to longish processing times on devices

package io.particle.particlemesh.meshsetup

// FIXME: REVIEW ALL THESE VALUES!

// this has to be LONG for some of the messages to be processed (like AuthRequest)
const val BLE_PROTO_REQUEST_TIMEOUT_MILLIS = 15000


Add traits sample although this one generates exception.

package Objects.Traits

fun main(args : Array<String>){
    var adam = Cowboy("Adam")
    adam.does()
}

trait Shooting {
    abstract var name : String
    fun does(){
        print("$name can Shoot")
    }
}

class Cowboy (name : String): Shooting{
   override var name = name
}


package iii_properties

import junit.framework.Assert
import org.junit.Test as test

class _18_Properties {
    test fun testPropertyWithCounter() {
        val q = PropertyExample()
        q.propertyWithCounter = 14
        q.propertyWithCounter = 21
        q.propertyWithCounter = 32
        Assert.assertEquals("The property q.changeCounter should contain the number of assignments to q.propertyWithCounter:",
                3, q.counter)
        Assert.assertEquals("The property q.propertyWithCounter should be set:", 32, q.propertyWithCounter)
    }

}

Build fix: workaround for false smart cast impossible

package iii_properties

import junit.framework.Assert
import org.junit.Test as test

class _18_Properties {
    test fun testPropertyWithCounter() {
        val q = PropertyExample()
        q.propertyWithCounter = 14
        q.propertyWithCounter = 21
        q.propertyWithCounter = 32
        Assert.assertEquals("The property q.changeCounter should contain the number of assignments to q.propertyWithCounter:",
                3, q.counter)
        // Here we have to use !! due to false smart cast impossible
        Assert.assertEquals("The property q.propertyWithCounter should be set:", 32, q.propertyWithCounter!!)
    }

}


import org.apollo.game.model.entity.Skill
import org.apollo.game.model.entity.SkillSet
import org.apollo.game.model.entity.setting.PrivilegeLevel

/**
 * Maximises the player's skill set.
 */
on_command("max", PrivilegeLevel.ADMINISTRATOR)
        .then { player ->
            val skills = player.skillSet

            for (skill in 0 until skills.size()) {
                skills.addExperience(skill, SkillSet.MAXIMUM_EXP)
            }
        }

/**
 * Levels the specified skill to the specified level, optionally updating the current level as well.
 */
on_command("level", PrivilegeLevel.ADMINISTRATOR)
        .then { player ->
            val invalidSyntax = "Invalid syntax - ::level [skill-id] [level] <old>"
            if (arguments.size !in 2..3) {
                player.sendMessage(invalidSyntax)
                return@then
            }

            val skillId = arguments[0].toInt()
            val level = arguments[1].toInt()
            if (skillId !in 0..20 || level !in 1..99) {
                player.sendMessage(invalidSyntax)
                return@then
            }

            val experience = SkillSet.getExperienceForLevel(level).toDouble()
            var current = level

            if (arguments.size == 3 && arguments[2] == "old") {
                val skill = player.skillSet.getSkill(skillId)
                current = skill.currentLevel
            }

            player.skillSet.setSkill(skillId, Skill(experience, current, level))
        }

/**
 * Adds the specified amount of experience to the specified skill.
 */
on_command("xp", PrivilegeLevel.ADMINISTRATOR)
        .then { player ->
            val invalidSyntax = "Invalid syntax - ::xp [skill-id] [experience]"
            if (arguments.size != 2) {
                player.sendMessage(invalidSyntax)
                return@then
            }

            val skillId = arguments[0].toInt()
            val experience = arguments[1].toDouble()
            if (skillId !in 0..20 || experience <= 0) {
                player.sendMessage("Invalid syntax - ::xp [skill-id] [experience]")
                return@then
            }

            player.skillSet.addExperience(skillId, experience)
        }


package io.clappr.player.utils

import org.junit.Assert.*
import org.junit.Test

class EnvironmentTest {

    @Test
    fun `should have a not empty playerId`() {
        val environment = Environment()

        assertFalse(environment.playerId.isEmpty())
    }
}


// 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.changes

import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.jetbrains.changeReminder.anyGitRootsForIndexing
import com.jetbrains.changeReminder.getGitRoots
import com.jetbrains.changeReminder.plugin.UserSettings

class ChangeReminderCheckAction :
  ToggleAction(),
  DumbAware {

  private val userSettings = service<UserSettings>()

  override fun update(e: AnActionEvent) {
    super.update(e)
    val project = e.project!!
    if (!project.anyGitRootsForIndexing()) {
      e.presentation.isEnabled = false
      if (project.getGitRoots().isEmpty()) {
        e.presentation.isVisible = false
      }
      else {
        e.presentation.description = "Git index is disabled"
      }
    }
  }

  override fun isSelected(e: AnActionEvent) = userSettings.isPluginEnabled

  override fun setSelected(e: AnActionEvent, state: Boolean) {
    userSettings.isPluginEnabled = state
  }
}

Fix NPE: event may not contain project

// 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.changes

import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.jetbrains.changeReminder.anyGitRootsForIndexing
import com.jetbrains.changeReminder.getGitRoots
import com.jetbrains.changeReminder.plugin.UserSettings

class ChangeReminderCheckAction :
  ToggleAction(),
  DumbAware {

  private val userSettings = service<UserSettings>()

  override fun update(e: AnActionEvent) {
    super.update(e)
    val project = e.project ?: let {
      e.presentation.isEnabledAndVisible = false
      return
    }
    if (!project.anyGitRootsForIndexing()) {
      e.presentation.isEnabled = false
      if (project.getGitRoots().isEmpty()) {
        e.presentation.isVisible = false
      }
      else {
        e.presentation.description = "Git index is disabled"
      }
    }
  }

  override fun isSelected(e: AnActionEvent) = userSettings.isPluginEnabled

  override fun setSelected(e: AnActionEvent, state: Boolean) {
    userSettings.isPluginEnabled = state
  }
}


package jetbrains.buildServer.nuget.agent.util.impl

import com.intellij.openapi.util.SystemInfo
import jetbrains.buildServer.nuget.agent.util.SystemInformation

class SystemInformationImpl : SystemInformation {
    override val isWindows: Boolean
        get() = SystemInfo.isWindows

    override val userName: String by lazy {
        if (SystemInfo.isWindows) {
            try {
                Class.forName("com.sun.security.auth.module.NTSystem")
                return@lazy com.sun.security.auth.module.NTSystem().name
            } catch (ignored: ClassNotFoundException) {
            }
        }
        System.getProperty("user.name")
    }
}

Fix compilation under linux due to NTSystem usage

package jetbrains.buildServer.nuget.agent.util.impl

import com.intellij.openapi.util.SystemInfo
import jetbrains.buildServer.nuget.agent.util.SystemInformation

class SystemInformationImpl : SystemInformation {
    override val isWindows: Boolean
        get() = SystemInfo.isWindows

    override val userName: String by lazy {
        if (SystemInfo.isWindows) {
            try {
                Class.forName("com.sun.security.auth.module.NTSystem")?.let { ntSystemClass ->
                    val ntSystem = ntSystemClass.newInstance()
                    val getNameMethod = ntSystem.javaClass.getMethod("getName")
                    return@lazy getNameMethod.invoke(ntSystem) as String
                }
            } catch (ignored: ClassNotFoundException) {
            }
        }
        System.getProperty("user.name")
    }
}


package com.jakewharton.diffuse.report.text

import com.jakewharton.diffuse.ArchiveFile.Type
import com.jakewharton.diffuse.diff.JarDiff
import com.jakewharton.diffuse.diff.toDetailReport
import com.jakewharton.diffuse.diff.toSummaryTable
import com.jakewharton.diffuse.report.DiffReport

internal class JarDiffTextReport(private val jarDiff: JarDiff) : DiffReport {
  override fun write(appendable: Appendable) {
    appendable.apply {
      append("OLD: ")
      append(jarDiff.newJar.filename)

      append("NEW: ")
      append(jarDiff.newJar.filename)

      appendln()
      appendln(jarDiff.archive.toSummaryTable("JAR", Type.JAR_TYPES))
      appendln()
      appendln(jarDiff.jars.toSummaryTable())
      if (jarDiff.archive.changed) {
        appendln()
        appendln("=================")
        appendln("====   JAR   ====")
        appendln("=================")
        appendln(jarDiff.archive.toDetailReport())
      }
      if (jarDiff.jars.changed) {
        appendln()
        appendln("=====================")
        appendln("====   CLASSES   ====")
        appendln("=====================")
        appendln(jarDiff.jars.toDetailReport())
      }
    }
  }

  override fun toString() = buildString { write(this) }
}

Add missing newlines to jar diff text report

package com.jakewharton.diffuse.report.text

import com.jakewharton.diffuse.ArchiveFile.Type
import com.jakewharton.diffuse.diff.JarDiff
import com.jakewharton.diffuse.diff.toDetailReport
import com.jakewharton.diffuse.diff.toSummaryTable
import com.jakewharton.diffuse.report.DiffReport

internal class JarDiffTextReport(private val jarDiff: JarDiff) : DiffReport {
  override fun write(appendable: Appendable) {
    appendable.apply {
      append("OLD: ")
      appendln(jarDiff.oldJar.filename)

      append("NEW: ")
      appendln(jarDiff.newJar.filename)

      appendln()
      appendln(jarDiff.archive.toSummaryTable("JAR", Type.JAR_TYPES))
      appendln()
      appendln(jarDiff.jars.toSummaryTable())
      if (jarDiff.archive.changed) {
        appendln()
        appendln("=================")
        appendln("====   JAR   ====")
        appendln("=================")
        appendln(jarDiff.archive.toDetailReport())
      }
      if (jarDiff.jars.changed) {
        appendln()
        appendln("=====================")
        appendln("====   CLASSES   ====")
        appendln("=====================")
        appendln(jarDiff.jars.toDetailReport())
      }
    }
  }

  override fun toString() = buildString { write(this) }
}


plugins {
    java
}

// tag::file-deps[]
repositories {
    flatDir {
        name = "libs dir"
        dir(file("libs"))  // <1>
    }
}

dependencies {
    implementation(files("libs/our-custom.jar"))  // <2>
    implementation(":log4j:1.2.8")     // <3>
    implementation(":commons-io:2.1")  // <3>
}
// end::file-deps[]

// tag::retrieve-deps[]
tasks {
    create<Copy>("retrieveRuntimeDependencies") {
        into("$buildDir/libs")
        from(configurations.runtimeClasspath)
    }
}
// end::retrieve-deps[]

// tag::properties[]
val tmpDistDir by extra { file("$buildDir/dist") }

tasks {
    create<Jar>("javadocJar") {
        from(tasks.javadoc)  // <1>
        classifier = "javadoc"
    }

    create<Copy>("unpackJavadocs") {
        from(zipTree(tasks.getByName<Jar>("javadocJar").archivePath))  // <2>
        into(tmpDistDir)  // <3>
    }
}
// end::properties[]

Fix ant import Kotlin DSL samples

plugins {
    java
}

// tag::file-deps[]
repositories {
    flatDir {
        name = "libs dir"
        dir(file("libs"))  // <1>
    }
}

dependencies {
    implementation(files("libs/our-custom.jar"))  // <2>
    implementation(":log4j:1.2.8")     // <3>
    implementation(":commons-io:2.1")  // <3>
}
// end::file-deps[]

// tag::retrieve-deps[]
tasks {
    create<Copy>("retrieveRuntimeDependencies") {
        into("$buildDir/libs")
        from(configurations.runtimeClasspath)
    }
}
// end::retrieve-deps[]

// tag::properties[]
val tmpDistDir by extra { file("$buildDir/dist") }

tasks {
    create<Jar>("javadocJar") {
        from(javadoc)  // <1>
        classifier = "javadoc"
    }

    create<Copy>("unpackJavadocs") {
        from(zipTree(getByName<Jar>("javadocJar").archivePath))  // <2>
        into(tmpDistDir)  // <3>
    }
}
// end::properties[]


package com.sandjelkovic.dispatchd.content.daemon

import com.sandjelkovic.dispatchd.content.contentRefreshTaskExecutorBeanName
import com.sandjelkovic.dispatchd.content.service.ContentRefreshService
import mu.KLogging
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component

/**
 * @author sandjelkovic
 * @date 10.2.18.
 */
@Component
class Scheduler(val contentRefreshService: ContentRefreshService) {
    companion object : KLogging()

    @Async(contentRefreshTaskExecutorBeanName)
    @Scheduled(fixedDelayString = "#{\${content.refresh.interval.minutes:1}*1000*60}", initialDelay = (1000 * 5).toLong())
    fun invokeContentRefresh() {
        logger.info("Content refresh started.")
        try {
            val count = contentRefreshService.updateContentIfStale()
            logger.info("Content refresh finished. Updated $count shows.", count)
        } catch (e: RuntimeException) {
            logger.info("Exception occurred during content refresh", e)
        }
    }
}

Fix import return value handling

package com.sandjelkovic.dispatchd.content.daemon

import com.sandjelkovic.dispatchd.content.contentRefreshTaskExecutorBeanName
import com.sandjelkovic.dispatchd.content.service.ContentRefreshService
import mu.KLogging
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component

/**
 * @author sandjelkovic
 * @date 10.2.18.
 */
@Component
class Scheduler(val contentRefreshService: ContentRefreshService) {
    companion object : KLogging()

    @Async(contentRefreshTaskExecutorBeanName)
    @Scheduled(fixedDelayString = "#{\${content.refresh.interval.minutes:1}*1000*60}", initialDelay = (1000 * 5).toLong())
    fun invokeContentRefresh() {
        logger.info("Content refresh started.")
        try {
            contentRefreshService.updateContentIfStale()
                .fold(
                    { logger.warn("Exception occurred during content refresh", it) },
                    { logger.info("Content refresh finished. Updated ${it.size} shows.") }
                )
        } catch (e: RuntimeException) {
            logger.info("Exception occurred during content refresh", e)
        }
    }
}


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

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

kotlin {
    jvm()
    js { useCommonJs() }
    macos()
    ios(supportArm32 = true)
    configure(targets) { configureMavenPublication() }
    setupSourceSets()
    sourceSets {
        commonMain.dependencies {
            api(Kotlin.stdlib.common)
        }
        jvmMain.dependencies {
            api(Kotlin.stdlib.jdk7)
        }
        jsMain.dependencies {
            api(Kotlin.stdlib.js)
        }
    }
}

publishing {
    setupAllPublications(project)
}

Add Linux & MingW x64 support to bitflags

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

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

kotlin {
    jvm()
    js { useCommonJs() }
    macos()
    ios(supportArm32 = true)
    linux(x64 = true)
    mingw(x64 = true)
    configure(targets) { configureMavenPublication() }
    setupSourceSets()
    sourceSets {
        commonMain.dependencies {
            api(Kotlin.stdlib.common)
        }
        jvmMain.dependencies {
            api(Kotlin.stdlib.jdk7)
        }
        jsMain.dependencies {
            api(Kotlin.stdlib.js)
        }
    }
}

publishing {
    setupAllPublications(project)
}


val deps: Map<String, String> by extra

dependencies {
    implementation(project(":shims"))

    testImplementation("org.junit.jupiter:junit-jupiter-api:${deps["jupiter"]}")
    testImplementation("org.junit.jupiter:junit-jupiter-params:${deps["jupiter"]}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${deps["jupiter"]}")
    testImplementation("com.google.guava:guava:${deps["guava"]}")
    testImplementation("org.apache.commons:commons-lang3:${deps["commons-lang"]}")
    testImplementation("com.esotericsoftware:kryo:5.0.0-RC6")
    testImplementation("com.fasterxml.jackson.core", "jackson-databind", "2.10.3")
}

tasks.test {
    systemProperty("kryo.unsafe", "false")
    mustRunAfter(tasks.checkstyleMain)
    useJUnitPlatform()
    failFast = true
}

Add details in logs about failed tests

val deps: Map<String, String> by extra

dependencies {
    implementation(project(":shims"))

    testImplementation("org.junit.jupiter:junit-jupiter-api:${deps["jupiter"]}")
    testImplementation("org.junit.jupiter:junit-jupiter-params:${deps["jupiter"]}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${deps["jupiter"]}")
    testImplementation("com.google.guava:guava:${deps["guava"]}")
    testImplementation("org.apache.commons:commons-lang3:${deps["commons-lang"]}")
    testImplementation("com.esotericsoftware:kryo:5.0.0-RC6")
    testImplementation("com.fasterxml.jackson.core", "jackson-databind", "2.10.3")
}

tasks.test {
    systemProperty("kryo.unsafe", "false")
    mustRunAfter(tasks.checkstyleMain)
    useJUnitPlatform()
    failFast = true
    testLogging {
        // We exclude 'passed' events
        events( "skipped", "failed")
        showStackTraces = true
        exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
    }
}


import org.jetbrains.kotlin.gradle.dsl.Coroutines

plugins {
    application
    id("nebula.kotlin") version "1.1.0"
}

application {
    mainClassName = "samples.HelloCoroutinesKt"
}

kotlin { // configure<org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension>
    experimental.coroutines = Coroutines.ENABLE
}

repositories {
    jcenter()
}

Revert "Decorrelate the embedded kotlin and nebula.kotlin versions in samples"

import org.jetbrains.kotlin.gradle.dsl.Coroutines

plugins {
    application
    id("nebula.kotlin") version embeddedKotlinVersion
}

application {
    mainClassName = "samples.HelloCoroutinesKt"
}

kotlin { // configure<org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension>
    experimental.coroutines = Coroutines.ENABLE
}

repositories {
    jcenter()
}


package com.squareup.sqldelight.intellij

import com.alecstrong.sql.psi.core.DialectPreset
import com.intellij.icons.AllIcons
import com.intellij.ide.FileIconProvider
import com.intellij.lang.LanguageUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.squareup.sqldelight.core.SqlDelightProjectService
import com.squareup.sqldelight.core.lang.SqlDelightLanguage
import javax.swing.Icon

class SqlDelightFileIconProvider : FileIconProvider {

  override fun getIcon(file: VirtualFile, flags: Int, project: Project?): Icon? {
    return if (project != null && LanguageUtil.getFileLanguage(file) == SqlDelightLanguage) {
      when (SqlDelightProjectService.getInstance(project).dialectPreset) {
        DialectPreset.SQLITE_3_18 -> AllIcons.Providers.Sqlite
        DialectPreset.SQLITE_3_24 -> AllIcons.Providers.Sqlite
        DialectPreset.MYSQL -> AllIcons.Providers.Mysql
        DialectPreset.POSTGRESQL -> AllIcons.Providers.Postgresql
        DialectPreset.HSQL -> AllIcons.Providers.Hsqldb
      }
    } else {
      null
    }
  }
}

Add support for dialect icons for migration files

package com.squareup.sqldelight.intellij

import com.alecstrong.sql.psi.core.DialectPreset
import com.intellij.icons.AllIcons
import com.intellij.ide.FileIconProvider
import com.intellij.lang.LanguageUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.squareup.sqldelight.core.SqlDelightProjectService
import com.squareup.sqldelight.core.lang.MigrationLanguage
import com.squareup.sqldelight.core.lang.SqlDelightLanguage
import javax.swing.Icon

class SqlDelightFileIconProvider : FileIconProvider {

  private val supportedLanguages = setOf(SqlDelightLanguage, MigrationLanguage)

  override fun getIcon(file: VirtualFile, flags: Int, project: Project?): Icon? {
    return if (project != null && LanguageUtil.getFileLanguage(file) in supportedLanguages) {
      when (SqlDelightProjectService.getInstance(project).dialectPreset) {
        DialectPreset.SQLITE_3_18 -> AllIcons.Providers.Sqlite
        DialectPreset.SQLITE_3_24 -> AllIcons.Providers.Sqlite
        DialectPreset.MYSQL -> AllIcons.Providers.Mysql
        DialectPreset.POSTGRESQL -> AllIcons.Providers.Postgresql
        DialectPreset.HSQL -> AllIcons.Providers.Hsqldb
      }
    } else {
      null
    }
  }
}


Create a builder for GenericType.TypeVariable

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

package io.michaelrocks.grip.mirrors.signature

import io.michaelrocks.grip.commons.LazyList

internal class TypeVariableBuilder(
    private val name: String
) {
  private var classBound: GenericType = OBJECT_RAW_TYPE
  private val interfaceBounds = LazyList<GenericType>()

  fun classBound(classBound: GenericType) = apply {
    this.classBound = classBound
  }

  fun addInterfaceBound(interfaceBound: GenericType) = apply {
    interfaceBounds += interfaceBound
  }

  fun build(): GenericType.TypeVariable {
    return GenericType.TypeVariable(name, classBound, interfaceBounds.detachImmutableCopy())
  }
}


Add IrLetSequence extension for IrBlockBuilder

package org.jetbrains.kotlin.backend.konan.ir

import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.expressions.IrExpression

inline fun IrBlockBuilder.irLetSequence(
        value: IrExpression,
        nameHint: String? = null,
        body: IrBlockBuilder.(VariableDescriptor) -> Unit
): IrExpression  = block {
    val irTemporary = defineTemporary(value, nameHint)
    this.body(irTemporary)
}


plugins {
    application
}

application {
    mainClassName = "samples.HelloWorld"
}

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

dependencies {
    implementation("org.gradle.kotlin.dsl.samples.source-control:compute:latest.integration")
}

Fix source-control sample for Java 12

plugins {
    application
}

application {
    mainClassName = "samples.HelloWorld"
}

dependencies {
    implementation("org.gradle.kotlin.dsl.samples.source-control:compute:latest.integration")
}


plugins {
    id("io.quarkus")
    kotlin("jvm")
}

dependencies {
    implementation(project(":port"))
    implementation(project(":domain"))
    implementation(kotlin("stdlib-jdk8"))
    implementation("io.quarkus:quarkus-resteasy")
}

Set default jvm-target in kotlin sample project

plugins {
    id("io.quarkus")
    kotlin("jvm")
}

// This is a fix as kotlin 1.5.30 does not support Java 17 yet
if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_17)) {
    tasks.quarkusDev {
        compilerArgs = listOf("-jvm-target", "16")
    }
}
dependencies {
    implementation(project(":port"))
    implementation(project(":domain"))
    implementation(kotlin("stdlib-jdk8"))
    implementation("io.quarkus:quarkus-resteasy")
}


import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import java.util.*

/**
 * Created by elifarley on 31/08/16.
 */

object DateTimeKit {

    @JvmOverloads
    fun TemporalAccessor.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.from(this).toDate(zoneOffset)

    @JvmOverloads
    fun LocalDate.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.atStartOfDay().toDate(zoneOffset)

    @JvmOverloads
    fun LocalDateTime.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = Date.from(this.toInstant(zoneOffset))!!

    @JvmOverloads
    fun Instant.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneOffset)!!

    @JvmOverloads
    fun Date.toLocalDateTime(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.toInstant().toLocalDateTime(zoneOffset)

    fun Instant.toGregorianCalendar() =
        GregorianCalendar.from(ZonedDateTime.ofInstant(this, ZoneOffset.UTC))

    val DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd.HHmmss").withZone(ZoneOffset.UTC)!!
    fun DateTimeFormatter.format(date: Date) = this.format(date.toInstant())!!

}

Use ZoneId; Check for java.sql.Date instance

import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import java.util.*

/**
 * Created by elifarley on 31/08/16.
 */

object DateTimeKit {

    @JvmOverloads
    fun TemporalAccessor.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = LocalDateTime.from(this).toDate(zoneOffset)

    @JvmOverloads
    fun LocalDate.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = this.atStartOfDay().toDate(zoneOffset)

    @JvmOverloads
    fun LocalDateTime.toDate(zoneOffset: ZoneOffset = ZoneOffset.UTC) = Date.from(this.toInstant(zoneOffset))!!

    @JvmOverloads
    fun Instant.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = LocalDateTime.ofInstant(this, zoneId)!!

    @JvmOverloads
    fun Date.toLocalDateTime(zoneId: ZoneId = ZoneOffset.UTC) = when {
        this is java.sql.Date -> Date(this.time).toInstant().toLocalDateTime(zoneId)
        else -> this.toInstant().toLocalDateTime(zoneId)
    }

    fun Instant.toGregorianCalendar() =
        GregorianCalendar.from(ZonedDateTime.ofInstant(this, ZoneOffset.UTC))

    val DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd.HHmmss").withZone(ZoneOffset.UTC)!!
    fun DateTimeFormatter.format(date: Date) = this.format(date.toInstant())!!

}


package com.sedsoftware.yaptalker.data.model

interface Content

class PostText(val text: String) : Content

class PostQuote(val text: String) : Content

class PostQuoteAuthor(val text: String) : Content

class PostHiddenText(val text: String) : Content

class PostScript(val text: String) : Content

class PostLink(val url: String, val title: String) : Content


package xyz.nulldev.androidcompat

import android.app.Application
import xyz.nulldev.androidcompat.androidimpl.CustomContext

class AndroidCompat {

    val context by lazy {
        CustomContext()
    }

    fun startApp(application: Application) {
        application.attach(context)
        application.onCreate()
    }
}

Fix Context being initialized twice.

package xyz.nulldev.androidcompat

import android.app.Application
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.conf.global
import com.github.salomonbrys.kodein.instance
import com.github.salomonbrys.kodein.lazy
import xyz.nulldev.androidcompat.androidimpl.CustomContext

class AndroidCompat {

    val context: CustomContext by Kodein.global.lazy.instance()

    fun startApp(application: Application) {
        application.attach(context)
        application.onCreate()
    }
}


package configurations

import jetbrains.buildServer.configs.kotlin.v10.BuildType
import model.CIBuildModel
import model.OS
import model.TestCoverage
import model.TestType

class FunctionalTest(model: CIBuildModel, testCoverage : TestCoverage, subProject: String = "") : BuildType({
    uuid = testCoverage.asConfigurationId(model, subProject)
    extId = uuid
    name = testCoverage.asName() + if (!subProject.isEmpty()) " ($subProject)" else ""
    val testTask = if (!subProject.isEmpty()) { subProject + ":" } else { "" } + testCoverage.testType.name + "Test"
    val quickTest = testCoverage.testType == TestType.quick
    applyDefaults(model, this, testTask, subProject = subProject, notQuick = !quickTest,
            runsOnWindows = testCoverage.os == OS.windows, timeout = if (quickTest) 60 else 210)

    params {
        param("env.JAVA_HOME", "%${testCoverage.os}.${testCoverage.version}.${testCoverage.vendor}.64bit%")
        if (testCoverage.os == OS.linux) {
            param("env.JAVA_9", "%linux.java9.oracle.64bit%")
            param("env.ANDROID_HOME", "/opt/android/sdk")
        }
    }
})

Revert "Increase timeout for long running functional tests"

package configurations

import jetbrains.buildServer.configs.kotlin.v10.BuildType
import model.CIBuildModel
import model.OS
import model.TestCoverage
import model.TestType

class FunctionalTest(model: CIBuildModel, testCoverage : TestCoverage, subProject: String = "") : BuildType({
    uuid = testCoverage.asConfigurationId(model, subProject)
    extId = uuid
    name = testCoverage.asName() + if (!subProject.isEmpty()) " ($subProject)" else ""
    val testTask = if (!subProject.isEmpty()) { subProject + ":" } else { "" } + testCoverage.testType.name + "Test"
    val quickTest = testCoverage.testType == TestType.quick
    applyDefaults(model, this, testTask, subProject = subProject, notQuick = !quickTest,
            runsOnWindows = testCoverage.os == OS.windows, timeout = if (quickTest) 60 else 180)

    params {
        param("env.JAVA_HOME", "%${testCoverage.os}.${testCoverage.version}.${testCoverage.vendor}.64bit%")
        if (testCoverage.os == OS.linux) {
            param("env.JAVA_9", "%linux.java9.oracle.64bit%")
            param("env.ANDROID_HOME", "/opt/android/sdk")
        }
    }
})


/*
 * Copyright (C) 2020 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.debugger

import com.intellij.openapi.vfs.VirtualFile
import uk.co.reecedunn.intellij.plugin.intellij.xdebugger.frame.QueryStackFrame
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.Location

class SaxonInstructionFrame(location: Location, query: VirtualFile) : QueryStackFrame(query) {
    override val uri: String? = location.getSystemId()
    override val line: Int = location.getLineNumber().let { if (it == -1) 1 else it }
    override val column: Int = location.getColumnNumber().let { if (it == -1) 1 else it }
    override val context: String? = null
}

Use the instruction's object QName for the stack frame context.

/*
 * Copyright (C) 2020 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.debugger

import com.intellij.openapi.vfs.VirtualFile
import uk.co.reecedunn.intellij.plugin.intellij.xdebugger.frame.QueryStackFrame
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.trace.InstructionInfo

class SaxonInstructionFrame(instruction: InstructionInfo, query: VirtualFile) : QueryStackFrame(query) {
    override val uri: String? = instruction.getSystemId()
    override val line: Int = instruction.getLineNumber().let { if (it == -1) 1 else it }
    override val column: Int = instruction.getColumnNumber().let { if (it == -1) 1 else it }
    override val context: String? = instruction.getObjectName()?.toString()
}


package io.gitlab.arturbosch.detekt.core

import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile

/**
 * @author Artur Bosch
 */

fun KtFile.unnormalizedContent(): String {
	val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
	require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
	return this.text.replace("\n", lineSeparator!!)
}

val KtFile.relativePath: String?
	get() = this.getUserData(KtCompiler.RELATIVE_PATH)

Convert Kotlin source code strings to Unix line endings

package io.gitlab.arturbosch.detekt.core

import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtFile

/**
 * @author Artur Bosch
 */

fun KtFile.unnormalizedContent(): String {
	val lineSeparator = this.getUserData(KtCompiler.LINE_SEPARATOR)
	require(lineSeparator != null) { "No line separator entry for ktFile ${this.javaFileFacadeFqName.asString()}" }
	return StringUtilRt.convertLineSeparators("\n", lineSeparator!!)
}

val KtFile.relativePath: String?
	get() = this.getUserData(KtCompiler.RELATIVE_PATH)


package com.chibatching.kotpref.preference.dsl

@Experimental(level = Experimental.Level.WARNING)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ExperimentalPreferenceScreenDsl

Replace Experimental annotation with RequiresOptIn annotation

package com.chibatching.kotpref.preference.dsl

@RequiresOptIn(level = RequiresOptIn.Level.WARNING)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ExperimentalPreferenceScreenDsl


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

package org.rust.ide.refactoring

import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringActionHandler
import org.rust.ide.refactoring.extractFunction.RsExtractFunctionHandler
import org.rust.ide.refactoring.introduceParameter.RsIntroduceParameterHandler
import org.rust.ide.refactoring.introduceVariable.RsIntroduceVariableHandler
import org.rust.lang.core.psi.RsPatBinding

class RsRefactoringSupportProvider : RefactoringSupportProvider() {
    override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean = element is RsPatBinding

    override fun getIntroduceVariableHandler(): RefactoringActionHandler = RsIntroduceVariableHandler()

    // needed this one too to get it to show up in the dialog.
    override fun getIntroduceVariableHandler(element: PsiElement?): RefactoringActionHandler =
        RsIntroduceVariableHandler()

    override fun getExtractMethodHandler(): RefactoringActionHandler = RsExtractFunctionHandler()

    override fun getIntroduceParameterHandler(): RefactoringActionHandler = RsIntroduceParameterHandler()
}

Make member inplace rename available for identifier owners

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

package org.rust.ide.refactoring

import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringActionHandler
import org.rust.ide.refactoring.extractFunction.RsExtractFunctionHandler
import org.rust.ide.refactoring.introduceParameter.RsIntroduceParameterHandler
import org.rust.ide.refactoring.introduceVariable.RsIntroduceVariableHandler
import org.rust.lang.core.psi.RsPatBinding
import org.rust.lang.core.psi.ext.RsNameIdentifierOwner

class RsRefactoringSupportProvider : RefactoringSupportProvider() {
    override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean =
        element is RsPatBinding

    override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean =
        element is RsNameIdentifierOwner

    override fun getIntroduceVariableHandler(): RefactoringActionHandler = RsIntroduceVariableHandler()

    // needed this one too to get it to show up in the dialog.
    override fun getIntroduceVariableHandler(element: PsiElement?): RefactoringActionHandler =
        RsIntroduceVariableHandler()

    override fun getExtractMethodHandler(): RefactoringActionHandler = RsExtractFunctionHandler()

    override fun getIntroduceParameterHandler(): RefactoringActionHandler = RsIntroduceParameterHandler()
}


package de.christinecoenen.code.zapp.app

import android.content.Context
import org.acra.ACRA
import timber.log.Timber
import timber.log.Timber.DebugTree

class ZappApplication : ZappApplicationBase() {

	override fun setUpLogging() {
		Timber.plant(DebugTree())
	}

	override fun attachBaseContext(base: Context) {
		super.attachBaseContext(base)

		// The following line triggers the initialization of ACRA
		ACRA.init(this)
	}

}

Fix build error in release build

package de.christinecoenen.code.zapp.app

import timber.log.Timber
import timber.log.Timber.DebugTree

class ZappApplication : ZappApplicationBase() {

	override fun setUpLogging() {
		Timber.plant(DebugTree())
	}

}


package io.gitlab.arturbosch.detekt.core

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

/**
 * @author Artur Bosch
 */
internal class KtCompilerTest {

	@Test
	fun ktFileHasExtraUserData() {
		val ktCompiler = KtCompiler(path)

		val ktFile = ktCompiler.compile(path.resolve("Default.kt"))

		assertThat(ktFile.getUserData(KtCompiler.LINE_SEPARATOR)).isEqualTo("\n")
		assertThat(ktFile.getUserData(KtCompiler.RELATIVE_PATH)).isEqualTo("Default.kt")
	}

}

Correct test case having project name in path

package io.gitlab.arturbosch.detekt.core

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

/**
 * @author Artur Bosch
 */
internal class KtCompilerTest {

	@Test
	fun ktFileHasExtraUserData() {
		val ktCompiler = KtCompiler(path)

		val ktFile = ktCompiler.compile(path.resolve("Default.kt"))

		assertThat(ktFile.getUserData(KtCompiler.LINE_SEPARATOR)).isEqualTo("\n")
		assertThat(ktFile.getUserData(KtCompiler.RELATIVE_PATH)).isEqualTo(path.fileName.resolve("Default.kt").toString())
	}
}


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

package tech.pronghorn.server.handlers

import tech.pronghorn.http.HttpExchange
import tech.pronghorn.http.HttpResponse

abstract class DirectHttpRequestHandler : NonSuspendableHttpRequestHandler() {
    override fun handle(exchange: HttpExchange): HttpResponse {
        return handleDirect(exchange)
    }

    internal abstract fun handleDirect(exchange: HttpExchange): HttpResponse
}

Fix for a function being marked internal that shouldn't have been.

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

package tech.pronghorn.server.handlers

import tech.pronghorn.http.HttpExchange
import tech.pronghorn.http.HttpResponse

abstract class DirectHttpRequestHandler : NonSuspendableHttpRequestHandler() {
    override fun handle(exchange: HttpExchange): HttpResponse {
        return handleDirect(exchange)
    }

    abstract fun handleDirect(exchange: HttpExchange): HttpResponse
}


plugins {
    application
    kotlin("jvm") version "1.4.32"
}

description = "An action sequencer to do the boring tasks on the game http://www.riseoflords.com."

application {
    mainClass.set("org.hildan.bots.riseoflords.RolAutomizerKt")
}

repositories {
    mavenCentral()
}

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
    kotlinOptions {
        jvmTarget = "15"
        freeCompilerArgs = listOf("-Xopt-in=kotlin.RequiresOptIn")
    }
}

dependencies {
    implementation("com.github.ajalt.clikt:clikt:3.0.1")
    implementation("org.jsoup:jsoup:1.9.2")
    implementation("ch.qos.logback:logback-classic:1.2.3")
    implementation("javax.mail:mail:1.4.3") // to send emails with logback
}

// to build a fat jar with all dependencies included
tasks.jar {
    manifest { attributes["Main-Class"] = application.mainClass.get() }
    from({
        configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }
    })
}

Fix main class manifest entry

plugins {
    application
    kotlin("jvm") version "1.4.32"
}

description = "An action sequencer to do the boring tasks on the game http://www.riseoflords.com."

application {
    mainClass.set("org.hildan.bots.riseoflords.RolAutomizerKt")
}

repositories {
    mavenCentral()
}

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
    kotlinOptions {
        jvmTarget = "15"
        freeCompilerArgs = listOf("-Xopt-in=kotlin.RequiresOptIn")
    }
}

dependencies {
    implementation("com.github.ajalt.clikt:clikt:3.0.1")
    implementation("org.jsoup:jsoup:1.9.2")
    implementation("ch.qos.logback:logback-classic:1.2.3")
    implementation("javax.mail:mail:1.4.3") // to send emails with logback
}

// to build a fat jar with all dependencies included
tasks.jar {
    duplicatesStrategy = DuplicatesStrategy.INCLUDE
    manifest { attributes["Main-Class"] = application.mainClass.get() }
    from({
        configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) }
    })
}


pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.39.0"
        id("com.diffplug.spotless") version "6.11.0"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "3.0.2"
        id("org.domaframework.doma.compile") version "2.0.0"
        kotlin("jvm") version "1.7.20"
        kotlin("kapt") version "1.7.20"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")
include("doma-template")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-additional")
include("integration-test-kotlin")

Update plugin com.diffplug.eclipse.apt to v3.40.0

pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.40.0"
        id("com.diffplug.spotless") version "6.11.0"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "3.0.2"
        id("org.domaframework.doma.compile") version "2.0.0"
        kotlin("jvm") version "1.7.20"
        kotlin("kapt") version "1.7.20"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")
include("doma-template")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-additional")
include("integration-test-kotlin")


pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.35.0"
        id("com.diffplug.spotless") version "6.2.0"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "2.8.1"
        id("org.seasar.doma.compile") version "1.1.0"
        kotlin("jvm") version "1.6.10"
        kotlin("kapt") version "1.6.10"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-latest")
include("integration-test-kotlin")

Update plugin com.diffplug.spotless to v6.2.1

pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.35.0"
        id("com.diffplug.spotless") version "6.2.1"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "2.8.1"
        id("org.seasar.doma.compile") version "1.1.0"
        kotlin("jvm") version "1.6.10"
        kotlin("kapt") version "1.6.10"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-latest")
include("integration-test-kotlin")


pluginManagement {
    repositories {
        maven("https://repo.spongepowered.org/repository/maven-public/") {
            name = "sponge"
        }
    }

    plugins {
        val indraVersion = "2.0.0"
        id("com.gradle.plugin-publish") version "0.14.0"
        id("net.kyori.indra") version indraVersion
        id("net.kyori.indra.license-header") version indraVersion
        id("net.kyori.indra.publishing.gradle-plugin") version indraVersion
    }
}

rootProject.name = "SpongeGradle"

sequenceOf("convention", "plugin-development").forEach {
    include(it)
    findProject(":$it")?.name = "${rootProject.name.toLowerCase(java.util.Locale.ROOT)}-$it"
}

Bump indra to fix publishing

pluginManagement {
    repositories {
        maven("https://repo.spongepowered.org/repository/maven-public/") {
            name = "sponge"
        }
    }

    plugins {
        val indraVersion = "2.0.1"
        id("com.gradle.plugin-publish") version "0.14.0"
        id("net.kyori.indra") version indraVersion
        id("net.kyori.indra.license-header") version indraVersion
        id("net.kyori.indra.publishing.gradle-plugin") version indraVersion
    }
}

rootProject.name = "SpongeGradle"

sequenceOf("convention", "plugin-development").forEach {
    include(it)
    findProject(":$it")?.name = "${rootProject.name.toLowerCase(java.util.Locale.ROOT)}-$it"
}


package com.sedsoftware.yaptalker.commons.extensions

import android.widget.Toast
import com.bluelinelabs.conductor.Controller
import es.dmoral.toasty.Toasty

fun Controller.toastError(message: String) {
  view?.let {
    Toasty.error(it.context, message, Toast.LENGTH_SHORT, true).show()
  }
}

fun Controller.toastSuccess(message: String) {
  view?.let {
    Toasty.success(it.context, message, Toast.LENGTH_SHORT, true).show()
  }
}

fun Controller.toastInfo(message: String) {
  view?.let {
    Toasty.info(it.context, message, Toast.LENGTH_SHORT, true).show()
  }
}

fun Controller.toastWarning(message: String) {
  view?.let {
    Toasty.warning(it.context, message, Toast.LENGTH_SHORT, true).show()
  }
}


package com.example.dennis.proxertv.base

import okhttp3.Interceptor
import okhttp3.Response

/**
 * An interceptor that overrides the cache header
 */
class ProxerCacheRewriteInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response? {

        val request = chain.request()
        val response = chain.proceed(request)

        if (request.url().host().contains("proxer.me")) {
            return response.newBuilder()
                    .header("Cache-Control", "max-age=600")
                    .removeHeader("Pragma")
                    .build()
        } else {
            return response
        }
    }
}

Increase cache validity to 30 min

package com.example.dennis.proxertv.base

import okhttp3.Interceptor
import okhttp3.Response

/**
 * An interceptor that overrides the cache header
 */
class ProxerCacheRewriteInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response? {

        val request = chain.request()
        val response = chain.proceed(request)

        if (request.url().host().contains("proxer.me")) {
            return response.newBuilder()
                    .header("Cache-Control", "max-age=1800")
                    .removeHeader("Pragma")
                    .build()
        } else {
            return response
        }
    }
}


package com.commit451.addendum

import android.annotation.TargetApi
import android.app.Activity
import android.graphics.Point
import android.view.View
import android.view.WindowManager

@TargetApi(16)
fun Activity.flagFullscreen() {
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
}

fun Activity.screenHeight(): Int {
    val display = windowManager.defaultDisplay
    val size = Point()
    display.getSize(size)
    return size.y
}

fun Activity.screenWidth(): Int {
    val display = windowManager.defaultDisplay
    val size = Point()
    display.getSize(size)
    return size.x
}

/**
 * Call this before setContentView
 */
fun Activity.maxBrightness() {
    val params = window.attributes
    params.screenBrightness = 1f // range from 0 - 1 as per docs
    window.attributes = params
    window.addFlags(WindowManager.LayoutParams.FLAGS_CHANGED)
}

Change signature of brightness call, add bindView similar to KotterKnife

package com.commit451.addendum

import android.annotation.TargetApi
import android.app.Activity
import android.graphics.Point
import android.support.annotation.IdRes
import android.view.View
import android.view.WindowManager

@TargetApi(16)
fun Activity.flagFullscreen() {
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
}

fun Activity.screenHeight(): Int {
    val display = windowManager.defaultDisplay
    val size = Point()
    display.getSize(size)
    return size.y
}

fun Activity.screenWidth(): Int {
    val display = windowManager.defaultDisplay
    val size = Point()
    display.getSize(size)
    return size.x
}

/**
 * Sets the screen brightness. Call this before setContentView.
 * 0 is dimmest, 1 is brightest. Default value is 1
 */
fun Activity.brightness(brightness: Float = 1f) {
    val params = window.attributes
    params.screenBrightness = brightness // range from 0 - 1 as per docs
    window.attributes = params
    window.addFlags(WindowManager.LayoutParams.FLAGS_CHANGED)
}

fun <T: View> Activity.bindView(@IdRes id: Int): Lazy<T> {
    @Suppress("UNCHECKED_CAST")
    return lazy(LazyThreadSafetyMode.NONE) { findViewById(id) as T }
}


package uy.kohesive.injekt.example

import uy.kohesive.injekt.*

// our module exports an injektable singletone for an Amazon S3 client, perfectly configured!

public object AmazonS3InjektModule : InjektModule {
    override fun InjektRegistrar.exportInjektables() {
        addSingletonFactory { AmazonS3Client(defaultCredentialsProviderChain()) }
    }
}

// mock classes

private fun defaultCredentialsProviderChain(): AWSCredentialsProviderChain { return AWSCredentialsProviderChain() }

data class AWSCredentialsProviderChain()
data class AmazonS3Client(providerChain: AWSCredentialsProviderChain)

Update samples and test to 1.1.0 code

package uy.kohesive.injekt.example

import uy.kohesive.injekt.*

// our module exports an injectable singletone for an Amazon S3 client, perfectly configured!

public object AmazonS3InjektModule : InjektModule {
    override fun InjektRegistrar.registerInjectables() {
        addSingletonFactory { AmazonS3Client(defaultCredentialsProviderChain()) }
    }
}

// mock classes

private fun defaultCredentialsProviderChain(): AWSCredentialsProviderChain { return AWSCredentialsProviderChain() }

data class AWSCredentialsProviderChain()
data class AmazonS3Client(providerChain: AWSCredentialsProviderChain)


package com.satsumasoftware.timetable.framework

import org.threeten.bp.LocalDate

class Assignment(val id: Int, val classId: Int, val title: String, val detail: String,
                 val dueDate: LocalDate)

Add a property for recording completion progress of assignments

package com.satsumasoftware.timetable.framework

import org.threeten.bp.LocalDate

class Assignment(val id: Int, val classId: Int, val title: String, val detail: String,
                 val dueDate: LocalDate, val completionProgress: Int)


package io.mockk.impl.recording.states

import io.mockk.MockKException
import io.mockk.impl.recording.CommonCallRecorder

class StubbingState(recorder: CommonCallRecorder) : RecordingState(recorder) {
    override fun recordingDone(): CallRecordingState {
        checkMissingCalls()
        return recorder.factories.stubbingAwaitingAnswerState(recorder)
    }

    private fun checkMissingCalls() {
        if (recorder.calls.isEmpty()) {
            throw MockKException("Cannot use every { ... } block with not mocked class")
        }
    }
}

Apply suggestions on exception message

package io.mockk.impl.recording.states

import io.mockk.MockKException
import io.mockk.impl.recording.CommonCallRecorder

class StubbingState(recorder: CommonCallRecorder) : RecordingState(recorder) {
    override fun recordingDone(): CallRecordingState {
        checkMissingCalls()
        return recorder.factories.stubbingAwaitingAnswerState(recorder)
    }

    private fun checkMissingCalls() {
        if (recorder.calls.isEmpty()) {
            throw MockKException("Cannot use every { ... } block with a non mocked class")
        }
    }
}


package io.kotlintest.properties

import io.kotlintest.assertions.readSystemProperty

object PropertyTesting {
  var shouldPrintGeneratedValues: Boolean = readSystemProperty("kotlintest.propertytest.output.generated-values", "false") == "true"
  var shouldPrintShrinkSteps: Boolean = readSystemProperty("kotlintest.propertytest.output.shrink-steps", "false") == "true"
}

Disable shrink steps for kotlintest's own shrink tests

package io.kotlintest.properties

import io.kotlintest.assertions.readSystemProperty

object PropertyTesting {
  var shouldPrintGeneratedValues: Boolean = readSystemProperty("kotlintest.propertytest.output.generated-values", "false") == "true"
  var shouldPrintShrinkSteps: Boolean = readSystemProperty("kotlintest.propertytest.output.shrink-steps", "true") == "true"
}


package com.jgreubel

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
open class TreelineApplication

fun main(args: Array<String>) {
    SpringApplication.run(TreelineApplication::class.java, *args)
}

Print server port on app launch

package com.jgreubel

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
open class TreelineApplication

fun main(args: Array<String>) {
    val app = SpringApplication.run(TreelineApplication::class.java, *args)
    println("local server port: " + app.environment.getProperty("local.server.port"))
    println("server port" + app.environment.getProperty("server.port"))
}


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

open class Greeting : DefaultTask() {
    // Configurable by the user
    @get:Input
    val message: Property<String> = project.objects.property()

    // Read-only property calculated from the message
    @get:Internal
    val fullMessage: Provider<String> = message.map { "$it from Gradle" }

    @TaskAction
    fun printMessage() {
        logger.quiet(fullMessage.get())
    }
}

tasks.create<Greeting>("greeting") {
    message.set("Hi")
}

Align Kotlin example of `propertyAndProvider` sample with Groovy

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

open class Greeting : DefaultTask() {
    // Configurable by the user
    @get:Input
    val message: Property<String> = project.objects.property()

    // Read-only property calculated from the message
    @get:Internal
    val fullMessage: Provider<String> = message.map { it + " from Gradle" }

    @TaskAction
    fun printMessage() {
        logger.quiet(fullMessage.get())
    }
}

task<Greeting>("greeting") {
    message.set("Hi")
}


import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

buildscript {
  repositories {
    mavenCentral()
    google()
    jcenter()
  }
}

repositories {
  mavenCentral()
  google()
  jcenter()
}

plugins {
  kotlin("jvm") version "1.3.70"
  `kotlin-dsl`
  `java-gradle-plugin`
}

kotlinDslPluginOptions {
  experimentalWarning.set(false)
}

gradlePlugin {
  plugins {
    create("CatchUpPlugin") {
      id = "catchup"
      implementationClass = "dev.zacsweers.catchup.gradle.CatchUpPlugin"
    }
  }
}

tasks.withType<KotlinCompile>().configureEach {
  kotlinOptions {
    @Suppress("SuspiciousCollectionReassignment")
    freeCompilerArgs += listOf("-Xuse-experimental=kotlin.ExperimentalStdlibApi")
  }
}

dependencies {
  implementation("com.android.tools.build:gradle:4.1.0-alpha02")
  implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.70")
}

Update deps in buildSrc too

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

buildscript {
  repositories {
    mavenCentral()
    google()
    maven {
      setUrl("https://dl.bintray.com/kotlin/kotlin-eap")
    }
    jcenter()
  }
}

repositories {
  mavenCentral()
  google()
  maven {
    setUrl("https://dl.bintray.com/kotlin/kotlin-eap")
  }
  jcenter()
}

plugins {
  kotlin("jvm") version "1.3.71"
  `kotlin-dsl`
  `java-gradle-plugin`
}

kotlinDslPluginOptions {
  experimentalWarning.set(false)
}

gradlePlugin {
  plugins {
    create("CatchUpPlugin") {
      id = "catchup"
      implementationClass = "dev.zacsweers.catchup.gradle.CatchUpPlugin"
    }
  }
}

tasks.withType<KotlinCompile>().configureEach {
  kotlinOptions {
    @Suppress("SuspiciousCollectionReassignment")
    freeCompilerArgs += listOf("-Xuse-experimental=kotlin.ExperimentalStdlibApi")
  }
}

dependencies {
  implementation("com.android.tools.build:gradle:4.1.0-alpha04")
  implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.71")
}


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

package splitties.stetho.init

import android.content.Context
import android.support.annotation.Keep
import androidx.startup.Initializer
import com.facebook.stetho.Stetho

@Keep // Needed because there's no default R8/proguard rules for App Startup Initializers.
@Suppress("unused") // False positive. Used in the manifest, but tooling analysis is incomplete.
internal class StethoInitializer : Initializer<StethoInitializer> {

    override fun create(context: Context): StethoInitializer {
        Stetho.initializeWithDefaults(context)
        return this
    }

    override fun dependencies() = emptyList<Nothing>()
}

Use Keep annotation from AndroidX instead of android.support

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

package splitties.stetho.init

import android.content.Context
import androidx.annotation.Keep
import androidx.startup.Initializer
import com.facebook.stetho.Stetho

@Keep // Needed because there's no default R8/proguard rules for App Startup Initializers.
@Suppress("unused") // False positive. Used in the manifest, but tooling analysis is incomplete.
internal class StethoInitializer : Initializer<StethoInitializer> {

    override fun create(context: Context): StethoInitializer {
        Stetho.initializeWithDefaults(context)
        return this
    }

    override fun dependencies() = emptyList<Nothing>()
}


package org.strykeforce.thirdcoast.telemetry.grapher

import mu.KotlinLogging
import okio.Buffer
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit.MILLISECONDS

private val logger = KotlinLogging.logger {}

/** Handles data streaming with Grapher client.  */
class ClientHandler(private val port: Int, private val socket: DatagramSocket) {

    private var scheduler: ScheduledExecutorService? = null

    /**
     * Start streaming the items specified in the subscription.
     *
     * @param subscription Items to stream to client
     */
    fun start(subscription: Subscription) {
        if (scheduler != null) return

        val address = InetSocketAddress(subscription.client, port)
        val packet = DatagramPacket(ByteArray(0), 0, address)
        val buffer = Buffer()
        val runnable = {
            subscription.measurementsToJson(buffer)
            val bytes = buffer.readByteArray()
            packet.setData(bytes, 0, bytes.size)
            socket.send(packet)
        }

        scheduler = Executors.newSingleThreadScheduledExecutor().also {
            it.scheduleAtFixedRate(runnable, 0, 5, MILLISECONDS)
        }
        logger.info { "sending graph data to ${subscription.client}:$port" }
    }

    /** Stop streaming to client.  */
    fun shutdown() {
        scheduler?.let { it.shutdown() }
        scheduler = null
        logger.info("stopped streaming graph data")
    }

}

Move period value to constant

package org.strykeforce.thirdcoast.telemetry.grapher

import mu.KotlinLogging
import okio.Buffer
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit.MILLISECONDS

private const val PERIOD = 5L // milliseconds

private val logger = KotlinLogging.logger {}

/** Handles data streaming with Grapher client.  */
class ClientHandler(private val port: Int, private val socket: DatagramSocket) {

    private var scheduler: ScheduledExecutorService? = null

    /**
     * Start streaming the items specified in the subscription.
     *
     * @param subscription Items to stream to client
     */
    fun start(subscription: Subscription) {
        if (scheduler != null) return

        val address = InetSocketAddress(subscription.client, port)
        val packet = DatagramPacket(ByteArray(0), 0, address)
        val buffer = Buffer()
        val runnable = {
            subscription.measurementsToJson(buffer)
            val bytes = buffer.readByteArray()
            packet.setData(bytes, 0, bytes.size)
            socket.send(packet)
        }

        scheduler = Executors.newSingleThreadScheduledExecutor().also {
            it.scheduleAtFixedRate(runnable, 0, PERIOD, MILLISECONDS)
        }
        logger.info { "sending graph data to ${subscription.client}:$port" }
    }

    /** Stop streaming to client.  */
    fun shutdown() {
        scheduler?.let { it.shutdown() }
        scheduler = null
        logger.info("stopped streaming graph data")
    }

}


Verify receive from response in exception

/*
 * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.client.tests

import io.ktor.client.*
import io.ktor.client.engine.mock.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.test.dispatcher.*
import kotlin.test.*

class ExceptionsTest {
    @Test
    fun testReadResponseFromException() = testSuspend {
        val client = HttpClient(MockEngine) {
            engine {
                addHandler {
                    respondError(HttpStatusCode.BadRequest)
                }
            }
        }

        try {
            client.get<String>("www.google.com")
        } catch (exception: ResponseException) {
            val text = exception.response.readText()
            assertEquals(HttpStatusCode.BadRequest.description, text)
        }
    }
}


pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.37.0"
        id("com.diffplug.spotless") version "6.7.2"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "2.8.1"
        id("org.seasar.doma.compile") version "1.1.0"
        kotlin("jvm") version "1.6.21"
        kotlin("kapt") version "1.6.21"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-additional")
include("integration-test-kotlin")

Update plugin com.diffplug.eclipse.apt to v3.37.1

pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.37.1"
        id("com.diffplug.spotless") version "6.7.2"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "2.8.1"
        id("org.seasar.doma.compile") version "1.1.0"
        kotlin("jvm") version "1.6.21"
        kotlin("kapt") version "1.6.21"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-additional")
include("integration-test-kotlin")


buildscript {
    repositories {
        google()
        jcenter()
    }
}

plugins {
    id("com.github.ben-manes.versions") version "0.22.0"
}

tasks.wrapper {
    distributionType = Wrapper.DistributionType.ALL
}

tasks.register<Delete>("clean") {
    delete("build")
}

tasks.register("ciBuild") {
    val isMaster = System.getenv("CIRCLE_BRANCH") == "master"
    val isPr = System.getenv("CIRCLE_PULL_REQUEST") != null

    if (isMaster && !isPr) { // Release build
        dependsOn(":plugin:build", ":plugin:publish")
    } else {
        dependsOn(":plugin:check")
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Fix bug causing non-snapshot builds to fail

buildscript {
    repositories {
        google()
        jcenter()
    }
}

plugins {
    id("com.github.ben-manes.versions") version "0.22.0"
}

tasks.wrapper {
    distributionType = Wrapper.DistributionType.ALL
}

tasks.register<Delete>("clean") {
    delete("build")
}

tasks.register("ciBuild") {
    val isMaster = System.getenv("CIRCLE_BRANCH") == "master"
    val isPr = System.getenv("CIRCLE_PULL_REQUEST") != null
    val isSnapshot = project("plugin").version.toString().contains("snapshot", true)

    if (isMaster && !isPr) { // Release build
        if (isSnapshot) {
            dependsOn(":plugin:build", ":plugin:publish")
        } else {
            dependsOn(":plugin:build")
        }
    } else {
        dependsOn(":plugin:check")
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}


package com.github.bumblebee.command.brent.bitfinex

enum class BitfinexTickerLabel(val title: String, val code: String) {
    BTC("Bitcoin",  "tBTCUSD"),
    BTCASH("Bitcoin Cash", "tBCHUSD"),
    LTC("Litecoin", "tLTCUSD"),
    RIPPLE("Ripple", "tXRPUSD"),
    ETH("Ethereum", "tETHUSD");

    override fun toString(): String = code
}

Add Dash and Monero to CurrenciesCommand.

package com.github.bumblebee.command.brent.bitfinex

enum class BitfinexTickerLabel(val title: String, val code: String) {
    BTC("Bitcoin",  "tBTCUSD"),
    BTCASH("Bitcoin Cash", "tBCHUSD"),
    LTC("Litecoin", "tLTCUSD"),
    RIPPLE("Ripple", "tXRPUSD"),
    MONERO("Monero", "tXMRUSD"),
    DASH("Dash", "tDSHUSD"),
    ETH("Ethereum", "tETHUSD");

    override fun toString(): String = code
}


package com.gulden.unity_wallet.ui

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.gulden.jniunifiedbackend.TransactionRecord
import com.gulden.jniunifiedbackend.TransactionType
import com.gulden.unity_wallet.R
import kotlinx.android.synthetic.main.transaction_list_item.view.*

class TransactionAdapter(private val context: Context, private val dataSource: ArrayList<TransactionRecord>) : BaseAdapter() {
    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    override fun getCount(): Int {
        return dataSource.size
    }

    override fun getItem(position: Int): Any {
        return dataSource[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var rowView = inflater.inflate(R.layout.transaction_list_item, parent, false)
        val transactionRecord = getItem(position) as TransactionRecord

        var prefix = "+";
        if (transactionRecord.type == TransactionType.SEND)
            prefix = "-";

        rowView.textViewTime.text = java.text.SimpleDateFormat("HH:mm").format(java.util.Date(transactionRecord.timestamp * 1000L))
        rowView.textViewAmount.text = transactionRecord.amount.toString();
        return rowView;
    }
}

Fix currency formatting in transaction view

package com.gulden.unity_wallet.ui

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.gulden.jniunifiedbackend.TransactionRecord
import com.gulden.jniunifiedbackend.TransactionType
import com.gulden.unity_wallet.R
import kotlinx.android.synthetic.main.transaction_list_item.view.*

class TransactionAdapter(private val context: Context, private val dataSource: ArrayList<TransactionRecord>) : BaseAdapter() {
    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    override fun getCount(): Int {
        return dataSource.size
    }

    override fun getItem(position: Int): Any {
        return dataSource[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var rowView = inflater.inflate(R.layout.transaction_list_item, parent, false)
        val transactionRecord = getItem(position) as TransactionRecord

        var prefix = "+";
        if (transactionRecord.type == TransactionType.SEND)
            prefix = "-";

        rowView.textViewTime.text = java.text.SimpleDateFormat("HH:mm").format(java.util.Date(transactionRecord.timestamp * 1000L))
        rowView.textViewAmount.text = (" "+prefix+"%.2f").format(transactionRecord.amount.toDouble() / 100000000)
        return rowView;
    }
}


// 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 org.jetbrains.plugins.github.authentication.accounts

import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.internal.statistic.utils.getBooleanUsage
import com.intellij.internal.statistic.utils.getCountingUsage
import com.intellij.openapi.components.service
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.plugins.github.api.GithubServerPath

internal class GithubAccountsStatisticsCollector : ApplicationUsagesCollector() {
  override fun getUsages(): Set<UsageDescriptor> {
    val accountManager = service<GithubAccountManager>()
    val hasAccountsWithNonDefaultHost = accountManager.accounts.any {
      !StringUtil.equalsIgnoreCase(it.server.host, GithubServerPath.DEFAULT_HOST)
    }

    return setOf(getCountingUsage("github.accounts.count", accountManager.accounts.size, listOf(0, 1, 2)),
      getBooleanUsage("github.accounts.not.default.host", hasAccountsWithNonDefaultHost))
  }

  override fun getGroupId(): String = "vcs.github"
}

Update account statistics collector to the new format

// 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 org.jetbrains.plugins.github.authentication.accounts

import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.beans.newMetric
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.openapi.components.service
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.plugins.github.api.GithubServerPath

internal class GithubAccountsStatisticsCollector : ApplicationUsagesCollector() {

  override fun getVersion() = 2

  override fun getMetrics(): Set<MetricEvent> {
    val accountManager = service<GithubAccountManager>()
    val hasAccountsWithNonDefaultHost = accountManager.accounts.any {
      !StringUtil.equalsIgnoreCase(it.server.host, GithubServerPath.DEFAULT_HOST)
    }

    return setOf(
      newMetric("accounts", FeatureUsageData()
        .addCount(accountManager.accounts.size)
        .addData("has_enterprise", hasAccountsWithNonDefaultHost)))
  }

  override fun getGroupId(): String = "vcs.github"
}


plugins {
    id("gradlebuild.internal.java")
}

dependencies {
    integTestImplementation(project(":base-services"))
    integTestImplementation(project(":core-api"))
    integTestImplementation(project(":process-services"))
    integTestImplementation(project(":persistent-cache"))
    integTestImplementation(libs.groovy)
    integTestImplementation(libs.slf4jApi)
    integTestImplementation(libs.guava)
    integTestImplementation(libs.ant)
    integTestImplementation(libs.sampleCheck) {
        exclude(group = "org.codehaus.groovy", module = "groovy-all")
        exclude(module = "slf4j-simple")
    }
    integTestImplementation(testFixtures(project(":core")))
    integTestImplementation(testFixtures(project(":model-core")))

    integTestDistributionRuntimeOnly(project(":distributions-full"))
}

integTest.usesSamples.set(true)
testFilesCleanup.reportOnly.set(true)

Remove javadoc snippets test configuration from samples subproject

plugins {
    id("gradlebuild.internal.java")
}

dependencies {
    integTestImplementation(project(":base-services"))
    integTestImplementation(project(":core-api"))
    integTestImplementation(project(":process-services"))
    integTestImplementation(project(":persistent-cache"))
    integTestImplementation(libs.groovy)
    integTestImplementation(libs.slf4jApi)
    integTestImplementation(libs.guava)
    integTestImplementation(libs.ant)
    integTestImplementation(libs.sampleCheck) {
        exclude(group = "org.codehaus.groovy", module = "groovy-all")
        exclude(module = "slf4j-simple")
    }
    integTestImplementation(testFixtures(project(":core")))
    integTestImplementation(testFixtures(project(":model-core")))

    integTestDistributionRuntimeOnly(project(":distributions-full"))
}

testFilesCleanup.reportOnly.set(true)