package io.michaelrocks.databindingcompat

import com.android.build.gradle.internal.Version

object PluginVersion {
  val major: Int
  val minor: Int
  val patch: Int
  val suffix: String

  init {
    val version = Version.ANDROID_GRADLE_PLUGIN_VERSION
    suffix = version.substringAfter('-', "")
    val prefix = version.substringBefore('-')
    val parts = prefix.split('.', limit = 3)
    major = parts.getOrNull(0)?.toIntOrNull() ?: 0
    minor = parts.getOrNull(1)?.toIntOrNull() ?: 0
    patch = parts.getOrNull(2)?.toIntOrNull() ?: 0
  }
}

Use a proper Version class from Android Gradle plugin

package io.michaelrocks.databindingcompat

import com.android.builder.model.Version

object PluginVersion {
  val major: Int
  val minor: Int
  val patch: Int
  val suffix: String

  init {
    val version = Version.ANDROID_GRADLE_PLUGIN_VERSION
    suffix = version.substringAfter('-', "")
    val prefix = version.substringBefore('-')
    val parts = prefix.split('.', limit = 3)
    major = parts.getOrNull(0)?.toIntOrNull() ?: 0
    minor = parts.getOrNull(1)?.toIntOrNull() ?: 0
    patch = parts.getOrNull(2)?.toIntOrNull() ?: 0
  }
}


package de.theunknownxy.mcdocs.gui.document.render

import org.lwjgl.opengl.GL11
import de.theunknownxy.mcdocs.docs.HeadingElement
import net.minecraft.client.Minecraft

public class HeadingBlock(val heading: HeadingElement) : Block() {
    override var height: Float
        private set(v: Float) {
        }
        get() {
            return 14f
        }

    override fun draw(x: Float, y: Float, z: Float) {
        GL11.glPushMatrix()
        GL11.glTranslatef(x, y, z)

        // TODO: Scale heading depending on level
        GL11.glScalef(1.3f, 1.3f, 1f)
        val mc = Minecraft.getMinecraft().fontRenderer
        mc.drawString("§n" + heading.text, 0, 0, 0xFFFFFF)

        GL11.glPopMatrix()
    }
}

Scale heading depending on level.

package de.theunknownxy.mcdocs.gui.document.render

import org.lwjgl.opengl.GL11
import de.theunknownxy.mcdocs.docs.HeadingElement
import net.minecraft.client.Minecraft

public class HeadingBlock(val heading: HeadingElement) : Block() {
    private val base_height = 9f
    private fun font_height(): Float = heading_scale() * base_height
    private fun heading_scale(): Float = -0.15f * heading.level + 1.5f

    override var height: Float
        private set(v: Float) {
        }
        get() {
            return font_height()
        }

    override fun draw(x: Float, y: Float, z: Float) {
        GL11.glPushMatrix()
        GL11.glTranslatef(x, y, z)

        // TODO: Scale heading depending on level
        GL11.glScalef(heading_scale(), heading_scale(), 1f)
        val mc = Minecraft.getMinecraft().fontRenderer
        mc.drawString("§n" + heading.text, 0, 0, 0xFFFFFF)

        GL11.glPopMatrix()
    }
}


package com.elpassion.android.commons.espresso

import android.app.Instrumentation
import android.content.Intent
import android.os.Bundle
import android.support.test.InstrumentationRegistry
import android.support.test.rule.ActivityTestRule
import android.widget.TextView
import org.junit.Rule
import org.junit.Test

class ActivityTestRuleUtilsTest {

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

    @Test(expected = RuntimeException::class)
    fun shouldFailWhenActivityNotStarted() {
        onText("text").doesNotExist()
    }

    @Test
    fun shouldStartActivity() {
        activityRule.startActivity()
        onText("text").doesNotExist()
    }

    @Test
    fun shouldStartActivityWithIntent() {
        activityRule.startActivity(Intent().apply { putExtra("TEXT_KEY", "text") })
        onText("text").isDisplayed()
    }

    class Activity : android.app.Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(TextView(this).apply {
                text = intent.getStringExtra("TEXT_KEY")
            })
        }
    }
}

Change test to improve test performance

package com.elpassion.android.commons.espresso

import android.app.Instrumentation
import android.content.Intent
import android.os.Bundle
import android.support.test.InstrumentationRegistry
import android.support.test.rule.ActivityTestRule
import android.widget.TextView
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test

class ActivityTestRuleUtilsTest {

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

    @Test
    fun shouldNotStartActivity() {
        assertNull(activityRule.activity)
    }

    @Test
    fun shouldStartActivity() {
        activityRule.startActivity()
        onText("text").doesNotExist()
    }

    @Test
    fun shouldStartActivityWithIntent() {
        activityRule.startActivity(Intent().apply { putExtra("TEXT_KEY", "text") })
        onText("text").isDisplayed()
    }

    class Activity : android.app.Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(TextView(this).apply {
                text = intent.getStringExtra("TEXT_KEY")
            })
        }
    }
}


package org.luxons.sevenwonders.server.test

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.simp.SimpMessagingTemplate
import kotlin.test.assertNotNull

fun mockSimpMessagingTemplate(): SimpMessagingTemplate = SimpMessagingTemplate(object : MessageChannel {
    override fun send(message: Message<*>): Boolean = true
    override fun send(message: Message<*>, timeout: Long): Boolean = true
})

fun runAsyncTest(timeoutMillis: Long = 5000, block: suspend CoroutineScope.() -> Unit) = runBlocking {
    val result = withTimeoutOrNull(timeoutMillis, block)
    assertNotNull(result, "Test timed out, exceeded ${timeoutMillis}ms")
}

Increase test timeout to make sure it's not about time

package org.luxons.sevenwonders.server.test

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.simp.SimpMessagingTemplate
import kotlin.test.assertNotNull

fun mockSimpMessagingTemplate(): SimpMessagingTemplate = SimpMessagingTemplate(object : MessageChannel {
    override fun send(message: Message<*>): Boolean = true
    override fun send(message: Message<*>, timeout: Long): Boolean = true
})

fun runAsyncTest(timeoutMillis: Long = 10000, block: suspend CoroutineScope.() -> Unit) = runBlocking {
    val result = withTimeoutOrNull(timeoutMillis, block)
    assertNotNull(result, "Test timed out, exceeded ${timeoutMillis}ms")
}


package com.alexstyl.specialdates.people

import com.alexstyl.specialdates.contact.ContactsProvider
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject

class PeoplePresenter(
        private val contactProvider: ContactsProvider,
        private val workScheduler: Scheduler,
        private val resultScheduler: Scheduler) {

    private val subject = PublishSubject.create<Int>()
    private var disposable: Disposable? = null

    fun startPresentingInto(view: PeopleView) {
        disposable =
                Observable.fromCallable {
                    contactProvider.allContacts
                }
                        .observeOn(workScheduler)
                        .map { contacts ->
                            val viewModels = arrayListOf<PeopleViewModel>()
                            contacts.forEach { contact ->
                                viewModels.add(PeopleViewModel(contact,
                                        contact.displayName.toString(),
                                        contact.imagePath,
                                        contact.contactID,
                                        contact.source))
                            }
                            viewModels
                        }
                        .observeOn(resultScheduler)
                        .subscribe { viewModels ->
                            view.displayPeople(viewModels)
                        }

    }

    fun stopPresenting() {
        disposable?.dispose()
    }
}

Sort contacts according to their names

package com.alexstyl.specialdates.people

import com.alexstyl.specialdates.contact.ContactsProvider
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable

class PeoplePresenter(
        private val contactProvider: ContactsProvider,
        private val workScheduler: Scheduler,
        private val resultScheduler: Scheduler) {

    private var disposable: Disposable? = null

    fun startPresentingInto(view: PeopleView) {
        disposable =
                Observable.fromCallable {
                    contactProvider.allContacts
                }
                        .observeOn(workScheduler)
                        .map { contacts ->
                            val viewModels = arrayListOf<PeopleViewModel>()
                            contacts.forEach { contact ->
                                viewModels.add(PeopleViewModel(contact,
                                        contact.displayName.toString(),
                                        contact.imagePath,
                                        contact.contactID,
                                        contact.source))
                            }
                            viewModels.sortedWith(compareBy({ it.personName }))
                        }
                        .observeOn(resultScheduler)
                        .subscribe { viewModels ->
                            view.displayPeople(viewModels)
                        }

    }

    fun stopPresenting() {
        disposable?.dispose()
    }
}


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

import org.hamcrest.CoreMatchers.containsString
import org.junit.Assert.assertThat
import org.junit.Test

class BuildScanSampleTest : AbstractSampleTest("build-scan") {

    @Test
    fun `publishes build scan`() {
        assertThat(build("tasks", "--scan").output, containsString("Publishing build information..."))
    }
}


Add a default implementation for FileSource.Factory and FileSink.Factory

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

package io.michaelrocks.lightsaber.processor.io

import java.io.File

object IoFactory : FileSource.Factory, FileSink.Factory {
  override fun createFileSource(inputFile: File): FileSource =
      inputFile.run {
        when (fileType) {
          FileType.EMPTY -> EmptyFileSource
          FileType.DIRECTORY -> DirectoryFileSource(this)
          FileType.JAR -> JarFileSource(this)
        }
      }

  override fun createFileSink(inputFile: File, outputFile: File): FileSink =
      outputFile.run {
        when (inputFile.fileType) {
          FileType.EMPTY -> EmptyFileSink
          FileType.DIRECTORY -> DirectoryFileSink(this)
          FileType.JAR -> JarFileSink(this)
        }
      }

  private val File.fileType: FileType
    get() = when {
      !exists() -> FileType.EMPTY
      isDirectory -> FileType.DIRECTORY
      extension.endsWith("jar", ignoreCase = true) -> FileType.JAR
      else -> error("Unknown file type for file $this")
    }

  private enum class FileType { EMPTY, DIRECTORY, JAR }
}


package com.battlelancer.seriesguide.ui.shows

import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.R
import com.google.android.material.floatingactionbutton.FloatingActionButton

/**
 * Hides the floating action button when scrolling down, shows it when scrolling up. If the view can
 * no longer scroll down, shows the button also.
 *
 * Built upon https://github.com/makovkastar/FloatingActionButton scroll detectors.
 */
internal class FabRecyclerViewScrollDetector(private val button: FloatingActionButton) :
    RecyclerView.OnScrollListener() {

    private val scrollThreshold: Int =
        button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold)

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        // no action if RecyclerView is no longer visible, such as its tab was swiped away
        if (!recyclerView.hasFocus()) {
            return
        }

        // always show if scrolled to bottom
        if (!recyclerView.canScrollVertically(1 /* down */)) {
            button.show()
            return
        }

        val isSignificantDelta = Math.abs(dy) > scrollThreshold
        if (isSignificantDelta) {
            if (dy > 0) {
                onScrollDown()
            } else {
                onScrollUp()
            }
        }
    }

    private fun onScrollDown() {
        button.hide()
    }

    private fun onScrollUp() {
        button.show()
    }

}

Fix floating add show button not hiding on scroll.

package com.battlelancer.seriesguide.ui.shows

import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.R
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlin.math.abs

/**
 * Hides the floating action button when scrolling down, shows it when scrolling up. If the view can
 * no longer scroll down, shows the button also.
 *
 * Built upon https://github.com/makovkastar/FloatingActionButton scroll detectors.
 */
internal class FabRecyclerViewScrollDetector(private val button: FloatingActionButton) :
    RecyclerView.OnScrollListener() {

    private val scrollThreshold: Int =
        button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold)

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        // always show if scrolled to bottom
        if (!recyclerView.canScrollVertically(1 /* down */)) {
            button.show()
            return
        }

        val isSignificantDelta = abs(dy) > scrollThreshold
        if (isSignificantDelta) {
            if (dy > 0) {
                onScrollDown()
            } else {
                onScrollUp()
            }
        }
    }

    private fun onScrollDown() {
        button.hide()
    }

    private fun onScrollUp() {
        button.show()
    }

}


package com.jeremiahzucker.pandroid.util

import android.graphics.*

/**
 * BitmapUtil
 *
 * Author: Jeremiah Zucker
 * Date:   9/7/2017
 * Desc:   TODO: Complete
 */
// TODO: Should convert into transformation
fun Bitmap.getCroppedBitmap(): Bitmap {
    val output = Bitmap.createBitmap(width,
            height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(output)

    val color = 0xff424242.toInt()
    val paint = Paint()
    val rect = Rect(0, 0, width, height)

    paint.isAntiAlias = true
    canvas.drawARGB(0, 0, 0, 0)
    paint.color = color
    // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(),
            (width / 2).toFloat(), paint)
    paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    canvas.drawBitmap(this, rect, rect, paint)
    //Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
    //return _bmp;
    return output
}

Add code for a small center hole.

package com.jeremiahzucker.pandroid.util

import android.graphics.*

/**
 * BitmapUtil
 *
 * Author: Jeremiah Zucker
 * Date:   9/7/2017
 * Desc:   TODO: Complete
 */
// TODO: Should convert into transformation
fun Bitmap.getCroppedBitmap(): Bitmap {
    val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(output)

    val color = 0xff424242.toInt()
    val paint = Paint()
    val rect = Rect(0, 0, width, height)

    paint.isAntiAlias = true
    canvas.drawARGB(0, 0, 0, 0)
    paint.color = color

    canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), (width / 2).toFloat(), paint)

//    TODO: Make a decision on whether or not we want this center hole
//    val transparentPaint = Paint()
//    transparentPaint.color = 0x507E9F.toInt()
//    transparentPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
//    canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), (width / 15).toFloat(), transparentPaint)

    paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    canvas.drawBitmap(this, rect, rect, paint)

    //return _bmp;
    return output
}


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

plugins {
  kotlin("jvm").version("1.6.20")
  id("com.vanniktech.maven.publish") version ("0.19.0")
}

repositories {
  mavenCentral()
}

buildscript {
  extra["kotlinVersion"] = "1.6.20"
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
    classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0")
  }
}

dependencies {
  api("org.jsoup:jsoup:1.13.1")
  api("com.squareup.okhttp3:okhttp:4.9.0")
  implementation("org.apache.commons:commons-text:1.9")
  testImplementation("junit:junit:4.13")
}

configurations.all {
  // Re-run tests every time test cases are updated, even if sources haven’t changed.
  resolutionStrategy.cacheChangingModulesFor(0, "seconds")
}

tasks.jar {
  archiveBaseName.set("crux")
}

tasks.withType<KotlinCompile>().configureEach {
  kotlinOptions {
    allWarningsAsErrors = true
  }
}

Add plugin `com.github.ben-manes.versions` to keep dependencies updated.

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

plugins {
  kotlin("jvm").version("1.6.20")
  id("com.vanniktech.maven.publish") version ("0.19.0")
  id("com.github.ben-manes.versions") version "0.42.0"
}

repositories {
  mavenCentral()
}

buildscript {
  extra["kotlinVersion"] = "1.6.20"
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath(kotlin("gradle-plugin", version = rootProject.extra["kotlinVersion"] as String?))
    classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
    classpath("com.vanniktech:gradle-maven-publish-plugin:0.19.0")
  }
}

dependencies {
  api("org.jsoup:jsoup:1.13.1")
  api("com.squareup.okhttp3:okhttp:4.9.0")
  implementation("org.apache.commons:commons-text:1.9")
  testImplementation("junit:junit:4.13")
}

configurations.all {
  // Re-run tests every time test cases are updated, even if sources haven’t changed.
  resolutionStrategy.cacheChangingModulesFor(0, "seconds")
}

tasks.jar {
  archiveBaseName.set("crux")
}

tasks.withType<KotlinCompile>().configureEach {
  kotlinOptions {
    allWarningsAsErrors = true
  }
}


package com.github.ramonrabello.kiphy.trends.data

import com.github.ramonrabello.kiphy.trends.TrendingApi
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify

class RemoteTrendingDataSourceTest {

    private lateinit var api: TrendingApi

    private lateinit var remoteTrendingDataSource: TrendingDataSource

    @Before
    fun setUp() {
        api = mock(TrendingApi::class.java)
        remoteTrendingDataSource = TrendingDataSource.Remote(api)
    }

    @Test
    fun `when loading trending verify if api was called`() {
        remoteTrendingDataSource.loadTrending()
        verify(api).loadTrending()
    }
}

Update unit test with new packages.

package com.github.ramonrabello.kiphy.trends.data

import com.github.ramonrabello.kiphy.trends.TrendingApi
import com.github.ramonrabello.kiphy.trends.data.source.TrendingDataSource
import com.github.ramonrabello.kiphy.trends.data.source.remote.RemoteTrendingDataSource
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify

class RemoteTrendingDataSourceTest {

    private lateinit var api: TrendingApi

    private lateinit var remoteTrendingDataSource: TrendingDataSource

    @Before
    fun setUp() {
        api = mock(TrendingApi::class.java)
        remoteTrendingDataSource = RemoteTrendingDataSource(api)
    }

    @Test
    fun `when loading trending verify if api was called`() {
        remoteTrendingDataSource.loadTrending()
        verify(api).loadTrending()
    }
}


package com.chibatching.kotpref.livedata

import android.content.SharedPreferences
import androidx.lifecycle.LiveData
import com.chibatching.kotpref.KotprefModel
import kotlin.reflect.KProperty0

fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> {
    return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
        private val key: String = this@asLiveData.getPrefKey(property)
            ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref")

        init {
            postValue(property.get())
        }

        override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) {
            if (propertyName == key) {
                postValue(property.get())
            }
        }

        override fun onActive() {
            this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this)
            if (value != property.get()) {
                value = property.get()
            }
        }

        override fun onInactive() {
            this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this)
        }
    }
}

Fix that LiveData initial value fires twice

package com.chibatching.kotpref.livedata

import android.content.SharedPreferences
import androidx.lifecycle.LiveData
import com.chibatching.kotpref.KotprefModel
import kotlin.reflect.KProperty0

fun <T> KotprefModel.asLiveData(property: KProperty0<T>): LiveData<T> {
    return object : LiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
        private val key: String = this@asLiveData.getPrefKey(property)
            ?: throw IllegalArgumentException("Failed to get preference key, check property ${property.name} is delegated to Kotpref")

        override fun onSharedPreferenceChanged(prefs: SharedPreferences, propertyName: String) {
            if (propertyName == key) {
                postValue(property.get())
            }
        }

        override fun onActive() {
            this@asLiveData.preferences.registerOnSharedPreferenceChangeListener(this)
            if (value != property.get()) {
                value = property.get()
            }
        }

        override fun onInactive() {
            this@asLiveData.preferences.unregisterOnSharedPreferenceChangeListener(this)
        }
    }
}


Add non imported types to completion proposals

package org.jetbrains.kotlin.ui.editors.codeassist

import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.eclipse.jdt.core.search.TypeNameMatchRequestor
import org.eclipse.jdt.core.search.TypeNameMatch
import org.eclipse.jdt.core.Flags
import org.eclipse.jdt.core.search.SearchEngine
import org.eclipse.jdt.core.search.SearchPattern
import org.eclipse.jdt.core.search.IJavaSearchConstants
import org.eclipse.jdt.core.IJavaProject
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory
import org.eclipse.jface.text.contentassist.ICompletionProposal
import org.jetbrains.kotlin.psi.KtFile

fun lookupNonImportedTypes(
        simpleNameExpression: KtSimpleNameExpression,
        identifierPart: String,
        ktFile: KtFile,
        javaProject: IJavaProject): List<TypeNameMatch> {
    val callTypeAndReceiver = CallTypeAndReceiver.detect(simpleNameExpression)

    if (callTypeAndReceiver !is CallTypeAndReceiver.TYPE || callTypeAndReceiver !is CallTypeAndReceiver.DEFAULT) {
        return emptyList()
    }

    val importsSet = ktFile.getImportDirectives()
            .mapNotNull { it.getImportedFqName()?.asString() }
            .toSet()

    // TODO: exclude variants by callType.descriptorKind
    return searchFor(identifierPart, javaProject)
            .filter { it.fullyQualifiedName !in importsSet && it.packageName !in importsSet }
}

private fun searchFor(identifierPart: String, javaProject: IJavaProject): List<TypeNameMatch> {
    val foundTypes = arrayListOf<TypeNameMatch>()
    val collector = object : TypeNameMatchRequestor() {
        override fun acceptTypeNameMatch(match: TypeNameMatch) {
            val type = match.type
            if (Flags.isPublic(type.flags)) {
                foundTypes.add(match)
            }
        }
    }

    val searchEngine = SearchEngine()

    val javaProjectSearchScope = JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(javaProject, true)
    searchEngine.searchAllTypeNames(null,
                SearchPattern.R_EXACT_MATCH,
                identifierPart.toCharArray(),
                SearchPattern.R_CAMELCASE_MATCH,
                IJavaSearchConstants.TYPE,
                javaProjectSearchScope,
                collector,
                IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH,
                null)

    return foundTypes
}


/*
 * Copyright (c) 2017. Louis Cognault Ayeva Derman
 *
 * 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 splitties.checkedlazy

import splitties.exceptions.illegal
import splitties.uithread.checkUiThread

private inline val currentThread: Thread get() = Thread.currentThread()

val uiChecker = { checkUiThread() }

fun accessOn(thread: Thread) = {
    if (thread !== currentThread) illegal("Access expected on thread: $thread. Current: $currentThread")
}

Remove currentThread property from checkedlazy

/*
 * Copyright (c) 2017. Louis Cognault Ayeva Derman
 *
 * 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 splitties.checkedlazy

import splitties.exceptions.illegal
import splitties.uithread.checkUiThread

val uiChecker = { checkUiThread() }

fun accessOn(thread: Thread) = {
    Thread.currentThread().let {
        if (thread !== it) illegal("Access expected on thread: $thread. Current: $it")
    }
}


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

import kotlin.time.Duration
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy

/** A flow that never emits anything. */
fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }

fun TestScope.advanceTimeBy(duration: Duration) {
  advanceTimeBy(duration.inWholeMilliseconds)
}

Remove now-unused test helper function

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

import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

/** A flow that never emits anything. */
fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }


plugins {
    id("java")
    id("application")
}

application {
    mainClassName = "com.github.k0kubun.gitstar_ranking.Main"
}

repositories {
    mavenCentral()
}

dependencies {
    compile("ch.qos.logback:logback-classic:1.3.0-alpha4")
    compile("com.google.guava:guava:21.0")
    compile("com.google.http-client:google-http-client:1.22.0")
    compile("io.sentry:sentry:1.5.2")
    compile("javax.json:javax.json-api:1.1")
    compile("javax.ws.rs:javax.ws.rs-api:2.0.1")
    compile("org.postgresql:postgresql:42.2.19")
    compile("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2
    compile("org.glassfish:javax.json:1.1")
    compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
    compile("org.jdbi:jdbi:2.78")
    testCompile("junit:junit:4.12")
}

Fix deprecation warnings in the Gradle config

plugins {
    id("java")
    id("application")
}

application {
    mainClass.set("com.github.k0kubun.gitstar_ranking.Main")
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("ch.qos.logback:logback-classic:1.3.0-alpha4")
    implementation("com.google.guava:guava:21.0")
    implementation("com.google.http-client:google-http-client:1.22.0")
    implementation("io.sentry:sentry:1.5.2")
    implementation("javax.json:javax.json-api:1.1")
    implementation("javax.ws.rs:javax.ws.rs-api:2.0.1")
    implementation("org.postgresql:postgresql:42.2.19")
    implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2
    implementation("org.glassfish:javax.json:1.1")
    implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final")
    implementation("org.jdbi:jdbi:2.78")
    testImplementation("junit:junit:4.12")
}


package org.stepik.android.data.course.repository

import org.stepik.android.domain.course.repository.CoursePurchaseDataRepository
import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode
import org.stepik.android.presentation.course_purchase.model.CoursePurchaseDataResult
import javax.inject.Inject

class CoursePurchaseDataRepositoryImpl
@Inject
constructor() : CoursePurchaseDataRepository {
    private var deeplinkPromoCode: DeeplinkPromoCode = DeeplinkPromoCode.EMPTY
    private var coursePurchaseDataResult: CoursePurchaseDataResult = CoursePurchaseDataResult.Empty

    @Synchronized
    override fun getDeeplinkPromoCode(): DeeplinkPromoCode =
        deeplinkPromoCode

    @Synchronized
    override fun getCoursePurchaseData(): CoursePurchaseDataResult =
        coursePurchaseDataResult

    override fun savePurchaseData(deeplinkPromoCode: DeeplinkPromoCode, coursePurchaseDataResult: CoursePurchaseDataResult) {
        this.deeplinkPromoCode = deeplinkPromoCode
        this.coursePurchaseDataResult = coursePurchaseDataResult
    }
}

Add synchronized to save operation

package org.stepik.android.data.course.repository

import org.stepik.android.domain.course.repository.CoursePurchaseDataRepository
import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode
import org.stepik.android.presentation.course_purchase.model.CoursePurchaseDataResult
import javax.inject.Inject

class CoursePurchaseDataRepositoryImpl
@Inject
constructor() : CoursePurchaseDataRepository {
    private var deeplinkPromoCode: DeeplinkPromoCode = DeeplinkPromoCode.EMPTY
    private var coursePurchaseDataResult: CoursePurchaseDataResult = CoursePurchaseDataResult.Empty

    @Synchronized
    override fun getDeeplinkPromoCode(): DeeplinkPromoCode =
        deeplinkPromoCode

    @Synchronized
    override fun getCoursePurchaseData(): CoursePurchaseDataResult =
        coursePurchaseDataResult

    @Synchronized
    override fun savePurchaseData(deeplinkPromoCode: DeeplinkPromoCode, coursePurchaseDataResult: CoursePurchaseDataResult) {
        this.deeplinkPromoCode = deeplinkPromoCode
        this.coursePurchaseDataResult = coursePurchaseDataResult
    }
}


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

package splitties.arch.lifecycle

import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

inline fun <reified VM : ViewModel> FragmentActivity.viewModels(
    noinline factory: () -> VM
): Lazy<VM> = viewModels { TypeSafeViewModelFactory(factory) }

inline fun <reified VM : ViewModel> Fragment.activityViewModels(
    noinline factory: () -> VM
): Lazy<VM> = activityViewModels { TypeSafeViewModelFactory(factory) }

inline fun <reified VM : ViewModel> Fragment.viewModels(
    noinline factory: () -> VM
): Lazy<VM> = viewModels { TypeSafeViewModelFactory(factory) }

@PublishedApi
internal class TypeSafeViewModelFactory<VM : ViewModel>(
    private val factory: () -> VM
) : ViewModelProvider.Factory {
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel?> create(modelClass: Class<T>) = factory() as T
}

Fix nullability issue after AndroidX library was migrated to Kotlin

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

package splitties.arch.lifecycle

import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

inline fun <reified VM : ViewModel> FragmentActivity.viewModels(
    noinline factory: () -> VM
): Lazy<VM> = viewModels { TypeSafeViewModelFactory(factory) }

inline fun <reified VM : ViewModel> Fragment.activityViewModels(
    noinline factory: () -> VM
): Lazy<VM> = activityViewModels { TypeSafeViewModelFactory(factory) }

inline fun <reified VM : ViewModel> Fragment.viewModels(
    noinline factory: () -> VM
): Lazy<VM> = viewModels { TypeSafeViewModelFactory(factory) }

@PublishedApi
internal class TypeSafeViewModelFactory<VM : ViewModel>(
    private val factory: () -> VM
) : ViewModelProvider.Factory {
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>) = factory() as T
}


package com.sedsoftware.yaptalker.commons.extensions

import android.content.Context
import android.support.annotation.BoolRes
import android.support.annotation.StringRes

fun Context.booleanRes(@BoolRes resId: Int) = resources.getBoolean(resId)
fun Context.stringRes(@StringRes resId: Int) = resources.getString(resId)


package ch.rmy.android.http_shortcuts.activities.response

import android.content.Context
import android.util.AttributeSet
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import ch.rmy.android.http_shortcuts.extensions.consume
import ch.rmy.android.http_shortcuts.extensions.mapIf
import ch.rmy.android.http_shortcuts.extensions.openURL

class ResponseWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
) : WebView(context, attrs) {

    init {
        webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String) = consume {
                context.openURL(url)
            }
        }

        with(settings) {
            setAppCacheEnabled(false)
            cacheMode = WebSettings.LOAD_NO_CACHE
            javaScriptEnabled = false
            saveFormData = false
            allowContentAccess = false
            allowFileAccess = false
            allowFileAccessFromFileURLs = false
            allowUniversalAccessFromFileURLs = false
        }
    }

    fun loadFromString(data: String, baseUrl: String?) {
        val url = baseUrl
            ?.mapIf(!baseUrl.endsWith("/")) {
                it.plus("/")
            }
        loadDataWithBaseURL(url, data, "text/html", "UTF-8", null)
    }

}

Use same user agent for webviews as for HTTP requests

package ch.rmy.android.http_shortcuts.activities.response

import android.content.Context
import android.util.AttributeSet
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import ch.rmy.android.http_shortcuts.extensions.consume
import ch.rmy.android.http_shortcuts.extensions.mapIf
import ch.rmy.android.http_shortcuts.extensions.openURL
import ch.rmy.android.http_shortcuts.utils.UserAgentUtil

class ResponseWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
) : WebView(context, attrs) {

    init {
        webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String) = consume {
                context.openURL(url)
            }
        }

        with(settings) {
            setAppCacheEnabled(false)
            cacheMode = WebSettings.LOAD_NO_CACHE
            javaScriptEnabled = false
            saveFormData = false
            allowContentAccess = false
            allowFileAccess = false
            allowFileAccessFromFileURLs = false
            allowUniversalAccessFromFileURLs = false
            userAgentString = UserAgentUtil.userAgent
        }
    }

    fun loadFromString(data: String, baseUrl: String?) {
        val url = baseUrl
            ?.mapIf(!baseUrl.endsWith("/")) {
                it.plus("/")
            }
        loadDataWithBaseURL(url, data, "text/html", "UTF-8", null)
    }

}


package com.example.billing.reocurringPayments

import com.example.payments.Gateway
import org.springframework.boot.actuate.metrics.CounterService
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import javax.inject.Inject

@RestController
class Controller @Inject constructor(val paymentGateway: Gateway, val counter: CounterService, val service: Service) {

    @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST))
    fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> {
        val responseHeaders = HttpHeaders().apply {
            add("content-type", MediaType.APPLICATION_JSON_VALUE)
        }

        service.thisMayFail()

        val createSuccessful = paymentGateway.createReocurringPayment(data["amount"] as Int)

        val response = if (createSuccessful) {
            counter.increment("billing.reocurringPayment.created")
            ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED)
        } else {
            ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST)
        }

        return response
    }
}

Add note about using delegation

package com.example.billing.reocurringPayments

import com.example.payments.Gateway
import org.springframework.boot.actuate.metrics.CounterService
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import javax.inject.Inject

// Can you use delegation here???
//  https://youtu.be/mSg9kSYfeX0?t=22m35s
@RestController
class Controller @Inject constructor(val paymentGateway: Gateway, val counter: CounterService, val service: Service) {

    @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST))
    fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> {
        val responseHeaders = HttpHeaders().apply {
            add("content-type", MediaType.APPLICATION_JSON_VALUE)
        }

        service.thisMayFail()

        val createSuccessful = paymentGateway.createReocurringPayment(data["amount"] as Int)

        val response = if (createSuccessful) {
            counter.increment("billing.reocurringPayment.created")
            ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED)
        } else {
            ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST)
        }

        return response
    }
}


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

import com.intellij.util.ui.UIUtil.makeTransparent
import com.intellij.xml.breadcrumbs.DefaultCrumbsPresentation
import uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter.xml.toLineMarkerColor
import java.awt.Color

class ColoredCrumbPresentation(private val color: Color?) : DefaultCrumbsPresentation() {
    override fun getBackgroundColor(selected: Boolean, hovered: Boolean, light: Boolean): Color? {
        val baseColor = super.getBackgroundColor(selected, hovered, light)
        return when {
            baseColor == null -> toLineMarkerColor(0x92, color)
            color != null -> makeTransparent(color, baseColor, 0.1)
            else -> baseColor
        }
    }
}

Fix using the makeTransparent compatibility function.

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

import com.intellij.compat.util.ui.UIUtil.makeTransparent
import com.intellij.xml.breadcrumbs.DefaultCrumbsPresentation
import uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter.xml.toLineMarkerColor
import java.awt.Color

class ColoredCrumbPresentation(private val color: Color?) : DefaultCrumbsPresentation() {
    override fun getBackgroundColor(selected: Boolean, hovered: Boolean, light: Boolean): Color? {
        val baseColor = super.getBackgroundColor(selected, hovered, light)
        return when {
            baseColor == null -> toLineMarkerColor(0x92, color)
            color != null -> makeTransparent(color, baseColor, 0.1)
            else -> baseColor
        }
    }
}


package com.github.kittinunf.reactiveandroid.support.v4.widget

import android.support.v4.widget.SwipeRefreshLayout
import com.github.kittinunf.reactiveandroid.Action
import com.github.kittinunf.reactiveandroid.rx.addTo
import com.github.kittinunf.reactiveandroid.rx.bindTo
import rx.Subscription
import rx.subscriptions.CompositeSubscription

fun SwipeRefreshLayout.rx_applyAction(action: Action<Unit, *>): Subscription {
    val subscriptions = CompositeSubscription()
    rx_refreshing.bindTo(action.enabled).addTo(subscriptions)
    rx_refresh().map { Unit }.bindTo(action, Action<Unit, *>::execute).addTo(subscriptions)
    return subscriptions
}

Fix bugs in refresh layout

package com.github.kittinunf.reactiveandroid.support.v4.widget

import android.support.v4.widget.SwipeRefreshLayout
import com.github.kittinunf.reactiveandroid.Action
import com.github.kittinunf.reactiveandroid.rx.addTo
import com.github.kittinunf.reactiveandroid.rx.bindTo
import rx.Subscription
import rx.subscriptions.CompositeSubscription

fun SwipeRefreshLayout.rx_applyAction(action: Action<Unit, *>): Subscription {
    val subscriptions = CompositeSubscription()
    rx_refreshing.bindTo(action.executing).addTo(subscriptions)
    rx_refresh().map { Unit }.bindTo(action, Action<Unit, *>::execute).addTo(subscriptions)
    return subscriptions
}


Implement base class for common adapter injections

package com.sedsoftware.yaptalker.base

import com.github.salomonbrys.kodein.LazyKodein
import com.github.salomonbrys.kodein.LazyKodeinAware
import com.github.salomonbrys.kodein.instance
import com.sedsoftware.yaptalker.YapTalkerApp
import com.sedsoftware.yaptalker.data.remote.video.ThumbnailsManager
import com.sedsoftware.yaptalker.features.settings.SettingsHelper

abstract class BaseAdapterInjections : LazyKodeinAware {

  override val kodein: LazyKodein
    get() = LazyKodein { YapTalkerApp.kodeinInstance }

  // Kodein injections
  protected val thumbnailsLoader: ThumbnailsManager by instance()
  private val settings: SettingsHelper by instance()

  protected val normalFontSize by lazy {
    settings.getNormalFontSize()
  }

  protected val bigFontSize by lazy {
    settings.getBigFontSize()
  }

  protected val smallFontSize by lazy {
    settings.getSmallFontSize()
  }
}


package com.reduks.reduks

interface Action<in State> {
    fun action(state: State)
}

Make action creator return a state

package com.reduks.reduks

interface Action<State> {
    fun action(state: State) : State
}


/* 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.functionalities.randomgenerators

import java.util.*

/**
 * @param radius radius of the range
 * @param enablePseudoRandom if true use pseudo-random with a seed
 * @param seed seed used for the pseudo-random
 */
class FixedRangeRandom(
  val radius: Double = 0.01,
  val enablePseudoRandom: Boolean = true,
  val seed: Long = 1
) : RandomGenerator {

  /**
   *
   */
  private val rndGenerator = if (enablePseudoRandom) Random(seed) else Random()

  /**
   * @return a pseudo-random value in the range [-radius, radius]
   * */
  override fun next(): Double = (2.0 * rndGenerator.nextDouble() * radius) - radius
}

Update default pseudo random seed

/* 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.functionalities.randomgenerators

import java.util.*

/**
 * @param radius radius of the range
 * @param enablePseudoRandom if true use pseudo-random with a seed
 * @param seed seed used for the pseudo-random
 */
class FixedRangeRandom(
  val radius: Double = 0.01,
  val enablePseudoRandom: Boolean = true,
  val seed: Long = 743
) : RandomGenerator {

  /**
   *
   */
  private val rndGenerator = if (enablePseudoRandom) Random(seed) else Random()

  /**
   * @return a pseudo-random value in the range [-radius, radius]
   * */
  override fun next(): Double = (2.0 * rndGenerator.nextDouble() * radius) - radius
}


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 = "",
        @OneToMany(cascade = [CascadeType.ALL])
        @JoinColumn(name = "target_id")
        var parameters: MutableList<TargetParameters> = mutableListOf(),
        @OneToMany(cascade = [CascadeType.ALL])
        @JoinColumn(name = "target_id")
        var offers: MutableList<Offer> = mutableListOf()
)

Remove property and offer entries without relationship.

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 = "",
        @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()
)


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

sealed class Message(val text: String) {
    class RemoteMessage(text: String) : Message(text)
    class LocalMessage(text: String) : Message(text)
}

Add comment explaining remote and local messages

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

/**
 * This sealed class represents the messages sent between connected devices.
 * The RemoteMessage class represents a message coming from a remote device.
 * The LocalMessage class represents a message the user wants to send to the remote device.
 *
 * @param text is the message text the user sends to the other connected device.
 */
sealed class Message(val text: String) {
    class RemoteMessage(text: String) : Message(text)
    class LocalMessage(text: String) : Message(text)
}


Add a new Variable to represent a list variable

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

import com.intellij.debugger.streams.trace.impl.handler.type.GenericType

/**
 * @author Vitaliy.Bibaev
 */
class ListVariableImpl(name: String, elementType: GenericType)
  : VariableImpl("java.util.List<${elementType.genericTypeName}>", name, "new java.util.ArrayList<>()")


package com.ianhanniballake.contractiontimer.appwidget

import android.content.Context
import android.os.Build

/**
 * Handles updating all App Widgets
 */
abstract class AppWidgetUpdateHandler {
    companion object {
        /**
         * Creates a version appropriate AppWidgetUpdateHandler instance
         *
         * @return an appropriate AppWidgetUpdateHandler
         */
        @JvmStatic
        fun createInstance(): AppWidgetUpdateHandler {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                AppWidgetUpdateHandlerV11()
            else
                AppWidgetUpdateHandlerBase()
        }
    }

    /**
     * Updates all App Widgets with the latest information. This should be called whenever a
     * contraction is updated
     *
     * @param context Context used to trigger updates, must not be null
     */
    abstract fun updateAllWidgets(context: Context)
}

Remove no longer needed @JvmStatic

package com.ianhanniballake.contractiontimer.appwidget

import android.content.Context
import android.os.Build

/**
 * Handles updating all App Widgets
 */
abstract class AppWidgetUpdateHandler {
    companion object {
        /**
         * Creates a version appropriate AppWidgetUpdateHandler instance
         *
         * @return an appropriate AppWidgetUpdateHandler
         */
        fun createInstance(): AppWidgetUpdateHandler {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                AppWidgetUpdateHandlerV11()
            else
                AppWidgetUpdateHandlerBase()
        }
    }

    /**
     * Updates all App Widgets with the latest information. This should be called whenever a
     * contraction is updated
     *
     * @param context Context used to trigger updates, must not be null
     */
    abstract fun updateAllWidgets(context: Context)
}


package com.st8vrt.mitsumame.configuration

import com.st8vrt.mitsumame.storage.providers.InMemoryStorageProvider
import com.st8vrt.mitsumame.storage.interfaces.SessionStorageProvider
import com.st8vrt.mitsumame.storage.interfaces.DeviceStorageProvider
import com.st8vrt.mitsumame.storage.interfaces.UserStorageProvider

/**
 * Created with IntelliJ IDEA.
 * User: swishy
 * Date: 10/5/13
 * Time: 10:04 PM
 * To change this template use File | Settings | File Templates.
 */

// Static instance to reference.
public var mitsumameConfiguration : MitsumameConfiguration = MitsumameConfiguration()

public class MitsumameConfiguration
{
    // Can be assigned to custom providers.
    public var sessionStorageProvider : SessionStorageProvider = InMemoryStorageProvider()

    public var deviceStorageProvider : DeviceStorageProvider = InMemoryStorageProvider()

    public var userStorageProvider : UserStorageProvider = InMemoryStorageProvider()

    // Default to 2 hours.
    public var sessionDuration : Long = 7200000
}

Add key iterations to the current config

package com.st8vrt.mitsumame.configuration

import com.st8vrt.mitsumame.storage.providers.InMemoryStorageProvider
import com.st8vrt.mitsumame.storage.interfaces.SessionStorageProvider
import com.st8vrt.mitsumame.storage.interfaces.DeviceStorageProvider
import com.st8vrt.mitsumame.storage.interfaces.UserStorageProvider

/**
 * Created with IntelliJ IDEA.
 * User: swishy
 * Date: 10/5/13
 * Time: 10:04 PM
 * To change this template use File | Settings | File Templates.
 */

// Static instance to reference.
public var mitsumameConfiguration : MitsumameConfiguration = MitsumameConfiguration()

public class MitsumameConfiguration
{
    // Can be assigned to custom providers.
    public var sessionStorageProvider : SessionStorageProvider = InMemoryStorageProvider()

    public var deviceStorageProvider : DeviceStorageProvider = InMemoryStorageProvider()

    public var userStorageProvider : UserStorageProvider = InMemoryStorageProvider()

    // Default to 2 hours.
    public var sessionDuration : Long = 7200000

    // Default to 1024 iterations during key strengthening.
    public var keyIterations : Int = 1024
}


package vcsroots

import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.VcsSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot

object GradleAllBranches : GitVcsRoot({
    name = "Gradle All Branches"
    url = "https://github.com/gradle/gradle.git"
    branch = "master"
    branchSpec = "+:refs/heads/*"
    agentGitPath = "%env.TEAMCITY_GIT_PATH%"
    useMirrors = false
})

val gradleMasterVersionedSettings = "GradleMaster"
val gradleReleaseVersionedSettings = "GradleRelease"
val gradlePromotionMaster = "Gradle_GradlePromoteMaster"
val gradlePromotionBranches = "Gradle_GradlePromoteBranches"

fun VcsSettings.useAbsoluteVcs(absoluteId: String) {
    root(AbsoluteId(absoluteId))

    checkoutMode = CheckoutMode.ON_AGENT
    this.cleanCheckout = cleanCheckout
    showDependenciesChanges = true
}

Use same default branch and branch spec as before

package vcsroots

import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.VcsSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot

object GradleAllBranches : GitVcsRoot({
    name = "Gradle All Branches"
    url = "https://github.com/gradle/gradle.git"
    branch = "%defaultBranchName%"
    branchSpec = """+:refs/heads/*
+:refs/(pull/*/head)"""
    agentGitPath = "%env.TEAMCITY_GIT_PATH%"
    useMirrors = false
})

val gradleMasterVersionedSettings = "GradleMaster"
val gradleReleaseVersionedSettings = "GradleRelease"
val gradlePromotionMaster = "Gradle_GradlePromoteMaster"
val gradlePromotionBranches = "Gradle_GradlePromoteBranches"

fun VcsSettings.useAbsoluteVcs(absoluteId: String) {
    root(AbsoluteId(absoluteId))

    checkoutMode = CheckoutMode.ON_AGENT
    this.cleanCheckout = cleanCheckout
    showDependenciesChanges = true
}


package com.rhm.pwn.model

import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey

@Entity
data class PWNLog constructor(val logLevel: Char, val classname: String, val message: String, val datetime: String) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}


package nl.deltadak.plep.database

import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.Transaction
import java.sql.Connection
import org.jetbrains.exposed.sql.transactions.transaction
import java.io.File

/**
 * Use instead of [transaction], as this sets default flags to work with SQLite.
 * Also sets the path of the database, which should be stored next to executable/jar file.
 */
fun <T> regularTransaction(statement: Transaction.() -> T): T {
    val databasePath = "jdbc:sqlite:${File(DatabaseFacade::class.java.protectionDomain.codeSource.location.toURI()).parent}\\plep.db"
    Database.connect(databasePath, driver = "org.sqlite.JDBC") // Database for actual application.
//    Database.connect("jdbc:sqlite:file:test", driver = "org.sqlite.JDBC") // Database for testing.

    return transaction(Connection.TRANSACTION_SERIALIZABLE, 2, statement = statement)
}

Change backward slash to forward slash for linux compatibility

package nl.deltadak.plep.database

import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.Transaction
import java.sql.Connection
import org.jetbrains.exposed.sql.transactions.transaction
import java.io.File

/**
 * Use instead of [transaction], as this sets default flags to work with SQLite.
 * Also sets the path of the database, which should be stored next to executable/jar file.
 */
fun <T> regularTransaction(statement: Transaction.() -> T): T {
    val databasePath = "jdbc:sqlite:${File(DatabaseFacade::class.java.protectionDomain.codeSource.location.toURI()).parent}/plep.db"
    Database.connect(databasePath, driver = "org.sqlite.JDBC") // Database for actual application.
//    Database.connect("jdbc:sqlite:file:test", driver = "org.sqlite.JDBC") // Database for testing.

    return transaction(Connection.TRANSACTION_SERIALIZABLE, 2, statement = statement)
}


plugins {
    `kotlin-dsl`
    `java-library`
    idea
}

subprojects {
    dependencies {
        gradleApi()
        gradleKotlinDsl()
    }
    apply(plugin = "org.gradle.kotlin.kotlin-dsl")
    apply(plugin = "org.spongepowered.gradle.sponge.dev")
}

repositories {
    mavenLocal()
    mavenCentral()
    gradlePluginPortal()
    jcenter()
    maven(url = "https://files.minecraftforge.net/maven")
    maven("https://repo.spongepowered.org/maven")
}

dependencies {
    implementation("net.minecrell.licenser:net.minecrell.licenser.gradle.plugin:0.4.1")
    implementation("net.minecraftforge.gradle:ForgeGradle:3.+")
    implementation(group = "org.spongepowered", name = "spongegradle", version = "0.11.1")
}

Fix the SpongeGradle name representation for SpongeCommon.

plugins {
    `kotlin-dsl`
    `java-library`
    idea
}

subprojects {
    dependencies {
        gradleApi()
        gradleKotlinDsl()
    }
    apply(plugin = "org.gradle.kotlin.kotlin-dsl")
    apply(plugin = "org.spongepowered.gradle.sponge.dev")
}

repositories {
    mavenLocal()
    mavenCentral()
    gradlePluginPortal()
    jcenter()
    maven(url = "https://files.minecraftforge.net/maven")
    maven("https://repo.spongepowered.org/maven")
}

dependencies {
    implementation("net.minecrell.licenser:net.minecrell.licenser.gradle.plugin:0.4.1")
    implementation("net.minecraftforge.gradle:ForgeGradle:3.+")
    implementation(group = "org.spongepowered", name = "SpongeGradle", version = "0.11.1")
}


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

@file:Suppress("PackageDirectoryMismatch")

import org.gradle.api.Project
import org.gradle.kotlin.dsl.extra
import java.util.Properties

object ProjectVersions {
    const val androidBuildTools = "29.0.2"
    const val androidSdk = 29
}

val Project.thisLibraryVersion: String
    get() {
        val key = "splitties.version"
        return rootProject.extra.properties.getOrElse(key) {
            Properties().also {
                it.load(rootProject.file("libraries_version.properties").reader())
            }.getProperty(key).also { value ->
                rootProject.extra.properties[key] = value // Cache it in root project's extra properties.
            }
        } as String
    }

val Project.isDevVersion get() = thisLibraryVersion.contains("-dev-")

Use getOrPut instead of getOrElse + put

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

@file:Suppress("PackageDirectoryMismatch")

import org.gradle.api.Project
import org.gradle.kotlin.dsl.extra
import java.util.Properties

object ProjectVersions {
    const val androidBuildTools = "29.0.2"
    const val androidSdk = 29
}

val Project.thisLibraryVersion: String
    get() {
        val key = "splitties.version"
        return rootProject.extra.properties.getOrPut(key) {
            Properties().also {
                it.load(rootProject.file("libraries_version.properties").reader())
            }.getProperty(key)
        } as String
    }

val Project.isDevVersion get() = thisLibraryVersion.contains("-dev-")


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

package io.michaelrocks.lightsaber.processor.commons

import java.util.*

inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByIndexedTo(destination: M,
    keySelector: (Int, T) -> K, valueSelector: (Int, T) -> V): M {
  forEachIndexed { index, element ->
    destination.put(keySelector(index, element), valueSelector(index, element))
  }
  return destination
}

inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Iterable<T>.groupNotNullByTo(destination: M,
    keySelector: (T) -> K, valueTransform: (T) -> V?): M {
  for (element in this) {
    valueTransform(element)?.let { value ->
      val key = keySelector(element)
      val list = destination.getOrPut(key) { ArrayList<V>() }
      list.add(value)
    }
  }
  return destination
}


package com.jetbrains.rider.plugins.unity.actions

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.jetbrains.rider.plugins.unity.run.UnityProcessPickerDialog

class AttachToUnityProcessAction : AnAction(), DumbAware {
    override fun actionPerformed(e: AnActionEvent) {
        val project = e.project?: return

        val dialog = UnityProcessPickerDialog(project)
        dialog.show()
    }
}

Attach to Unity process no longer DumbAware

package com.jetbrains.rider.plugins.unity.actions

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.rider.plugins.unity.run.UnityProcessPickerDialog

class AttachToUnityProcessAction : AnAction() {
    override fun actionPerformed(e: AnActionEvent) {
        val project = e.project?: return

        val dialog = UnityProcessPickerDialog(project)
        dialog.show()
    }
}


Add a partial test for the expression simplification.

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import semlang.api.getNativeContext
import semlang.parser.parseFile
import semlang.parser.validateContext
import semlang.transforms.simplifyExpressions
import java.io.File

@RunWith(Parameterized::class)
class SimplifyExpressionsTest(private val file: File) {
    companion object ParametersSource {
        @Parameterized.Parameters(name = "{0}")
        @JvmStatic
        fun data(): Collection<Array<Any?>> {
            val folder = File("../kotlin-parser/src/test/semlang/validatorTests/pass")
            return folder.listFiles().map { file ->
                arrayOf(file as Any?)
            }
        }
    }

    @Test
    fun testSimplification() {
        val context = validateContext(parseFile(file), listOf(getNativeContext()))

        // TODO: Check that the semantics of any examples are actually unchanged, according to our interpreter
        // (This requires storing inputs to try with each given code sample; ideally we'd combine this
        // with storing the expected outputs, so interpreter tests can use the same framework)
        val simplified = simplifyExpressions(context)
        // TODO: Test sem0 output and parsing round-trip
    }

}


Create an empty Android test for the Android sample

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

package io.michaelrocks.lightsaber.sample

import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.test.suitebuilder.annotation.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
  @get:Rule
  val activityTestRule = ActivityTestRule(MainActivity::class.java)

  @Test
  fun mainActivityTest() = Unit
}


package com.pinterest.ktlint.core.api

@RequiresOptIn(
    message = "This Ktlint feature is highly experimental, and most probably will change in the future releases.",
    level = RequiresOptIn.Level.ERROR
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
public annotation class FeatureInAlphaState

@RequiresOptIn(
    message = "This Ktlint feature is experimental, and may change in the future releases.",
    level = RequiresOptIn.Level.WARNING
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
public annotation class FeatureInBetaState

Allow to annotate type aliases as well.

package com.pinterest.ktlint.core.api

@RequiresOptIn(
    message = "This Ktlint feature is highly experimental, and most probably will change in the future releases.",
    level = RequiresOptIn.Level.ERROR
)
@Retention(AnnotationRetention.BINARY)
@Target(
    AnnotationTarget.CLASS,
    AnnotationTarget.FUNCTION,
    AnnotationTarget.TYPEALIAS,
)
public annotation class FeatureInAlphaState

@RequiresOptIn(
    message = "This Ktlint feature is experimental, and may change in the future releases.",
    level = RequiresOptIn.Level.WARNING
)
@Retention(AnnotationRetention.BINARY)
@Target(
    AnnotationTarget.CLASS,
    AnnotationTarget.FUNCTION,
    AnnotationTarget.TYPEALIAS,
)
public annotation class FeatureInBetaState


package com.s13g.aoc.aoc2021

import com.s13g.aoc.Result
import com.s13g.aoc.Solver

/**
 * --- Day 1: Sonar Sweep ---
 * https://adventofcode.com/2021/day/1
 */
class Day1 : Solver {
  override fun solve(lines: List<String>): Result {
    val measurements = lines.map { it.toLong() }.toList()
    val measurements2 = mutableListOf<Long>()
    for (i in 0 until measurements.size - 2) {
      measurements2.add(measurements[i] + measurements[i + 1] + measurements[i + 2])
    }
    return Result(measure(measurements).toString(), measure(measurements2).toString())
  }

  private fun measure(list: List<Long>): Int {
    var count = 0
    for (i in 1 until list.size) {
      if (list[i] > list[i - 1]) count++
    }
    return count
  }
}

Make the code shorter for Day 1

package com.s13g.aoc.aoc2021

import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom

/**
 * --- Day 1: Sonar Sweep ---
 * https://adventofcode.com/2021/day/1
 */
class Day1 : Solver {
  override fun solve(lines: List<String>): Result {
    val m1 = lines.map { it.toLong() }.toList()
    val m2 = m1.mapIndexedNotNull { i, _ -> if (i < m1.size - 2) m1[i] + m1[i + 1] + m1[i + 2] else null }
    return resultFrom(m1.measure(), m2.measure())
  }

  private fun List<Long>.measure() = this.mapIndexed { i, v -> if (i == 0) false else v > this[i - 1] }.count { it }
}


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

package common

interface Jvm {
    val version: JvmVersion
    val vendor: JvmVendor
}

data class DefaultJvm(
    override val version: JvmVersion,
    override val vendor: JvmVendor
) : Jvm

object BuildToolBuildJvm : Jvm {
    override val version: JvmVersion
        get() = JvmVersion.java11
    override val vendor: JvmVendor
        get() = JvmVendor.openjdk
}

Use adoptium ad build JDK

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

package common

interface Jvm {
    val version: JvmVersion
    val vendor: JvmVendor
}

data class DefaultJvm(
    override val version: JvmVersion,
    override val vendor: JvmVendor
) : Jvm

object BuildToolBuildJvm : Jvm {
    override val version: JvmVersion
        get() = JvmVersion.java11
    override val vendor: JvmVendor
        get() = JvmVendor.adoptiumopenjdk
}


package org.wordpress.aztec.plugins.shortcodes

import org.wordpress.aztec.plugins.html2visual.IHtmlPreprocessor
import org.wordpress.aztec.plugins.visual2html.IHtmlPostprocessor

class VideoShortcodePlugin : IHtmlPreprocessor, IHtmlPostprocessor {

    private val TAG = "video"

    override fun processHtmlBeforeParsing(source: String): String {
        return source.replace(Regex("\\[$TAG([^\\]]*)\\]"), "<$TAG$1 />")
    }

    override fun processHtmlAfterSerialization(source: String): String {
        return source.replace(Regex("<$TAG([^>]*)/?>"), "[$TAG$1]")
    }
}


package nl.hannahsten.texifyidea.completion

import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.PlatformIcons
import com.intellij.util.ProcessingContext
import com.intellij.util.containers.ContainerUtil
import nl.hannahsten.texifyidea.completion.handlers.TokenTypeInsertHandler
import nl.hannahsten.texifyidea.lang.BibtexDefaultEntry

/**
 * @author Hannah Schellekens
 */
object BibtexTypeTokenProvider : CompletionProvider<CompletionParameters>() {

    override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
        result.addAllElements(ContainerUtil.map2List(BibtexDefaultEntry.values()) {
            LookupElementBuilder.create(it, it.token)
                    .withPresentableText(it.token)
                    .bold()
                    .withIcon(PlatformIcons.ANNOTATION_TYPE_ICON)
                    .withTailText("  (${it.dependency.name})", true)
                    .withInsertHandler(TokenTypeInsertHandler)
        })
    }
}

Fix autocomplete text on bibtex type

package nl.hannahsten.texifyidea.completion

import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.PlatformIcons
import com.intellij.util.ProcessingContext
import com.intellij.util.containers.ContainerUtil
import nl.hannahsten.texifyidea.completion.handlers.TokenTypeInsertHandler
import nl.hannahsten.texifyidea.lang.BibtexDefaultEntry
import nl.hannahsten.texifyidea.lang.Dependend
import nl.hannahsten.texifyidea.lang.Package

/**
 * @author Hannah Schellekens
 */
object BibtexTypeTokenProvider : CompletionProvider<CompletionParameters>() {

    override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
        result.addAllElements(ContainerUtil.map2List(BibtexDefaultEntry.values()) {
            LookupElementBuilder.create(it, it.token)
                    .withPresentableText(it.token)
                    .bold()
                    .withIcon(PlatformIcons.ANNOTATION_TYPE_ICON)
                    .withTailText(packageName(it), true)
                    .withInsertHandler(TokenTypeInsertHandler)
        })
    }

    private fun packageName(dependend: Dependend): String {
        return when(val dependency = dependend.dependency) {
            Package.DEFAULT -> ""
            else -> "  (${dependency.name})"
        }
    }
}


package org.wordpress.aztec.plugins

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.toolbar.AztecToolbar
import org.wordpress.aztec.toolbar.IToolbarAction
import org.wordpress.aztec.toolbar.RippleToggleButton

interface IToolbarButton : IAztecPlugin {
    val action: IToolbarAction
    val context: Context

    fun toggle()

    fun matchesKeyShortcut(keyCode: Int, event: KeyEvent): Boolean {
        return false
    }

    fun inflateButton(parent: ViewGroup)
}

Add documentation to the toolbar plugin interface

package org.wordpress.aztec.plugins

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.toolbar.AztecToolbar
import org.wordpress.aztec.toolbar.IToolbarAction
import org.wordpress.aztec.toolbar.RippleToggleButton

/**
 * An interface for implementing toolbar plugins.
 *
 * @property action the toolbar action type.
 * @property context the Android context.
 */
interface IToolbarButton : IAztecPlugin {
    val action: IToolbarAction
    val context: Context

    /**
     * Toggles a particular style.
     *
     * This method is called when the associated toolbar button is tapped or key shortcut is pressed.
     */
    fun toggle()

    /**
     * Determines, whether a particular key shortcut should trigger the toolbar action.
     *
     * @return true, if the key combination matches the action shortcut, false otherwise.
     */
    fun matchesKeyShortcut(keyCode: Int, event: KeyEvent): Boolean {
        return false
    }

    /**
     * A callback method used during the toolbar initialization.
     *
     * The implementor is responsible for implementing the inflation of a [RippleToggleButton] under the *parent*.
     *
     * @param parent view to be the parent of the generated hierarchy.
     */
    fun inflateButton(parent: ViewGroup)
}


package org.jetbrains.dokka

import com.google.inject.Inject
import com.google.inject.name.Named
import org.jetbrains.dokka.Utilities.impliedPlatformsName

open class JekyllOutputBuilder(to: StringBuilder,
                               location: Location,
                               locationService: LocationService,
                               languageService: LanguageService,
                               extension: String,
                               impliedPlatforms: List<String>)
    : MarkdownOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms)
{
    override fun appendNodes(nodes: Iterable<DocumentationNode>) {
        to.appendln("---")
        appendFrontMatter(nodes, to)
        to.appendln("---")
        to.appendln("")
        super.appendNodes(nodes)
    }

    protected open fun appendFrontMatter(nodes: Iterable<DocumentationNode>, to: StringBuilder) {
        to.appendln("title: ${getPageTitle(nodes)}")
    }
}

open class JekyllFormatService(locationService: LocationService,
                               signatureGenerator: LanguageService,
                               linkExtension: String,
                               impliedPlatforms: List<String>)
: MarkdownFormatService(locationService, signatureGenerator, linkExtension, impliedPlatforms) {

    @Inject constructor(locationService: LocationService,
                        signatureGenerator: LanguageService,
                        @Named(impliedPlatformsName) impliedPlatforms: List<String>): this(locationService, signatureGenerator, "md", impliedPlatforms)

    override fun createOutputBuilder(to: StringBuilder, location: Location): FormattedOutputBuilder =
        JekyllOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms)

}

Set jekyll links extension to .html

package org.jetbrains.dokka

import com.google.inject.Inject
import com.google.inject.name.Named
import org.jetbrains.dokka.Utilities.impliedPlatformsName

open class JekyllOutputBuilder(to: StringBuilder,
                               location: Location,
                               locationService: LocationService,
                               languageService: LanguageService,
                               extension: String,
                               impliedPlatforms: List<String>)
    : MarkdownOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms)
{
    override fun appendNodes(nodes: Iterable<DocumentationNode>) {
        to.appendln("---")
        appendFrontMatter(nodes, to)
        to.appendln("---")
        to.appendln("")
        super.appendNodes(nodes)
    }

    protected open fun appendFrontMatter(nodes: Iterable<DocumentationNode>, to: StringBuilder) {
        to.appendln("title: ${getPageTitle(nodes)}")
    }
}

open class JekyllFormatService(locationService: LocationService,
                               signatureGenerator: LanguageService,
                               linkExtension: String,
                               impliedPlatforms: List<String>)
: MarkdownFormatService(locationService, signatureGenerator, linkExtension, impliedPlatforms) {

    @Inject constructor(locationService: LocationService,
                        signatureGenerator: LanguageService,
                        @Named(impliedPlatformsName) impliedPlatforms: List<String>): this(locationService, signatureGenerator, "html", impliedPlatforms)

    override fun createOutputBuilder(to: StringBuilder, location: Location): FormattedOutputBuilder =
        JekyllOutputBuilder(to, location, locationService, languageService, extension, impliedPlatforms)

}


package venus.assembler.pseudos

import venus.assembler.AssemblerPassOne
import venus.assembler.LineTokens
import venus.assembler.PseudoWriter
import venus.riscv.insts.dsl.relocators.PCRelHiRelocator
import venus.riscv.insts.dsl.relocators.PCRelLoRelocator

/**
 * Writes a store pseudoinstruction. (Those applied to a label)
 */
object Store : PseudoWriter() {
    override operator fun invoke(args: LineTokens, state: AssemblerPassOne): List<LineTokens> {
        checkArgsLength(args, 4)

        val auipc = listOf("auipc", args[3], "0")
        state.addRelocation(PCRelHiRelocator, state.getOffset(), args[2])

        val store = listOf(args[0], args[1], "0", args[3])
        state.addRelocation(PCRelLoRelocator, state.getOffset() + 4, args[2])

        return listOf(auipc, store)
    }
}

Fix bug where store immediate was treated as label

package venus.assembler.pseudos

import venus.assembler.AssemblerPassOne
import venus.assembler.LineTokens
import venus.assembler.PseudoWriter
import venus.riscv.insts.dsl.relocators.PCRelHiRelocator
import venus.riscv.insts.dsl.relocators.PCRelLoRelocator
import venus.riscv.userStringToInt

/**
 * Writes a store pseudoinstruction. (Those applied to a label)
 */
object Store : PseudoWriter() {
    override operator fun invoke(args: LineTokens, state: AssemblerPassOne): List<LineTokens> {
        checkArgsLength(args, 4)
        val label = args[2]
        try {
            userStringToInt(label)
            /* if it's a number, this is just an ordinary store instruction */
            return listOf(args)
        } catch (e: NumberFormatException) {
            /* assume it's a label */
        }

        val auipc = listOf("auipc", args[3], "0")
        state.addRelocation(PCRelHiRelocator, state.getOffset(), label)

        val store = listOf(args[0], args[1], "0", args[3])
        state.addRelocation(PCRelLoRelocator, state.getOffset() + 4, label)

        return listOf(auipc, store)
    }
}


Add convenience variable to get the Firestore

/*
 * Copyright 2014-2019 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.mymartlet.util

import com.google.firebase.firestore.FirebaseFirestore

/**
 * General utility methods
 * @author Julien Guerinet
 * @since 2.0.0
 */

/** Convenience variable for the Firestore instance */
val firestore: FirebaseFirestore
    get() = FirebaseFirestore.getInstance()


import org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED

tasks.named<Test>("test").configure {
	useJUnitPlatform {
		includeEngines("junit-jupiter")
	}
	include("**/*Test.class", "**/*Tests.class")
	testLogging {
		events = setOf(FAILED)
		exceptionFormat = FULL
	}
	systemProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager")
}

dependencies {
	"testImplementation"("org.assertj:assertj-core:${Versions.assertJ}")
	"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.mockito}") {
		exclude(module = "junit-jupiter-engine")
	}

	if (project.name != "junit-jupiter-engine") {
		"testImplementation"(project(":junit-jupiter-api"))
		"testImplementation"(project(":junit-jupiter-params"))

		"testRuntimeOnly"(project(":junit-jupiter-engine"))
	}

	"testRuntimeOnly"(project(":junit-platform-launcher"))

	"testRuntimeOnly"("org.apache.logging.log4j:log4j-core:${Versions.log4j}")
	"testRuntimeOnly"("org.apache.logging.log4j:log4j-jul:${Versions.log4j}")
}

Enable experimental byte-buddy features to run on JDK 14

import org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED

tasks.named<Test>("test").configure {
	useJUnitPlatform {
		includeEngines("junit-jupiter")
	}
	include("**/*Test.class", "**/*Tests.class")
	testLogging {
		events = setOf(FAILED)
		exceptionFormat = FULL
	}
	systemProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager")
	if (JavaVersion.current() == JavaVersion.VERSION_HIGHER) {
		systemProperty("net.bytebuddy.experimental", true)
	}
}

dependencies {
	"testImplementation"("org.assertj:assertj-core:${Versions.assertJ}")
	"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.mockito}") {
		exclude(module = "junit-jupiter-engine")
	}

	if (project.name != "junit-jupiter-engine") {
		"testImplementation"(project(":junit-jupiter-api"))
		"testImplementation"(project(":junit-jupiter-params"))

		"testRuntimeOnly"(project(":junit-jupiter-engine"))
	}

	"testRuntimeOnly"(project(":junit-platform-launcher"))

	"testRuntimeOnly"("org.apache.logging.log4j:log4j-core:${Versions.log4j}")
	"testRuntimeOnly"("org.apache.logging.log4j:log4j-jul:${Versions.log4j}")
}


/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

/**
 * A number of common helper methods for writing unit tests.
 */
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")

package kotlin.test

import kotlin.reflect.KClass

/**
 * Takes the given [block] of test code and _doesn't_ execute it.
 *
 * This keeps the code under test referenced, but doesn't actually test it until it is implemented.
 */
@Suppress("UNUSED_PARAMETER")
public actual inline fun todo(block: () -> Unit) {
    println("TODO")
}

@PublishedApi
internal actual fun <T : Throwable> checkResultIsFailure(exceptionClass: KClass<T>, message: String?, blockResult: Result<Unit>): T {
    blockResult.fold(
            onSuccess = {
                asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was completed successfully.")
            },
            onFailure = { e ->
                if (exceptionClass.isInstance(e)) {
                    @Suppress("UNCHECKED_CAST")
                    return e as T
                }
                asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was $e")
            }
    )
}

internal actual fun lookupAsserter(): Asserter = DefaultAsserter

Introduce 'fail' method to throw AssertionError with cause

/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

/**
 * A number of common helper methods for writing unit tests.
 */
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")

package kotlin.test

import kotlin.reflect.KClass

/**
 * Takes the given [block] of test code and _doesn't_ execute it.
 *
 * This keeps the code under test referenced, but doesn't actually test it until it is implemented.
 */
@Suppress("UNUSED_PARAMETER")
public actual inline fun todo(block: () -> Unit) {
    println("TODO")
}

@PublishedApi
internal actual fun <T : Throwable> checkResultIsFailure(exceptionClass: KClass<T>, message: String?, blockResult: Result<Unit>): T {
    blockResult.fold(
            onSuccess = {
                asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was completed successfully.")
            },
            onFailure = { e ->
                if (exceptionClass.isInstance(e)) {
                    @Suppress("UNCHECKED_CAST")
                    return e as T
                }
                asserter.fail(messagePrefix(message) + "Expected an exception of ${exceptionClass.qualifiedName} to be thrown, but was $e")
            }
    )
}

/** Platform-specific construction of AssertionError with cause */
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun AssertionErrorWithCause(message: String?, cause: Throwable?): AssertionError =
        AssertionError(message, cause)

internal actual fun lookupAsserter(): Asserter = DefaultAsserter


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 isJenkins = "JENKINS_HOME" in System.getenv()
    val gradleKotlinDslVersion = "1.1.2"
    val kotlinVersion = "1.3.20"
    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.1.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 isTravis = "TRAVIS" in System.getenv()
    val isJenkins = "JENKINS_HOME" in System.getenv()
    val gradleKotlinDslVersion = "1.1.3"
    val kotlinVersion = "1.3.20"
    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 engineer.carrot.warren.thump.plugin.irc

import net.minecraft.util.text.TextComponentString
import net.minecraft.util.text.TextFormatting
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

class IrcChatFormatterTests {

    lateinit var formatter: IrcChatFormatter

    @Before
    fun setUp() {
        formatter = IrcChatFormatter()
    }

    @Test
    fun `format plaintext wraps input in a string component`() {
        val text = formatter.format("the quick brown fox jumps over the lazy dog")

        assertEquals(TextComponentString("the quick brown fox jumps over the lazy dog"), text)
    }

    @Test
    fun `format textcomponent returns unformatted text in a single string`() {
        val firstComponent = TextComponentString("the quick brown fox jumps over the lazy")
        val secondComponent = TextComponentString(" dog")
        secondComponent.style.bold = true
        secondComponent.style.italic = true
        secondComponent.style.color = TextFormatting.BLUE

        val plaintext = formatter.format(firstComponent.appendSibling(secondComponent))

        assertEquals("the quick brown fox jumps over the lazy dog", plaintext)
    }

}

Fix non object reference in tests

package engineer.carrot.warren.thump.plugin.irc

import net.minecraft.util.text.TextComponentString
import net.minecraft.util.text.TextFormatting
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

class IrcChatFormatterTests {

    lateinit var formatter: IrcChatFormatter

    @Before
    fun setUp() {
        formatter = IrcChatFormatter
    }

    @Test
    fun `format plaintext wraps input in a string component`() {
        val text = formatter.format("the quick brown fox jumps over the lazy dog")

        assertEquals(TextComponentString("the quick brown fox jumps over the lazy dog"), text)
    }

    @Test
    fun `format textcomponent returns unformatted text in a single string`() {
        val firstComponent = TextComponentString("the quick brown fox jumps over the lazy")
        val secondComponent = TextComponentString(" dog")
        secondComponent.style.bold = true
        secondComponent.style.italic = true
        secondComponent.style.color = TextFormatting.BLUE

        val plaintext = formatter.format(firstComponent.appendSibling(secondComponent))

        assertEquals("the quick brown fox jumps over the lazy dog", plaintext)
    }

}


/*
 * 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.room.dao

import androidx.room.Insert

/**
 * Basic Dao INSERT functions for one model
 * @author Julien Guerinet
 * @since 4.2.1
 */
interface BaseInsertDao<T> {

    /**
     * Inserts 1 [obj] into the database
     */
    @Insert
    fun insert(obj: T)

    /**
     * Inserts a list of [objects] into the database
     */
    @Insert
    fun insert(objects: List<T>)
}

Switch the OnConflictStrategy to replace.

/*
 * 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.room.dao

import androidx.room.Insert
import androidx.room.OnConflictStrategy

/**
 * Basic Dao INSERT functions for one model
 * @author Julien Guerinet
 * @since 4.2.1
 */
interface BaseInsertDao<T> {

    /**
     * Inserts 1 [obj] into the database
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(obj: T)

    /**
     * Inserts a list of [objects] into the database
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(objects: List<T>)
}