package com.vimeo.networking2.config

import retrofit2.Retrofit

/**
 * As Retrofit services are created, they are cached in this class.
 */
class RetrofitServicesCache(val retrofit: Retrofit) {

    /**
     * Cache of Retrofit API Services.  Objects created by calling getService().
     */
    private val cache = mutableMapOf<Class<*>, Any>()

    /**
     * Create and cache instance of the given Retrofit Service interface.
     */
    fun <T> getService(serviceClass: Class<T>): T {
        if (cache[serviceClass] == null) {
            cache[serviceClass] = retrofit.create(serviceClass) as Any
        }
        return serviceClass.cast(cache[serviceClass])
    }

    /**
     * Empty service endpoint cache.
     */
    fun clear() {
        cache.clear()
    }

}

Fix lint warning in retrofit services cache

package com.vimeo.networking2.config

import retrofit2.Retrofit

/**
 * As Retrofit services are created, they are cached in this class.
 */
class RetrofitServicesCache(private val retrofit: Retrofit) {

    /**
     * Cache of Retrofit API Services.  Objects created by calling getService().
     */
    private val cache = mutableMapOf<Class<*>, Any>()

    /**
     * Create and cache instance of the given Retrofit Service interface.
     */
    fun <T> getService(serviceClass: Class<T>): T {
        if (cache[serviceClass] == null) {
            cache[serviceClass] = retrofit.create(serviceClass) as Any
        }
        return serviceClass.cast(cache[serviceClass])
    }

    /**
     * Empty service endpoint cache.
     */
    fun clear() {
        cache.clear()
    }

}


package com.sebastian.sokolowski.auctionhunter.rest

import com.sebastian.sokolowski.auctionhunter.rest.response.Categories
import com.sebastian.sokolowski.auctionhunter.rest.response.CategoryDto
import com.sebastian.sokolowski.auctionhunter.rest.response.CategoryParameters
import com.sebastian.sokolowski.auctionhunter.rest.response.Listing
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.QueryMap

interface AllegroService {
    companion object {
        const val baseUrl = "https://api.allegro.pl"
    }

    @GET("/sale/categories")
    fun getCategories(@Query("parent.id") parentId: String): Call<Categories>

    @GET("/sale/categories/{id}")
    fun getCategory(@Path("id") id: Int): Call<CategoryDto>

    @GET("/sale/categories/{categoryId}/parameters")
    fun getCategoryParameters(@Path("categoryId") categoryId: String): Call<CategoryParameters>

    @GET("/offers/listing")
    fun getOffers(
            @Query("category.id") categoryId: String? = null,
            @Query("phrase") phrase: String? = null,
            @Query("fallback") fallback: Boolean = false,
            @Query("sort") sort: String = "+price",
            @QueryMap parameters: Map<String, String>
    ): Call<Listing>
}

Improve searching a new offers by get only list of items.

package com.sebastian.sokolowski.auctionhunter.rest

import com.sebastian.sokolowski.auctionhunter.rest.response.Categories
import com.sebastian.sokolowski.auctionhunter.rest.response.CategoryDto
import com.sebastian.sokolowski.auctionhunter.rest.response.CategoryParameters
import com.sebastian.sokolowski.auctionhunter.rest.response.Listing
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.QueryMap

interface AllegroService {
    companion object {
        const val baseUrl = "https://api.allegro.pl"
    }

    @GET("/sale/categories")
    fun getCategories(@Query("parent.id") parentId: String): Call<Categories>

    @GET("/sale/categories/{id}")
    fun getCategory(@Path("id") id: Int): Call<CategoryDto>

    @GET("/sale/categories/{categoryId}/parameters")
    fun getCategoryParameters(@Path("categoryId") categoryId: String): Call<CategoryParameters>

    @GET("/offers/listing")
    fun getOffers(
            @Query("category.id") categoryId: String? = null,
            @Query("phrase") phrase: String? = null,
            @Query("fallback") fallback: Boolean = false,
            @Query("sort") sort: String = "+price",
            @Query("include") excludeObjects: String = "-all",
            @Query("include") includeObjects: String = "items",
            @QueryMap parameters: Map<String, String>
    ): Call<Listing>
}


package io.ktor.tests.server.netty

import io.ktor.server.netty.*
import io.ktor.server.testing.*

class NettyEngineTest : EngineTestSuite<NettyApplicationEngine, NettyApplicationEngine.Configuration>(Netty) {
    override fun configure(configuration: NettyApplicationEngine.Configuration) {
        configuration.shareWorkGroup = true
    }
}

Revert "Enable Netty TLS tests"

package io.ktor.tests.server.netty

import io.ktor.server.netty.*
import io.ktor.server.testing.*

class NettyEngineTest : EngineTestSuite<NettyApplicationEngine, NettyApplicationEngine.Configuration>(Netty) {
    init {
        enableSsl = false
    }
    override fun configure(configuration: NettyApplicationEngine.Configuration) {
        configuration.shareWorkGroup = true
    }
}


package com.developerphil.adbidea.adb

import com.android.ddmlib.IDevice
import com.intellij.openapi.project.Project
import org.jetbrains.android.sdk.AndroidSdkUtils

interface Bridge {
    fun isReady(): Boolean
    fun connectedDevices(): List<IDevice>
}

class BridgeImpl(project: Project) : Bridge {

    val androidBridge = AndroidSdkUtils.getDebugBridge(project)

    override fun isReady(): Boolean {
        if (androidBridge == null) {
            return false
        }

        return androidBridge.isConnected && androidBridge.hasInitialDeviceList()
    }

    override fun connectedDevices(): List<IDevice> {
        return androidBridge?.devices?.asList() ?: emptyList()
    }
}

Fix a bug where we couldn't send any command after restarting the adb server.

package com.developerphil.adbidea.adb

import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.IDevice
import com.intellij.openapi.project.Project
import org.jetbrains.android.sdk.AndroidSdkUtils

interface Bridge {
    fun isReady(): Boolean
    fun connectedDevices(): List<IDevice>
}

class BridgeImpl(private val project: Project) : Bridge {

    private val androidBridge: AndroidDebugBridge?
        get() = AndroidSdkUtils.getDebugBridge(project)

    override fun isReady() = androidBridge?.let {
        it.isConnected && it.hasInitialDeviceList()
    } ?: false

    override fun connectedDevices(): List<IDevice> {
        return androidBridge?.devices?.asList() ?: emptyList()
    }
}


package org.wikipedia.commons

import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import java.util.*

object ImageTagsProvider {
    fun getImageTagsObservable(pageId: String, langCode: String): Observable<Map<String, String>> {
        return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId")
                .subscribeOn(Schedulers.io())
                .flatMap { claims ->
                    val depicts = claims.claims()["P180"]
                    val ids = mutableListOf<String?>()
                    depicts?.forEach {
                        ids.add(it.mainSnak?.dataValue?.value?.id)
                    }
                    ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getWikidataLabels(ids.joinToString(separator = "|"), langCode)
                }
                .subscribeOn(Schedulers.io())
                .map { entities ->
                    val captions = HashMap<String, String>()
                    for (label in entities.first!!.labels().values) {
                        captions[label.language()] = label.value()
                    }
                    captions
                }
    }
}

Add all tags from the API calls

package org.wikipedia.commons

import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import java.util.*

object ImageTagsProvider {
    fun getImageTagsObservable(pageId: String, langCode: String): Observable<Map<String, List<String>>> {
        return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getClaims("M$pageId")
                .subscribeOn(Schedulers.io())
                .flatMap { claims ->
                    val depicts = claims.claims()["P180"]
                    val ids = mutableListOf<String?>()
                    depicts?.forEach {
                        ids.add(it.mainSnak?.dataValue?.value?.id)
                    }
                    ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getWikidataLabels(ids.joinToString(separator = "|"), langCode)
                }
                .subscribeOn(Schedulers.io())
                .map { entities ->
                    val tags = HashMap<String, MutableList<String>>()
                    entities.entities().forEach {
                        it.value.labels().values.forEach { label ->
                            if (tags[label.language()].isNullOrEmpty()) {
                                tags[label.language()] = mutableListOf(label.value())
                            } else {
                                tags[label.language()]!!.add(label.value())
                            }
                        }
                    }
                    tags
                }
    }
}


package com.github.shiraji.butai

import android.app.Activity
import android.app.Application
import android.os.Bundle

internal class ButaiActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks, Butai {
    enum class AppStatus(val isForeground: Boolean) {
        BACKGROUND(false),
        JUST_APPEARED(true),
        FOREGROUND(true);
    }

    private var runningActivities = 0

    private var appStatus = AppStatus.FOREGROUND

    override fun onActivityStarted(p0: Activity?) {
        appStatus = when {
            runningActivities == 0 -> AppStatus.JUST_APPEARED
            runningActivities > 0 -> AppStatus.FOREGROUND
            else -> AppStatus.BACKGROUND
        }
        runningActivities++
    }

    override fun onActivityStopped(p0: Activity?) {
        runningActivities--
        if (runningActivities == 0) appStatus = AppStatus.BACKGROUND
    }

    override fun onActivityPaused(p0: Activity?) = Unit
    override fun onActivityDestroyed(p0: Activity?) = Unit
    override fun onActivitySaveInstanceState(p0: Activity?, p1: Bundle?) = Unit
    override fun onActivityCreated(p0: Activity?, p1: Bundle?) = Unit
    override fun onActivityResumed(p0: Activity?) = Unit

    override fun isReturnedFromBackground() = appStatus == AppStatus.JUST_APPEARED
    override fun isBackground() = !isForeground()
    override fun isForeground() = appStatus.isForeground
}

Make runningActivities 0 if it is negative number

package com.github.shiraji.butai

import android.app.Activity
import android.app.Application
import android.os.Bundle

internal class ButaiActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks, Butai {
    enum class AppStatus(val isForeground: Boolean) {
        BACKGROUND(false),
        JUST_APPEARED(true),
        FOREGROUND(true);
    }

    private var runningActivities = 0

    private var appStatus = AppStatus.FOREGROUND

    override fun onActivityStarted(p0: Activity?) {
        appStatus = when {
            runningActivities == 0 -> AppStatus.JUST_APPEARED
            runningActivities > 0 -> AppStatus.FOREGROUND
            else -> AppStatus.BACKGROUND
        }
        runningActivities++
    }

    override fun onActivityStopped(p0: Activity?) {
        runningActivities--
        if (runningActivities <= 0) {
            appStatus = AppStatus.BACKGROUND
            runningActivities = 0
        }
    }

    override fun onActivityPaused(p0: Activity?) = Unit
    override fun onActivityDestroyed(p0: Activity?) = Unit
    override fun onActivitySaveInstanceState(p0: Activity?, p1: Bundle?) = Unit
    override fun onActivityCreated(p0: Activity?, p1: Bundle?) = Unit
    override fun onActivityResumed(p0: Activity?) = Unit

    override fun isReturnedFromBackground() = appStatus == AppStatus.JUST_APPEARED
    override fun isBackground() = !isForeground()
    override fun isForeground() = appStatus.isForeground
}


Implement logical lines of code algorithmus

package io.gitlab.arturbosch.detekt.core.visitors.util

/**
 * @author Artur Bosch
 */
object LLOC {

	private val comments = arrayOf("//", "/*", "*/", "*")
	private val escapes = arrayOf("import", "package")

	fun analyze(lines: List<String>,
				isCommentMode: Boolean = false,
				isFullMode: Boolean = false): Int = Counter(lines, isCommentMode, isFullMode).run()

	private class Counter(private val lines: List<String>,
						  private val isCommentMode: Boolean = false,
						  private val isFullMode: Boolean = false) {

		private var counter = 0
		private var openedBrackets = 0
		private var closedBrackets = 0
		private var escape: Boolean = false

		internal fun run(): Int {
			for (line in lines) {

				val trimmed = line.trim()

				if (trimmed.isEmpty()) {
					continue
				}

				countOrEscapeComment(trimmed)
				if (escape) {
					continue
				}

				countOrEscapeAdditionalStatements(trimmed)
				if (escape) {
					continue
				}

				countStatementsAndDeclarations(trimmed)
			}

			return counter + if (openedBrackets - closedBrackets == 0) openedBrackets else -1
		}

		private fun countStatementsAndDeclarations(trimmed: String) {
			if (trimmed.contains(";")) {
				counter++
			}

			if (trimmed.contains("{")) {
				openedBrackets += frequency(trimmed, "{")
			} else if (trimmed.isAnnotationOrBraceletsDeclaration()) {
				counter++
			}

			if (trimmed.contains("}")) {
				closedBrackets += frequency(trimmed, "}")
			}
		}

		private fun countOrEscapeAdditionalStatements(trimmed: String) {
			escape = isEscaped(trimmed, escapes)
			if (escape && isFullMode) {
				counter++
			}
		}

		private fun countOrEscapeComment(trimmed: String) {
			escape = isEscaped(trimmed, comments)
			if (isCommentMode && escape) {
				counter++
			}
		}

		private fun String.isAnnotationOrBraceletsDeclaration() = startsWith("@")/* annotations */ ||
				contains("class ") /* sealed data enum annotation class etc */ || contains("interface ")

		private fun isEscaped(trimmed: String, rules: Array<String>): Boolean {
			return rules.any { trimmed.startsWith(it) }
		}

		private fun frequency(source: String, part: String): Int {

			if (source.isEmpty() || part.isEmpty()) {
				return 0
			}

			var count = 0
			var pos = source.indexOf(part, 0)
			while (pos != -1) {
				pos += part.length
				count++
				pos = source.indexOf(part, pos)
			}

			return count
		}

	}
}


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

package sample

import kotlinx.serialization.internal.IntSerializer
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class SampleTestsJVM {
    @Test
    fun testHello() {
        assertTrue("JVM" in hello())
    }

    @Test
    fun kindSimpleName() {
        val kind = IntSerializer.descriptor.kind
        val name = kind.toString()
        assertEquals("INT", name)
    }
}

Check that kotlin-reflect.jar is not required

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

package sample

import kotlinx.serialization.internal.IntSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class SampleTestsJVM {
    @Test
    fun testHello() {
        assertTrue("JVM" in hello())
    }

    @Test
    fun kindSimpleName() {
        val kind = IntSerializer.descriptor.kind
        val name = kind.toString()
        assertEquals("INT", name)
    }

    @Test
    fun kotlinReflectNotInClasspath() {
        val klass = Json::class
        assertFailsWith<KotlinReflectionNotSupportedError> {
            println(klass.qualifiedName)
        }
    }
}


package com.github.jackparisi.droidbox.wrapper

import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.github.jackparisi.droidbox.architecture.model.DroidViewModel

/**
 * Created by Giacomo Parisi on 20/10/17.
 * https://github.com/JackParisi
 */

/**
 *
 * Data for the wrapper
 *
 * @param viewModel The droidViewModel of the page to bind the wrapper
 * @param pageLayout The layout of the page
 * @param context The context of the page
 * @param params The layout params for the wrapper layout
 *
 * @return Return the view that wrap the page with the wrapper layout
 */
open class DroidWrapperSettings(
        val viewModel: DroidViewModel,
        val pageLayout: View,
        val wrapperLayout: View?,
        val context: Context,
        val params: ViewGroup.LayoutParams
)

Update droid wrapper settings docs

package com.github.jackparisi.droidbox.wrapper

import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.github.jackparisi.droidbox.architecture.model.DroidViewModel

/**
 * Created by Giacomo Parisi on 20/10/17.
 * https://github.com/JackParisi
 */

/**
 *
 * Class of date used for perform a wrap
 *
 * @param viewModel The droidViewModel of the page to bind the wrapper
 * @param pageLayout The layout of the page
 * @param context The context of the page
 * @param params The layout params for the wrapper layout
 *
 * @return Return the view that wrap the page with the wrapper layout
 */
open class DroidWrapperSettings(
        val viewModel: DroidViewModel,
        val pageLayout: View,
        val wrapperLayout: View?,
        val context: Context,
        val params: ViewGroup.LayoutParams
)


Add worker to print error into Gradle console.

package org.jlleitschuh.gradle.ktlint.worker

import com.pinterest.ktlint.core.LintError
import org.gradle.api.GradleException
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.logging.Logging
import org.gradle.api.provider.Property
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import java.io.FileInputStream
import java.io.ObjectInputStream

@Suppress("UnstableApiUsage")
internal abstract class ConsoleReportWorkAction : WorkAction<ConsoleReportWorkAction.ConsoleReportParameters> {

    private val logger = Logging.getLogger("ktlint-console-report-worker")

    override fun execute() {
        val errors = loadErrors()

        if (parameters.outputToConsole.getOrElse(false)) {
            val verbose = parameters.verbose.get()
            errors.forEach { lintErrorResult ->
                val filePath = lintErrorResult.lintedFile.absolutePath
                lintErrorResult
                    .lintErrors
                    .filter { !it.second }
                    .forEach {
                        it.first.lintError.logError(filePath, verbose)
                    }
            }
        }

        if (errors.any { it.lintErrors.any { !it.second } } &&
            !parameters.ignoreFailures.getOrElse(false)
        ) {
            throw GradleException("KtLint found code style violations.")
        }
    }

    private fun loadErrors(): List<LintErrorResult> =
        ObjectInputStream(FileInputStream(parameters.discoveredErrors.asFile.get()))
            .use {
                @Suppress("UNCHECKED_CAST")
                it.readObject() as List<LintErrorResult>
            }

    private fun LintError.logError(
        filePath: String,
        verbose: Boolean
    ) {
        val verboseSuffix = if (verbose) " ($ruleId)" else ""
        val errorDetail = if (!canBeAutoCorrected) {
            "$detail (cannot be auto-corrected)"
        } else {
            detail
        }
        logger.warn("$filePath:$line:$col $errorDetail$verboseSuffix")
    }

    internal interface ConsoleReportParameters : WorkParameters {
        val discoveredErrors: RegularFileProperty
        val outputToConsole: Property<Boolean>
        val ignoreFailures: Property<Boolean>
        val verbose: Property<Boolean>
    }
}


package com.intellij.debugger.streams.ui.impl

import com.intellij.debugger.streams.ui.ValueWithPosition
import com.intellij.ui.JBColor
import java.awt.Graphics
import javax.swing.JPanel

/**
 * @author Vitaliy.Bibaev
 */
class MappingPane(private val beforeValues: List<ValueWithPosition>) : JPanel() {

  override fun paintComponent(g: Graphics?) {
    if (g == null) {
      return
    }

    val x1 = x
    val x2 = x + width
    for (value in beforeValues) {
      val position: Int = value.position
      for (nextValue in value.nextValues.filter { it.isVisible }) {
        g.color = JBColor.WHITE
        g.drawLine(x1, position, x2, nextValue.position)
      }
    }
  }
}

Add component which drawing a mapping between before and after values

package com.intellij.debugger.streams.ui.impl

import com.intellij.debugger.streams.ui.LinkedValuesMapping
import com.intellij.debugger.streams.ui.ValueWithPosition
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import java.awt.BorderLayout
import java.awt.Graphics
import javax.swing.JPanel

/**
 * @author Vitaliy.Bibaev
 */
class MappingPane(private val beforeValues: List<ValueWithPosition>,
                  private val mapping: LinkedValuesMapping) : JPanel(BorderLayout()) {
  init {
    add(JBLabel("map"), BorderLayout.NORTH)
    add(MyDrawPane(), BorderLayout.CENTER)
  }

  private inner class MyDrawPane : JPanel() {
    override fun paintComponent(g: Graphics?) {
      if (g == null) {
        return
      }

      val x1 = x
      val x2 = x + width
      for (value in beforeValues) {
        if (!value.isVisible) continue
        val position: Int = value.position
        val linkedValues = mapping.getLinkedValues(value) ?: continue
        for (nextValue in linkedValues.filter { it.isVisible }) {
          g.color = JBColor.BLACK
          g.drawLine(x1, position, x2, nextValue.position)
        }
      }
    }
  }
}


package io.sensefly.dynamodbtos3.commandline

import com.beust.jcommander.JCommander
import io.sensefly.dynamodbtos3.BackupRunner
import io.sensefly.dynamodbtos3.RestoreTable
import org.springframework.boot.CommandLineRunner
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component
import javax.inject.Inject

@Component
@Profile("!test")
class CommandLineParser @Inject constructor(
    private val backupRunner: BackupRunner,
    private val restoreTable: RestoreTable) : CommandLineRunner {

  internal val backupCmd = BackupCommand()
  internal val restoreCmd = RestoreCommand()

  override fun run(vararg args: String?) {
    val jc = JCommander.newBuilder()
        .addObject(MainCommand())
        .addCommand("backup", backupCmd)
        .addCommand("restore", restoreCmd)
        .build()
    jc.parse(*args)

    when (jc.parsedCommand) {
      "backup" -> {
        backupRunner.run(backupCmd.parseTables(), backupCmd.bucket, backupCmd.cron, backupCmd.readPercentage, backupCmd.pattern)
      }
      "restore" -> {
        restoreTable.restore(restoreCmd.source!!, restoreCmd.table, restoreCmd.writePercentage)
      }
      null -> {
        jc.usage()
      }
    }
  }

}

Add log for command line params

package io.sensefly.dynamodbtos3.commandline

import com.beust.jcommander.JCommander
import io.sensefly.dynamodbtos3.BackupRunner
import io.sensefly.dynamodbtos3.RestoreTable
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component
import javax.inject.Inject

@Component
@Profile("!test")
class CommandLineParser @Inject constructor(
    private val backupRunner: BackupRunner,
    private val restoreTable: RestoreTable) : CommandLineRunner {

  private val log = LoggerFactory.getLogger(javaClass)

  internal val backupCmd = BackupCommand()
  internal val restoreCmd = RestoreCommand()

  override fun run(vararg args: String?) {
    log.info("Run with {}", args.joinToString(" "))

    val jc = JCommander.newBuilder()
        .addObject(MainCommand())
        .addCommand("backup", backupCmd)
        .addCommand("restore", restoreCmd)
        .build()
    jc.parse(*args)

    when (jc.parsedCommand) {
      "backup" -> {
        backupRunner.run(backupCmd.parseTables(), backupCmd.bucket, backupCmd.cron, backupCmd.readPercentage, backupCmd.pattern)
      }
      "restore" -> {
        restoreTable.restore(restoreCmd.source!!, restoreCmd.table, restoreCmd.writePercentage)
      }
      null -> {
        jc.usage()
      }
    }
  }

}


package com.sebastiansokolowski.auctionhunter.entity

import javax.persistence.*

@Entity
@Table(name = "target")
data class Target(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long = 0,
        var name: String = "",
        var categoryId: String = "",
        var phrase: String? = null,
        @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
        @JoinColumn(name = "target_id")
        var parameters: MutableList<TargetParameters> = mutableListOf(),
        @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
        @JoinColumn(name = "target_id")
        var offers: MutableList<Offer> = mutableListOf()
)

Make the categoryId field nullable.

package com.sebastiansokolowski.auctionhunter.entity

import javax.persistence.*

@Entity
@Table(name = "target")
data class Target(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id: Long = 0,
        var name: String = "",
        var categoryId: String? = null,
        var phrase: String? = null,
        @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
        @JoinColumn(name = "target_id")
        var parameters: MutableList<TargetParameters> = mutableListOf(),
        @OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
        @JoinColumn(name = "target_id")
        var offers: MutableList<Offer> = mutableListOf()
)


package eu.kanade.tachiyomi.data.updater.github

import eu.kanade.tachiyomi.network.NetworkHelper
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get

/**
 * Used to connect with the GitHub API.
 */
interface GithubService {

    companion object {
        fun create(): GithubService {
            val restAdapter = Retrofit.Builder()
                    .baseUrl("https://api.github.com")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(Injekt.get<NetworkHelper>().client)
                    .build()

            return restAdapter.create(GithubService::class.java)
        }
    }

    @GET("/repos/inorichi/tachiyomi/releases/latest")
    suspend fun getLatestVersion(): GithubRelease

}

Remove unused RxJavaCallAdapterFactory for app updater

package eu.kanade.tachiyomi.data.updater.github

import eu.kanade.tachiyomi.network.NetworkHelper
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get

/**
 * Used to connect with the GitHub API.
 */
interface GithubService {

    companion object {
        fun create(): GithubService {
            val restAdapter = Retrofit.Builder()
                    .baseUrl("https://api.github.com")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(Injekt.get<NetworkHelper>().client)
                    .build()

            return restAdapter.create(GithubService::class.java)
        }
    }

    @GET("/repos/inorichi/tachiyomi/releases/latest")
    suspend fun getLatestVersion(): GithubRelease

}


package com.alexstyl.specialdates.events.peopleevents

import com.alexstyl.specialdates.events.namedays.NamedayDatabaseRefresher
import io.reactivex.Observable
import io.reactivex.Scheduler

open class PeopleEventsUpdater(private val peopleEventsStaticEventsRefresher: PeopleEventsStaticEventsRefresher,
                               private val namedayDatabaseRefresher: NamedayDatabaseRefresher,
                               private val viewRefresher: UpcomingEventsViewRefresher,
                               private val workScheduler: Scheduler,
                               private val resultScheduler: Scheduler) {

    open fun updateEvents() = Observable.fromCallable {
        peopleEventsStaticEventsRefresher.rebuildEvents()
        namedayDatabaseRefresher.refreshNamedaysIfEnabled()
    }
            .subscribeOn(workScheduler)
            .observeOn(resultScheduler)
            .map {
                viewRefresher.refreshViews()
            }!!
}

Mark events as initialised after done

package com.alexstyl.specialdates.events.peopleevents

import com.alexstyl.specialdates.events.namedays.NamedayDatabaseRefresher
import io.reactivex.Observable
import io.reactivex.Scheduler

open class PeopleEventsUpdater(private val peopleEventsStaticEventsRefresher: PeopleEventsStaticEventsRefresher,
                               private val namedayDatabaseRefresher: NamedayDatabaseRefresher,
                               private val viewRefresher: UpcomingEventsViewRefresher,
                               private val peopleSettings: UpcomingEventsSettings,
                               private val workScheduler: Scheduler,
                               private val resultScheduler: Scheduler) {

    open fun updateEvents() = Observable.fromCallable {
        peopleEventsStaticEventsRefresher.rebuildEvents()
        namedayDatabaseRefresher.refreshNamedaysIfEnabled()
        peopleSettings.markEventsAsInitialised()
    }
            .subscribeOn(workScheduler)
            .observeOn(resultScheduler)
            .map {
                viewRefresher.refreshViews()
            }!!
}


package io.github.sirlantis.rubymine.rubocop

import com.intellij.CommonBundle
import kotlin.properties.Delegates
import java.lang.ref.Reference
import java.util.ResourceBundle
import java.lang.ref.SoftReference

class RubocopBundle {
    class object {
        val BUNDLE: String = "io.github.sirlantis.rubymine.RubocopBundle"
        val LOG_ID: String = "io.github.sirlantis.rubymine"

        fun message(key: String, vararg params: Any?): String {
            return CommonBundle.message(instance, key, *params)
        }

        private var ourBundle: Reference<ResourceBundle>? = null

        val instance: ResourceBundle
            get() {
                var bundle = com.intellij.reference.SoftReference.dereference(ourBundle)

                if (bundle == null) {
                    bundle = ResourceBundle.getBundle(BUNDLE)
                    ourBundle = SoftReference(bundle)
                }

                return bundle
            }
    }
}

Fix BUNDLE identifier and LOG identifier

package io.github.sirlantis.rubymine.rubocop

import com.intellij.CommonBundle
import kotlin.properties.Delegates
import java.lang.ref.Reference
import java.util.ResourceBundle
import java.lang.ref.SoftReference

class RubocopBundle {
    class object {
        val BUNDLE: String = "io.github.sirlantis.rubymine.rubocop.RubocopBundle"
        val LOG_ID: String = "io.github.sirlantis.rubymine.rubocop"

        fun message(key: String, vararg params: Any?): String {
            return CommonBundle.message(instance, key, *params)
        }

        private var ourBundle: Reference<ResourceBundle>? = null

        val instance: ResourceBundle
            get() {
                var bundle = com.intellij.reference.SoftReference.dereference(ourBundle)

                if (bundle == null) {
                    bundle = ResourceBundle.getBundle(BUNDLE)
                    ourBundle = SoftReference(bundle)
                }

                return bundle
            }
    }
}


package com.tasomaniac.openwith.settings

import android.content.Intent
import android.support.v7.preference.Preference
import com.tasomaniac.openwith.R
import com.tasomaniac.openwith.data.Analytics
import com.tasomaniac.openwith.intro.IntroActivity
import com.tasomaniac.openwith.preferred.PreferredAppsActivity
import javax.inject.Inject

class GeneralSettings @Inject constructor(
    fragment: SettingsFragment,
    private val analytics: Analytics
) : Settings(fragment) {

  override fun setup() {
    addPreferencesFromResource(R.xml.pref_general)

    findPreference(R.string.pref_key_about).onPreferenceClickListener = onPreferenceClickListener
    findPreference(R.string.pref_key_preferred).onPreferenceClickListener = onPreferenceClickListener
  }

  private val onPreferenceClickListener = Preference.OnPreferenceClickListener {
    when {
      it.isKeyEquals(R.string.pref_key_about) -> {
        startActivity(Intent(activity, IntroActivity::class.java))
      }
      it.isKeyEquals(R.string.pref_key_preferred) -> {
        startActivity(Intent(activity, PreferredAppsActivity::class.java))
      }
    }

    analytics.sendEvent("Preference", "Item Click", it.key)
    true
  }
}

Add click handling back for Browser settings

package com.tasomaniac.openwith.settings

import android.content.Intent
import android.support.v7.preference.Preference
import com.tasomaniac.openwith.R
import com.tasomaniac.openwith.browser.PreferredBrowserActivity
import com.tasomaniac.openwith.data.Analytics
import com.tasomaniac.openwith.intro.IntroActivity
import com.tasomaniac.openwith.preferred.PreferredAppsActivity
import javax.inject.Inject

class GeneralSettings @Inject constructor(
    fragment: SettingsFragment,
    private val analytics: Analytics
) : Settings(fragment) {

  override fun setup() {
    addPreferencesFromResource(R.xml.pref_general)

    findPreference(R.string.pref_key_about).onPreferenceClickListener = onPreferenceClickListener
    findPreference(R.string.pref_key_preferred).onPreferenceClickListener = onPreferenceClickListener
    findPreference(R.string.pref_key_browser).onPreferenceClickListener = onPreferenceClickListener
  }

  private val onPreferenceClickListener = Preference.OnPreferenceClickListener {
    when {
      it.isKeyEquals(R.string.pref_key_about) -> {
        startActivity(Intent(activity, IntroActivity::class.java))
      }
      it.isKeyEquals(R.string.pref_key_preferred) -> {
        startActivity(Intent(activity, PreferredAppsActivity::class.java))
      }
      it.isKeyEquals(R.string.pref_key_browser) -> {
        startActivity(Intent(activity, PreferredBrowserActivity::class.java))
      }
    }

    analytics.sendEvent("Preference", "Item Click", it.key)
    true
  }
}


/*
 * Copyright (C) 2020, Alashov Berkeli
 * All rights reserved.
 */
package tm.alashow.datmusic.util

import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
import java.util.Locale
import okhttp3.Interceptor
import okhttp3.Response
import tm.alashow.Config as BaseConfig
import tm.alashow.datmusic.Config

internal class AppHeadersInterceptor(context: Context) : Interceptor {
    @SuppressLint("HardwareIds")
    private val clientId = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder()
            .header("User-Agent", Config.APP_USER_AGENT)
            .header("Accept-Language", Locale.getDefault().language)
            .run {
                val host = chain.request().url.host
                when (host.contains(BaseConfig.BASE_HOST)) {
                    true -> this.header("X-Datmusic-Id", clientId).header("X-Datmusic-Version", Config.APP_USER_AGENT)
                    else -> this
                }
            }
            .build()
        return chain.proceed(request)
    }
}

Fix appheaders to use androidId function

/*
 * Copyright (C) 2020, Alashov Berkeli
 * All rights reserved.
 */
package tm.alashow.datmusic.util

import android.content.Context
import java.util.Locale
import okhttp3.Interceptor
import okhttp3.Response
import tm.alashow.Config as BaseConfig
import tm.alashow.base.ui.utils.extensions.androidId
import tm.alashow.datmusic.Config

internal class AppHeadersInterceptor(context: Context) : Interceptor {
    private val clientId = context.androidId()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder()
            .header("User-Agent", Config.APP_USER_AGENT)
            .header("Accept-Language", Locale.getDefault().language)
            .run {
                val host = chain.request().url.host
                when (host.contains(BaseConfig.BASE_HOST)) {
                    true -> this.header("X-Datmusic-Id", clientId).header("X-Datmusic-Version", Config.APP_USER_AGENT)
                    else -> this
                }
            }
            .build()
        return chain.proceed(request)
    }
}


package org.gradle.gradlebuild

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

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

Upgrade Kotlin DSL 0.19.{2 => 3}

package org.gradle.gradlebuild

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

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


object Ci {

   // this is the version used for building snapshots
   // .buildnumber-snapshot will be appended
   private const val snapshotBase = "4.6.0"

   private val githubBuildNumber = System.getenv("GITHUB_RUN_NUMBER")

   private val snapshotVersion = when (githubBuildNumber) {
      null -> "$snapshotBase-LOCAL"
      else -> "$snapshotBase.${githubBuildNumber}-SNAPSHOT"
   }

   private val releaseVersion = System.getenv("RELEASE_VERSION")

   val isRelease = releaseVersion != null
   val publishVersion = releaseVersion ?: snapshotVersion
}

Set snapshot base to 4.7.0

object Ci {

   // this is the version used for building snapshots
   // .buildnumber-snapshot will be appended
   private const val snapshotBase = "4.7.0"

   private val githubBuildNumber = System.getenv("GITHUB_RUN_NUMBER")

   private val snapshotVersion = when (githubBuildNumber) {
      null -> "$snapshotBase-LOCAL"
      else -> "$snapshotBase.${githubBuildNumber}-SNAPSHOT"
   }

   private val releaseVersion = System.getenv("RELEASE_VERSION")

   val isRelease = releaseVersion != null
   val publishVersion = releaseVersion ?: snapshotVersion
}


/*
 * 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.
 */
import accessors.java
import org.gradle.gradlebuild.unittestandcompile.ModuleType

plugins {
    `java-library`
    id("gradlebuild.classycle")
}

description = "Execution engine that takes a unit of work and makes it happen"

dependencies {
    api(project(":coreApi"))
    api(library("guava"))
    api(library("jsr305"))
    api(library("inject"))

    implementation(project(":baseServices"))
    implementation(project(":snapshots"))
    implementation(project(":buildCachePackaging"))
    implementation(library("commons_io"))
    implementation(library("commons_lang"))

    testImplementation(project(":internalTesting"))
}

java {
    gradlebuildJava {
        moduleType = ModuleType.CORE
    }
}

testFixtures {
    from(":baseServices")
    from(":files")
    from(":messaging")
    from(":snapshots")
    from(":core")
}

Enable strict compile for the execution project

/*
 * 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.
 */
import accessors.java
import org.gradle.gradlebuild.unittestandcompile.ModuleType

plugins {
    `java-library`
    gradlebuild.`strict-compile`
    gradlebuild.classycle
}

description = "Execution engine that takes a unit of work and makes it happen"

dependencies {
    api(project(":coreApi"))
    api(library("guava"))
    api(library("jsr305"))
    api(library("inject"))

    implementation(project(":baseServices"))
    implementation(project(":snapshots"))
    implementation(project(":buildCachePackaging"))
    implementation(library("commons_io"))
    implementation(library("commons_lang"))

    testImplementation(project(":internalTesting"))
}

java {
    gradlebuildJava {
        moduleType = ModuleType.CORE
    }
}

testFixtures {
    from(":baseServices")
    from(":files")
    from(":messaging")
    from(":snapshots")
    from(":core")
}


package com.jetbrains.rider

import com.intellij.openapi.project.Project
import com.jetbrains.rider.projectView.indexing.contentModel.ContentModelExcludes
import java.io.File

class UnityConfigurationImpl(private val project: Project, unityProjectDiscoverer: UnityProjectDiscoverer, excludes: ContentModelExcludes) {

    companion object {
        private val ignoredDirectories = arrayOf("Library", "Temp")
    }

    init {
        if (unityProjectDiscoverer.isUnityProject) {
            val excludePaths = ignoredDirectories
                    .mapNotNull(::getChildAsFile)
                    .toHashSet()
            excludes.updateExcludes(this, excludePaths)
        }
    }

    private fun getChildAsFile(directoryName: String) : File?
    {
        val libraryFolder = project.projectDir.findChild(directoryName)
        val path = libraryFolder?.canonicalPath ?: return null
        return File(path)
    }
}

Include Packages folder in index

package com.jetbrains.rider

import com.intellij.openapi.project.Project
import com.jetbrains.rider.projectView.indexing.contentModel.ContentModelExcludes
import com.jetbrains.rider.projectView.indexing.contentModel.ContentModelUserStore
import com.jetbrains.rider.projectView.indexing.contentModel.tryInclude
import java.io.File

class UnityConfigurationImpl(private val project: Project, unityProjectDiscoverer: UnityProjectDiscoverer,
                             excludes: ContentModelExcludes, userStore: ContentModelUserStore) {

    companion object {
        private val ignoredDirectories = arrayOf("Library", "Temp")
    }

    init {
        if (unityProjectDiscoverer.isUnityProject) {
            val excludePaths = ignoredDirectories
                    .mapNotNull(::getChildAsFile)
                    .toHashSet()
            excludes.updateExcludes(this, excludePaths)

            getChildAsFile("Packages")?.let { userStore.tryInclude(arrayOf(it)) }
        }
    }

    private fun getChildAsFile(directoryName: String) : File?
    {
        val libraryFolder = project.projectDir.findChild(directoryName)
        val path = libraryFolder?.canonicalPath ?: return null
        return File(path)
    }
}


plugins {
  id("adventure.parent-build-logic")
}

group = "net.kyori"
version = "4.9.0"
description = "A user-interface library for Minecraft: Java Edition."

Prepare for development on 4.9.1

plugins {
  id("adventure.parent-build-logic")
}

group = "net.kyori"
version = "4.9.1-SNAPSHOT"
description = "A user-interface library for Minecraft: Java Edition."


package com.zhuinden.simplestackexamplekotlin

import android.os.Parcelable
import paperparcel.PaperParcel

/**
 * Created by Owner on 2017.11.13.
 */

@PaperParcel
data class DashboardKey(val tag: String = DashboardKey::javaClass.name) : BaseKey() {
    // using data class makes you not need to implement hashCode/equals/toString
    // the other option is using `object` where you MUST override `toString`
    override fun createFragment(): BaseFragment = DashboardFragment()

    companion object {
        @JvmField val CREATOR: Parcelable.Creator<DashboardKey> = PaperParcelDashboardKey.CREATOR
    }
}

Fix the tag used by the Data class

package com.zhuinden.simplestackexamplekotlin

import android.os.Parcelable
import paperparcel.PaperParcel

/**
 * Created by Owner on 2017.11.13.
 */

@PaperParcel
data class DashboardKey(val tag: String = DashboardKey::class.java.name) : BaseKey() {
    // using data class makes you not need to implement hashCode/equals/toString
    // the other option is using `object` where you MUST override `toString`
    override fun createFragment(): BaseFragment = DashboardFragment()

    companion object {
        @JvmField val CREATOR: Parcelable.Creator<DashboardKey> = PaperParcelDashboardKey.CREATOR
    }
}


package org.wfanet.measurement.service.testing.storage

import kotlin.properties.Delegates
import org.wfanet.measurement.common.commandLineMain
import org.wfanet.measurement.service.common.CommonServer
import picocli.CommandLine

private class FakeStorageServiceFlags {
  @set:CommandLine.Option(
    names = ["--port", "-p"],
    description = ["TCP port for gRPC server."],
    required = true,
    defaultValue = "8080"
  )
  var port: Int by Delegates.notNull()
    private set
}

@CommandLine.Command(
  name = "gcp_worker_server",
  mixinStandardHelpOptions = true,
  showDefaultValues = true
)
private fun run(@CommandLine.Mixin fakeStorageServiceFlags: FakeStorageServiceFlags) {
  CommonServer(
    "FakeStorageService",
    fakeStorageServiceFlags.port,
    FakeStorageService()
  ).start().blockUntilShutdown()
}

fun main(args: Array<String>) = commandLineMain(::run, args)

Fix storage fake to support verbose logging.

package org.wfanet.measurement.service.testing.storage

import org.wfanet.measurement.common.commandLineMain
import org.wfanet.measurement.service.common.CommonServer
import picocli.CommandLine

@CommandLine.Command(
  name = "fake_storage_server",
  mixinStandardHelpOptions = true,
  showDefaultValues = true
)
private fun run(
  @CommandLine.Mixin commonServerFlags: CommonServer.Flags) {
  CommonServer.fromFlags(
    commonServerFlags,
    "FakeStorageService",
    FakeStorageService()
  ).start().blockUntilShutdown()
}

fun main(args: Array<String>) = commandLineMain(::run, args)


package org.mtransit.android.commons.data

import androidx.collection.LruCache

operator fun <K : Any, V : Any> LruCache<K, V>.set(key: K, value: V): V? {
    return this.put(key, value)
}


package org.http4k.streaming

import org.http4k.core.HttpHandler
import org.http4k.server.Http4kServer
import org.http4k.server.ServerConfig

class MemoryStreamingContract : StreamingContract(StreamingTestConfiguration(5, 100, 100)) {
    override fun serverConfig(port: Int): ServerConfig = DummyServerConfig
    override fun createClient(): HttpHandler = server
}

object DummyServerConfig : ServerConfig {
    override fun toServer(handler: HttpHandler): Http4kServer = object : Http4kServer {
        override fun start(): Http4kServer = this
        override fun stop() = Unit
    }
}

Make test class match file name

package org.http4k.streaming

import org.http4k.core.HttpHandler
import org.http4k.server.Http4kServer
import org.http4k.server.ServerConfig

class MemoryStreamingTest : StreamingContract(StreamingTestConfiguration(5, 100, 100)) {
    override fun serverConfig(port: Int): ServerConfig = DummyServerConfig
    override fun createClient(): HttpHandler = server
}

object DummyServerConfig : ServerConfig {
    override fun toServer(handler: HttpHandler): Http4kServer = object : Http4kServer {
        override fun start(): Http4kServer = this
        override fun stop() = Unit
    }
}


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

package androidx.compose.ui.tooling

import org.junit.Assert.assertNotNull
import org.junit.Test

class HotReloaderTest {
    /**
     * Ensure that the `HotReloader` interface used by the preview is not modified inadvertently.
     *
     * This test replicates the sequence of calls done from the preview to obtain the methods from
     * `HotReloader`.
     */
    @Test
    fun checkViaReflection() {
        val hotReloader = HotReloaderTest::class.java.classLoader!!
            .loadClass("androidx.compose.runtime.HotReloader")
        val hotReloaderInstance = hotReloader.getDeclaredField("Companion").let {
            it.isAccessible = true
            it.get(null)
        }
        val saveStateAndDisposeMethod =
            hotReloaderInstance.javaClass.getDeclaredMethod("saveStateAndDispose", Any::class.java)
                .also {
                    it.isAccessible = true
                }
        val loadStateAndDisposeMethod =
            hotReloaderInstance.javaClass.getDeclaredMethod("loadStateAndCompose", Any::class.java)
                .also {
                    it.isAccessible = true
                }
        assertNotNull(saveStateAndDisposeMethod)
        assertNotNull(loadStateAndDisposeMethod)
    }
}


Add a convenient extension function to get the errors of a given parameter

/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 * ------------------------------------------------------------------*/

package com.kotlinnlp.simplednn.core.optimizer

import com.kotlinnlp.simplednn.core.arrays.ParamsArray

/**
 * @param param a parameters
 *
 * @return the first params errors referring to the given [param], or `null` if no errors refer to it.
 */
fun ParamsErrorsList.getErrorsOf(param: ParamsArray): ParamsArray.Errors<*>? = this.find { it.refParams === param}


package jp.toastkid.yobidashi.browser

import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.support.v7.app.AlertDialog
import android.webkit.WebView

import jp.toastkid.yobidashi.R

/**
 * Method object of displaying page information dialog.

 * @author toastkidjp
 */
internal class PageInformationDialog(private val webView: WebView) {

    private val context: Context

    init {
        this.context = webView.context
    }

    fun show() {
        val builder = AlertDialog.Builder(context)
                .setTitle(R.string.title_menu_page_information)
                .setMessage("Title: " + webView.title
                        + System.getProperty("line.separator")
                        + "URL: " + webView.url
                        + System.getProperty("line.separator")
                )
                .setCancelable(true)
                .setPositiveButton(R.string.close) { d, i -> d.dismiss() }
        if (webView.favicon != null) {
            builder.setIcon(BitmapDrawable(context.resources, webView.favicon))
        }
        builder.show()
    }
}

Implement copy URL to page information dialog.

package jp.toastkid.yobidashi.browser

import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.BitmapDrawable
import android.support.v7.app.AlertDialog
import android.webkit.WebView

import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.libs.Toaster
import jp.toastkid.yobidashi.libs.clip.Clipboard
import jp.toastkid.yobidashi.libs.preference.PreferenceApplier

/**
 * Method object of displaying page information dialog.
 *
 * @param webView
 * @author toastkidjp
 */
internal class PageInformationDialog(private val webView: WebView) {

    /**
     * Context.
     */
    private val context: Context = webView.context

    /**
     * Show dialog.
     */
    fun show() {
        val builder = AlertDialog.Builder(context)
                .setTitle(R.string.title_menu_page_information)
                .setMessage(makeMessage())
                .setCancelable(true)
                .setNeutralButton("Clip URL") { d, _ -> clipUrl(d) }
                .setPositiveButton(R.string.close) { d, _ -> d.dismiss() }
        if (webView.favicon != null) {
            builder.setIcon(BitmapDrawable(context.resources, webView.favicon))
        }
        builder.show()
    }

    /**
     * Copy URL to Clipboard.
     *
     * @param d
     */
    private fun clipUrl(d: DialogInterface) {
        Clipboard.clip(context, webView.url)
        Toaster.snackShort(
                webView,
                "It has copied URL to clipboard.${lineSeparator}${webView.url}",
                PreferenceApplier(context).colorPair()
        )
        d.dismiss()
    }

    /**
     * Make message.
     */
    private fun makeMessage(): String =
            "Title: ${webView.title}${lineSeparator}URL: ${webView.url}${lineSeparator}"

    companion object {

        /**
         * Line separator.
         */
        private val lineSeparator = System.getProperty("line.separator")

    }
}


package com.elpassion.android.commons.espresso

import android.os.Bundle
import android.support.test.rule.ActivityTestRule
import android.widget.Button
import android.widget.FrameLayout
import org.junit.Rule
import org.junit.Test

class HasChildWithTextAssertionsTest {

    @JvmField @Rule
    val activityRule = ActivityTestRule(Activity::class.java)

    @Test
    fun shouldConfirmHasChildWithText() {
        onId(anId).hasChildWithText(firstText)
    }

    @Test
    fun shouldConfirmHasChildWithTextRes() {
        onId(anId).hasChildWithText(secondTextRes)
    }

    class Activity : android.app.Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(FrameLayout(this).apply {
                id = anId
                addView(Button(this.context).apply {
                    text = firstText
                })
                addView(Button(this.context).apply {
                    setText(secondTextRes)
                })
            })
        }
    }

    companion object {
        private val anId = 124
        private val firstText = "text"
        private val secondTextRes = R.string.app_name
    }
}

Add does not have ChildWithTextAssertionsTests

package com.elpassion.android.commons.espresso

import android.os.Bundle
import android.support.test.rule.ActivityTestRule
import android.widget.Button
import android.widget.FrameLayout
import org.junit.Rule
import org.junit.Test

class HasChildWithTextAssertionsTest {

    @JvmField @Rule
    val activityRule = ActivityTestRule(Activity::class.java)

    @Test
    fun shouldConfirmHasChildWithText() {
        onId(anId).hasChildWithText(firstText)
    }

    @Test
    fun shouldConfirmHasChildWithTextRes() {
        onId(anId).hasChildWithText(secondTextRes)
    }

    @Test
    fun shouldConfirmDoesNotHaveChildWithText() {
        onId(anId).doesNotHaveChildWithText("not existing text")
    }

    @Test
    fun shouldConfirmDoesNotHaveChildWithTextRes() {
        onId(anId).doesNotHaveChildWithText(123)
    }

    class Activity : android.app.Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(FrameLayout(this).apply {
                id = anId
                addView(Button(this.context).apply {
                    text = firstText
                })
                addView(Button(this.context).apply {
                    setText(secondTextRes)
                })
            })
        }
    }

    companion object {
        private val anId = 124
        private val firstText = "text"
        private val secondTextRes = R.string.app_name
    }
}


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

object AndroidComponents {
    const val VERSION = "92.0.20210809190134"
}

Update Android Components version to 93.0.20210812143121.

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

object AndroidComponents {
    const val VERSION = "93.0.20210812143121"
}


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

package org.rust.ide.inspections

import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.RsMacroCall
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsTryExpr
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.macroName

/**
 * Change `try!` macro to `?` operator.
 */
class RsTryMacroInspection : RsLocalInspectionTool() {
    override fun getDisplayName() = "try! macro usage"

    override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() {
        override fun visitMacroCall(o: RsMacroCall) {
            if (o.macroName?.text != "try" || o.tryMacroArgument == null) return
            holder.registerProblem(
                o,
                "try! macro can be replaced with ? operator",
                object : LocalQuickFix {
                    override fun getName() = "Change try! to ?"

                    override fun getFamilyName() = name

                    override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
                        val macro = descriptor.psiElement as RsMacroCall
                        val body = macro.tryMacroArgument!!.expr
                        val tryExpr = RsPsiFactory(project).createExpression("${body.text}?") as RsTryExpr
                        macro.replace(tryExpr)
                    }
                }
            )
        }
    }
}

Fix exceptions after running the "Change try! to ?" inspection

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

package org.rust.ide.inspections

import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.macroName

/**
 * Change `try!` macro to `?` operator.
 */
class RsTryMacroInspection : RsLocalInspectionTool() {
    override fun getDisplayName() = "try! macro usage"

    override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() {
        override fun visitMacroExpr(o: RsMacroExpr) {
            if (o.macroCall.macroName?.text != "try" || o.macroCall.tryMacroArgument == null) return
            holder.registerProblem(
                o,
                "try! macro can be replaced with ? operator",
                object : LocalQuickFix {
                    override fun getName() = "Change try! to ?"

                    override fun getFamilyName() = name

                    override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
                        val macro = descriptor.psiElement as RsMacroExpr
                        val body = macro.macroCall.tryMacroArgument!!.expr
                        val tryExpr = RsPsiFactory(project).createExpression("${body.text}?") as RsTryExpr
                        macro.replace(tryExpr)
                    }
                }
            )
        }
    }
}


plugins {
    id("com.android.library") version "$androidPluginVersion" apply false
    kotlin("jvm") version "$kotlinVersion" apply false
    kotlin("android") version "$kotlinVersion" apply false
    kotlin("multiplatform") version "$kotlinVersion" apply false
}

subprojects {
    apply(plugin = "maven-publish")

    repositories {
        google()
        mavenCentral()
    }

    group = "example"
    version = "1.0"

    extensions.getByType<PublishingExtension>().apply {
        repositories {
            maven {
                setUrl(File(rootDir, "repo"))
            }
        }
    }

    plugins.withType<JavaPlugin> {
        extensions.configure<JavaPluginExtension> {
            sourceCompatibility = JavaVersion.VERSION_1_8
            targetCompatibility = JavaVersion.VERSION_1_8
        }
    }
}

Revert smoke test to using jcenter with explainer comment

plugins {
    id("com.android.library") version "$androidPluginVersion" apply false
    kotlin("jvm") version "$kotlinVersion" apply false
    kotlin("android") version "$kotlinVersion" apply false
    kotlin("multiplatform") version "$kotlinVersion" apply false
}

subprojects {
    apply(plugin = "maven-publish")

    repositories {
        google()
        mavenCentral()
        /*
        jcenter() requried because:
        > Could not resolve all files for configuration ':android-kotlin-library:lintClassPath'.
           > Could not find org.jetbrains.trove4j:trove4j:20160824.
             Searched in the following locations:
               - https://dl.google.com/dl/android/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
               - https://repo.maven.apache.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom
             Required by:
                 project :android-kotlin-library > com.android.tools.lint:lint-gradle:27.0.2 > com.android.tools:sdk-common:27.0.2
                 project :android-kotlin-library > com.android.tools.lint:lint-gradle:27.0.2 > com.android.tools.external.com-intellij:intellij-core:27.0.2

         Newer versions of this library are available in Maven Central: https://search.maven.org/artifact/org.jetbrains.intellij.deps/trove4j
         */
        jcenter()
    }

    group = "example"
    version = "1.0"

    extensions.getByType<PublishingExtension>().apply {
        repositories {
            maven {
                setUrl(File(rootDir, "repo"))
            }
        }
    }

    plugins.withType<JavaPlugin> {
        extensions.configure<JavaPluginExtension> {
            sourceCompatibility = JavaVersion.VERSION_1_8
            targetCompatibility = JavaVersion.VERSION_1_8
        }
    }
}


package org.jetbrains.ktor.config

import com.typesafe.config.*

/**
 * Implements [ApplicationEnvironment] by loading configuration from HOCON data structures
 */
open class HoconApplicationConfig(private val config: Config) : ApplicationConfig {
    override fun property(path: String): ApplicationConfigValue {
        if (!config.hasPath(path))
            throw ApplicationConfigurationException("Property $path not found.")
        return HoconApplicationConfigValue(config, path)
    }

    override fun propertyOrNull(path: String): ApplicationConfigValue? {
        if (!config.hasPath(path))
            return null
        return HoconApplicationConfigValue(config, path)
    }

    override fun configList(path: String): List<ApplicationConfig> {
        return config.getConfigList(path).map { HoconApplicationConfig(it) }
    }

    override fun config(path: String): ApplicationConfig {
        throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    private class HoconApplicationConfigValue(val config: Config, val path: String) : ApplicationConfigValue {
        override fun getString(): String = config.getString(path)
        override fun getList(): List<String> = config.getStringList(path)
    }
}

Implement missing operation in Hocon Config

package org.jetbrains.ktor.config

import com.typesafe.config.*

/**
 * Implements [ApplicationEnvironment] by loading configuration from HOCON data structures
 */
open class HoconApplicationConfig(private val config: Config) : ApplicationConfig {
    override fun property(path: String): ApplicationConfigValue {
        if (!config.hasPath(path))
            throw ApplicationConfigurationException("Property $path not found.")
        return HoconApplicationConfigValue(config, path)
    }

    override fun propertyOrNull(path: String): ApplicationConfigValue? {
        if (!config.hasPath(path))
            return null
        return HoconApplicationConfigValue(config, path)
    }

    override fun configList(path: String): List<ApplicationConfig> {
        return config.getConfigList(path).map { HoconApplicationConfig(it) }
    }

    override fun config(path: String): ApplicationConfig = HoconApplicationConfig(config.getConfig(path))

    private class HoconApplicationConfigValue(val config: Config, val path: String) : ApplicationConfigValue {
        override fun getString(): String = config.getString(path)
        override fun getList(): List<String> = config.getStringList(path)
    }
}


Move ZonedDateTime extensions to a separate file. Add code to allow ranges of ZonedDateTimes

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

package com.guerinet.suitcase.date

import org.threeten.bp.ZonedDateTime

/**
 * [ZonedDateTime] extensions
 * @author Julien Guerinet
 * @since 2.3.0
 */

/**
 * Returns true if this ZonedDateTime is in the past, false otherwise (today would return false)
 */
fun ZonedDateTime.isPast(): Boolean {
    return ZonedDateTime.now().isAfter(this)
}

/**
 * Returns true if this ZonedDateTime is in the future, false otherwise (today would return false)
 */
fun ZonedDateTime.isFuture(): Boolean {
    return ZonedDateTime.now().isBefore(this)
}

/**
 * Returns the RFC 1123 String representation of the [ZonedDateTime] in the UTC time zone,
 *  null if the [ZonedDateTime] was null
 */
fun ZonedDateTime?.getRFC1123String(): String? {
    return if (this == null) null else Format.rfc1123Formatter.format(this)
}

/**
 * Allows us to use the [ZonedDateTime] as a range
 */
operator fun ZonedDateTime.rangeTo(other: ZonedDateTime) = DateProgression(this, other)

class DateIterator(startDate: ZonedDateTime, val endDateInclusive: ZonedDateTime,
                   val stepDays: Long) : Iterator<ZonedDateTime> {

    private var currentDate = startDate

    override fun hasNext() = currentDate <= endDateInclusive

    override fun next(): ZonedDateTime {
        val next = currentDate
        currentDate = currentDate.plusDays(stepDays)
        return next
    }
}

class DateProgression(override val start: ZonedDateTime,
                      override val endInclusive: ZonedDateTime,
                      val stepDays: Long = 1) :
        Iterable<ZonedDateTime>, ClosedRange<ZonedDateTime> {

    override fun iterator(): Iterator<ZonedDateTime> =
            DateIterator(start, endInclusive, stepDays)

    infix fun step(days: Long) = DateProgression(start, endInclusive, days)
}


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

import com.intellij.openapi.fileTypes.FileType
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap

class IndexingJobStatistics {
  val timesPerIndexer: ConcurrentMap<String, PerThreadTime> = ConcurrentHashMap()
  val timesPerFileType: ConcurrentMap<String, PerThreadTime> = ConcurrentHashMap()
  val numberOfFilesPerFileType: ConcurrentMap<String, Int> = ConcurrentHashMap()
  val contentLoadingTime = PerThreadTime()
  val indexingTime = PerThreadTime()

  fun addFileStatistics(fileStatistics: FileIndexingStatistics, fileType: FileType) {
    fileStatistics.perIndexerTimes.forEach { (indexId, time) ->
      timesPerFileType.computeIfAbsent(indexId.name) { PerThreadTime() }
        .addTimeSpentInCurrentThread(time)
    }
    val fileTypeName = fileType.name
    numberOfFilesPerFileType.compute(fileTypeName) { _, currentNumber -> (currentNumber ?: 0) + 1 }
    timesPerFileType
      .computeIfAbsent(fileTypeName) { PerThreadTime() }
      .addTimeSpentInCurrentThread(fileStatistics.totalTime)
  }

  fun addIndexingTime(nanoTime: TimeNano) {
    indexingTime.addTimeSpentInCurrentThread(nanoTime)
  }

  fun addContentLoadingTime(nanoTime: TimeNano) {
    contentLoadingTime.addTimeSpentInCurrentThread(nanoTime)
  }
}

Index diagnostic: fix calculation of per-indexer spent time.

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

import com.intellij.openapi.fileTypes.FileType
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap

class IndexingJobStatistics {
  val timesPerIndexer: ConcurrentMap<String /* ID.name() */, PerThreadTime> = ConcurrentHashMap()
  val timesPerFileType: ConcurrentMap<String /* File type name */, PerThreadTime> = ConcurrentHashMap()
  val numberOfFilesPerFileType: ConcurrentMap<String /* File type name */, Int> = ConcurrentHashMap()
  val contentLoadingTime = PerThreadTime()
  val indexingTime = PerThreadTime()

  fun addFileStatistics(fileStatistics: FileIndexingStatistics, fileType: FileType) {
    fileStatistics.perIndexerTimes.forEach { (indexId, time) ->
      timesPerIndexer.computeIfAbsent(indexId.name) { PerThreadTime() }
        .addTimeSpentInCurrentThread(time)
    }
    val fileTypeName = fileType.name
    numberOfFilesPerFileType.compute(fileTypeName) { _, currentNumber -> (currentNumber ?: 0) + 1 }
    timesPerFileType
      .computeIfAbsent(fileTypeName) { PerThreadTime() }
      .addTimeSpentInCurrentThread(fileStatistics.totalTime)
  }

  fun addIndexingTime(nanoTime: TimeNano) {
    indexingTime.addTimeSpentInCurrentThread(nanoTime)
  }

  fun addContentLoadingTime(nanoTime: TimeNano) {
    contentLoadingTime.addTimeSpentInCurrentThread(nanoTime)
  }
}


package com.elpassion.intelijidea.action.configure.selector

import com.elpassion.android.commons.rxjavatest.thenJust
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever

class MFSelectorTest : LightPlatformCodeInsightFixtureTestCase() {

    private val uiSelector = mock<MFUiSelector>()

    fun testShouldReturnEmptyItemsListWhenNoConfigurationInProject() {
        whenever(uiSelector.invoke(any())).thenJust(emptyList())
        mfSelector(project, uiSelector).test().assertValue { it.isEmpty() }
    }

    fun testShouldReturnNotSelectedConfigurationWhenNoChangeInSelector() {
        val selectorItem = MFSelectorItem(mock(), false, false)
        whenever(uiSelector.invoke(any())).thenJust(listOf(selectorItem))
        mfSelector(project, uiSelector).test().assertValue { it == listOf(selectorItem) }
    }
}

Return selected configuration on change in ui

package com.elpassion.intelijidea.action.configure.selector

import com.elpassion.android.commons.rxjavatest.thenJust
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever

class MFSelectorTest : LightPlatformCodeInsightFixtureTestCase() {

    private val uiSelector = mock<MFUiSelector>()

    fun testShouldReturnEmptyItemsListWhenNoConfigurationInProject() {
        whenever(uiSelector.invoke(any())).thenJust(emptyList())
        mfSelector(project, uiSelector).test().assertValue { it.isEmpty() }
    }

    fun testShouldReturnSelectedConfigurationOnChangeInUi() {
        val selectorItem = MFSelectorItem(mock(), false, false)
        whenever(uiSelector.invoke(any())).thenJust(listOf(selectorItem.copy(isSelected = true)))
        mfSelector(project, uiSelector).test().assertValue { it == listOf(selectorItem.copy(isSelected = true)) }
    }
}


package com.github.shiraji.findpullrequest

import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.util.GithubUtil

class FindPullRequestAction : AnAction() {

    override fun actionPerformed(e: AnActionEvent) {
        val eventData = calcData(e)

        Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
                "Plugin Importer+Exporter",
                "EventData Repo br: " + eventData?.repository?.branches
                + " " + eventData?.repository?.remotes,
                NotificationType.INFORMATION))
    }

    private fun calcData(e : AnActionEvent): EventData? {
        val project = e.getData(CommonDataKeys.PROJECT)
        project ?: return null

        val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE)
        virtualFile ?: return null

        val document = FileDocumentManager.getInstance().getDocument(virtualFile)
        document ?: return null

        val repository = GithubUtil.getGitRepository(project, virtualFile)
        repository ?: return null

        return EventData(project, repository)
    }

    private data class EventData(val project: Project, val repository: GitRepository) {
    }
}

Add debug info. It may not work since there is no runtime dependancy

package com.github.shiraji.findpullrequest

import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.util.GithubUtil

class FindPullRequestAction : AnAction() {

    override fun actionPerformed(e: AnActionEvent) {
        val eventData = calcData(e)

        val foo = eventData?.repository?.remotes?.joinToString {
            it.pushUrls.toString() + "\n"
        }

        Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
                "Plugin Importer+Exporter",
                "EventData: " + foo,
                NotificationType.INFORMATION))
    }

    private fun calcData(e : AnActionEvent): EventData? {
        val project = e.getData(CommonDataKeys.PROJECT)
        project ?: return null

        val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE)
        virtualFile ?: return null

        val document = FileDocumentManager.getInstance().getDocument(virtualFile)
        document ?: return null

        val repository = GithubUtil.getGitRepository(project, virtualFile)
        repository ?: return null

        return EventData(project, repository)
    }

    private data class EventData(val project: Project, val repository: GitRepository) {
    }
}


package hypr.a255bits.com.hypr.Util

import android.graphics.Bitmap
import java.io.ByteArrayOutputStream

class BitmapManipulator{

    fun compressBitmapToByteArray(compressionFormat: Bitmap.CompressFormat, image: Bitmap): ByteArray? {
        val outputStream = ByteArrayOutputStream()
        image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
        return outputStream.toByteArray()
    }
}


/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 * ------------------------------------------------------------------*/

package com.kotlinnlp.simplednn.deeplearning.mergelayers

import com.kotlinnlp.simplednn.core.layers.LayerParameters

/**
 * The parameters of a merge layer.
 * It has two inputs instead of one.
 *
 * @property inputSize1 the size of the first input
 * @property inputSize2 the size of the second input
 * @property outputSize the size of the output
 * @property sparseInput whether the weights connected to the input are sparse or not
 */
abstract class MergeLayerParameters(
  val inputSize1: Int,
  val inputSize2: Int,
  outputSize: Int,
  protected val sparseInput: Boolean
) : LayerParameters(
  inputSize = inputSize1,
  outputSize = outputSize
)

Set sparseInput property as public

/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 * ------------------------------------------------------------------*/

package com.kotlinnlp.simplednn.deeplearning.mergelayers

import com.kotlinnlp.simplednn.core.layers.LayerParameters

/**
 * The parameters of a merge layer.
 * It has two inputs instead of one.
 *
 * @property inputSize1 the size of the first input
 * @property inputSize2 the size of the second input
 * @property outputSize the size of the output
 * @property sparseInput whether the weights connected to the input are sparse or not
 */
abstract class MergeLayerParameters(
  val inputSize1: Int,
  val inputSize2: Int,
  outputSize: Int,
  val sparseInput: Boolean
) : LayerParameters(
  inputSize = inputSize1,
  outputSize = outputSize
)


package org.gradle.gradlebuild

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

object BuildEnvironment {
    val isCiServer = "CI" in System.getenv()
    val isTravis = "TRAVIS" in System.getenv()
    val gradleKotlinDslVersion = "1.0.4"
    val kotlinVersion = "1.3.10"
    val jvm = org.gradle.internal.jvm.Jvm.current()
    val javaVersion = JavaVersion.current()
    val isWindows = OperatingSystem.current().isWindows
    val isSlowInternetConnection
        get() = System.getProperty("slow.internet.connection", "false").toBoolean()
    val agentNum: Int
        get() {
            if (System.getenv().containsKey("USERNAME")) {
                val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
                if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
                    return agentNumEnv.toInt()
                }
            }
            return 1
        }
}

Upgrade Kotlin DSL to 1.0.5 and Kotlin to 1.3.11

package org.gradle.gradlebuild

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

object BuildEnvironment {
    val isCiServer = "CI" in System.getenv()
    val isTravis = "TRAVIS" in System.getenv()
    val gradleKotlinDslVersion = "1.0.5"
    val kotlinVersion = "1.3.11"
    val jvm = org.gradle.internal.jvm.Jvm.current()
    val javaVersion = JavaVersion.current()
    val isWindows = OperatingSystem.current().isWindows
    val isSlowInternetConnection
        get() = System.getProperty("slow.internet.connection", "false").toBoolean()
    val agentNum: Int
        get() {
            if (System.getenv().containsKey("USERNAME")) {
                val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
                if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
                    return agentNumEnv.toInt()
                }
            }
            return 1
        }
}


package eu.kanade.tachiyomi.extension.api

import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import eu.kanade.tachiyomi.network.NetworkHelper
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.http.GET
import uy.kohesive.injekt.injectLazy

/**
 * Used to get the extension repo listing from GitHub.
 */
interface ExtensionGithubService {

    companion object {
        private val client by lazy {
            val network: NetworkHelper by injectLazy()
            network.client.newBuilder()
                .addNetworkInterceptor { chain ->
                    val originalResponse = chain.proceed(chain.request())
                    originalResponse.newBuilder()
                        .header("Content-Encoding", "gzip")
                        .header("Content-Type", "application/json")
                        .build()
                }
                .build()
        }

        fun create(): ExtensionGithubService {
            val adapter = Retrofit.Builder()
                .baseUrl(ExtensionGithubApi.BASE_URL)
                .addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
                .client(client)
                .build()

            return adapter.create(ExtensionGithubService::class.java)
        }
    }

    @GET("${ExtensionGithubApi.REPO_URL_PREFIX}index.json.gz")
    suspend fun getRepo(): JsonArray
}

Use regular minified extensions JSON instead of explicitly handling gzip encoding

package eu.kanade.tachiyomi.extension.api

import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import eu.kanade.tachiyomi.network.NetworkHelper
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.http.GET
import uy.kohesive.injekt.injectLazy

/**
 * Used to get the extension repo listing from GitHub.
 */
interface ExtensionGithubService {

    companion object {
        fun create(): ExtensionGithubService {
            val network: NetworkHelper by injectLazy()
            val adapter = Retrofit.Builder()
                .baseUrl(ExtensionGithubApi.BASE_URL)
                .addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
                .client(network.client)
                .build()

            return adapter.create(ExtensionGithubService::class.java)
        }
    }

    @GET("${ExtensionGithubApi.REPO_URL_PREFIX}index.min.json")
    suspend fun getRepo(): JsonArray
}


package androidx.build

/**
 * Library groups for unpublished libraries.
 *
 * <p>This is being used temporarily for development of androidx.camera.
 * TODO(b/124783972): Merge into LibraryGroups.kt when ready.
 */
object UnpublishedLibraryGroups {
    const val CAMERA = "androidx.camera"
}

Change string to LibraryGroup for CAMERA

package androidx.build

/**
 * Library groups for unpublished libraries.
 *
 * <p>This is being used temporarily for development of androidx.camera.
 * TODO(b/124783972): Merge into LibraryGroups.kt when ready.
 */
object UnpublishedLibraryGroups {
    val CAMERA = LibraryGroup("androidx.camera", false)
}


package com.elpassion.android.commons.espresso

import android.app.Activity
import android.support.test.espresso.intent.Intents
import android.support.test.espresso.intent.matcher.IntentMatchers

fun checkIntent(clazz: Class<out Activity>) {
    Intents.intended(IntentMatchers.hasComponent(clazz.name))
}


package nl.dionsegijn.konfetti.Emitter

import nl.dionsegijn.konfetti.emitters.StreamEmitter
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito

/**
 * Created by dionsegijn on 4/2/17.
 */
class StreamEmitterTests {

    private lateinit var streamEmitter: StreamEmitter
    private lateinit var mockInvokeMethodClass: MockInvokeMethodClass

    @Before
    fun before() {
        mockInvokeMethodClass = Mockito.mock(MockInvokeMethodClass::class.java)
        streamEmitter = StreamEmitter()
        streamEmitter.addConfettiFunc = mockInvokeMethodClass::invokeMethod
    }

    @Test
    fun test_Stream_OneParticlePerSecond() {
        streamEmitter.build(
                particlesPerSecond = 1,
                emittingTime = 3000
        )

        // Test how many particles are created in three seconds
        // Expected: 3
        val threeSeconds = 3f
        streamEmitter.createConfetti(threeSeconds)
        Mockito.verify(mockInvokeMethodClass, Mockito.times(3)).invokeMethod()

        // Test how many particles are created in one more second
        // Expected: 3
        // Still 3 because emmitingTime = 3000ms so the streamer is done emitting
        val oneSecond = 1f
        streamEmitter.createConfetti(oneSecond)
        Mockito.verify(mockInvokeMethodClass, Mockito.times(3)).invokeMethod()
    }

    @Test
    fun test_Stream_HundredParticlesPerSecond() {
        streamEmitter.build(
                particlesPerSecond = 100,
                emittingTime = 3000
        )

        // Test how many particles are created in 100ms
        // Expected: 10
        streamEmitter.createConfetti(0.1f)
        Mockito.verify(mockInvokeMethodClass, Mockito.times(10)).invokeMethod()

        // Test how many particles are created in one second
        // Expected: 110 (including 10 from the previous test)
        val oneSecond = 1f
        streamEmitter.createConfetti(oneSecond)
        Mockito.verify(mockInvokeMethodClass, Mockito.times(110)).invokeMethod()
    }

    @Test
    fun test_Stream_tenParticlesPerSecond_maxTwelveParticles() {
        streamEmitter.build(
                particlesPerSecond = 10,
                maxParticles = 12
        )

        // Test how many particles are created in one second
        // Expected: 10
        streamEmitter.createConfetti(1f)
        Mockito.verify(mockInvokeMethodClass, Mockito.times(10)).invokeMethod()

        // Another second means 2 more particles instead of 10 because maximum is reached
        streamEmitter.createConfetti(1f)
        Mockito.verify(mockInvokeMethodClass, Mockito.times(12)).invokeMethod()
    }
}

class MockInvokeMethodClass {
    fun invokeMethod() {

    }
}


package nl.orangeflamingo.voornameninliedjesbackend.domain

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.Instant

@Document(collection = "Songs")
data class Song(
        @Id
        val id: String,
        val artist: String,
        val title: String,
        val name: String,
        val dateInserted: Instant,
        val dateModified: Instant?,
        val userInserted: String,
        val userModified: String?
)

Add JsonFormat for parsing dates directly

package nl.orangeflamingo.voornameninliedjesbackend.domain

import com.fasterxml.jackson.annotation.JsonFormat
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.Instant

@Document(collection = "Songs")
data class Song(
        @Id
        val id: String,
        val artist: String,
        val title: String,
        val name: String,

        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Amsterdam")
        val dateInserted: Instant,

        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Amsterdam")
        val dateModified: Instant?,

        val userInserted: String,
        val userModified: String?
)


package br.com.bloder.migration.internal

/**
 * Created by bloder on 24/09/16.
 */
interface InternalMigration {

    fun up()
    fun down()
    fun change()
}

Remove change function from internal migration

package br.com.bloder.migration.internal

/**
 * Better Migrations actions
 */
interface InternalMigration {

    fun up()
    fun down()
}


package com.anvigudach

import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner

@RunWith(SpringRunner::class)
@SpringBootTest
class ConfigserverApplicationTests {

	@Test
	fun contextLoads() {
	}

}

Change Tab indentation to spaces


package io.particle.android.sdk.utils

import android.app.Activity
import android.widget.Toast

import javax.annotation.ParametersAreNonnullByDefault

@Deprecated(
    "Deprecated; will be removed in a future release",
    replaceWith = ReplaceWith("io.particle.mesh.setup.utils.safeToast()")
)
@ParametersAreNonnullByDefault
object Toaster {

    /**
     * Shows a toast message for a short time.
     *
     *
     * This is safe to call from background/worker threads.
     */
    fun s(activity: Activity, msg: String?) {
        showToast(activity, msg, Toast.LENGTH_SHORT)
    }

    /**
     * Shows a toast message for a longer time than [.s].
     *
     *
     * This is safe to call from background/worker threads.
     */
    fun l(activity: Activity, msg: String?) {
        showToast(activity, msg, Toast.LENGTH_LONG)
    }

    private fun showToast(
        activity: Activity, msg: String?,
        length: Int
    ) {
        Preconditions.checkNotNull(activity, "Activity must not be null!")

        val toastRunnable = { Toast.makeText(activity, msg, length).show() }

        if (EZ.isThisTheMainThread()) {
            toastRunnable()
        } else {
            EZ.runOnMainThread(toastRunnable)
        }
    }
}

Make these calls accessible from Java again

package io.particle.android.sdk.utils

import android.app.Activity
import android.widget.Toast

import javax.annotation.ParametersAreNonnullByDefault

@Deprecated(
    "Deprecated; will be removed in a future release",
    replaceWith = ReplaceWith("io.particle.mesh.setup.utils.safeToast()")
)
@ParametersAreNonnullByDefault
object Toaster {

    /**
     * Shows a toast message for a short time.
     *
     *
     * This is safe to call from background/worker threads.
     */
    @JvmStatic
    fun s(activity: Activity, msg: String?) {
        showToast(activity, msg, Toast.LENGTH_SHORT)
    }

    /**
     * Shows a toast message for a longer time than [.s].
     *
     *
     * This is safe to call from background/worker threads.
     */
    @JvmStatic
    fun l(activity: Activity, msg: String?) {
        showToast(activity, msg, Toast.LENGTH_LONG)
    }

    private fun showToast(
        activity: Activity, msg: String?,
        length: Int
    ) {
        Preconditions.checkNotNull(activity, "Activity must not be null!")

        val toastRunnable = { Toast.makeText(activity, msg, length).show() }

        if (EZ.isThisTheMainThread()) {
            toastRunnable()
        } else {
            EZ.runOnMainThread(toastRunnable)
        }
    }
}


Add extension method with returns future

package com.github.inikolaev.vertx.web.kotlin

import io.vertx.core.Future
import io.vertx.ext.web.client.HttpRequest

fun <T> HttpRequest<T>.send(): Future<T> {
    val future = Future.future<T>()

    try {
        this.send {
            it.map {
                future.complete(it.body())
            }.otherwise {
                future.fail(it)
            }
        }
    } catch (e: Exception) {
        future.fail(e)
    }

    return future
}


package org.jetbrains.dokka.base.resolvers.external

import org.jetbrains.dokka.links.DRI

interface ExternalLocationProvider {

    val param: String
    fun DRI.toLocation(): String
}

interface ExternalLocationProviderFactory {

    fun getExternalLocationProvider(param: String): ExternalLocationProvider?
}

class ExternalLocationProviderFactoryWithCache(val ext: ExternalLocationProviderFactory) : ExternalLocationProviderFactory {

    private val locationProviders: MutableList<ExternalLocationProvider> = mutableListOf()

    override fun getExternalLocationProvider(param: String): ExternalLocationProvider? =
        locationProviders.find { it.param == param } ?: ext.getExternalLocationProvider(param)?.also { locationProviders.add(it) }
}

Fix racecondition on caching of external providers

package org.jetbrains.dokka.base.resolvers.external

import org.jetbrains.dokka.links.DRI
import java.util.concurrent.ConcurrentHashMap

interface ExternalLocationProvider {

    val param: String
    fun DRI.toLocation(): String
}

interface ExternalLocationProviderFactory {

    fun getExternalLocationProvider(param: String): ExternalLocationProvider?
}

class ExternalLocationProviderFactoryWithCache(val ext: ExternalLocationProviderFactory) : ExternalLocationProviderFactory {

    private val locationProviders = ConcurrentHashMap<String, ExternalLocationProvider>()

    override fun getExternalLocationProvider(param: String): ExternalLocationProvider? =
        locationProviders.getOrPut(param) { ext.getExternalLocationProvider(param) }
}


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

@file:Suppress("SpellCheckingInspection")

buildscript {
    repositories { setupForProject() }
    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:_")
        classpath("com.android.tools.build:gradle:_")
    }
}

plugins {
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.

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

allprojects {
    repositories { setupForProject() }
    tasks.whenTaskAdded {
        if("DebugUnitTest" in name || "ReleaseUnitTest" in name) {
            enabled = false
            // MPP + Android unit testing is so broken we just disable it altogether,
            // (discussion here https://kotlinlang.slack.com/archives/C3PQML5NU/p1572168720226200)
        }
    }
}

Add missing space after if keyword

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

@file:Suppress("SpellCheckingInspection")

buildscript {
    repositories { setupForProject() }
    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:_")
        classpath("com.android.tools.build:gradle:_")
    }
}

plugins {
}

// Top-level build file where you can add configuration options common to all sub-projects/modules.

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

allprojects {
    repositories { setupForProject() }
    tasks.whenTaskAdded {
        if ("DebugUnitTest" in name || "ReleaseUnitTest" in name) {
            enabled = false
            // MPP + Android unit testing is so broken we just disable it altogether,
            // (discussion here https://kotlinlang.slack.com/archives/C3PQML5NU/p1572168720226200)
        }
    }
}


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

@file:Suppress("PackageDirectoryMismatch")

import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.androidJvm
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.common
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.js
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.jvm
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.native
import org.jetbrains.kotlin.gradle.plugin.KotlinTarget

fun KotlinTarget.configureMavenPublication() {
    val suffix = when (platformType) {
        common -> "-metadata"
        jvm -> ""
        js -> "-js"
        androidJvm -> ""
        native -> "-$name"
    }
    mavenPublication { artifactId = "splitties-${project.name}$suffix" }
}

Make mavenPublication use lowerCase target name

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

@file:Suppress("PackageDirectoryMismatch")

import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.androidJvm
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.common
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.js
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.jvm
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType.native
import org.jetbrains.kotlin.gradle.plugin.KotlinTarget
import java.util.Locale

fun KotlinTarget.configureMavenPublication() {
    val suffix = when (platformType) {
        common -> "-metadata"
        jvm -> ""
        js -> "-js"
        androidJvm -> ""
        native -> "-${name.toLowerCase(Locale.ROOT)}"
    }
    mavenPublication { artifactId = "splitties-${project.name}$suffix" }
}