path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/test/kotlin/examples/kotlin/ktor/login/OAuth2LoginAppTest.kt
navikt
235,432,421
false
null
package examples.kotlin.ktor.login import io.kotest.assertions.asClue import io.kotest.matchers.shouldBe import io.ktor.client.request.prepareGet import io.ktor.server.application.Application import io.ktor.server.engine.ApplicationEngine import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import kotlinx.coroutines.runBlocking import no.nav.security.mock.oauth2.MockOAuth2Server import no.nav.security.mock.oauth2.token.DefaultOAuth2TokenCallback import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail import java.io.IOException import java.net.ServerSocket internal class OAuth2LoginAppTest { private val mockOAuth2Server = MockOAuth2Server() @BeforeEach fun setup() = mockOAuth2Server.start() @AfterEach fun after() = mockOAuth2Server.shutdown() @Test fun `login with google or github should return appropriate subject`() { mockOAuth2Server.enqueueCallback(DefaultOAuth2TokenCallback(issuerId = "google", subject = "googleSubject")) mockOAuth2Server.enqueueCallback(DefaultOAuth2TokenCallback(issuerId = "github", subject = "githubSubject")) val port = randomPort() withEmbeddedServer( { module(authConfig()) }, port, ) { get<String>("http://localhost:$port/login/google").asClue { it shouldBe "welcome googleSubject" } get<String>("http://localhost:$port/login/github").asClue { it shouldBe "welcome githubSubject" } } } private inline fun <reified R> get(url: String): R = runBlocking { httpClient.prepareGet(url).body() } private fun <R> withEmbeddedServer( moduleFunction: Application.() -> Unit, port: Int, test: ApplicationEngine.() -> R, ): R { val engine = embeddedServer(Netty, port = port) { moduleFunction(this) } engine.start() try { return engine.test() } finally { engine.stop(0L, 0L) } } private fun randomPort() = try { ServerSocket(0).use { serverSocket -> serverSocket.localPort } } catch (e: IOException) { fail("Port is not available") } private fun authConfig() = AuthConfig( listOf( AuthConfig.IdProvider( name = "google", authorizationEndpoint = mockOAuth2Server.authorizationEndpointUrl("google").toString(), tokenEndpoint = mockOAuth2Server.tokenEndpointUrl("google").toString(), ), AuthConfig.IdProvider( name = "github", authorizationEndpoint = mockOAuth2Server.authorizationEndpointUrl("github").toString(), tokenEndpoint = mockOAuth2Server.tokenEndpointUrl("github").toString(), ), ), ) }
8
Kotlin
57
70
a2201da1c4ca42298b7adfd0e986512d451f1a84
3,059
mock-oauth2-server
MIT License
thirdparty/controlsfx-layouts/tests/src/org/controlsfx/control/InfoOverlayTest.kt
hendraanggrian
102,934,147
false
null
package ktfx.controlsfx.layouts import ktfx.layouts.KtfxPane import com.hendraanggrian.ktfx.test.LayoutsTest import org.controlsfx.control.InfoOverlay import kotlin.test.assertNull class InfoOverlayTest : LayoutsTest<KtfxPane, InfoOverlay>() { override fun manager() = KtfxPane() override fun KtfxPane.childCount() = children.size override fun child1() = infoOverlay { } override fun KtfxPane.child2() = infoOverlay() override fun KtfxPane.child3() = infoOverlay { } override fun InfoOverlay.testDefaultValues() { assertNull(content) assertNull(text) } }
1
null
2
15
ea4243fb75edb70d6710e7488fa08834084f6169
602
ktfx
Apache License 2.0
android/src/main/kotlin/tech/soit/quiet/player/PlayMode.kt
boyan01
203,903,720
false
null
package app.toarbit.muse_player.player /** * * PlayMode of MusicPlayer * * @author 杨彬 */ sealed class PlayMode( val rawValue: Int ) { companion object { fun valueOf(value: Int): PlayMode = when (value) { 0 -> Shuffle 1 -> Single 2 -> Sequence else -> Undefined(value) } } //随机播放 object Shuffle : PlayMode(0) //单曲循环 object Single : PlayMode(1) //列表循环 object Sequence : PlayMode(2) class Undefined(value: Int) : PlayMode(value) }
4
null
31
77
434e6fdc79a81d1a2a0877339ae29004c0f32734
547
flutter-music-player
MIT License
src/main/kotlin/org/arend/tracer/ArendTraceProcess.kt
JetBrains
96,068,447
false
null
package org.arend.tracer import com.intellij.execution.ui.RunnerLayoutUi import com.intellij.execution.ui.layout.LayoutAttractionPolicy import com.intellij.execution.ui.layout.LayoutViewOptions import com.intellij.execution.ui.layout.PlaceInGrid import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.ui.components.JBPanelWithEmptyText import com.intellij.util.ui.JBUI import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider import com.intellij.xdebugger.evaluation.XDebuggerEditorsProviderBase import com.intellij.xdebugger.frame.XSuspendContext import com.intellij.xdebugger.impl.DebuggerSupport import com.intellij.xdebugger.impl.actions.* import com.intellij.xdebugger.impl.actions.handlers.XDebuggerActionHandler import com.intellij.xdebugger.ui.XDebugTabLayouter import org.arend.ArendFileType import org.arend.psi.ext.ArendExpr import org.arend.psi.ArendFile import org.arend.psi.ArendPsiFactory import org.arend.util.ArendBundle import org.jetbrains.uast.util.classSetOf import org.jetbrains.uast.util.isInstanceOf import javax.swing.Icon class ArendTraceProcess(session: XDebugSession, private val tracingData: ArendTracingData) : XDebugProcess(session) { private val trace = tracingData.trace private var traceEntryIndex: Int = tracingData.firstEntryIndex private val contextViewPanel = JBUI.Panels.simplePanel() private val emptyContextView = JBPanelWithEmptyText().withEmptyText(ArendBundle.message("arend.tracer.nothing.to.show")) private lateinit var contextView: ArendTraceContextView override fun registerAdditionalActions( leftToolbar: DefaultActionGroup, topToolbar: DefaultActionGroup, settings: DefaultActionGroup ) { super.registerAdditionalActions(leftToolbar, topToolbar, settings) leftToolbar.childActionsOrStubs .filter { it.isInstanceOf(removedLeftToolbarActions) } .forEach(leftToolbar::remove) topToolbar.childActionsOrStubs .filter { it.isInstanceOf(removedTopToolbarActions) } .forEach(topToolbar::remove) val runToCursorAction = ActionManager.getInstance().getAction(RUN_TO_CURSOR_ACTION_ID) val nextEntryAction = TracerAction( ArendBundle.message("arend.trace.next.entry.action.name"), ArendBundle.message("arend.trace.next.entry.action.description"), AllIcons.Vcs.Arrow_right, NextEntryActionHandler() ) val prevEntryAction = TracerAction( ArendBundle.message("arend.trace.prev.entry.action.name"), ArendBundle.message("arend.trace.prev.entry.action.description"), AllIcons.Vcs.Arrow_left, PrevEntryActionHandler() ) topToolbar.add(Separator.create(), Constraints.FIRST) runToCursorAction ?.run { topToolbar.add(this, Constraints.FIRST) } ?: LOGGER.error("Cannot add 'Run To Cursor' action to the toolbar") topToolbar.add(nextEntryAction, Constraints.FIRST) topToolbar.add(prevEntryAction, Constraints.FIRST) } override fun createTabLayouter(): XDebugTabLayouter = object : XDebugTabLayouter() { override fun registerAdditionalContent(ui: RunnerLayoutUi) { contextView = ArendTraceContextView(session.project) contextViewPanel.add(contextView.component!!) val contextContent = ui.createContent(CONTEXT_CONTENT, contextViewPanel, "Context", null, null) ui.addContent(contextContent, 0, PlaceInGrid.center, false) } } override fun sessionInitialized() { focusContextViewOnStartup() if (trace.entries.isEmpty()) { session.reportMessage(ArendBundle.message("arend.tracer.nothing.to.trace"), MessageType.WARNING) session.stop() return } if (tracingData.hasErrors) { session.reportMessage(ArendBundle.message("arend.tracer.declaration.has.errors"), MessageType.WARNING) } val firstEntry = trace.entries.getOrNull(traceEntryIndex) if (firstEntry == null) { session.reportMessage( ArendBundle.message("arend.tracer.cannot.find.starting.expression"), MessageType.WARNING ) traceEntryIndex = 0 session.positionReached(ArendSuspendContext(trace.entries[0], contextView)) return } session.positionReached(ArendSuspendContext(firstEntry, contextView)) } override fun resume(context: XSuspendContext?) { doNothing(context) } override fun startStepOver(context: XSuspendContext?) { doNothing(context) } override fun startStepInto(context: XSuspendContext?) { doNothing(context) } override fun startStepOut(context: XSuspendContext?) { doNothing(context) } override fun runToPosition(position: XSourcePosition, context: XSuspendContext?) { ActionUtil.underModalProgress(session.project, ArendBundle.message("arend.tracer.collecting.tracing.data")) { try { val entryIndex = findEntryIndex(position) val entry = trace.entries.getOrNull(entryIndex) if (entry == null) { session.reportMessage(ArendBundle.message("arend.tracer.cannot.trace.here"), MessageType.WARNING) doNothing(context) return@underModalProgress } traceEntryIndex = entryIndex session.positionReached(ArendSuspendContext(entry, contextView)) } catch (e: ProcessCanceledException) { doNothing(context) } } } override fun stop() { contextViewPanel.removeAll() contextViewPanel.add(emptyContextView) contextView.release() } override fun getEditorsProvider(): XDebuggerEditorsProvider = EditorsProvider private fun focusContextViewOnStartup() { session.ui.defaults.initContentAttraction( CONTEXT_CONTENT, LayoutViewOptions.STARTUP, LayoutAttractionPolicy.FocusOnce(false) ) } private fun doNothing(context: XSuspendContext?) { if (context != null) { session.positionReached(context) } else { session.reportError(ArendBundle.message("arend.tracer.command.failed")) session.stop() } } private fun findEntryIndex(position: XSourcePosition): Int { val file = PsiManager.getInstance(session.project).findFile(position.file) as? ArendFile ?: return -1 val expression = PsiTreeUtil.findElementOfClassAtOffset(file, position.offset, ArendExpr::class.java, false) ?: return -1 return trace.indexOfEntry(expression) } private inner class NextEntryActionHandler : XDebuggerSuspendedActionHandler() { override fun perform(session: XDebugSession, dataContext: DataContext?) { session.sessionResumed() val entry = trace.entries.getOrNull(++traceEntryIndex) if (entry == null) { session.stop() return } session.positionReached(ArendSuspendContext(entry, contextView)) } } private inner class PrevEntryActionHandler : XDebuggerSuspendedActionHandler() { override fun perform(session: XDebugSession, dataContext: DataContext?) { session.sessionResumed() val entry = trace.entries.getOrNull(--traceEntryIndex) if (entry == null) { doNothing(session.suspendContext) return } session.positionReached(ArendSuspendContext(entry, contextView)) } override fun isEnabled(project: Project, event: AnActionEvent?): Boolean = super.isEnabled(project, event) && traceEntryIndex > 0 } private class TracerAction( text: String, description: String, icon: Icon, private val handler: XDebuggerActionHandler ) : XDebuggerActionBase() { init { templatePresentation.text = text templatePresentation.description = description templatePresentation.icon = icon } override fun getHandler(debuggerSupport: DebuggerSupport): DebuggerActionHandler = handler } private object EditorsProvider : XDebuggerEditorsProviderBase() { override fun getFileType(): FileType = ArendFileType.INSTANCE override fun createExpressionCodeFragment( project: Project, text: String, context: PsiElement?, isPhysical: Boolean ): PsiFile = ArendPsiFactory(project).injected(text) } companion object { private val LOGGER = Logger.getInstance(ArendTraceProcess::class.java) private const val RUN_TO_CURSOR_ACTION_ID = "RunToCursor" private const val CONTEXT_CONTENT = "ArendTraceContextContent" private val removedLeftToolbarActions = classSetOf( ResumeAction::class.java, PauseAction::class.java, ViewBreakpointsAction::class.java, MuteBreakpointAction::class.java ) private val removedTopToolbarActions = classSetOf( StepOverAction::class.java, StepIntoAction::class.java, ForceStepIntoAction::class.java, StepOutAction::class.java, RunToCursorAction::class.java ) } }
68
null
13
90
7a6608a2e44369e11c5baad3ef2928d6f9c971b2
10,169
intellij-arend
Apache License 2.0
libs/state-manager/state-manager-api/src/main/kotlin/net/corda/libs/statemanager/api/Metadata.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.libs.statemanager.api /** * Metadata key used to store the actual State Type, if relevant. * * TODO-[CORE-16416]: remove once Isolated State Managers per State Type has been implemented. */ const val STATE_TYPE = "state.type" /** * Map that allows only primitive types to be used as values. */ class Metadata( private val map: Map<String, Any> = emptyMap() ) : Map<String, Any> by map { companion object { private val supportedType = listOf( String::class.java, java.lang.String::class.java, Number::class.java, java.lang.Number::class.java, Boolean::class.java, java.lang.Boolean::class.java, ) private fun isPrimitiveOrBoxedValue(value: Any): Boolean { return supportedType.any { it.isAssignableFrom(value.javaClass) } } } init { map.filter { kvp -> !isPrimitiveOrBoxedValue(kvp.value) }.takeIf { it.isNotEmpty() }?.also { kvp -> val invalidPairs = kvp.entries.joinToString { "${it.key}/${it.value::class.java.name}" } throw IllegalArgumentException("Type(s) not supported: $invalidPairs") } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Metadata if (map != other.map) return false return true } override fun hashCode(): Int { return map.hashCode() } fun containsKeyWithValue(key: String, value: Any) = map.containsKey(key) && map[key]!! == value } fun metadata(): Metadata = Metadata() fun metadata(vararg pairs: Pair<String, Any>): Metadata = Metadata(mapOf(*pairs))
83
Kotlin
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
1,740
corda-runtime-os
Apache License 2.0
app/src/androidMain/kotlin/org/androidaudioplugin/composeaudiocontrols/demoapp/MainActivity.kt
atsushieno
648,495,810
false
null
package org.androidaudioplugin.composeaudiocontrols.demoapp import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.OnBackPressedCallback import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import dev.atsushieno.ktmidi.AndroidMidi2Access import org.androidaudioplugin.composeaudiocontrols.demoapp.MainContent import org.androidaudioplugin.composeaudiocontrols.demoapp.theme.ComposeAudioControlsTheme import kotlin.system.exitProcess class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) midiAccess = AndroidMidi2Access(this, true) setContent { ComposeAudioControlsTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainContent() } } } onBackPressedDispatcher.addCallback(object: OnBackPressedCallback(true) { private var lastBackPressed = System.currentTimeMillis() override fun handleOnBackPressed() { if (System.currentTimeMillis() - lastBackPressed < 2000) { finish() exitProcess(0) } else Toast.makeText(this@MainActivity, "Tap once more to quit", Toast.LENGTH_SHORT).show() lastBackPressed = System.currentTimeMillis() } }) } }
0
null
0
8
2624d445c05c16611c6804a1a3d41efa882036bf
1,921
compose-audio-controls
MIT License
fuzionSDK/src/commonMain/kotlin/com/mayonlabs/fuzion_sdk/entity/MixtureSetting.kt
cindzky
322,179,154
false
null
package com.mayonlabs.fuzion_sdk.entity import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MixtureSetting( @SerialName("id") val id: Int, @SerialName("name") val name: String, @SerialName("slug") val slug: String?, @SerialName("description") val description: String?, @SerialName("default_value") val defaultValue: Int?, @SerialName("max_value") val maxValue: Int? )
0
Kotlin
0
0
9cd2c6ce423a3237a973f476f1315c020c098498
477
FuzionSDK
Apache License 2.0
stripe/src/main/java/com/stripe/android/view/CountryUtils.kt
swdreams
220,836,994
false
null
package com.stripe.android.view import java.util.Locale internal object CountryUtils { private val NO_POSTAL_CODE_COUNTRIES = arrayOf("AE", "AG", "AN", "AO", "AW", "BF", "BI", "BJ", "BO", "BS", "BW", "BZ", "CD", "CF", "CG", "CI", "CK", "CM", "DJ", "DM", "ER", "FJ", "GD", "GH", "GM", "GN", "GQ", "GY", "HK", "IE", "JM", "KE", "KI", "KM", "KN", "KP", "LC", "ML", "MO", "MR", "MS", "MU", "MW", "NR", "NU", "PA", "QA", "RW", "SB", "SC", "SL", "SO", "SR", "ST", "SY", "TF", "TK", "TL", "TO", "TT", "TV", "TZ", "UG", "VU", "YE", "ZA", "ZW") private val NO_POSTAL_CODE_COUNTRIES_SET = setOf(*NO_POSTAL_CODE_COUNTRIES) private val COUNTRY_NAMES_TO_CODES: Map<String, String> get() { return Locale.getISOCountries() .associateBy { Locale("", it).displayCountry } } @JvmStatic fun getCountryCode(countryName: String?): String? { return COUNTRY_NAMES_TO_CODES[countryName] } @JvmStatic fun getOrderedCountries(currentLocale: Locale): List<String> { // Show user's current locale first, followed by countries alphabetized by display name return listOf(currentLocale.displayCountry) .plus( COUNTRY_NAMES_TO_CODES.keys.toList() .sortedWith(compareBy { it.toLowerCase(Locale.ROOT) }) .minus(currentLocale.displayCountry) ) } @JvmStatic fun doesCountryUsePostalCode(countryCode: String): Boolean { return !NO_POSTAL_CODE_COUNTRIES_SET.contains(countryCode) } }
0
null
1
2
413c85d6213d894510cc78684287783e36eeb53b
1,565
stripe-android
MIT License
app/src/main/java/com/example/weatherens/data/remote/model/main/ApiCurrentWeather.kt
akrnch
338,175,865
false
null
package com.example.weatherens.data.remote.model.main import com.example.weatherens.data.local.WeatherEntity import com.example.weatherens.data.remote.model.ApiLocation import com.example.weatherens.data.remote.model.ApiWeather import com.google.gson.annotations.SerializedName data class ApiCurrentWeather ( @SerializedName("location") val apiLocation : ApiLocation, @SerializedName("current") val current : ApiWeather ) { fun toRoom(): WeatherEntity { return WeatherEntity(null, apiLocation.name, current.lastUpdatedEpoch, apiLocation.lat, apiLocation.lon, current.isDay, current.tempC, current.tempF, current.condition.icon, current.condition.text, current.windKph, current.windMph, current.precipMm, current.precipIn, current.humidity) } }
0
Kotlin
0
1
293a566b90fcd205201706bf16c7f2ab8bfd8b5a
938
weatherens
Apache License 2.0
src/main/kotlin/io/goauthentik/api/models/TokenModel.kt
goauthentik
687,459,450
false
{"Kotlin": 3862001, "Go": 1227, "Makefile": 859}
/** * authentik * * Making authentication simple. * * The version of the OpenAPI document: 2023.8.3 * Contact: <EMAIL> * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package io.goauthentik.api.models import io.goauthentik.api.models.OAuth2Provider import io.goauthentik.api.models.User import com.squareup.moshi.Json /** * Serializer for BaseGrantModel and ExpiringBaseGrant * * @param pk * @param provider * @param user * @param isExpired Check if token is expired yet. * @param scope * @param expires */ data class ExpiringBaseGrantModel ( @Json(name = "pk") val pk: kotlin.Int, @Json(name = "provider") val provider: OAuth2Provider, @Json(name = "user") val user: User, /* Check if token is expired yet. */ @Json(name = "is_expired") val isExpired: kotlin.Boolean, @Json(name = "scope") val scope: kotlin.collections.List<kotlin.String>, @Json(name = "expires") val expires: java.time.OffsetDateTime? = null )
1
Kotlin
0
0
e154ce74126d3e0c94e1e2583f45396f531d1187
1,215
client-kotlin
Info-ZIP License
backend/src/main/kotlin/at/ac/tuwien/waecm/ss18/group09/BackendApplication.kt
fuvidani
125,189,492
false
null
package at.ac.tuwien.waecm.ss18.group09 import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication /** * <h4>About this class</h4> * * <p>Description</p> * * @author <NAME> * @version 1.0.0 * @since 1.0.0 */ @SpringBootApplication class BackendApplication { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(BackendApplication::class.java, *args) } } }
0
Kotlin
3
2
46edad80694a5238715c99afed463a49e02732b4
501
web-app-engineering
MIT License
src/test/resources/examples/externalReferences/aggressive/models/ClientModels.kt
cjbooms
229,844,927
false
{"Kotlin": 874094, "Handlebars": 4874}
package examples.externalReferences.aggressive.models import com.fasterxml.jackson.`annotation`.JsonAnyGetter import com.fasterxml.jackson.`annotation`.JsonAnySetter import com.fasterxml.jackson.`annotation`.JsonIgnore import com.fasterxml.jackson.`annotation`.JsonProperty import com.fasterxml.jackson.`annotation`.JsonSubTypes import com.fasterxml.jackson.`annotation`.JsonTypeInfo import com.fasterxml.jackson.`annotation`.JsonValue import javax.validation.Valid import javax.validation.constraints.NotNull import kotlin.String import kotlin.collections.List import kotlin.collections.Map import kotlin.collections.MutableMap public data class ConflictingSchemaName( @param:JsonProperty("conflictsInMainSpecFile") @get:JsonProperty("conflictsInMainSpecFile") @get:NotNull public val conflictsInMainSpecFile: String, ) public data class ConflictingSchemaNameExtra( @param:JsonProperty("conflictsInExternalSpecFile") @get:JsonProperty("conflictsInExternalSpecFile") @get:NotNull public val conflictsInExternalSpecFile: String, ) public data class ContainingExternalReference( @param:JsonProperty("some-external-reference") @get:JsonProperty("some-external-reference") @get:Valid public val someExternalReference: ExternalObject? = null, @param:JsonProperty("inlineObject") @get:JsonProperty("inlineObject") @get:Valid public val inlineObject: FirstInlineObject? = null, ) public data class ExternalObject( @param:JsonProperty("another") @get:JsonProperty("another") @get:Valid public val another: ExternalObjectTwo? = null, @param:JsonProperty("one_of") @get:JsonProperty("one_of") @get:Valid public val oneOf: ParentOneOf? = null, @param:JsonProperty("anotherExternal") @get:JsonProperty("anotherExternal") @get:Valid public val anotherExternal: ReferencedFromOtherExternalFile? = null, @param:JsonProperty("conflicting") @get:JsonProperty("conflicting") @get:Valid public val conflicting: ConflictingSchemaNameExtra? = null, ) public data class ExternalObjectFour( @param:JsonProperty("blah") @get:JsonProperty("blah") public val blah: String? = null, ) public data class ExternalObjectThree( @param:JsonProperty("enum") @get:JsonProperty("enum") @get:NotNull public val `enum`: ExternalObjectThreeEnum, @param:JsonProperty("description") @get:JsonProperty("description") @get:NotNull public val description: String, ) public enum class ExternalObjectThreeEnum( @JsonValue public val `value`: String, ) { ONE("one"), TWO("two"), THREE("three"), ; public companion object { private val mapping: Map<String, ExternalObjectThreeEnum> = values().associateBy(ExternalObjectThreeEnum::value) public fun fromValue(`value`: String): ExternalObjectThreeEnum? = mapping[value] } } public data class ExternalObjectTwo( @param:JsonProperty("list-others") @get:JsonProperty("list-others") @get:Valid public val listOthers: List<ExternalObjectThree>? = null, @get:JsonIgnore public val properties: MutableMap<String, Map<String, ExternalObjectFour>> = mutableMapOf(), ) { @JsonAnyGetter public fun `get`(): Map<String, Map<String, ExternalObjectFour>> = properties @JsonAnySetter public fun `set`(name: String, `value`: Map<String, ExternalObjectFour>) { properties[name] = value } } public enum class ExternalParameter( @JsonValue public val `value`: String, ) { ONE("ONE"), TWO("TWO"), THREE("THREE"), ; public companion object { private val mapping: Map<String, ExternalParameter> = values().associateBy(ExternalParameter::value) public fun fromValue(`value`: String): ExternalParameter? = mapping[value] } } public data class FirstInlineObject( @param:JsonProperty("generation") @get:JsonProperty("generation") @get:Valid public val generation: FirstInlineObjectGeneration? = null, ) public data class FirstInlineObjectCallHome( @param:JsonProperty("url") @get:JsonProperty("url") @get:NotNull public val url: String, ) public data class FirstInlineObjectDatabaseView( @param:JsonProperty("view_name") @get:JsonProperty("view_name") @get:NotNull public val viewName: String, ) public data class FirstInlineObjectGeneration( @param:JsonProperty("call_home") @get:JsonProperty("call_home") @get:Valid public val callHome: FirstInlineObjectCallHome? = null, @param:JsonProperty("database_view") @get:JsonProperty("database_view") @get:Valid public val databaseView: FirstInlineObjectDatabaseView? = null, @param:JsonProperty("direct") @get:JsonProperty("direct") public val direct: String? = null, @param:JsonProperty("externalInlineObject") @get:JsonProperty("externalInlineObject") @get:Valid public val externalInlineObject: SecondInlineObject? = null, ) public data class OneOfOne( @param:JsonProperty("oneOfOne") @get:JsonProperty("oneOfOne") public val oneOfOne: String? = null, @get:JsonProperty("discriminator") @get:NotNull @param:JsonProperty("discriminator") override val discriminator: String = "OneOfOne", ) : ParentOneOf() public data class OneOfTwo( @param:JsonProperty("oneOfTwo") @get:JsonProperty("oneOfTwo") public val oneOfTwo: String? = null, @get:JsonProperty("discriminator") @get:NotNull @param:JsonProperty("discriminator") override val discriminator: String = "OneOfTwo", ) : ParentOneOf() @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "discriminator", visible = true, ) @JsonSubTypes( JsonSubTypes.Type(value = OneOfOne::class, name = "OneOfOne"), JsonSubTypes.Type( value = OneOfTwo::class, name = "OneOfTwo", ), ) public sealed class ParentOneOf() { public abstract val discriminator: String } public data class ReferencedFromOtherExternalFile( @param:JsonProperty("another") @get:JsonProperty("another") public val another: String? = null, ) public data class SecondInlineObject( @param:JsonProperty("generation") @get:JsonProperty("generation") @get:Valid public val generation: SecondInlineObjectGeneration? = null, ) public data class SecondInlineObjectCallHome( @param:JsonProperty("url") @get:JsonProperty("url") @get:NotNull public val url: String, ) public data class SecondInlineObjectDatabaseView( @param:JsonProperty("view_name") @get:JsonProperty("view_name") @get:NotNull public val viewName: String, ) public data class SecondInlineObjectGeneration( @param:JsonProperty("call_home") @get:JsonProperty("call_home") @get:Valid public val callHome: SecondInlineObjectCallHome? = null, @param:JsonProperty("database_view") @get:JsonProperty("database_view") @get:Valid public val databaseView: SecondInlineObjectDatabaseView? = null, @param:JsonProperty("direct") @get:JsonProperty("direct") public val direct: String? = null, ) public data class UnreferencedExternalObjectFive( @param:JsonProperty("blah") @get:JsonProperty("blah") public val blah: String? = null, )
33
Kotlin
41
154
b95cb5bd8bb81e59eca71e467118cd61a1848b3f
7,358
fabrikt
Apache License 2.0
Jetsurvey/app/src/main/java/com/example/compose/jetsurvey/signinsignup/UserRepository.kt
android
211,288,349
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.compose.jetsurvey.signinsignup import androidx.compose.runtime.Immutable sealed class User { @Immutable data class LoggedInUser(val email: String) : User() object GuestUser : User() object NoUserLoggedIn : User() } /** * Repository that holds the logged in user. * * In a production app, this class would also handle the communication with the backend for * sign in and sign up. */ object UserRepository { private var _user: User = User.NoUserLoggedIn val user: User get() = _user @Suppress("UNUSED_PARAMETER") fun signIn(email: String, password: String) { _user = User.LoggedInUser(email) } @Suppress("UNUSED_PARAMETER") fun signUp(email: String, password: String) { _user = User.LoggedInUser(email) } fun signInAsGuest() { _user = User.GuestUser } fun isKnownUserEmail(email: String): Boolean { // if the email contains "sign up" we consider it unknown return !email.contains("signup") } }
66
null
4
9,752
82e5bf054680503726fd8a80039606d80a51bca8
1,654
compose-samples
Apache License 2.0
kase/src/main/kotlin/com/rickbusarow/kase/overloads/Kase10.kt
rickbusarow
692,975,358
false
{"Kotlin": 1086813, "Shell": 4276}
/* * Copyright (C) 2023 <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress( "DestructuringDeclarationWithTooManyEntries", "DuplicatedCode", "MaxLineLength", "PackageDirectoryMismatch" ) @file:JvmMultifileClass @file:JvmName("KasesKt") package com.rickbusarow.kase import com.rickbusarow.kase.files.TestFunctionCoordinates import com.rickbusarow.kase.internal.KaseInternal import dev.drewhamilton.poko.Poko import org.junit.jupiter.api.DynamicNode import org.junit.jupiter.api.DynamicTest import java.util.stream.Stream /** * A strongly typed version of [Kase] for 10 parameters. * * @since 0.1.0 */ public interface Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> : Kase9<A1, A2, A3, A4, A5, A6, A7, A8, A9> { /** The 10th parameter. */ public val a10: A10 /** @see Kase10.a10 */ public operator fun component10(): A10 = a10 } @Poko @PublishedApi internal class DefaultKase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>( override val a1: A1, override val a2: A2, override val a3: A3, override val a4: A4, override val a5: A5, override val a6: A6, override val a7: A7, override val a8: A8, override val a9: A9, override val a10: A10, private val displayNameFactory: KaseDisplayNameFactory<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> ) : Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>, KaseInternal { override val displayName: String by lazy(LazyThreadSafetyMode.NONE) { with(displayNameFactory) { createDisplayName() } } override operator fun component1(): A1 = a1 override operator fun component2(): A2 = a2 override operator fun component3(): A3 = a3 override operator fun component4(): A4 = a4 override operator fun component5(): A5 = a5 override operator fun component6(): A6 = a6 override operator fun component7(): A7 = a7 override operator fun component8(): A8 = a8 override operator fun component9(): A9 = a9 override operator fun component10(): A10 = a10 } private fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> defaultKase10DisplayNameFactory(): KaseDisplayNameFactory<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> { return KaseDisplayNameFactory { "a1: $a1 | a2: $a2 | a3: $a3 | a4: $a4 | a5: $a5 | a6: $a6 | a7: $a7 | a8: $a8 | a9: $a9 | a10: $a10" } } /** * Creates a new [Kase] with the given parameters. * * @param a1 the [Kase10.a1] parameter. * @param a2 the [Kase10.a2] parameter. * @param a3 the [Kase10.a3] parameter. * @param a4 the [Kase10.a4] parameter. * @param a5 the [Kase10.a5] parameter. * @param a6 the [Kase10.a6] parameter. * @param a7 the [Kase10.a7] parameter. * @param a8 the [Kase10.a8] parameter. * @param a9 the [Kase10.a9] parameter. * @param a10 the [Kase10.a10] parameter. * @param displayNameFactory defines the name used in test environments and dynamic tests * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> kase( a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, displayNameFactory: KaseDisplayNameFactory<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> = defaultKase10DisplayNameFactory() ): Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> = DefaultKase10( a1 = a1, a2 = a2, a3 = a3, a4 = a4, a5 = a5, a6 = a6, a7 = a7, a8 = a8, a9 = a9, a10 = a10, displayNameFactory = displayNameFactory ) /** * Creates a new [Kase] with the given parameters. * * @param displayName the name used in test environments and dynamic tests * @param a1 the [Kase10.a1] parameter. * @param a2 the [Kase10.a2] parameter. * @param a3 the [Kase10.a3] parameter. * @param a4 the [Kase10.a4] parameter. * @param a5 the [Kase10.a5] parameter. * @param a6 the [Kase10.a6] parameter. * @param a7 the [Kase10.a7] parameter. * @param a8 the [Kase10.a8] parameter. * @param a9 the [Kase10.a9] parameter. * @param a10 the [Kase10.a10] parameter. * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> kase( displayName: String, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10 ): Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> = DefaultKase10( a1 = a1, a2 = a2, a3 = a3, a4 = a4, a5 = a5, a6 = a6, a7 = a7, a8 = a8, a9 = a9, a10 = a10, displayNameFactory = { displayName } ) /** * Returns a list of [Kase10]s from the given parameters. * * @param args1 values mapped to the [Kase10.a1] parameter. * @param args2 values mapped to the [Kase10.a2] parameter. * @param args3 values mapped to the [Kase10.a3] parameter. * @param args4 values mapped to the [Kase10.a4] parameter. * @param args5 values mapped to the [Kase10.a5] parameter. * @param args6 values mapped to the [Kase10.a6] parameter. * @param args7 values mapped to the [Kase10.a7] parameter. * @param args8 values mapped to the [Kase10.a8] parameter. * @param args9 values mapped to the [Kase10.a9] parameter. * @param args10 values mapped to the [Kase10.a10] parameter. * @param displayNameFactory defines the name used in test environments and dynamic tests * @return a list of [Kase10]s from the given parameters. * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> kases( args1: Iterable<A1>, args2: Iterable<A2>, args3: Iterable<A3>, args4: Iterable<A4>, args5: Iterable<A5>, args6: Iterable<A6>, args7: Iterable<A7>, args8: Iterable<A8>, args9: Iterable<A9>, args10: Iterable<A10>, displayNameFactory: KaseDisplayNameFactory<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> = defaultKase10DisplayNameFactory() ): List<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> { return buildList { for (a1 in args1) { for (a2 in args2) { for (a3 in args3) { for (a4 in args4) { for (a5 in args5) { for (a6 in args6) { for (a7 in args7) { for (a8 in args8) { for (a9 in args9) { for (a10 in args10) { add(kase(a1 = a1, a2 = a2, a3 = a3, a4 = a4, a5 = a5, a6 = a6, a7 = a7, a8 = a8, a9 = a9, a10 = a10, displayNameFactory = displayNameFactory)) } } } } } } } } } } } } /** * Returns a sequence of [Kase10]s from the given parameters. * * @param args1 values mapped to the [Kase10.a1] parameter. * @param args2 values mapped to the [Kase10.a2] parameter. * @param args3 values mapped to the [Kase10.a3] parameter. * @param args4 values mapped to the [Kase10.a4] parameter. * @param args5 values mapped to the [Kase10.a5] parameter. * @param args6 values mapped to the [Kase10.a6] parameter. * @param args7 values mapped to the [Kase10.a7] parameter. * @param args8 values mapped to the [Kase10.a8] parameter. * @param args9 values mapped to the [Kase10.a9] parameter. * @param args10 values mapped to the [Kase10.a10] parameter. * @param displayNameFactory defines the name used in test environments and dynamic tests * @return a sequence of [Kase10]s from the given parameters. * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> kases( args1: Sequence<A1>, args2: Sequence<A2>, args3: Sequence<A3>, args4: Sequence<A4>, args5: Sequence<A5>, args6: Sequence<A6>, args7: Sequence<A7>, args8: Sequence<A8>, args9: Sequence<A9>, args10: Sequence<A10>, displayNameFactory: KaseDisplayNameFactory<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> = defaultKase10DisplayNameFactory() ): Sequence<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> { return sequence { for (a1 in args1) { for (a2 in args2) { for (a3 in args3) { for (a4 in args4) { for (a5 in args5) { for (a6 in args6) { for (a7 in args7) { for (a8 in args8) { for (a9 in args9) { for (a10 in args10) { yield(kase(a1 = a1, a2 = a2, a3 = a3, a4 = a4, a5 = a5, a6 = a6, a7 = a7, a8 = a8, a9 = a9, a10 = a10, displayNameFactory = displayNameFactory)) } } } } } } } } } } } } /** * Creates a new [Kase10] instance and [TestEnvironment] * from these parameters, then executes [testAction]. * * @param a1 the [Kase10.a1] parameter. * @param a2 the [Kase10.a2] parameter. * @param a3 the [Kase10.a3] parameter. * @param a4 the [Kase10.a4] parameter. * @param a5 the [Kase10.a5] parameter. * @param a6 the [Kase10.a6] parameter. * @param a7 the [Kase10.a7] parameter. * @param a8 the [Kase10.a8] parameter. * @param a9 the [Kase10.a9] parameter. * @param a10 the [Kase10.a10] parameter. * @param displayNameFactory defines the name used for this test environment's working directory * @param testFunctionCoordinates the [TestFunctionCoordinates] from which the test is being run. * @param testAction the test action to execute. * @see KaseTestFactory * @since 0.1.0 */ public fun <T: TestEnvironment, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> KaseTestFactory<T, Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.test( a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, displayNameFactory: KaseDisplayNameFactory<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>> = defaultKase10DisplayNameFactory(), testFunctionCoordinates: TestFunctionCoordinates = TestFunctionCoordinates.get(), testAction: suspend T.() -> Unit ) { this@KaseTestFactory.test( kase = kase(a1 = a1, a2 = a2, a3 = a3, a4 = a4, a5 = a5, a6 = a6, a7 = a7, a8 = a8, a9 = a9, a10 = a10, displayNameFactory = displayNameFactory), testFunctionCoordinates = testFunctionCoordinates, testAction = testAction ) } /** * Creates a [Stream] of [DynamicNode]s from this [Iterable] of [Kase10]s. * * @param testAction the test action to run for each kase. * @return a [Stream] of [DynamicNode]s from these kases. * @see Kase10 * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.asTests( testAction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10) -> Unit ): Stream<out DynamicNode> { return testFactory { this@asTests.asTests { testAction(it.a1, it.a2, it.a3, it.a4, it.a5, it.a6, it.a7, it.a8, it.a9, it.a10) } } } /** * A test factory which returns a stream of [DynamicNode]s from the given parameters. * - Each [DynamicTest] in the stream uses its [Kase10] element to create * a new [TestEnvironment] instance, then executes [testAction]. * - Each [DynamicNode] has a display name which includes the values of the parameters. * * @param kases the [Kase10]s to use for this test factory * @param testAction the test action to execute. * @return a [Stream] of [DynamicNode]s from the given parameters. * @see Kase10 * @see TestEnvironmentFactory * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> testFactory( vararg kases: Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>, testAction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10) -> Unit ): Stream<out DynamicNode> { return testFactory { kases.asSequence().asTests { testAction(it.a1, it.a2, it.a3, it.a4, it.a5, it.a6, it.a7, it.a8, it.a9, it.a10) } } } /** * A test factory which returns a stream of [DynamicNode]s from the given parameters. * - Each [DynamicTest] in the stream uses its [Kase10] element to create * a new [TestEnvironment] instance, then executes [testAction]. * - Each [DynamicNode] has a display name which includes the values of the parameters. * * @param kases the [Kase10]s to use for this test factory * @param testAction the test action to execute. * @return a [Stream] of [DynamicNode]s from the given parameters. * @see Kase10 * @see TestEnvironmentFactory * @since 0.1.0 */ public fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> testFactory( kases: Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>, testAction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10) -> Unit ): Stream<out DynamicNode> { return testFactory { kases.asTests { testAction(it.a1, it.a2, it.a3, it.a4, it.a5, it.a6, it.a7, it.a8, it.a9, it.a10) } } } /** * @param others the [Kase1] to combine with this [Kase10] * @return a list of [Kase11]s from the cartesian product of this [Kase10] and the given [Kase1]. * @since 0.1.0 */ @JvmName("kase10timesKase1") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase1<B1>> ): List<Kase11<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1) } } /** * @param others the [Kase2] to combine with this [Kase10] * @return a list of [Kase12]s from the cartesian product of this [Kase10] and the given [Kase2]. * @since 0.1.0 */ @JvmName("kase10timesKase2") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase2<B1, B2>> ): List<Kase12<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2) } } /** * @param others the [Kase3] to combine with this [Kase10] * @return a list of [Kase13]s from the cartesian product of this [Kase10] and the given [Kase3]. * @since 0.1.0 */ @JvmName("kase10timesKase3") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase3<B1, B2, B3>> ): List<Kase13<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3) } } /** * @param others the [Kase4] to combine with this [Kase10] * @return a list of [Kase14]s from the cartesian product of this [Kase10] and the given [Kase4]. * @since 0.1.0 */ @JvmName("kase10timesKase4") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase4<B1, B2, B3, B4>> ): List<Kase14<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4) } } /** * @param others the [Kase5] to combine with this [Kase10] * @return a list of [Kase15]s from the cartesian product of this [Kase10] and the given [Kase5]. * @since 0.1.0 */ @JvmName("kase10timesKase5") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase5<B1, B2, B3, B4, B5>> ): List<Kase15<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5) } } /** * @param others the [Kase6] to combine with this [Kase10] * @return a list of [Kase16]s from the cartesian product of this [Kase10] and the given [Kase6]. * @since 0.1.0 */ @JvmName("kase10timesKase6") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase6<B1, B2, B3, B4, B5, B6>> ): List<Kase16<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6) } } /** * @param others the [Kase7] to combine with this [Kase10] * @return a list of [Kase17]s from the cartesian product of this [Kase10] and the given [Kase7]. * @since 0.1.0 */ @JvmName("kase10timesKase7") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase7<B1, B2, B3, B4, B5, B6, B7>> ): List<Kase17<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6, b7) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6, b7) } } /** * @param others the [Kase8] to combine with this [Kase10] * @return a list of [Kase18]s from the cartesian product of this [Kase10] and the given [Kase8]. * @since 0.1.0 */ @JvmName("kase10timesKase8") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase8<B1, B2, B3, B4, B5, B6, B7, B8>> ): List<Kase18<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6, b7, b8) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6, b7, b8) } } /** * @param others the [Kase9] to combine with this [Kase10] * @return a list of [Kase19]s from the cartesian product of this [Kase10] and the given [Kase9]. * @since 0.1.0 */ @JvmName("kase10timesKase9") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase9<B1, B2, B3, B4, B5, B6, B7, B8, B9>> ): List<Kase19<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6, b7, b8, b9) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6, b7, b8, b9) } } /** * @param others the [Kase10] to combine with this [Kase10] * @return a list of [Kase20]s from the cartesian product of this [Kase10] and the given [Kase10]. * @since 0.1.0 */ @JvmName("kase10timesKase10") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase10<B1, B2, B3, B4, B5, B6, B7, B8, B9, B10>> ): List<Kase20<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6, b7, b8, b9, b10) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10) } } /** * @param others the [Kase11] to combine with this [Kase10] * @return a list of [Kase21]s from the cartesian product of this [Kase10] and the given [Kase11]. * @since 0.1.0 */ @JvmName("kase10timesKase11") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase11<B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11>> ): List<Kase21<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11) } } /** * @param others the [Kase12] to combine with this [Kase10] * @return a list of [Kase22]s from the cartesian product of this [Kase10] and the given [Kase12]. * @since 0.1.0 */ @JvmName("kase10timesKase12") public operator fun <A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12> Iterable<Kase10<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>>.times( others: Iterable<Kase12<B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12>> ): List<Kase22<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12>> = flatMap { (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) -> others.map { (b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12) -> kase(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12) } }
1
Kotlin
0
0
dd8ec55bc3e52932739cd1e5a526fcc3821fa410
21,117
kase
Apache License 2.0
app/src/main/java/io/github/bkmioa/nexusrss/model/Item.kt
bkmioa
100,779,791
false
null
package io.github.bkmioa.nexusrss.model import io.github.bkmioa.nexusrss.Settings import org.simpleframework.xml.Attribute import org.simpleframework.xml.Element import org.simpleframework.xml.Root import java.io.Serializable @Root(strict = false) class Item : Serializable { companion object { private val IGNORED_IMAGE_PATTERN = arrayOf( "pic/trans\\.gif" , "pic/smilies/" ).joinToString("|").toRegex() } @set:Element(name = "title", required = false) @get:Element(name = "title", required = false) var originTitle: String? = null set(value) { if (value != null) { subTitle = Regex("\\[([^\\]].*)\\]").find(value)?.groupValues?.get(1) title = value.removeSuffix("[$subTitle]") } } get var title: String? = null var subTitle: String? = null @field:Element(required = false) lateinit var link: String @field:Element(required = false) lateinit var pubDate: String @field:Element(required = false) lateinit var description: String @field:Element(required = false) lateinit var author: String @field:Element(required = false) lateinit var guid: String @field:Element(required = false) var enclosure: Data? = null @field:Element(required = false) lateinit var category: String @field:Element(required = false) lateinit var comments: String val imageUrl: String? by lazy { resolveImageUrl() } private fun resolveImageUrl(): String? { var url = Regex("<img[^>]+src=\"([^\">]+)\"").findAll(description) .map { it.groupValues[1] } .find { !it.contains(IGNORED_IMAGE_PATTERN) } if (url != null && !url.startsWith("http")) { url = Settings.BASE_URL + "/" + url } return url } @Root class Data : Serializable { @field:Attribute(required = false) var length: Long? = null @field:Attribute(required = false) var type: String? = null @field:Attribute(required = false) var url: String? = null } }
0
Kotlin
1
6
94e1a1dd14daa8a4a3bc03b8f01e0ba31af90d3c
2,169
NexusRss
Apache License 2.0
app/src/main/java/uk/co/alt236/bluetoothconnectionlog/ui/detail/recycler/LogRecyclerAdapter.kt
alt236
196,390,058
false
null
package uk.co.alt236.bluetoothconnectionlog.ui.detail.recycler import android.view.LayoutInflater import android.view.ViewGroup import androidx.fragment.app.FragmentActivity import androidx.recyclerview.widget.RecyclerView import uk.co.alt236.bluetoothconnectionlog.db.entities.LogEntry import uk.co.alt236.bluetoothconnectionlog.ui.navigation.Navigator class LogRecyclerAdapter(parentActivity: FragmentActivity, navigator: Navigator) : RecyclerView.Adapter<ViewHolder>() { private val binder = ViewHolderBinder(parentActivity, navigator) private var data: List<LogEntry> = ArrayList() fun setData(data: List<LogEntry>) { this.data = data notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(ViewHolder.LAYOUT_ID, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = data[position] binder.onBindViewHolder(holder, item) } override fun getItemCount() = data.size }
0
Kotlin
2
1
51c7f8cbd70165ba089d469a0901fe472d71f3d4
1,131
bluetooth-connection-log
Apache License 2.0
http4k-core/src/testFixtures/kotlin/org/http4k/routing/RoutingHttpHandlerContract.kt
http4k
86,003,479
false
null
package org.http4k.routing import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.present import org.http4k.core.Filter import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.Status.Companion.OK import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasHeader import org.http4k.hamkrest.hasStatus import org.junit.jupiter.api.Test abstract class RoutingHttpHandlerContract { protected val validPath = "/route-contract" protected val prefix = "/prefix" private val prePrefix = "/pre-prefix" abstract val handler: RoutingHttpHandler open val expectedNotFoundBody = "" @Test fun `matches a particular route`() { val criteria = hasStatus(OK) assertThat(handler.matchAndInvoke(Request(GET, validPath)), present(criteria)) assertThat(handler(Request(GET, validPath)), criteria) } @Test open fun `does not match a particular route`() { assertThat(handler.matchAndInvoke(Request(GET, "/not-found")), absent()) assertThat(handler(Request(GET, "/not-found")), hasStatus(NOT_FOUND) and hasBody(expectedNotFoundBody)) } @Test fun `with filter - applies to matching handler`() { val filtered = handler.withFilter(filterAppending("bar")) val criteria = hasStatus(OK) and hasHeader("res-header", "bar") val request = Request(GET, validPath) assertThat(filtered.matchAndInvoke(request), present(criteria)) assertThat(filtered(request), criteria) } @Test open fun `with filter - applies when not found`() { val filtered = handler.withFilter(filterAppending("foo")) val request = Request(GET, "/not-found") assertThat(filtered.matchAndInvoke(request), absent()) assertThat(filtered(request), hasStatus(NOT_FOUND) and hasHeader("res-header", "foo") and hasBody(expectedNotFoundBody)) } @Test open fun `with filter - applies in correct order`() { val filtered = handler.withFilter(filterAppending("foo")).withFilter(filterAppending("bar")) val request = Request(GET, "/not-found") assertThat(filtered.matchAndInvoke(request), absent()) assertThat(filtered(request), hasStatus(NOT_FOUND) and hasHeader("res-header", "foobar")) } @Test fun `with base path - matches`() { val withBase = handler.withBasePath(prefix) val request = Request(GET, "$prefix$validPath") val criteria = hasStatus(OK) assertThat(withBase.matchAndInvoke(request), present(criteria)) assertThat(withBase(request), criteria) } @Test open fun `with base path - no longer matches original`() { val withBase = handler.withBasePath(prefix) val request = Request(GET, validPath) assertThat(withBase.matchAndInvoke(request), absent()) assertThat(withBase(request), hasStatus(NOT_FOUND)) } @Test fun `with base path - multiple levels`() { val withBase = handler.withBasePath(prefix).withBasePath(prePrefix) val request = Request(GET, "$prePrefix$prefix$validPath") val criteria = hasStatus(OK) assertThat(withBase.matchAndInvoke(request), present(criteria)) assertThat(withBase(request), criteria) } protected fun RoutingHttpHandler.matchAndInvoke(request: Request) = match(request)?.invoke(request) protected fun filterAppending(value: String) = Filter { next -> { val response = next(it) response.replaceHeader("res-header", response.header("res-header").orEmpty() + value) } } }
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
3,752
http4k
Apache License 2.0
src/main/kotlin/anissia/domain/session/service/DoTokenLogin.kt
anissia-net
319,510,882
false
{"Kotlin": 248254, "HTML": 5480, "HCL": 794}
package anissia.domain.session.service import anissia.domain.session.model.DoTokenLoginCommand import anissia.domain.session.model.LoginInfoItem import anissia.domain.session.model.Session import anissia.shared.ResultWrapper interface DoTokenLogin { fun handle(cmd: DoTokenLoginCommand, session: Session): ResultWrapper<LoginInfoItem> }
3
Kotlin
4
13
7266b0843f631ef0d4b154802cf83e42a2309a99
343
anissia-core
Creative Commons Attribution 4.0 International
src/main/kotlin/com/hmlr/api/Server.kt
LandRegistry
167,032,293
false
null
package com.hmlr.api import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import kotlin.concurrent.thread /** * Our Spring Boot application. */ @SpringBootApplication open class Server /** * Starts our Spring Boot application. */ fun main(args: Array<String>) { //Check required env vars exist require(System.getenv("CONFIG_RPC_HOST") != null) { "CONFIG_RPC_HOST env var was not set." } require(System.getenv("CONFIG_RPC_PORT") != null) { "CONFIG_RPC_PORT env var was not set." } require(System.getenv("CONFIG_RPC_USERNAME") != null) { "CONFIG_RPC_USERNAME env var was not set." } require(System.getenv("CONFIG_RPC_PASSWORD") != null) { "CONFIG_RPC_PASSWORD env var was not set." } require(System.getenv("LENDER_MANAGEMENT_API_URL") != null) { "LENDER_MANAGEMENT_API_URL env var was not set." } //Run main api thread(start=true, name="API") { SpringApplication.run(Server::class.java, *args) } }
0
Kotlin
3
0
3849cdb402a01bbaa3bf34710646e51ee2325d0e
1,013
digital-street-lender-api
MIT License
nlp/front/storage-mongo/target/generated-sources/kapt/compile/fr/vsct/tock/nlp/front/shared/build/ModelBuild_Deserializer.kt
cooksane
151,793,390
true
{"Kotlin": 2507910, "TypeScript": 358055, "HTML": 140949, "CSS": 33484, "JavaScript": 5174, "Shell": 1591}
package fr.vsct.tock.nlp.front.shared.build import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.deser.std.StdDeserializer import com.fasterxml.jackson.databind.module.SimpleModule import fr.vsct.tock.nlp.front.shared.config.ApplicationDefinition import fr.vsct.tock.nlp.front.shared.config.IntentDefinition import java.time.Duration import java.time.Instant import java.util.Locale import kotlin.Boolean import kotlin.Int import kotlin.String import org.litote.jackson.JacksonModuleServiceLoader import org.litote.kmongo.Id class ModelBuild_Deserializer : StdDeserializer<ModelBuild>(ModelBuild::class.java), JacksonModuleServiceLoader { override fun module() = SimpleModule().addDeserializer(ModelBuild::class.java, this) override fun deserialize(p: JsonParser, ctxt: DeserializationContext): ModelBuild { with(p) { var applicationId: Id<ApplicationDefinition>? = null var language: Locale? = null var type: ModelBuildType? = null var intentId: Id<IntentDefinition>? = null var entityTypeName: String? = null var nbSentences: Int? = null var duration: Duration? = null var error: Boolean? = null var errorMessage: String? = null var date: Instant? = null while (currentToken != JsonToken.END_OBJECT && currentToken != JsonToken.END_ARRAY) { nextToken() if (currentToken == JsonToken.END_OBJECT || currentToken == JsonToken.END_ARRAY) { break } val fieldName = currentName nextToken() if(currentToken != JsonToken.VALUE_NULL) when (fieldName) { "applicationId" -> applicationId = p.readValueAs(applicationId_reference) "language" -> language = p.readValueAs(Locale::class.java) "type" -> type = p.readValueAs(ModelBuildType::class.java) "intentId" -> intentId = p.readValueAs(intentId_reference) "entityTypeName" -> entityTypeName = p.text "nbSentences" -> nbSentences = p.readValueAs(Int::class.java) "duration" -> duration = p.readValueAs(Duration::class.java) "error" -> error = p.readValueAs(Boolean::class.java) "errorMessage" -> errorMessage = p.text "date" -> date = p.readValueAs(Instant::class.java) else -> if (currentToken == JsonToken.END_OBJECT || currentToken == JsonToken.END_ARRAY) { p.skipChildren() } else { nextToken() } } } return ModelBuild(applicationId!!, language!!, type!!, intentId, entityTypeName, nbSentences!!, duration!!, error!!, errorMessage, date!!) } } companion object { val applicationId_reference: TypeReference<Id<ApplicationDefinition>> = object : TypeReference<Id<ApplicationDefinition>>() {} val intentId_reference: TypeReference<Id<IntentDefinition>> = object : TypeReference<Id<IntentDefinition>>() {} } }
0
Kotlin
0
0
cd5c55e99cda91b5f7d790503de88137d3a3cc3c
3,079
tock
Apache License 2.0
juice/protocol/src/main/kotlin/com/linecorp/sample/juice/protocol/Juice.kt
yuinacor
250,445,765
true
{"Kotlin": 11744}
package com.linecorp.sample.juice.protocol data class Juice(val name: String)
0
null
0
0
874abe4e4703ab65ce52c5ce0f4c84b0063e4384
79
gradle-multi-project-support-sample
Freetype Project License
app/src/main/java/com/example/motionlayout/LeftToRightAnimationActivity.kt
saeed-younus
194,558,077
false
null
package com.example.motionlayout import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_left_to_right_animation.* class LeftToRightAnimationActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_left_to_right_animation) var isTransitionToEnd = false btn_animate.setOnClickListener { if(!isTransitionToEnd) { isTransitionToEnd = true motion_layout.transitionToEnd() } else { isTransitionToEnd = false motion_layout.transitionToStart() } } } }
0
Kotlin
9
87
06a226155228a5bda0838c36f7dc09ed50261a35
759
motion-layout-examples
Apache License 2.0
app/src/main/java/br/com/iesb/tarefas/TarefaAdapter.kt
matheusdepaula
128,274,126
false
null
package br.com.iesb.tarefas import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.tarefa_cell.view.* import java.text.SimpleDateFormat import java.util.* /** * Created by matheus.psousa on 05/04/2018. */ class TarefaAdapter(var listaTarefas : MutableList<Tarefa>, val onClickTarefa : (View?, Int) -> Unit) : RecyclerView.Adapter<TarefaAdapter.TarefaViewHolder>() {//, val tarefaListener: TarefaListener) : RecyclerView.Adapter<TarefaAdapter.TarefaViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TarefaViewHolder {//Inflate a XML and Return val view = LayoutInflater.from(parent?.context).inflate(R.layout.tarefa_cell, parent, false) return TarefaViewHolder(view) } override fun getItemCount(): Int {//NumberOfRows return listaTarefas.size } override fun onBindViewHolder(holder: TarefaViewHolder?, position: Int) { //CellForRowAtIndex, next onCreateViewHolder val view = holder?.itemView val tarefa = listaTarefas[position] tarefa.descricao?.let { view?.tarefaTextView?.text = it } view?.dataTextView?.text = if(tarefa.data != null) SimpleDateFormat("dd/MM/yyyy").format(tarefa.data) else "" view?.setOnClickListener(object : View.OnClickListener{ override fun onClick(p0: View?) { // tarefaListener.onClickTarefa(view, position) onClickTarefa(view, position) // val tarefa = Tarefa(view?.tarefaTextView.text.toString(), Date()) // TarefaService.cadastrarTarefa(tarefa) // Toast.makeText(this@MainActivity, teste[2].descricao, Toast.LENGTH_LONG).show() } }) } class TarefaViewHolder(view : View) : RecyclerView.ViewHolder(view) { /** * No Padrão antigo, Java, tinhamos que usar o findViewByID e setar em um atributo, mas o Kotlin encapsula essa complexidade */ } interface TarefaListener { fun onClickTarefa(view : View?, position: Int) } }
0
Kotlin
0
0
60dc75f050823fc1e485889ee320557800831807
2,180
kotlin_example_1
Apache License 2.0
formatters/src/commonMain/kotlin/lexi/JsonLogFormatter.kt
aSoft-Ltd
592,348,487
false
{"Kotlin": 36184}
package lexi class JsonLogFormatter(private val options: JsonLogFormatterOptions = JsonLogFormatterOptions()) : LogFormatter { override fun format(log: Log) = buildMap { put("level", log.level.name) put("message", log.message) if (options.source) { put("source", log.source) } if (log.status != null && options.status) { put("status", log.status.name) } if (options.verbose) { val map = log.metadata.toMutableMap() putAll(map) } }.entries.joinToString(prefix = "{${options.tab}\n", separator = ",\n", postfix = "\n}") { (key, value) -> """${options.tab}"$key": "$value"""" } }
0
Kotlin
0
0
cd3aaba761fc484cc5c5bba0dde0e19a396520e1
709
lexi
MIT License
src/main/kotlin/uk/matvey/slon/repo/RepoKit.kt
msmych
809,301,120
false
{"Kotlin": 56267}
package uk.matvey.slon.repo import uk.matvey.slon.RecordReader import uk.matvey.slon.access.AccessKit.deleteFrom import uk.matvey.slon.access.AccessKit.insertInto import uk.matvey.slon.access.AccessKit.insertReturningOne import uk.matvey.slon.access.AccessKit.insertReturning import uk.matvey.slon.access.AccessKit.insertReturningOneOrNull import uk.matvey.slon.access.AccessKit.update import uk.matvey.slon.param.Param import uk.matvey.slon.query.InsertQueryBuilder import uk.matvey.slon.query.InsertReturningQuery import uk.matvey.slon.query.Query import uk.matvey.slon.query.update.UpdateQuery import uk.matvey.slon.query.update.UpdateQueryBuilder object RepoKit { suspend fun <T> Repo.execute(query: Query<T>): T { return access { a -> a.execute(query) } } suspend fun Repo.executePlain(query: String) { access { a -> a.executePlain(query) } } suspend fun <T> Repo.query( query: String, params: List<Param> = listOf(), read: (RecordReader) -> T ): List<T> { return access { a -> a.query(query, params, read) } } suspend fun Repo.insertInto(table: String, query: InsertQueryBuilder.() -> Unit): Int { return access { a -> a.insertInto(table, query) } } suspend fun <T> Repo.insertReturning( table: String, query: InsertQueryBuilder.() -> InsertReturningQuery<T> ): List<T> { return access { a -> a.insertReturning(table, query) } } suspend fun <T> Repo.insertReturningOne( table: String, query: InsertQueryBuilder.() -> InsertReturningQuery<T> ): T { return access { a -> a.insertReturningOne(table, query) } } suspend fun <T> Repo.insertReturningOneOrNull( table: String, query: InsertQueryBuilder.() -> InsertReturningQuery<T> ): T? { return access { a -> a.insertReturningOneOrNull(table, query) } } suspend fun Repo.update(table: String, query: UpdateQueryBuilder.() -> UpdateQuery): Int { return access { a -> a.update(table, query) } } suspend fun <T> Repo.queryOne( query: String, params: List<Param> = listOf(), reader: (RecordReader) -> T ): T { return access { a -> a.queryOne(query, params, reader) } } suspend fun <T> Repo.queryOneOrNull( query: String, params: List<Param> = listOf(), reader: (RecordReader) -> T ): T? { return access { a -> a.queryOneOrNull(query, params, reader) } } suspend fun Repo.deleteFrom(table: String, where: String, params: List<Param>): Int { return access { a -> a.deleteFrom(table, where, params) } } suspend fun Repo.deleteFrom(table: String, where: String, vararg params: Param): Int { return this.deleteFrom(table, where, params.toList()) } }
0
Kotlin
0
0
20c373bbb1dd4cdbb1b8f501e734c09407c4bbb3
2,842
slon
Apache License 2.0
app/src/main/java/com/example/fit_x_logger_android/activities/MainActivity.kt
robert-solomon12
315,686,383
false
null
package com.example.fit_x_logger_android.activities import android.app.DatePickerDialog import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import com.example.fit_x_logger_android.R import com.example.fit_x_logger_android.main.MainApp import com.example.fit_x_logger_android.models.EmployeeModel import kotlinx.android.synthetic.main.activity_main.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import org.jetbrains.anko.toast import readImage import readImageFromPath import showImagePicker import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity(), AnkoLogger { var empData = EmployeeModel() lateinit var app: MainApp val IMAGE_REQUEST = 1 var edit = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) /* explicitly enabling the toolbar here upon calling the onCreate method for presenting the cancelling button here */ toolbarAdd.title = title setSupportActionBar(toolbarAdd) info("FIT-X-LOGGER App Activity started..") app = application as MainApp if (intent.hasExtra("Employee_data_edit")) { edit = true empData = intent.extras?.getParcelable<EmployeeModel>("Employee_data_edit")!! empName.setText(empData.name) empDateOfB.setText(empData.dateOfB) empEmail.setText(empData.email) empGender.setText(empData.gender) empSsNumber.setText(empData.ssNumber) empNationality.setText(empData.nationality) empJobTitle.setText(empData.jobTitle) empDataImage.setImageBitmap(readImageFromPath(this, empData.profilePic)) if (empData.profilePic != null) { chooseImage.setText(R.string.change_image) } btnAdd.setText(R.string.save_Btn) } btnAdd.setOnClickListener() { empData.name = empName.text.toString() empData.dateOfB = empDateOfB.text.toString() empData.email = empEmail.text.toString() empData.gender = empGender.text.toString() empData.ssNumber = empSsNumber.text.toString() empData.nationality = empNationality.text.toString() empData.jobTitle = empJobTitle.text.toString() if (empData.name.isEmpty()) { toast(R.string.promptInvalid_Emp) } else { if (edit) { app.empDatas.update(empData.copy()) } else { app.empDatas.create(empData.copy()) } } info(R.string.promptValid_Emp) setResult(AppCompatActivity.RESULT_OK) finish() } //event handler for Image chooseImage.setOnClickListener { showImagePicker(this, IMAGE_REQUEST) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_employeedata, menu) if (edit && menu != null) menu.getItem(0).setVisible(true) return super.onCreateOptionsMenu(menu) } //inflating the menu after cancel button is enabled override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.item_delete -> { app.empDatas.delete(empData) finish() } R.id.item_cancel -> { finish() } } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { IMAGE_REQUEST -> { if (data != null) { empData.profilePic = data.getData().toString() empDataImage.setImageBitmap(readImage(this, resultCode, data)) chooseImage.setText(R.string.change_image) } } } } }
0
Kotlin
0
1
1fec835381aeb07e394c760017f3b708492edc43
4,297
FIT-X-LOGGER-ANDROID
MIT License
src/test/kotlin/Day14Test.kt
N-Silbernagel
573,145,327
false
{"Kotlin": 118156}
package test import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class Day14Test: StringSpec ({ val testInput = "498,4 -> 498,6 -> 496,6\n" + "503,4 -> 502,4 -> 502,9 -> 494,9" "part 1 test input" { val output = Day14.part1( testInput .lines() ) output shouldBe 24 } "part 2 test input" { val output = Day14.part2( testInput .lines() ) output shouldBe 93 } })
0
Kotlin
0
0
b0d61ba950a4278a69ac1751d33bdc1263233d81
537
advent-of-code-2022
Apache License 2.0
src/commonMain/kotlin/com/dxc/ssi/agent/wallet/indy/IndyTrustee.kt
dxc-technology
259,322,339
false
{"Kotlin": 598967, "Objective-C": 537589, "Objective-C++": 442889, "C": 238203, "Ruby": 12614, "Shell": 7187, "Swift": 1114}
package com.dxc.ssi.agent.wallet.indy import com.dxc.ssi.agent.api.pluggable.wallet.Trustee import com.dxc.ssi.agent.api.pluggable.wallet.WalletHolder import com.dxc.ssi.agent.model.IdentityDetails class IndyTrustee(walletHolder: WalletHolder) : Trustee
3
Kotlin
6
5
9bede83e0358b16d6dc9459ccc2fd85541027b6c
256
ssi-mobile-sdk
Apache License 2.0
rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/RadioGroupToggleCheckedConsumer.kt
JakeWharton
32,775,739
false
null
@file:JvmName("RxRadioGroup") @file:JvmMultifileClass package com.jakewharton.rxbinding3.widget import androidx.annotation.CheckResult import android.widget.RadioGroup import io.reactivex.functions.Consumer /** * An action which sets the checked child of `view` with ID. Passing `-1` will clear * any checked view. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ @CheckResult fun RadioGroup.checked(): Consumer<in Int> { return Consumer { value -> if (value == -1) { clearCheck() } else { check(value!!) } } }
45
null
950
9,714
78f7ebdeb9dcf373abb9fc43bde838cfe2fef62a
614
RxBinding
Apache License 2.0
src/main/kotlin/ast/JsonString.kt
y9san9
673,971,849
false
null
package ast data class JsonString(val string: String) : JsonPrimitive
1
Kotlin
2
12
816319dad0f290a6f9fb7cb574ae501fecc635a6
71
kotlin-simple-json
MIT License
src/main/kotlin/ast/JsonString.kt
y9san9
673,971,849
false
null
package ast data class JsonString(val string: String) : JsonPrimitive
1
Kotlin
2
12
816319dad0f290a6f9fb7cb574ae501fecc635a6
71
kotlin-simple-json
MIT License
vector/src/main/java/im/vector/extensions/MatrixSdkExtensions.kt
LiMium
119,702,511
false
null
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ms.messageapp.extensions import org.matrix.androidsdk.MXSession import org.matrix.androidsdk.crypto.data.MXDeviceInfo import org.matrix.androidsdk.data.Room import org.matrix.androidsdk.rest.model.Event import kotlin.math.max /* ========================================================================================== * MXDeviceInfo * ========================================================================================== */ fun MXDeviceInfo.getFingerprintHumanReadable() = fingerprint() ?.chunked(4) ?.joinToString(separator = " ") /* ========================================================================================== * Room * ========================================================================================== */ /** * Helper method to retrieve the max power level contained in the room. * This value is used to indicate what is the power level value required * to be admin of the room. * * @return max power level of the current room */ fun Room?.getRoomMaxPowerLevel(): Int { if (this == null) { return 0 } var maxPowerLevel = 0 state?.powerLevels?.let { maxPowerLevel = max(it.users_default, it.users?.values?.max() ?: 0) } return maxPowerLevel } /** * Check if the user power level allows to update the room avatar. This is mainly used to * determine if camera permission must be checked or not. * * @param aSession the session * @return true if the user power level allows to update the avatar, false otherwise. */ fun Room.isPowerLevelEnoughForAvatarUpdate(aSession: MXSession?): Boolean { var canUpdateAvatarWithCamera = false if (null != aSession) { state.powerLevels?.let { val powerLevel = it.getUserPowerLevel(aSession.myUserId) // check the power level against avatar level canUpdateAvatarWithCamera = powerLevel >= it.minimumPowerLevelForSendingEventAsStateEvent(Event.EVENT_TYPE_STATE_ROOM_AVATAR) } } return canUpdateAvatarWithCamera } /* ========================================================================================== * Event * ========================================================================================== */ fun Event.getSessionId() = wireContent ?.takeIf { it.isJsonObject } ?.asJsonObject ?.get("session_id") ?.asString
13
null
4
44
09bf4c527429fe2c8283c71988efa5796dcc854b
2,981
mini-vector-android
Apache License 2.0
app/src/main/java/com/galudino/sampleuiandroid/MainActivity.kt
galudino
391,750,826
false
{"Kotlin": 2141}
/** * @file MainActivity.kt * @brief Encapsulates MainActivity class * * @author <NAME> * @date 26 Sep 2021 */ package com.galudino.sampleuiandroid import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.galudino.sampleuiandroid.databinding.ActivityMainBinding /** * @class MainActivity * @brief First activity to run; encapsulates entry point of application. */ class MainActivity : AppCompatActivity() { private lateinit var _binding: ActivityMainBinding /** * {@inheritDoc} * * Perform initialization of all fragments. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) } }
0
Kotlin
0
0
0aa211fae8bb2c86883854f68c35ceb9a6d8d91d
777
SampleUIAndroid
MIT License
core/framework/src/main/java/com/jojalvo/framework/base/network/DataState.kt
jose-ojalvo
619,971,179
false
null
package com.jojalvo.framework.base.network /** * @author jojalvo * @since 2/5/23 * @email <EMAIL> */ sealed class DataState<out T> { data class Success<out T>(val result: T) : DataState<T>() data class Error(val error: Throwable) : DataState<Nothing>() }
0
Kotlin
0
0
1e8528c9868aec7d08e6c3bee5ffbae07d0c769e
274
MobileChallenge
Apache License 2.0
src/main/kotlin/com/team4099/robot2022/commands/climber/TelescopingIdleCommand.kt
team4099
441,528,688
false
{"Kotlin": 349929, "Shell": 191}
package com.team4099.robot2022.commands.climber import com.team4099.robot2022.config.constants.TelescopingClimberConstants import com.team4099.robot2022.subsystems.climber.TelescopingClimber import edu.wpi.first.wpilibj2.command.CommandBase import org.littletonrobotics.junction.Logger class TelescopingIdleCommand(val telescopingClimber: TelescopingClimber) : CommandBase() { init { addRequirements(telescopingClimber) } override fun execute() { if (telescopingClimber.currentState == TelescopingClimberConstants.ActualTelescopeStates.START || telescopingClimber.currentState == TelescopingClimberConstants.ActualTelescopeStates.MAX_EXTENSION || !telescopingClimber.activelyHold ) { telescopingClimber.setOpenLoop(0.0, 0.0) } else { telescopingClimber.holdPosition(loaded = true) } Logger.getInstance().recordOutput("ActiveCommands/TelescopingIdleCommand", true) } override fun initialize() {} }
0
Kotlin
1
5
5fea34ad74f417f74017a396da277a6fa10d1e6c
970
RapidReact-2022
MIT License
DiscordBot/src/main/kotlin/dev/fstudio/mc_discord_bot/diskord/command/top/TopMessage.kt
Kamillaova
463,396,605
false
{"Kotlin": 78372}
package dev.fstudio.mc_discord_bot.diskord.command.top import com.jessecorbett.diskord.api.channel.Embed import com.jessecorbett.diskord.api.channel.EmbedField import com.jessecorbett.diskord.api.channel.EmbedFooter import dev.fstudio.mc_discord_bot.api.mcworldstats.common.response.Player import dev.fstudio.mc_discord_bot.footerText import dev.fstudio.mc_discord_bot.realDaysInDay import dev.fstudio.mc_discord_bot.topPlayersTitle import dev.fstudio.mc_discord_bot.utils.MicsUtil.convertToDead import dev.fstudio.mc_discord_bot.utils.MicsUtil.fixUnderline import dev.fstudio.mc_discord_bot.utils.MicsUtil.getRandomColor import dev.fstudio.mc_discord_bot.utils.MicsUtil.tickToTime fun Embed.embedPlayersTopMessage(data: List<Player>) { val topTen = mutableListOf<EmbedField>() for (i in 0..9) { topTen.add( EmbedField( "${i + 1}. ${data[i].name.fixUnderline().convertToDead(data[i].abandoned)}", "$realDaysInDay ${data[i].minecraftPlayOneMinute?.tickToTime()}", false ) ) } title = topPlayersTitle fields = topTen color = getRandomColor() footer = EmbedFooter(footerText) }
0
Kotlin
0
1
a935ae2b1831949a347c954c70c3df6628d3dde5
1,194
Ellison
MIT License
app/src/main/java/com/pokedex/illustratedbook/ui/screen/pokemon/PokemonViewModel.kt
li-lance
424,505,324
false
{"Kotlin": 63328}
package com.pokedex.illustratedbook.ui.screen.pokemon import androidx.lifecycle.ViewModel import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.pokedex.illustratedbook.api.ApiService import com.pokedex.illustratedbook.data.PokemonEntity import com.pokedex.illustratedbook.limit import com.pokedex.illustratedbook.repository.PokemonRepository import com.pokedex.illustratedbook.ui.screen.pokemon.list.PokemonSource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import javax.inject.Inject @HiltViewModel class PokemonViewModel @Inject constructor(private val repository: PokemonRepository) : ViewModel() { fun getPokemonList(): Flow<PagingData<PokemonEntity>> { return Pager(PagingConfig(pageSize = limit())) { PokemonSource(repository) }.flow } }
0
Kotlin
0
0
a079caf341441efa3d611de8c90eadc668c3471c
863
PokedexIllustratedBook
Apache License 2.0
src/main/kotlin/cn/yiiguxing/plugin/translate/wordbook/WordBookToolWindowFactory.kt
YiiGuxing
60,159,997
false
null
package cn.yiiguxing.plugin.translate.wordbook import cn.yiiguxing.plugin.translate.TranslationPlugin import cn.yiiguxing.plugin.translate.adaptedMessage import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.ui.settings.TranslationConfigurable import cn.yiiguxing.plugin.translate.util.* import cn.yiiguxing.plugin.translate.util.concurrent.successOnUiThread import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationAction import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ex.ToolWindowEx import org.jetbrains.concurrency.runAsync /** * Word book tool window factory */ class WordBookToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { // Try to fix: https://github.com/YiiGuxing/TranslationPlugin/issues/1186 if (project.isDisposed) { return } WordBookView.instance.setup(project, toolWindow) } override fun init(toolWindow: ToolWindow) { adaptedMessage("wordbook.window.title").let { title -> toolWindow.title = title toolWindow.stripeTitle = title } val project = (toolWindow as ToolWindowEx).project val toolWindowRef = DisposableRef.create(toolWindow.disposable, toolWindow) val isStripeButtonShown = toolWindow.isShowStripeButton val messageBusConnection = project.messageBus.connect(toolWindow.disposable) messageBusConnection.subscribe(RequireWordBookListener.TOPIC, object : RequireWordBookListener { override fun onRequire() { toolWindowRef.get()?.runIfSurvive { setAvailable(true) { if (isStripeButtonShown) { showStripeButton() } else { isShowStripeButton = true showGotItTooltipIfNeed() } show() } } } }) if (!isStripeButtonShown) { return } // 这里只是修改了状态的复本,这会导致真实的状态和已存储的状态不一致。见:`ToolWindow.showStripeButton()` toolWindow.isShowStripeButton = false messageBusConnection.subscribe(WordBookListener.TOPIC, object : WordBookListener { override fun onWordsAdded(service: WordBookService, words: List<WordBookItem>) { toolWindowRef.showStripeButton() } override fun onStoragePathChanged(service: WordBookService) { toolWindowRef.updateVisible() } }) val disposable = Disposer.newDisposable(toolWindow.disposable, "Wordbook tool window availability state") WordBookService.instance.stateBinding.observe(disposable) { state, _ -> if (state == WordBookState.RUNNING) { toolWindowRef.updateVisible() Disposer.dispose(disposable) } } if (WordBookService.instance.isInitialized) { toolWindowRef.updateVisible() Disposer.dispose(disposable) } } private fun ToolWindowEx.showStripeButton() { // 由于在`init(ToolWindow)`中设置`isShowStripeButton`为`false`时,只修改了状态的复本,导致真实的状态和记录 // 的状态(可能为`true`)不同步,直接设置为`true`可能无效,所以这里需要设置为`false`先同步一下状态。 isShowStripeButton = false isShowStripeButton = true showGotItTooltipIfNeed() } private fun ToolWindowEx.showGotItTooltipIfNeed() { if (PropertiesComponent.getInstance().getBoolean(GOT_IT_KEY, false)) { return } if (Settings.wordbookStoragePath.isNullOrEmpty()) { Notifications.showFullContentNotification( message("wordbook.window.title"), message("got.it.notification.text.wordbook.storage.path"), project = project ) { it.addAction( NotificationAction.createSimpleExpiring(message("action.got.it.text")) { PropertiesComponent.getInstance().setValue(GOT_IT_KEY, true) } ).addAction( NotificationAction.create(message("action.configure.text")) { _, notification -> notification.expire() PropertiesComponent.getInstance().setValue(GOT_IT_KEY, true) TranslationConfigurable.showSettingsDialog(project) } ) } } else { PropertiesComponent.getInstance().setValue(GOT_IT_KEY, true) } } private fun DisposableRef<ToolWindowEx>.showStripeButton() { get()?.runIfSurvive { showStripeButton() } } private fun DisposableRef<ToolWindowEx>.updateVisible() { runAsync { with(WordBookService.instance) { isInitialized && hasWords() } } .successOnUiThread(this, ModalityState.NON_MODAL) { toolWindow, available -> if (available) { toolWindow.showStripeButton() } } } override fun shouldBeAvailable(project: Project): Boolean = true companion object { const val TOOL_WINDOW_ID = "Translation.Wordbook" private const val GOT_IT_KEY = "${TranslationPlugin.PLUGIN_ID}.got.it.wordbook.storage.path" private val requirePublisher: RequireWordBookListener by lazy { Application.messageBus.syncPublisher(RequireWordBookListener.TOPIC) } fun requireWordBook() { checkDispatchThread { "Must only be invoked from the Event Dispatch Thread." } requirePublisher.onRequire() } private inline fun ToolWindowEx.runIfSurvive(crossinline action: ToolWindowEx.() -> Unit) { if (isDisposed) { return } invokeLater(ModalityState.NON_MODAL, project.disposed) { if (!isDisposed) { action() } } } } }
48
Kotlin
763
9,758
3a5cf29b7765e48ff828c23e3bb960aa72a583d4
6,368
TranslationPlugin
MIT License
domain/src/main/java/jp/kaleidot725/easycalc/domain/model/question/selector/QuestionSelector.kt
kaleidot725
727,725,457
false
{"Kotlin": 288088, "Ruby": 106}
package jp.kaleidot725.easycalc.domain.model.question.selector import jp.kaleidot725.easycalc.domain.model.question.generator.QuestionGenerator import jp.kaleidot725.easycalc.domain.model.text.MathText interface QuestionSelector { fun select(text: MathText): QuestionGenerator }
0
Kotlin
0
0
e6ed3eb42b6fad739e42be77eebd9619874ae548
285
EasyCalc
MIT License
src/test/kotlin/com/adrienben/tools/gltf/validation/ValidationTest.kt
adrien-ben
119,737,332
false
null
package com.adrienben.tools.gltf.validation import com.adrienben.tools.gltf.models.* import org.junit.Test import kotlin.test.assertFailsWith /** * Test class for [Validator] */ class ValidationTest { private val validAsset = AssetRaw(version = "2.0") @Test fun itShouldFailOnVersionError() = itShouldFailToValidate( failingField = "asset.version", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = AssetRaw( version = "2.1" // tested error )))) @Test fun itShouldValidateBuffer() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, buffers = listOf(BufferRaw( byteLength = 1 ))))) } @Test fun itShouldFailOnWrongBufferByteLength() = itShouldFailToValidate( failingField = "buffers[0].byteLength", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, buffers = listOf(BufferRaw( byteLength = 0 // tested error ))))) @Test fun itShouldFailOnEmptyBuffers() = itShouldFailToValidate( failingField = "buffers", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, buffers = emptyList() // tested error ))) @Test fun itShouldValidateBufferView() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = listOf(BufferViewRaw( buffer = 0, byteOffset = 0, byteLength = 1, byteStride = 4, target = 34962 ))))) } @Test fun itShouldFailOnWrongBufferViewBufferRef() = itShouldFailToValidate( failingField = "bufferViews[0].buffer", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = listOf(BufferViewRaw( buffer = -1, // tested error byteLength = 1 ))))) @Test fun itShouldFailOnWrongBufferViewByteOffset() = itShouldFailToValidate( failingField = "bufferViews[0].byteOffset", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = listOf(BufferViewRaw( buffer = 0, byteOffset = -1, // tested error byteLength = 1 ))))) @Test fun itShouldFailOnWrongBufferViewByteLength() = itShouldFailToValidate( failingField = "bufferViews[0].byteLength", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = listOf(BufferViewRaw( buffer = 0, byteLength = 0 // tested error ))))) @Test fun itShouldFailOnWrongBufferViewByteStride() = itShouldFailToValidate( failingField = "bufferViews[0].byteStride", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = listOf(BufferViewRaw( buffer = 0, byteLength = 1, byteStride = 0 // tested error ))))) @Test fun itShouldFailOnWrongBufferViewTarget() = itShouldFailToValidate( failingField = "bufferViews[0].target", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = listOf(BufferViewRaw( buffer = 0, byteLength = 1, target = 0 // tested error ))))) @Test fun itShouldFailOnEmptyBufferView() = itShouldFailToValidate( failingField = "bufferViews", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, bufferViews = emptyList() // tested error ))) @Test fun itShouldValidateAccessor() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( bufferView = 0, byteOffset = 0, componentType = 5120, count = 1, type = "SCALAR", max = listOf(1), min = listOf(1), sparse = SparseRaw( count = 1, indices = IndicesRaw( bufferView = 0, byteOffset = 0, componentType = 5121 ), values = ValuesRaw( bufferView = 0, byteOffset = 0 ))))))) } @Test fun itShouldFailOnWrongIndicesBufferViewRef() = itShouldFailToValidate( failingField = "accessors[0].sparse.indices.bufferView", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", sparse = SparseRaw( count = 1, indices = IndicesRaw( bufferView = -1, // tested error componentType = 5121 ), values = ValuesRaw( bufferView = 0 ))))))) @Test fun itShouldFailOnWrongIndicesByteOffset() = itShouldFailToValidate( failingField = "accessors[0].sparse.indices.byteOffset", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", sparse = SparseRaw( count = 1, indices = IndicesRaw( bufferView = 0, byteOffset = -1, // tested error componentType = 5121 ), values = ValuesRaw( bufferView = 0 ))))))) @Test fun itShouldFailOnWrongIndicesComponentType() = itShouldFailToValidate( failingField = "accessors[0].sparse.indices.componentType", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", sparse = SparseRaw( count = 1, indices = IndicesRaw( bufferView = 0, byteOffset = 0, componentType = 0 // tested error ), values = ValuesRaw( bufferView = 0 ))))))) @Test fun itShouldFailOnWrongValuesBufferViewRef() = itShouldFailToValidate( failingField = "accessors[0].sparse.values.bufferView", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", sparse = SparseRaw( count = 1, indices = IndicesRaw( bufferView = 0, componentType = 5121 ), values = ValuesRaw( bufferView = -1 // tested error ))))))) @Test fun itShouldFailOnWrongValuesByteOffset() = itShouldFailToValidate( failingField = "accessors[0].sparse.values.byteOffset", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", sparse = SparseRaw( count = 1, indices = IndicesRaw( bufferView = 0, componentType = 5121 ), values = ValuesRaw( bufferView = 0, byteOffset = -1 // tested error ))))))) @Test fun itShouldFailOnWrongSparseCount() = itShouldFailToValidate( failingField = "accessors[0].sparse.count", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", sparse = SparseRaw( count = 0, // tested error indices = IndicesRaw( bufferView = 0, componentType = 5121 ), values = ValuesRaw( bufferView = 0 ))))))) @Test fun itShouldFailOnWrongAccessorBufferViewRef() = itShouldFailToValidate( failingField = "accessors[0].bufferView", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( bufferView = -1, // tested error componentType = 5120, count = 1, type = "SCALAR" ))))) @Test fun itShouldFailOnWrongAccessorByteOffset() = itShouldFailToValidate( failingField = "accessors[0].byteOffset", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( byteOffset = -1, // tested error componentType = 5120, count = 1, type = "SCALAR" ))))) @Test fun itShouldFailOnWrongAccessorComponentType() = itShouldFailToValidate( failingField = "accessors[0].componentType", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 0, // tested error count = 1, type = "SCALAR" ))))) @Test fun itShouldFailOnWrongAccessorCount() = itShouldFailToValidate( failingField = "accessors[0].count", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 0, // tested error type = "SCALAR" ))))) @Test fun itShouldFailOnWrongAccessorType() = itShouldFailToValidate( failingField = "accessors[0].type", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "WRONG" // tested error ))))) @Test fun itShouldFailOnWrongAccessorMaxSize() = itShouldFailToValidate( failingField = "accessors[0].max", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", max = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongAccessorMinSize() = itShouldFailToValidate( failingField = "accessors[0].min", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = listOf(AccessorRaw( componentType = 5120, count = 1, type = "SCALAR", min = emptyList() // tested error ))))) @Test fun itShouldFailOnEmptyAccessors() = itShouldFailToValidate( failingField = "accessors", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, accessors = emptyList() // tested error ))) @Test fun itShouldValidateSampler() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, samplers = listOf(SamplerRaw( magFilter = 9728, minFilter = 9728, wrapS = 10497, wrapT = 10497 ))))) } @Test fun itShouldFailOnWrongSamplerMagFilter() = itShouldFailToValidate( failingField = "samplers[0].magFilter", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, samplers = listOf(SamplerRaw( magFilter = 0 // tested error ))))) @Test fun itShouldFailOnWrongSamplerMinFilter() = itShouldFailToValidate( failingField = "samplers[0].minFilter", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, samplers = listOf(SamplerRaw( minFilter = 0 // tested error ))))) @Test fun itShouldFailOnWrongSamplerWrapS() = itShouldFailToValidate( failingField = "samplers[0].wrapS", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, samplers = listOf(SamplerRaw( wrapS = 0 // tested error ))))) @Test fun itShouldFailOnWrongSamplerWrapT() = itShouldFailToValidate( failingField = "samplers[0].wrapT", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, samplers = listOf(SamplerRaw( wrapT = 0 // tested error ))))) @Test fun itShouldFailOnEmptySamplers() = itShouldFailToValidate( failingField = "samplers", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, samplers = emptyList() // tested error ))) @Test fun itShouldValidateImage() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, images = listOf(ImageRaw( mimeType = "image/png", bufferView = 0 ))))) } @Test fun itShouldFailOnWrongImageMimeType() = itShouldFailToValidate( failingField = "images[0].mimeType", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, images = listOf(ImageRaw( mimeType = "wrong" // tested error ))))) @Test fun itShouldFailOnWrongImageBufferViewRef() = itShouldFailToValidate( failingField = "images[0].bufferView", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, images = listOf(ImageRaw( bufferView = -1 // tested error ))))) @Test fun itShouldFailOnEmptyImages() = itShouldFailToValidate( failingField = "images", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, images = emptyList() // tested error ))) @Test fun itShouldValidateTexture() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, textures = listOf(TextureRaw( sampler = 0, source = 0 ))))) } @Test fun itShouldFailOnWrongTextureSamplerRef() = itShouldFailToValidate( failingField = "textures[0].sampler", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, textures = listOf(TextureRaw( sampler = -1 // tested error ))))) @Test fun itShouldFailOnWrongTextureSourceRef() = itShouldFailToValidate( failingField = "textures[0].source", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, textures = listOf(TextureRaw( source = -1 // tested error ))))) @Test fun itShouldFailOnEmptyTextures() = itShouldFailToValidate( failingField = "textures", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, textures = emptyList() // tested error ))) @Test fun itShouldValidateMaterial() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( baseColorFactor = listOf(1.0, 1.0, 1.0, 1.0), baseColorTexture = TextureInfoRaw( index = 0, texCoord = 0 ), metallicFactor = 0.0, roughnessFactor = 1.0, metallicRoughnessTexture = TextureInfoRaw( index = 1, texCoord = 0 ) ), normalTexture = NormalTextureInfoRaw( index = 2, texCoord = 0 ), occlusionTexture = OcclusionTextureInfoRaw( index = 3, texCoord = 0, strength = 1.0 ), emissiveTexture = TextureInfoRaw( index = 4, texCoord = 0 ), emissiveFactor = listOf(1.0, 1.0, 1.0), alphaMode = "OPAQUE", alphaCutoff = 0.5 ))))) } @Test fun itShouldFailOnWrongMaterialPbrColor() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.baseColorFactor", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( baseColorFactor = emptyList() // tested error )))))) @Test fun itShouldFailOnWrongMaterialPbrColorTextureIndex() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.baseColorTexture.index", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( baseColorTexture = TextureInfoRaw( index = -1 // tested error ) )))))) @Test fun itShouldFailOnWrongMaterialPbrColorTextureCoord() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.baseColorTexture.texCoord", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( baseColorTexture = TextureInfoRaw( index = 0, texCoord = -1 // tested error ) )))))) @Test fun itShouldFailOnWrongMaterialPbrMetallic() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.metallicFactor", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( metallicFactor = 2 // tested error )))))) @Test fun itShouldFailOnWrongMaterialPbrRoughness() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.roughnessFactor", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( roughnessFactor = 2 // tested error )))))) @Test fun itShouldFailOnWrongMaterialPbrMetallicRoughnessTextureIndex() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.metallicRoughnessTexture.index", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( metallicRoughnessTexture = TextureInfoRaw( index = -1 // tested error ) )))))) @Test fun itShouldFailOnWrongMaterialPbrMetallicRoughnessTextureCoord() = itShouldFailToValidate( failingField = "materials[0].pbrMetallicRoughness.metallicRoughnessTexture.texCoord", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( pbrMetallicRoughness = PbrMetallicRoughnessRaw( metallicRoughnessTexture = TextureInfoRaw( index = 0, texCoord = -1 // tested error ) )))))) @Test fun itShouldFailOnWrongMaterialNormalTextureIndex() = itShouldFailToValidate( failingField = "materials[0].normalTexture.index", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( normalTexture = NormalTextureInfoRaw( index = -1 // tested error )))))) @Test fun itShouldFailOnWrongMaterialNormalTextureCoord() = itShouldFailToValidate( failingField = "materials[0].normalTexture.texCoord", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( normalTexture = NormalTextureInfoRaw( index = 0, texCoord = -1 // tested error )))))) @Test fun itShouldFailOnWrongMaterialOcclusionTextureIndex() = itShouldFailToValidate( failingField = "materials[0].occlusionTexture.index", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( occlusionTexture = OcclusionTextureInfoRaw( index = -1 // tested error )))))) @Test fun itShouldFailOnWrongMaterialOcclusionTextureCoord() = itShouldFailToValidate( failingField = "materials[0].occlusionTexture.texCoord", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( occlusionTexture = OcclusionTextureInfoRaw( index = 0, texCoord = -1 // tested error )))))) @Test fun itShouldFailOnWrongMaterialOcclusionTextureStrength() = itShouldFailToValidate( failingField = "materials[0].occlusionTexture.strength", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( occlusionTexture = OcclusionTextureInfoRaw( index = 0, strength = 10 // tested error )))))) @Test fun itShouldFailOnWrongMaterialEmissiveTextureIndex() = itShouldFailToValidate( failingField = "materials[0].emissiveTexture.index", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( emissiveTexture = TextureInfoRaw( index = -1 // tested error )))))) @Test fun itShouldFailOnWrongMaterialEmissiveTextureCoord() = itShouldFailToValidate( failingField = "materials[0].emissiveTexture.texCoord", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( emissiveTexture = TextureInfoRaw( index = 0, texCoord = -1 // tested error )))))) @Test fun itShouldFailOnWrongMaterialEmissiveFactor() = itShouldFailToValidate( failingField = "materials[0].emissiveFactor", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( emissiveFactor = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongMaterialAlphaMode() = itShouldFailToValidate( failingField = "materials[0].alphaMode", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( alphaMode = "WRONG" // tested error ))))) @Test fun itShouldFailOnWrongMaterialAlphaCutoff() = itShouldFailToValidate( failingField = "materials[0].alphaCutoff", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = listOf(MaterialRaw( alphaCutoff = -2.0 // tested error ))))) @Test fun itShouldFailOnEmptyMaterials() = itShouldFailToValidate( failingField = "materials", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, materials = emptyList() // tested error ))) @Test fun itShouldValidateMesh() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0), indices = 1, material = 0, mode = 4, targets = listOf( mapOf("POSITION" to 2) ) )), weights = listOf(1) ))))) } @Test fun itShouldFailOnEmptyMeshPrimitiveAttributes() = itShouldFailToValidate( failingField = "meshes[0].primitives[0].attributes", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = emptyMap() // tested error ))))))) @Test fun itShouldFailOnWrongMeshPrimitiveIndicesRef() = itShouldFailToValidate( failingField = "meshes[0].primitives[0].indices", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0), indices = -1 // tested error ))))))) @Test fun itShouldFailOnWrongMeshPrimitiveMaterialRef() = itShouldFailToValidate( failingField = "meshes[0].primitives[0].material", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0), material = -1 // tested error ))))))) @Test fun itShouldFailOnWrongMeshPrimitiveMode() = itShouldFailToValidate( failingField = "meshes[0].primitives[0].mode", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0), mode = -1 // tested error ))))))) @Test fun itShouldFailOnEmptyMeshPrimitiveTargets() = itShouldFailToValidate( failingField = "meshes[0].primitives[0].targets", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0), targets = emptyList() // tested error ))))))) @Test fun itShouldFailOnEmptyMeshPrimitiveTargetElement() = itShouldFailToValidate( failingField = "meshes[0].primitives[0].targets[0]", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0), targets = listOf( emptyMap() // tested error )))))))) @Test fun itShouldFailOnEmptyMeshPrimitive() = itShouldFailToValidate( failingField = "meshes[0].primitives", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = emptyList() // tested error ))))) @Test fun itShouldFailOnEmptyMeshWeights() = itShouldFailToValidate( failingField = "meshes[0].weights", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = listOf(MeshRaw( primitives = listOf(PrimitiveRaw( attributes = mapOf("POSITION" to 0) )), weights = emptyList() // tested error ))))) @Test fun itShouldFailOnEmptyMeshes() = itShouldFailToValidate( failingField = "meshes", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, meshes = emptyList() // tested error ))) @Test fun itShouldValidateOrthographicCamera() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( orthographic = OrthographicRaw( xmag = 1, ymag = 1, zfar = 10, znear = 0 ), type = "orthographic" ))))) } @Test fun itShouldValidatePerspectiveCamera() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( perspective = PerspectiveRaw( aspectRatio = 1.77, yfov = 0.7, zfar = 100, znear = 0.1 ), type = "perspective" ))))) } @Test fun itShouldFailOnWrongOrthographicZFar() = itShouldFailToValidate( failingField = "cameras[0].orthographic.zfar", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "orthographic", orthographic = OrthographicRaw( xmag = 1.0, ymag = 1.0, zfar = 0.0, // tested error znear = 1.0 )))))) @Test fun itShouldFailOnWrongOrthographicZNear() = itShouldFailToValidate( failingField = "cameras[0].orthographic.znear", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "orthographic", orthographic = OrthographicRaw( xmag = 1.0, ymag = 1.0, zfar = 1.0, znear = -1 // tested error )))))) @Test fun itShouldFailOnWrongPerspectiveAspectRatio() = itShouldFailToValidate( failingField = "cameras[0].perspective.aspectRatio", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "perspective", perspective = PerspectiveRaw( aspectRatio = -1, // tested error yfov = 0.7, znear = 0.1 )))))) @Test fun itShouldFailOnWrongPerspectiveYFov() = itShouldFailToValidate( failingField = "cameras[0].perspective.yfov", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "perspective", perspective = PerspectiveRaw( yfov = 0.0, // tested error znear = 0.1 )))))) @Test fun itShouldFailOnWrongPerspectiveZFar() = itShouldFailToValidate( failingField = "cameras[0].perspective.zfar", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "perspective", perspective = PerspectiveRaw( yfov = 0.7, zfar = 0.0, // tested error znear = 0.1 )))))) @Test fun itShouldFailOnWrongPerspectiveZNear() = itShouldFailToValidate( failingField = "cameras[0].perspective.znear", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "perspective", perspective = PerspectiveRaw( yfov = 0.7, znear = 0.0 // tested error )))))) @Test fun itShouldFailOnWrongCameraType() = itShouldFailToValidate( failingField = "cameras[0].type", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = listOf(CameraRaw( type = "wrong" // tested error ))))) @Test fun itShouldFailOnEmptyCameras() = itShouldFailToValidate( failingField = "cameras", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, cameras = emptyList() // tested error ))) @Test fun itShouldValidateNode() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( camera = 0, children = listOf(1), skin = 0, matrix = listOf(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), mesh = 0, rotation = listOf(0, 1, 0, 0), scale = listOf(1, 1, 1), translation = listOf(0, 0, 0), weights = listOf(1) ))))) } @Test fun itShouldFailOnWrongNodeCameraRef() = itShouldFailToValidate( failingField = "nodes[0].camera", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( camera = -1 // tested error ))))) @Test fun itShouldFailOnEmptyNodeChildren() = itShouldFailToValidate( failingField = "nodes[0].children", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( children = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongNodeSkinRef() = itShouldFailToValidate( failingField = "nodes[0].skin", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( skin = -1 // tested error ))))) @Test fun itShouldFailOnWrongNodeMatrixSize() = itShouldFailToValidate( failingField = "nodes[0].matrix", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( matrix = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongNodeMeshRef() = itShouldFailToValidate( failingField = "nodes[0].mesh", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( mesh = -1 // tested error ))))) @Test fun itShouldFailOnWrongNodeRotationSize() = itShouldFailToValidate( failingField = "nodes[0].rotation", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( rotation = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongNodeScaleSize() = itShouldFailToValidate( failingField = "nodes[0].scale", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( scale = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongNodeTranslationSize() = itShouldFailToValidate( failingField = "nodes[0].translation", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( translation = emptyList() // tested error ))))) @Test fun itShouldFailOnEmptyNodeWeights() = itShouldFailToValidate( failingField = "nodes[0].weights", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = listOf(NodeRaw( weights = emptyList() // tested error ))))) @Test fun itShouldFailOnEmptyNodes() = itShouldFailToValidate( failingField = "nodes", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, nodes = emptyList() // tested error ))) @Test fun itShouldValidateSkin() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, skins = listOf(SkinRaw( inverseBindMatrices = 0, skeleton = 1, joints = listOf(0) ))))) } @Test fun itShouldFailOnWrongSkinMatricesRef() = itShouldFailToValidate( failingField = "skins[0].inverseBindMatrices", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, skins = listOf(SkinRaw( inverseBindMatrices = -1, // tested error joints = listOf(0) ))))) @Test fun itShouldFailOnWrongSkinSkeletonRef() = itShouldFailToValidate( failingField = "skins[0].skeleton", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, skins = listOf(SkinRaw( skeleton = -1, // tested error joints = listOf(0) ))))) @Test fun itShouldFailOnEmptySkinJoints() = itShouldFailToValidate( failingField = "skins[0].joints", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, skins = listOf(SkinRaw( joints = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongSkinJointsElement() = itShouldFailToValidate( failingField = "skins[0].joints[0]", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, skins = listOf(SkinRaw( joints = listOf(-1) // tested error ))))) @Test fun itShouldFailOnEmptySkins() = itShouldFailToValidate( failingField = "skins", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, skins = emptyList() // tested error ))) @Test fun itShouldValidateAnimation() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( node = 0, path = "translation" ) )), samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "LINEAR", output = 1 )) ))))) } @Test fun itShouldFailOnWrongAnimationTargetNodeRef() = itShouldFailToValidate( failingField = "animations[0].channels[0].target.node", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( node = -1, // tested error path = "translation" ))), samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "LINEAR", output = 1 ))))))) @Test fun itShouldFailOnWrongAnimationTargetPath() = itShouldFailToValidate( failingField = "animations[0].channels[0].target.path", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( path = "wrong" // tested error ))), samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "LINEAR", output = 1 ))))))) @Test fun itShouldFailOnWrongAnimationChannelSamplerRef() = itShouldFailToValidate( failingField = "animations[0].channels[0].sampler", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = -1, // tested error target = AnimationTargetRaw( path = "translation" ))), samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "LINEAR", output = 1 ))))))) @Test fun itShouldFailOnWrongAnimationSamplerInputRef() = itShouldFailToValidate( failingField = "animations[0].samplers[0].input", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( path = "translation" ))), samplers = listOf(AnimationSamplerRaw( input = -1, // tested error interpolation = "LINEAR", output = 1 ))))))) @Test fun itShouldFailOnWrongAnimationSamplerInterpolation() = itShouldFailToValidate( failingField = "animations[0].samplers[0].interpolation", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( path = "translation" ))), samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "WRONG", // tested error output = 1 ))))))) @Test fun itShouldFailOnWrongAnimationSamplerOutputRef() = itShouldFailToValidate( failingField = "animations[0].samplers[0].output", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( path = "translation" ))), samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "LINEAR", output = -1 // tested error ))))))) @Test fun itShouldFailOnEmptyAnimationChannels() = itShouldFailToValidate( failingField = "animations[0].channels", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = emptyList(), // tested error samplers = listOf(AnimationSamplerRaw( input = 0, interpolation = "LINEAR", output = 1 ))))))) @Test fun itShouldFailOnEmptyAnimationSamplers() = itShouldFailToValidate( failingField = "animations[0].samplers", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = listOf(AnimationRaw( channels = listOf(ChannelRaw( sampler = 0, target = AnimationTargetRaw( path = "translation" ))), samplers = emptyList() // tested error ))))) @Test fun itShouldFailOnEmptyAnimations() = itShouldFailToValidate( failingField = "animations", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, animations = emptyList() // tested error ))) @Test fun itShouldValidateScene() { Validator().validate(GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, scenes = listOf(SceneRaw( nodes = listOf(0) )), scene = 0 ))) } @Test fun itShouldFailOnEmptySceneNodes() = itShouldFailToValidate( failingField = "scenes[0].nodes", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, scenes = listOf(SceneRaw( nodes = emptyList() // tested error ))))) @Test fun itShouldFailOnWrongSceneNodesElement() = itShouldFailToValidate( failingField = "scenes[0].nodes[0]", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, scenes = listOf(SceneRaw( nodes = listOf(-1) // tested error ))))) @Test fun itShouldFailOnEmptyScenes() = itShouldFailToValidate( failingField = "scenes", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, scenes = emptyList() // tested error ))) @Test fun itShouldFailOnWrongSceneRef() = itShouldFailToValidate( failingField = "scene", gltfRaw = GltfRaw( data = emptyList(), gltfAssetRaw = GltfAssetRaw( asset = validAsset, scene = -1 // tested error ))) private fun itShouldFailToValidate(gltfRaw: GltfRaw, failingField: String) { val error = assertFailsWith(ValidationError::class) { Validator().validate(gltfRaw) } assert(error.field == failingField) { "Validation should have failed on field $failingField but failed because ${error.message}" } } }
0
Kotlin
3
3
0e692547afe057555670229b59be957da3a1089a
69,329
gltf-loader
MIT License
jvb/src/main/kotlin/org/jitsi/videobridge/octo/config/OctoRtpSender.kt
jitsi
9,657,943
false
null
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.octo.config import org.jitsi.nlj.Event import org.jitsi.nlj.PacketHandler import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.RtpSender import org.jitsi.nlj.rtcp.KeyframeRequester import org.jitsi.nlj.rtp.TransportCcEngine import org.jitsi.nlj.rtp.bandwidthestimation.BandwidthEstimator import org.jitsi.nlj.srtp.SrtpTransformers import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.stats.PacketStreamStats import org.jitsi.nlj.transform.NodeStatsVisitor import org.jitsi.nlj.transform.node.ConsumerNode import org.jitsi.nlj.transform.node.outgoing.OutgoingStatisticsSnapshot import org.jitsi.nlj.util.OrderedJsonObject import org.jitsi.nlj.util.ReadOnlyStreamInformationStore import org.jitsi.nlj.util.bps import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.createChildLogger import org.jitsi.videobridge.util.ByteBufferPool import java.util.concurrent.atomic.AtomicBoolean /** * An [RtpSender] for all data we want to send out over the Octo link(s). */ class OctoRtpSender( readOnlyStreamInformationStore: ReadOnlyStreamInformationStore, parentLogger: Logger ) : RtpSender() { private val logger = createChildLogger(parentLogger) private val running = AtomicBoolean(true) /** * A handler for packets to be sent out onto the network */ private var outgoingPacketHandler: PacketHandler? = null private val outputPipelineTerminationNode = object : ConsumerNode("Octo sender termination node") { override fun consume(packetInfo: PacketInfo) { outgoingPacketHandler?.processPacket(packetInfo) ?: packetDiscarded(packetInfo) } override fun trace(f: () -> Unit) = f.invoke() } /** * The [KeyframeRequester] used for all remote Octo endpoints */ private val keyframeRequester = KeyframeRequester(readOnlyStreamInformationStore, logger).apply { attach(outputPipelineTerminationNode) } /** * Add a handler to handle outgoing Octo packets */ override fun onOutgoingPacket(handler: PacketHandler) { outgoingPacketHandler = handler } override fun doProcessPacket(packetInfo: PacketInfo) { if (running.get()) { outgoingPacketHandler?.processPacket(packetInfo) } else { ByteBufferPool.returnBuffer(packetInfo.packet.buffer) } } private fun doSend(packetInfo: PacketInfo): Boolean { outgoingPacketHandler?.processPacket(packetInfo) return true } override fun requestKeyframe(mediaSsrc: Long?) { keyframeRequester.requestKeyframe(mediaSsrc) } override fun sendProbing(mediaSsrcs: Collection<Long>, numBytes: Int): Int = 0 override fun setSrtpTransformers(srtpTransformers: SrtpTransformers) {} override fun stop() { running.set(false) } override fun tearDown() { } override val bandwidthEstimator: BandwidthEstimator get() = TODO("Not implemented") override fun handleEvent(event: Event) {} override fun onRttUpdate(newRttMs: Double) {} override fun getPacketStreamStats(): PacketStreamStats.Snapshot = PacketStreamStats.Snapshot(0.bps, 0, 0, 0) override fun getTransportCcEngineStats(): TransportCcEngine.StatisticsSnapshot = TransportCcEngine.StatisticsSnapshot(0, 0, 0, 0, 0, 0) override fun getStreamStats(): OutgoingStatisticsSnapshot = OutgoingStatisticsSnapshot(mapOf()) override fun getNodeStats(): NodeStatsBlock = NodeStatsBlock("Octo sender").apply { addBlock(super.getNodeStats()) NodeStatsVisitor(this).reverseVisit(outputPipelineTerminationNode) } fun getDebugState(): OrderedJsonObject = OrderedJsonObject().apply { putAll(getNodeStats().toJson()) } }
175
null
934
2,576
046d1193a7a0369bc71a486007a64a6ea31f5637
4,389
jitsi-videobridge
Apache License 2.0
mobile/src/androidTest/java/com/google/samples/apps/iosched/tests/SetPreferencesRule.kt
google
18,347,476
false
null
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.tests import androidx.test.core.app.ApplicationProvider import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage import com.google.samples.apps.iosched.shared.di.ApplicationScope import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel import kotlinx.coroutines.runBlocking import org.junit.rules.TestWatcher import org.junit.runner.Description /** * Rule to be used in tests that sets the preferences needed for avoiding onboarding flows, * resetting filters, etc. */ class SetPreferencesRule : TestWatcher() { @InstallIn(SingletonComponent::class) @EntryPoint interface SetPreferencesRuleEntryPoint { fun preferenceStorage(): PreferenceStorage @ApplicationScope fun applicationScope(): CoroutineScope } override fun starting(description: Description?) { super.starting(description) EntryPointAccessors.fromApplication( ApplicationProvider.getApplicationContext(), SetPreferencesRuleEntryPoint::class.java ).preferenceStorage().apply { runBlocking { completeOnboarding(true) showScheduleUiHints(true) preferConferenceTimeZone(true) selectFilters("") sendUsageStatistics(false) showNotificationsPreference(true) } } } override fun finished(description: Description) { // At the end of every test, cancel the application scope // So DataStore is closed EntryPointAccessors.fromApplication( ApplicationProvider.getApplicationContext(), SetPreferencesRuleEntryPoint::class.java ).applicationScope().cancel() super.finished(description) } }
77
null
6259
21,755
738e1e008096fad5f36612325275e80c33dbe436
2,568
iosched
Apache License 2.0
src/main/Interval.kt
UrielSarrazin
243,283,788
false
null
enum class Interval(val semitones: Int) { UNISON(0), MINOR_SECOND(1), MAJOR_SECOND(2), MINOR_THIRD(3), MAJOR_THIRD(4), PERFECT_FOURTH(5), DIMINISHED_FIFTH(6), PERFECT_FIFTH(7), AUGMENTED_FIFTH(8), MAJOR_SIXTH(9), MINOR_SEVENTH(10), MAJOR_SEVENTH(11), OCTAVE(12); companion object { fun from(notes: List<Note>): List<Interval> = notes.map { from(notes[0], it) }.toList() fun from(from: Note, to: Note): Interval { val semitones = to.offset - from.offset val distance = if (semitones < UNISON.semitones) semitones + OCTAVE.semitones else semitones return from(distance) } private fun from(semitones: Int): Interval { return values().find { it.semitones == semitones } ?: throw UnknownIntervalException() } } }
1
Kotlin
0
0
407934faeafd420244d37be9f03b49b8e1b40bf9
858
chords
Apache License 2.0
src/test/kotlin/no/nav/bidrag/cucumber/backend/FellesTestdataEgenskaper.kt
navikt
213,854,393
false
null
package no.nav.bidrag.cucumber.backend import io.cucumber.java.no.Gitt import io.cucumber.java.no.Og import no.nav.bidrag.cucumber.backend.dokument.AvvikDataMottaksregistrertJp import no.nav.bidrag.cucumber.backend.dokument.RestTjenesteTestdata import org.assertj.core.api.Assertions.assertThat import org.springframework.http.HttpStatus class FellesTestdataEgenskaper { companion object { private lateinit var key: String private lateinit var restTjenesteTestdata: RestTjenesteTestdata val journalpostIdPerKey: MutableMap<String, String> = HashMap() fun useAsKey(cacheKey: String) { key = cacheKey } } @Gitt("resttjenesten {string} for manipulering av testdata") fun resttjenesten(alias: String) { restTjenesteTestdata = RestTjenesteTestdata(alias) } @Og("opprett journalpost når den ikke finnes for nøkkel:") fun `opprett journalpost`(jpJson: String) { if (!journalpostIdPerKey.containsKey(key)) { restTjenesteTestdata.opprettJournalpost(jpJson) assertThat(restTjenesteTestdata.hentHttpStatus()).isEqualTo(HttpStatus.CREATED) val opprettetJpMap = restTjenesteTestdata.hentResponseSomMap() journalpostIdPerKey[key] = opprettetJpMap["journalpostId"] as String } } @Og("opprett journalpost med nøkkel {string} når den ikke finnes:") fun `opprett journalpost med nokkel`(nokkel: String, jpJson: String) { if (!journalpostIdPerKey.containsKey(nokkel)) { restTjenesteTestdata.opprettJournalpost(jpJson) assertThat(restTjenesteTestdata.hentHttpStatus()).isEqualTo(HttpStatus.CREATED) val opprettetJpMap = restTjenesteTestdata.hentResponseSomMap() journalpostIdPerKey[nokkel] = opprettetJpMap["journalpostId"] as String } } @Og("opprettet journalpost har enhet {string}") fun `opprettet journalpost har enhet`(enhet: String) { assertThat(journalpostIdPerKey["jouranlforendeEnhet"]).isEqualTo(enhet) } @Gitt("at jeg oppretter journalpost for {string}:") fun `opprett journalpost`(key: String, jpJson: String) { if (!journalpostIdPerKey.containsKey(key)) { restTjenesteTestdata.opprettJournalpost(jpJson) assertThat(restTjenesteTestdata.hentHttpStatus()).isEqualTo(HttpStatus.CREATED) val opprettetJpMap = restTjenesteTestdata.hentResponseSomMap() journalpostIdPerKey[key] = opprettetJpMap["journalpostId"] as String } } fun `opprett journalpost`(avvikData: AvvikDataMottaksregistrertJp, jpJson: String) { if (!journalpostIdPerKey.containsKey(avvikData.testdataNokkel)) { restTjenesteTestdata.opprettJournalpost(jpJson) assertThat(restTjenesteTestdata.hentHttpStatus()).isEqualTo(HttpStatus.CREATED) val opprettetJpMap = restTjenesteTestdata.hentResponseSomMap() journalpostIdPerKey[avvikData.testdataNokkel] = opprettetJpMap["journalpostId"] as String } } @Og("en journalpostHendelse for nokkel {string} skal være produsert") fun `en journalpostHendelse skal vare produsert for journalpostId`(nokkel: String) { val journalpostId = journalpostIdPerKey[nokkel] val response = restTjenesteTestdata.exchangeGet("/hendelser/$journalpostId") assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body).isNotNull } @Og("lag bidragssak {string} når den ikke finnes fra før:") fun `lag bidragssak nar den ikke finnes fra for`(saksnummer: String, bidragssak: String) { restTjenesteTestdata.exchangePost("/sak/$saksnummer", bidragssak) } }
1
Kotlin
0
1
0838cfad100e4b4b2c91fc783412006bb17dd64f
3,726
bidrag-cucumber-backend
MIT License
src/main/kotlin/com/polydus/aoc19/Day1.kt
Polydus
160,193,832
false
null
package com.polydus.aoc19 import kotlin.math.floor class Day1: Day(1) { init { partTwo() } fun partOne(){ var total = 0 input.forEach { val mass = (floor(it.toDouble() / 3f) - 2).toInt() total += mass } println(total) } fun partTwo(){ var total = 0 input.forEach { var currentMass = it.toInt() var fuel = 0 while(currentMass > 0){ val addedFuel = getFuel(currentMass) fuel += addedFuel currentMass = addedFuel } total += fuel } println(total) } fun getFuel(mass: Int): Int{ return (floor(mass.toDouble() / 3f) - 2).toInt().coerceAtLeast(0) } }
0
Kotlin
0
0
e510e4a9801c228057cb107e3e7463d4a946bdae
798
advent-of-code-2018
MIT License
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/Detekt.kt
niraj8
272,693,530
true
{"Kotlin": 1474242, "Groovy": 3832, "Shell": 1055, "HTML": 698}
package io.gitlab.arturbosch.detekt import io.gitlab.arturbosch.detekt.extensions.CustomDetektReport import io.gitlab.arturbosch.detekt.extensions.DetektReportType import io.gitlab.arturbosch.detekt.extensions.DetektReports import io.gitlab.arturbosch.detekt.internal.configurableFileCollection import io.gitlab.arturbosch.detekt.internal.fileProperty import io.gitlab.arturbosch.detekt.invoke.AutoCorrectArgument import io.gitlab.arturbosch.detekt.invoke.BaselineArgument import io.gitlab.arturbosch.detekt.invoke.BuildUponDefaultConfigArgument import io.gitlab.arturbosch.detekt.invoke.ClasspathArgument import io.gitlab.arturbosch.detekt.invoke.ConfigArgument import io.gitlab.arturbosch.detekt.invoke.CustomReportArgument import io.gitlab.arturbosch.detekt.invoke.DebugArgument import io.gitlab.arturbosch.detekt.invoke.DefaultReportArgument import io.gitlab.arturbosch.detekt.invoke.DetektInvoker import io.gitlab.arturbosch.detekt.invoke.DisableDefaultRuleSetArgument import io.gitlab.arturbosch.detekt.invoke.FailFastArgument import io.gitlab.arturbosch.detekt.invoke.InputArgument import io.gitlab.arturbosch.detekt.invoke.JvmTargetArgument import io.gitlab.arturbosch.detekt.invoke.LanguageVersionArgument import io.gitlab.arturbosch.detekt.invoke.ParallelArgument import io.gitlab.arturbosch.detekt.invoke.PluginsArgument import org.gradle.api.Action import org.gradle.api.GradleException import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.Directory import org.gradle.api.file.FileCollection import org.gradle.api.file.RegularFile import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.reporting.ReportingExtension import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Classpath import org.gradle.api.tasks.Console import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Nested import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SourceTask import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.VerificationTask import org.gradle.language.base.plugins.LifecycleBasePlugin import java.io.File @CacheableTask open class Detekt : SourceTask(), VerificationTask { @Deprecated("Replace with getSource/setSource") var input: FileCollection @Internal get() = source set(value) = setSource(value) @get:Input @get:Optional @Deprecated("Replace with setIncludes/setExcludes") var filters: Property<String> = project.objects.property(String::class.java) @get:Classpath val detektClasspath = project.configurableFileCollection() @get:Classpath val pluginClasspath = project.configurableFileCollection() @get:InputFile @get:Optional @get:PathSensitive(PathSensitivity.RELATIVE) var baseline: RegularFileProperty = project.fileProperty() @Deprecated("Use baseline.set()") set @get:InputFiles @get:Optional @get:PathSensitive(PathSensitivity.RELATIVE) var config: ConfigurableFileCollection = project.configurableFileCollection() @Deprecated("Use config.setFrom()") set @get:Classpath @get:Optional val classpath = project.configurableFileCollection() @get:Input @get:Optional internal val languageVersionProp: Property<String> = project.objects.property(String::class.javaObjectType) var languageVersion: String @Internal get() = languageVersionProp.get() set(value) = languageVersionProp.set(value) @get:Input @get:Optional internal val jvmTargetProp: Property<String> = project.objects.property(String::class.javaObjectType) var jvmTarget: String @Internal get() = jvmTargetProp.get() set(value) = jvmTargetProp.set(value) @get:Input @get:Optional @Deprecated( "Set plugins using the detektPlugins configuration " + "(see https://arturbosch.github.io/detekt/extensions.html#let-detekt-know-about-your-extensions)" ) var plugins: Property<String> = project.objects.property(String::class.java) @get:Internal internal val debugProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) var debug: Boolean @Console get() = debugProp.getOrElse(false) set(value) = debugProp.set(value) @get:Internal internal val parallelProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) var parallel: Boolean @Internal get() = parallelProp.getOrElse(false) set(value) = parallelProp.set(value) @get:Internal internal val disableDefaultRuleSetsProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) var disableDefaultRuleSets: Boolean @Input get() = disableDefaultRuleSetsProp.getOrElse(false) set(value) = disableDefaultRuleSetsProp.set(value) @get:Internal internal val buildUponDefaultConfigProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) var buildUponDefaultConfig: Boolean @Input get() = buildUponDefaultConfigProp.getOrElse(false) set(value) = buildUponDefaultConfigProp.set(value) @get:Internal internal val failFastProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) var failFast: Boolean @Input get() = failFastProp.getOrElse(false) set(value) = failFastProp.set(value) @get:Internal internal val ignoreFailuresProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @Input override fun getIgnoreFailures(): Boolean = ignoreFailuresProp.getOrElse(false) override fun setIgnoreFailures(value: Boolean) = ignoreFailuresProp.set(value) @get:Internal internal val autoCorrectProp: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) var autoCorrect: Boolean @Input get() = autoCorrectProp.getOrElse(false) set(value) = autoCorrectProp.set(value) @get:Internal var reports = DetektReports(project) fun reports(configure: Action<DetektReports>) = configure.execute(reports) @get:Internal var reportsDir: Property<File> = project.objects.property(File::class.java) @Deprecated("Use reportsDir.set()") set val xmlReportFile: Provider<RegularFile> @OutputFile @Optional get() = reports.xml.getTargetFileProvider(effectiveReportsDir) val htmlReportFile: Provider<RegularFile> @OutputFile @Optional get() = reports.html.getTargetFileProvider(effectiveReportsDir) val txtReportFile: Provider<RegularFile> @OutputFile @Optional get() = reports.txt.getTargetFileProvider(effectiveReportsDir) private val defaultReportsDir: Directory = project.layout.buildDirectory.get() .dir(ReportingExtension.DEFAULT_REPORTS_DIR_NAME) .dir("detekt") private val effectiveReportsDir = project.provider { reportsDir.getOrElse(defaultReportsDir.asFile) } @Deprecated("Use reports {} to configure custom reports") val customReports: Provider<Collection<CustomDetektReport>> @Nested get() = project.provider { reports.custom } init { group = LifecycleBasePlugin.VERIFICATION_GROUP } @TaskAction fun check() { if (plugins.isPresent && !pluginClasspath.isEmpty) { throw GradleException( "Cannot set value for plugins on detekt task and apply detektPlugins configuration " + "at the same time." ) } val arguments = mutableListOf( InputArgument(source), ClasspathArgument(classpath), LanguageVersionArgument(languageVersionProp.orNull), JvmTargetArgument(jvmTargetProp.orNull), ConfigArgument(config), PluginsArgument(plugins.orNull), BaselineArgument(baseline.orNull), DefaultReportArgument(DetektReportType.XML, xmlReportFile.orNull), DefaultReportArgument(DetektReportType.HTML, htmlReportFile.orNull), DefaultReportArgument(DetektReportType.TXT, txtReportFile.orNull), DebugArgument(debugProp.getOrElse(false)), ParallelArgument(parallelProp.getOrElse(false)), BuildUponDefaultConfigArgument(buildUponDefaultConfigProp.getOrElse(false)), FailFastArgument(failFastProp.getOrElse(false)), AutoCorrectArgument(autoCorrectProp.getOrElse(false)), DisableDefaultRuleSetArgument(disableDefaultRuleSetsProp.getOrElse(false)) ) arguments.addAll(customReports.get().map { val reportId = it.reportIdProp.orNull val destination = it.destinationProperty.orNull checkNotNull(reportId) { "If a custom report is specified, the reportId must be present" } check(!DetektReportType.isWellKnownReportId(reportId)) { "The custom report reportId may not be same as one of the default reports" } checkNotNull(destination) { "If a custom report is specified, the destination must be present" } CustomReportArgument(reportId, destination) }) DetektInvoker.create(project).invokeCli( arguments = arguments.toList(), ignoreFailures = ignoreFailures, classpath = detektClasspath.plus(pluginClasspath), taskName = name ) } }
0
null
0
1
8536e848ec2d4470c970442a8ea4579937b4b2d8
9,822
detekt
Apache License 2.0
src/main/kotlin/com/figure/gradle/semver/SemverExtension.kt
FigureTechnologies
496,001,309
false
null
/* * Copyright (C) 2024 Figure Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.figure.gradle.semver import org.gradle.api.file.RegularFileProperty import org.gradle.api.initialization.Settings import org.gradle.api.plugins.ExtensionAware import org.gradle.api.provider.Property /** * Configuration for the Semver Settings Plugin that enables: * - Manually setting the rootProjectDir * - An initial version * - The main branch, if not `main` or `master` * - The development branch if not `develop`, `devel`, or `dev` * */ interface SemverExtension { val rootProjectDir: RegularFileProperty val initialVersion: Property<String> val mainBranch: Property<String> val developmentBranch: Property<String> val appendBuildMetadata: Property<String> companion object { const val NAME = "semver" } } fun Settings.semver(configure: SemverExtension.() -> Unit): Unit = (this as ExtensionAware).extensions.configure(SemverExtension.NAME, configure)
2
null
2
15
0c5f9d2beb60d980fa9f2a159c7cc6bc8865702c
1,527
gradle-semver-plugin
Apache License 2.0
src/main/kotlin/org/domaindrivenarchitecture/provs/framework/core/YamlUtils.kt
DomainDrivenArchitecture
671,424,521
false
{"Kotlin": 403360, "Shell": 38541, "Python": 3745, "Vim Script": 457, "Dockerfile": 374}
package org.domaindrivenarchitecture.provs.framework.core import com.charleskorn.kaml.Yaml import com.charleskorn.kaml.YamlConfiguration import kotlinx.serialization.serializer import java.io.BufferedReader import java.io.File import java.io.FileReader fun readFromFile(fileName: String): String { return BufferedReader(FileReader(fileName)).use { it.readText() } } fun writeToFile(fileName: String, text: String) { File(fileName).writeText(text) } inline fun <reified T : Any> String.yamlToType() = Yaml(configuration = YamlConfiguration(strictMode = false)).decodeFromString( serializer<T>(), this ) inline fun <reified T : Any> T.toYaml() = Yaml(configuration = YamlConfiguration(strictMode = false, encodeDefaults = false)).encodeToString( serializer<T>(), this )
0
Kotlin
0
1
c0985afaccd1500185269892cecae82a0a8f4078
800
provs
Apache License 2.0
core/src/main/kotlin/su/skaard/core/synchronization/handlers/VoiceChannelCreateHandler.kt
ya0igoddess
531,925,689
false
{"Kotlin": 55723, "CSS": 554, "Dockerfile": 104}
package su.skaard.core.synchronization.handlers import dev.kord.core.event.Event import dev.kord.core.event.channel.VoiceChannelCreateEvent import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import su.skaard.core.handlers.DiscordEventHandler import su.skaard.core.synchronization.services.ISynchronizationService @Component class VoiceChannelCreateHandler @Autowired constructor( private val ISynchronizationService: ISynchronizationService ) : DiscordEventHandler { override suspend fun handle(event: Event) { if (event !is VoiceChannelCreateEvent) return ISynchronizationService.handleVoiceChannelCreateEvent(event) } }
0
Kotlin
0
2
33cd9fabff08a34caa4a28940d857018d582ba35
711
skaard
MIT License
gradle-plugin/src/test/java/app/cash/better/dynamic/features/BetterDynamicFeaturesPluginTest.kt
cashapp
554,843,721
false
{"Kotlin": 242855}
/* * Copyright (C) 2023 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.better.dynamic.features import app.cash.better.dynamic.features.tasks.Version import app.cash.better.dynamic.features.utils.assertThat import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import org.junit.Test import java.io.File import kotlin.io.path.bufferedReader class BetterDynamicFeaturesPluginTest { @Test fun `base and feature apks have different library versions`() { val integrationRoot = File("src/test/fixtures/different-versions") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.squareup.okhttp3:okhttp:4.9.3 -> 5.0.0-alpha.2") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `base configurations have different dependency versions`() { val integrationRoot = File("src/test/fixtures/different-versions-in-base") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.squareup.okhttp3:okhttp:4.9.3 -> 5.0.0-alpha.2") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `base and feature apks have same library versions`() { val integrationRoot = File("src/test/fixtures/same-versions") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.squareup.okhttp3:okhttp:4.9.3") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |com.squareup.okhttp3:okhttp:4.9.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `lockfile updates if task run after dependency version change`() { val integrationRoot = File("src/test/fixtures/version-update") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val featureGradle = integrationRoot.resolve("feature/build.gradle") featureGradle.writeText(featureGradle.readText().replace("5.0.0-alpha.2", "4.9.3")) val result = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") .build() assertThat(result.output).contains("BUILD SUCCESSFUL") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:4.9.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) // Update dependency version featureGradle.writeText(featureGradle.readText().replace("4.9.3", "5.0.0-alpha.2")) val newGradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .withArguments(":base:writeLockfile") val newResult = newGradleRunner.build() assertThat(newResult.output).contains("BUILD SUCCESSFUL") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) // Undo that featureGradle.writeText(featureGradle.readText().replace("5.0.0-alpha.2", "4.9.3")) } @Test fun `plugin tasks do not build project module dependencies`() { val integrationRoot = File("src/test/fixtures/project-dependency") val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") val result = gradleRunner.build() assertThat(result.output).contains("BUILD SUCCESSFUL") assertThat(result.task(":library:jar")?.outcome).isNull() } @Test fun `lockfile includes transitive dependencies from feature dependencies`() { val integrationRoot = File("src/test/fixtures/transitive-dependency") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.squareup.okhttp3:okhttp:4.9.3 -> 5.0.0-alpha.2") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `lockfile includes transitive dependencies from base module project dependencies`() { val integrationRoot = File("src/test/fixtures/transitive-dependency-on-base") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.squareup.okhttp3:okhttp:4.9.3 -> 5.0.0-alpha.2") assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `variant-specific transitive dependencies from base module project dependencies are handled`() { val integrationRoot = File("src/test/fixtures/transitive-dependency-on-base-variant-aware") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() assertThat(baseProject.lockfile().readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.retrofit2:retrofit:2.9.0=debugRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `lockfiles activated on base runtime classpath configurations`() { val integrationRoot = File("src/test/fixtures/lockfile-activation") val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:build") val result = gradleRunner.buildAndFail() // The included lockfile is invalid, so if activated then these errors should be shown assertThat(result.output).contains("Resolved 'org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION' which is not part of the dependency lock state") assertThat(result.output).contains("Cannot find a version of 'com.squareup.okhttp3:okhttp' that satisfies the version constraints:") } @Test fun `lockfile handles variant-specific dependencies correctly`() { val integrationRoot = File("src/test/fixtures/variant-aware") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.jakewharton.picnic:picnic:0.4.0 -> 0.5.0") assertThat(baseProject.lockfile().readText()).contains( """ |com.jakewharton.picnic:picnic:0.5.0=debugCompileClasspath,debugRuntimeClasspath |com.squareup.okhttp3:okhttp:4.9.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath """.trimMargin(), ) assertThat(baseProject.lockfile().readText()).contains( """ |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath """.trimMargin(), ) } @Test fun `build with outdated lockfile fails`() { val integrationRoot = File("src/test/fixtures/out-of-date") val lockfile = integrationRoot.resolve("base/gradle.lockfile") integrationRoot.lockfile("base").writeText( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:4.9.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:installDebug") val result = gradleRunner.buildAndFail() assertThat(result.output).contains("The lockfile was out of date and has been updated. Rerun your build.") val lockfileContent = lockfile.readText() assertThat(lockfileContent).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `checkLockfile task stays up-to-date if dependencies unchanged`() { val integrationRoot = File("src/test/fixtures/up-to-date") integrationRoot.lockfile("base").writeText( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:5.0.0-alpha.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.9.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:preBuild") gradleRunner.build() val result = gradleRunner.withArguments(":base:preBuild").build() assertThat(result.output).contains("BUILD SUCCESSFUL") assertThat(result.task(":base:checkLockfile")?.outcome).isEqualTo(TaskOutcome.UP_TO_DATE) } @Test fun `lockfile references multiplatform dependencies correctly`() { val integrationRoot = File("src/test/fixtures/multiplatform-dependency") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") gradleRunner.build() val lockfile = baseProject.lockfile().readText() assertThat(lockfile).contains("com.squareup.sqldelight:runtime-jvm:1.5.4=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") assertThat(lockfile).contains("com.squareup.sqldelight:runtime:1.5.4=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") } @Test fun `lockfile does not include project dependencies`() { val integrationRoot = File("src/test/fixtures/project-dependency") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") gradleRunner.build() val lockfile = baseProject.lockfile().readText() assertThat(lockfile).doesNotContain("project-dependency:library:unspecified=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") } @Test fun `custom lockfile location is written correctly`() { val integrationRoot = File("src/test/fixtures/custom-lockfile") val baseProject = integrationRoot.resolve("base") val customLockfile = baseProject.resolve("custom.lockfile") customLockfile.takeIf { it.exists() }?.delete() val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.squareup.okhttp3:okhttp:4.9.3") assertThat(customLockfile.readText()).isEqualTo( """ |# This is a Gradle generated file for dependency locking. |# Manual edits can break the build and are not advised. |# This file is expected to be part of source control. |androidx.activity:activity:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.annotation:annotation:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.arch.core:core-runtime:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.collection:collection:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.core:core:1.2.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.customview:customview:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.fragment:fragment:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-common:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-livedata:2.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-runtime:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.loader:loader:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.savedstate:savedstate:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.versionedparcelable:versionedparcelable:1.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |androidx.viewpager:viewpager:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-basement:18.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.gms:play-services-tasks:18.0.2=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:core-common:2.0.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery-ktx:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.google.android.play:feature-delivery:2.1.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okhttp3:okhttp:4.9.3=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |com.squareup.okio:okio:2.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-common:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlin:kotlin-stdlib:$KOTLIN_VERSION=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains:annotations:13.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |empty= """.trimMargin(), ) } @Test fun `new transitive dependency is recorded in lockfile`() { val integrationRoot = File("src/test/fixtures/new-transitive-dependency") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") // Generate lockfile first, and then run dependencies task gradleRunner.build() val result = gradleRunner.withArguments(":base:dependencies").build() assertThat(result.output).contains("com.google.android.material:material:1.2.0 -> 1.7.0") // Dynamic animation is a new transitive dependency of material added after 1.2.0 assertThat(result.output).contains("androidx.dynamicanimation:dynamicanimation:1.0.0") val lockfileContent = baseProject.lockfile().readText() assertThat(lockfileContent).contains("com.google.android.material:material:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") assertThat(lockfileContent).contains("androidx.dynamicanimation:dynamicanimation:1.0.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") } @Test fun `constraints from BOMs are not pulled into lockfile`() { val integrationRoot = File("src/test/fixtures/has-constraints") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile") gradleRunner.build() val lockfileContent = baseProject.lockfile().readText() assertThat(lockfileContent).contains("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") assertThat(lockfileContent).contains("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") // These are constraints that exists on the BOM which shouldn't be pulled in assertThat(lockfileContent).doesNotContain("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.4=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") assertThat(lockfileContent).doesNotContain("org.jetbrains.kotlinx:kotlinx-coroutines-reactive:1.6.4=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath") } @Test fun `writeLockfile task passes with configureondemand enabled`() { val integrationRoot = File("src/test/fixtures/same-versions") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) // We run the clean task only on :base to avoid direct configuration of the :feature module // This tests that the :feature module is configured indirectly through being depended on by :base val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned(module = "base") .withArguments("-Dorg.gradle.configureondemand=true", ":base:writeLockfile") gradleRunner.build() } @Test fun `updating lockfile while with other tasks fails`() { val integrationRoot = File("src/test/fixtures/same-versions") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .withArguments("clean", ":base:writeLockfile") val result = gradleRunner.buildAndFail() assertThat(result.output).contains("Updating the lockfile and running other tasks together is an error. Update the lockfile first, and then run your other tasks separately.") } @Test fun `feature module compile classpath does not influence base module runtime classpath`() { val integrationRoot = File("src/test/fixtures/feature-compile-classpath") val baseProject = integrationRoot.resolve("base") clearLockfile(baseProject) val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:writeLockfile", "--stacktrace") gradleRunner.build() assertThat(baseProject.lockfile().readText()).contains( """ |org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath |org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0=debugCompileClasspath,debugRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath """.trimMargin(), ) } @Test fun `semver comparison is correct`() { val low = Version("2.8.7") val high = Version("2.10.1") assertThat(high).isGreaterThan(low) } @Test fun `missing dex patch works correctly`() { val integrationRoot = File("src/test/fixtures/missing-dex") val gradleRunner = GradleRunner.create() .withCommonConfiguration(integrationRoot) .cleaned() .withArguments(":base:packageDebugUniversalApk", "--stacktrace") gradleRunner.build() val dexContent = dexdump(integrationRoot.resolve("base/build/outputs/apk_from_bundle/debug/base-debug-universal.apk")) assertThat(dexContent.bufferedReader().lineSequence()).containsInConsecutiveOrder( """ Class descriptor : 'Lcom/example/JavaClass;'""", """ Access flags : 0x0001 (PUBLIC)""", """ Superclass : 'Ljava/lang/Object;'""", ) assertThat(dexContent.bufferedReader().lineSequence()).containsInConsecutiveOrder( """ Class descriptor : 'Lcom/example/KotlinClass;'""", """ Access flags : 0x0011 (PUBLIC FINAL)""", """ Superclass : 'Ljava/lang/Object;'""", ) } private fun clearLockfile(root: File) { root.lockfile().takeIf { it.exists() }?.delete() } private fun File.lockfile(module: String? = null) = resolve(if (module != null) "$module/gradle.lockfile" else "gradle.lockfile") }
5
Kotlin
3
80
a4afddeb6b7b4fcc29e422a9d25bfadb8288adc1
68,918
better-dynamic-features
Apache License 2.0
app/src/main/kotlin/na/komi/kodesh/ui/internal/BaseFragment2.kt
inshiro
174,658,194
false
null
package na.komi.kodesh.ui.internal import android.app.Activity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.AppCompatTextView import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.children import androidx.fragment.app.Fragment import com.google.android.material.navigation.NavigationView import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelChildren import na.komi.kodesh.R import na.komi.kodesh.ui.main.MainActivity import na.komi.kodesh.util.close import na.komi.kodesh.util.onClick import na.komi.kodesh.util.toggle import kotlin.coroutines.CoroutineContext abstract class BaseFragment2 : Fragment(), CoroutineScope, TitleListener, InjectListener { open val job by lazy { SupervisorJob() } override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job//ContextHelper.dispatcher + job abstract val layout: Int init { /** * This retains the state on config change and does not call oncreate again. * https://stackoverflow.com/a/18681837 */ retainInstance = true } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(layout, container, false) } /** * getBottomSheetBehavior * getToolbarTitleView * getNavigationView */ fun getBottomSheetContainer(): ConstraintLayout? = act?.bottomSheetContainer fun getBottomSheetBehavior(): BottomSheetBehavior2<ConstraintLayout>? = act?.bottomSheetBehavior fun getToolbarTitleView(): AppCompatTextView? = act?.getToolbarTitleView() fun getNavigationView(): NavigationView = act?.getNavigationView()!! fun getToolbar(): Toolbar? = act?.getToolbar() private val act get()= (activity as? MainActivity) /* override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) getToolbar()?.let { for (a in it.menu.children) a.isVisible = true } getNavigationView().let { it.setCheckedItem(R.id.action_read) for (a in it.menu.children) a.isEnabled = true } getToolbarTitleView()?.onClick { onToolbarTitleClick() } }*/ fun closeBottomSheet() = getBottomSheetBehavior()?.close() fun toggleBottomSheet() = getBottomSheetBehavior()?.toggle() override fun onDestroy() { super.onDestroy() coroutineContext.cancelChildren() } }
0
Kotlin
3
8
311fe579feb9948086e0523226c11a69dac26133
2,805
kodesh
Apache License 2.0
appModules/appFeatures/api/src/commonMain/kotlin/dev/reprator/appFeatures/api/utility/InternetChecker.kt
TheReprator
781,077,991
false
{"Kotlin": 399028, "Swift": 5325, "HTML": 357, "JavaScript": 92}
package dev.reprator.appFeatures.api.utility import kotlinx.coroutines.flow.StateFlow import kotlin.experimental.ExperimentalObjCRefinement import kotlin.native.HiddenFromObjC @OptIn(ExperimentalObjCRefinement::class) @HiddenFromObjC interface InternetChecker { val networkStatus: StateFlow<Boolean> }
1
Kotlin
0
0
1468ecc36c791f643973d0fadae9f6154d726b84
307
ExpenseManagment
Apache License 2.0
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/tasks/ListingFileRedirectTask.kt
RivanParmar
526,653,590
false
{"Java": 48334972, "Kotlin": 8897422, "HTML": 109232, "Lex": 13233, "ReScript": 3232, "Makefile": 2194}
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.tasks import com.android.build.api.artifact.Artifact import com.android.build.gradle.internal.component.ComponentCreationConfig import com.android.build.gradle.internal.tasks.factory.TaskCreationAction import com.android.build.gradle.internal.utils.setDisallowChanges import com.android.buildanalyzer.common.TaskCategory import com.android.ide.common.build.ListingFileRedirect import org.gradle.api.file.RegularFile import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskProvider import org.gradle.work.DisableCachingByDefault /** * [org.gradle.api.Task] to create a redirect file that contains the location of the IDE model * file. The location of the redirect file is never changing and cannot be "replaced" by anyone. * The location is passed through the model to the IDE which is expecting to always find the * redirect file at the same location independently on where tasks will put APK, Bundle, etc... * * For instance, if any other plugin decide to replace the APKs, the APK_IDE_MODEL will be * automatically created by the variant API in the new location. The redirect file will not change * and will just point to the new location for the model file. * * Caching is disabled as the full path to the listing file is used as input. Plus the task * execution should be so fast, that it outweighs the benefits in performance. */ @DisableCachingByDefault @BuildAnalyzer(primaryTaskCategory = TaskCategory.SYNC) abstract class ListingFileRedirectTask: NonIncrementalTask() { @get:OutputFile abstract val redirectFile: RegularFileProperty @get:InputFile @get:PathSensitive(PathSensitivity.ABSOLUTE) abstract val listingFile: RegularFileProperty override fun doTaskAction() { ListingFileRedirect.writeRedirect( listingFile = listingFile.asFile.get(), into = redirectFile.asFile.get() ) } internal class CreationAction( private val creationConfig: ComponentCreationConfig, taskSuffix: String, private val inputArtifactType: Artifact.Single<RegularFile>, private val outputArtifactType: Artifact.Single<RegularFile>, ) : TaskCreationAction<ListingFileRedirectTask>() { override val type = ListingFileRedirectTask::class.java override val name = creationConfig.computeTaskName( prefix = "create", suffix = "${taskSuffix}ListingFileRedirect") override fun handleProvider(taskProvider: TaskProvider<ListingFileRedirectTask>) { creationConfig.artifacts.setInitialProvider( taskProvider, ListingFileRedirectTask::redirectFile ).withName(ListingFileRedirect.REDIRECT_FILE_NAME).on(outputArtifactType) } override fun configure(task: ListingFileRedirectTask) { task.configureVariantProperties(variantName = "", creationConfig.services.buildServiceRegistry) task.listingFile.setDisallowChanges( creationConfig.artifacts.get(inputArtifactType) ) } } }
0
Java
2
17
a497291d77bba1aa34271808088fe1e8aab5efe2
3,904
androlabs
Apache License 2.0
mqtt/src/main/kotlin/org/sheedon/mqtt/Dispatcher.kt
Sheedon
253,232,370
false
null
package org.sheedon.mqtt import com.github.yitter.contract.IIdGenerator import com.github.yitter.contract.IdGeneratorOptions import com.github.yitter.idgen.DefaultIdGenerator import org.eclipse.paho.client.mqttv3.MqttMessage import org.sheedon.mqtt.* import org.sheedon.mqtt.internal.DataConverter import org.sheedon.mqtt.internal.binder.IBindHandler import org.sheedon.mqtt.internal.concurrent.CallbackEnum import org.sheedon.mqtt.internal.concurrent.ObserverCallArray import org.sheedon.mqtt.internal.concurrent.ReadyTask import org.sheedon.mqtt.internal.concurrent.RequestCallArray import org.sheedon.mqtt.internal.connection.RealCall import org.sheedon.mqtt.internal.connection.RealObservable import org.sheedon.mqtt.utils.Logger import org.sheedon.rr.timeout.DelayEvent.Companion.build import org.sheedon.rr.timeout.OnTimeOutListener import org.sheedon.rr.timeout.android.TimeOutHandler import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeoutException /** * MQTT request-response bound dispatcher, that policy on manage ready requests. * * 在调度者中,主要维持ID-Map、请求存储资源、订阅存储资源 和 超时触发器。 * * ID-Map:所有的请求和订阅任务,统一会产生一个id-key作为键,将就绪任务作为值,存入到map中[readyCalls], * 以便于在取消/超时触发时,根据ID得到目标任务,从而将task由[requestCalls]或[observerCalls]中移除。 * * requestCalls:作为请求响应模式下所记录的任务池,单一针对于反馈某一个请求所关联的响应消息,而且只反馈一次(未取消情况下, * 超时反馈,或者响应结果反馈)。因此,该对象提供三个方法: * [RequestCallArray.subscribe],订阅一个响应主题,topic/keyword/topic+keyword的组合形式,将任务添加到队列尾部。 * [RequestCallArray.unsubscribe],取消订阅一个响应主题,根据传入的 关联项,核实该消息是 通过「主题/关键字」取消队列中目标订阅。 * [RequestCallArray.callResponse],响应结果,根据传入的 关联项,核实该消息是 通过「主题/关键字」提取队列首个订阅,并且反馈这个响应。 * * observerCalls:作为订阅模式下所记录的任务池,在未执行取消的前提下,将永久保存在队列中。提供的方法如[requestCalls]一致, * [ObserverCallArray.subscribe], [ObserverCallArray.unsubscribe], [ObserverCallArray.callResponse] * 其中[ObserverCallArray.callResponse],将反馈所有符合条件的订阅信息。 * * timeoutHandler:超时触发器,登记并且执行超时事件,在超时的时间点回调记录的事件所包含的任务ID,dispatcher将对超时的任务ID, * 从readyCalls中找到对应的任务,并且向requestCalls执行取消订阅的行为。 * * * @Author: sheedon * @Email: <EMAIL> * @Date: 2022/3/28 9:47 下午 */ internal class Dispatcher( private val convertArray: ArrayList<DataConverter<ResponseBody, String>>, private val defaultTimeout: Long // 默认超时时间 ) : IBindHandler { // 以请求ID为键,以请求任务为值的请求数据池 private val readyCalls = ConcurrentHashMap<Long, ReadyTask>() // 请求队列池,反馈主题/关键字为键,同样的反馈主题的内容,依次存入有序队列中 private val requestCalls = RequestCallArray() // 请求队列池,反馈主题/关键字为键,同样的反馈主题的内容,依次存入有序队列中 private val observerCalls = ObserverCallArray() // 雪花飘移算法配置 private val idGenerator: IIdGenerator by lazy { val options = IdGeneratorOptions(1).apply { WorkerIdBitLength = 10 } DefaultIdGenerator(options) } // 超时执行者 private val timeoutHandler: TimeOutHandler<Long> = TimeOutHandler<Long>() .apply { setListener(TimeOutListener()) } /** * 订阅一个主题/关键字,通过传递请求对象/反馈呼叫对象/呼叫类型,转换成「准备就绪任务」,存入 readyCalls 中, * 并且将作为readyCalls键的ID返回,用于后续取消订阅的动作 * * @param request 请求或监听对象,其一为了响应时反馈请求或订阅信息,其二用于提取关键字,超时时间间隔 * @param back 呼叫对象,用于反馈结果 * @param type 呼叫类型,单次订阅/保留订阅 */ override fun subscribe( call: RealCall, back: IBack ): Pair<Long, Long> { Logger.info("Dispatcher", "subscribe to call: $call and type: ${CallbackEnum.SINGLE}") val request = call.originalRequest // 记录并且得到内部消息ID val id = requestCalls.subscribe( call, back, ::loadId, ::offerReadyCalls ) val relation = request.relation // 计算超时时长,若请求中未填,则采用默认超时时长 val timeout = relation.timeout.let { if (it == null || it == 0L) { return@let defaultTimeout } return@let it } // 追加超时事件 appendTimeoutEvent(timeout, id) // 将ID返回到调度者,以做后续取消订阅动作 // timeout 超时时长 return Pair(id, timeout) } /** * 订阅一个主题/关键字,通过传递请求对象/反馈呼叫对象/呼叫类型,转换成「准备就绪任务」,存入 readyCalls 中, * 并且将作为readyCalls键的ID返回,用于后续取消订阅的动作 * * @param observable 请求或监听对象,其一为了响应时反馈请求或订阅信息,其二用于提取关键字,超时时间间隔 * @param back 呼叫对象,用于反馈结果 */ override fun subscribe(observable: RealObservable, back: IBack): List<Long> { Logger.info( "Dispatcher", "subscribe to call: $observable and type: ${CallbackEnum.RETAIN}" ) // 将ID返回到调度者,以做后续取消订阅动作 return observerCalls.subscribe( observable, back, ::loadId, ::offerReadyCalls ) } /** * 追加一个超时事件到「超时处理器」中,由「超时处理器」在到达超时期限后,返回到当前执行超时反馈 * * @param timeout 超时时长 * @param id 消息ID */ private fun appendTimeoutEvent(timeout: Long, id: Long) { val event = build(id, timeout + System.currentTimeMillis()) Logger.info("Dispatcher", "addBinder to addEvent success") timeoutHandler.addEvent(event) } /** * 根据一个消息ID组,取消订阅一个就绪的任务 * * @param id 消息ID组 */ override fun unsubscribe(vararg id: Long) { id.forEach { val readyTask = readyCalls.remove(it) ?: return@forEach if (readyTask.type == CallbackEnum.SINGLE) { // 取消超时事件 timeoutHandler.removeEvent(it) // 取消单次订阅 requestCalls.unsubscribe(readyTask) } else if (readyTask.type == CallbackEnum.RETAIN) { // 取消保留订阅 observerCalls.unsubscribe(readyTask) } } } /** * 反馈mqtt结果 */ fun callResponse(topic: String, message: MqttMessage) { val responseBody = ResponseBody(topic, message) val keyword = responseBody.run { convertArray.forEach { val backKeyword = it.convert(this) if (backKeyword != null) { return@run backKeyword } } null } // 请求的反馈执行 requestCalls.callResponse(keyword, responseBody, ::pollReadyCallsById) // 订阅消息的通知 observerCalls.callResponse(keyword, responseBody) } /** * 根据消息ID 添加一个就绪的呼叫任务 * * @param id 消息ID */ private fun offerReadyCalls(id: Long, task: ReadyTask) { readyCalls[id] = task } /** * 根据消息ID 移除一个就绪的呼叫任务 * * @param id 消息ID */ private fun pollReadyCallsById(id: Long): ReadyTask? { // 同时移除超时任务 timeoutHandler.removeEvent(id) return readyCalls.remove(id) } /** * 获取消息ID */ private fun loadId(): Long { return idGenerator.newLong() } /** * 超时监听器 */ private inner class TimeOutListener : OnTimeOutListener<Long> { override fun onTimeOut(id: Long, e: TimeoutException?) { val readyTask = readyCalls.remove(id) ?: return Logger.info("Dispatcher", "onTimeout task($readyTask)") // 移除请求订阅内容 requestCalls.unsubscribe(readyTask) // 反馈超时消息 readyTask.back?.onFailure(e) } } /** * 取消全部任务事件 */ internal fun clearAll() { readyCalls.clear() requestCalls.clear() observerCalls.clear() } /** * 销毁动作 * 销毁超时执行器 */ internal fun destroy() { clearAll() timeoutHandler.destroy() } }
0
null
3
6
82bfdf15b61f0cd08d3ff2f751e516d1116ce711
7,362
MqttDispatcher
Apache License 2.0
java/java-tests/testSrc/com/intellij/java/codeInspection/Java9ModuleExportsPackageToItselfTest.kt
androidports
115,100,208
false
null
/* * 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.java.codeInspection import com.intellij.codeInspection.InspectionsBundle import com.intellij.codeInspection.java19modules.Java9ModuleExportsPackageToItselfInspection import com.intellij.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor import org.intellij.lang.annotations.Language /** * @author Pavel.Dolgov */ class Java9ModuleExportsPackageToItselfTest : LightJava9ModulesCodeInsightFixtureTestCase() { private val message = InspectionsBundle.message("inspection.module.exports.package.to.itself")!! private val fix1 = InspectionsBundle.message("exports.to.itself.delete.statement.fix")!! private val fix2 = InspectionsBundle.message("exports.to.itself.delete.module.ref.fix", "M")!! override fun setUp() { super.setUp() myFixture.enableInspections(Java9ModuleExportsPackageToItselfInspection()) addFile("module-info.java", "module M2 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2) addFile("module-info.java", "module M4 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M4) addFile("pkg/main/C.java", "package pkg.main; public class C {}") } fun testNoSelfModule() { highlight("module M {\n exports pkg.main to M2, M4;\n opens pkg.main to M2, M4;\n}") } fun testOnlySelfExport() { highlight("module M { exports pkg.main to <warning descr=\"$message\">M</warning>; }") fix("module M { exports pkg.main to <caret>M; }", "module M {\n}") } fun testOnlySelfOpen() { highlight("module M { opens pkg.main to <warning descr=\"$message\">M</warning>; }") fix("module M { opens pkg.main to <caret>M; }", "module M {\n}") } fun testOnlySelfModuleWithComments() { fix("module M { exports pkg.main to /*a*/ <caret>M /*b*/; }", "module M { /*a*/ /*b*/\n}") } fun testSelfModuleInList() { highlight("module M { exports pkg.main to M2, <warning descr=\"$message\">M</warning>, M4; }") fix("module M { exports pkg.main to M2, <caret>M , M4; }", "module M { exports pkg.main to M2, M4; }") } fun testSelfModuleInListWithComments() { fix("module M { exports pkg.main to M2, /*a*/ <caret>M /*b*/,/*c*/ M4; }", "module M { exports pkg.main to M2, /*a*/ /*b*//*c*/ M4; }") } private fun highlight(text: String) { myFixture.configureByText("module-info.java", text) myFixture.checkHighlighting() } private fun fix(textBefore: String, @Language("JAVA") textAfter: String) { myFixture.configureByText("module-info.java", textBefore) val action = myFixture.filterAvailableIntentions(fix1).firstOrNull() ?: myFixture.filterAvailableIntentions(fix2).first() myFixture.launchAction(action) myFixture.checkHighlighting() // no warning myFixture.checkResult("module-info.java", textAfter, false) } }
6
null
1
4
6e4f7135c5843ed93c15a9782f29e4400df8b068
3,494
intellij-community
Apache License 2.0
core/database/src/main/kotlin/com/google/samples/apps/nowinandroid/core/database/model/TopicFtsEntity.kt
Arturs1123
778,126,656
false
null
/* * Copyright 2023 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apps.longhrk.core.database.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Fts4 /** * Fts entity for the topic. See https://developer.android.com/reference/androidx/room/Fts4. */ @Entity(tableName = "topicsFts") @Fts4 data class TopicFtsEntity( @ColumnInfo(name = "topicId") val topicId: String, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "shortDescription") val shortDescription: String, @ColumnInfo(name = "longDescription") val longDescription: String, ) fun TopicEntity.asFtsEntity() = TopicFtsEntity( topicId = id, name = name, shortDescription = shortDescription, longDescription = longDescription, )
11
null
1
2
b16bc73ea6d4c778d6bdc0fb0b19459674bc1cd8
1,353
KotlinProject
Apache License 2.0
packages/server-core/src/test/kotlin/org/migor/feedless/plan/FeatureServiceTest.kt
damoeb
314,677,857
false
{"HTML": 3499376, "Kotlin": 1565240, "TypeScript": 647818, "SCSS": 67132, "TeX": 34128, "XSLT": 11997, "JavaScript": 10350, "Shell": 4928, "Dockerfile": 3860, "PLpgSQL": 480}
package org.migor.feedless.plan import kotlinx.coroutines.test.runTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.migor.feedless.AppProfiles import org.migor.feedless.license.LicenseService import org.migor.feedless.pipeline.PluginService import org.migor.feedless.secrets.UserSecretService import org.migor.feedless.source.SourceService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.boot.test.mock.mockito.MockBeans import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.DynamicPropertyRegistry import org.springframework.test.context.DynamicPropertySource import org.testcontainers.containers.PostgreSQLContainer import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import java.util.* @SpringBootTest @ActiveProfiles(profiles = ["test", AppProfiles.database]) @MockBeans( value = [ MockBean(PluginService::class), MockBean(LicenseService::class), MockBean(UserSecretService::class), MockBean(ProductService::class), MockBean(SourceService::class), ] ) @Testcontainers class FeatureServiceTest { private lateinit var childFeatureGroup: FeatureGroupEntity private lateinit var parentFeatureGroup: FeatureGroupEntity @Autowired lateinit var featureDAO: FeatureDAO @Autowired lateinit var featureService: FeatureService @Autowired lateinit var featureValueDAO: FeatureValueDAO @Autowired lateinit var featureGroupDAO: FeatureGroupDAO private fun createFeatureGroup(name: String, parentId: UUID?): FeatureGroupEntity { val group = FeatureGroupEntity() group.name = name group.parentFeatureGroupId = parentId return featureGroupDAO.findByName(name) ?: featureGroupDAO.save(group) } @BeforeEach fun beforeEach() { parentFeatureGroup = createFeatureGroup("parent", null) childFeatureGroup = createFeatureGroup("child", parentFeatureGroup.id) } @AfterEach fun afterEach() { featureGroupDAO.delete(childFeatureGroup) featureGroupDAO.delete(parentFeatureGroup) assertThat(featureGroupDAO.count()).isEqualTo(0) } @Test fun `given a featureGroup inheritance, feature values will be inherited from parent`() = runTest { // given val featureName = FeatureName.repositoriesMaxCountActiveInt val feature = resolveFeature(featureName) assertThat(featureValueDAO.resolveByFeatureGroupIdAndName(parentFeatureGroup.id, feature.name)).isNull() val randomInt = (Math.random() * 100).toLong() // when featureService.assignFeatureValues(parentFeatureGroup, mapOf(featureName to createFeatureValue(randomInt))) // then val parentValue = featureValueDAO.resolveByFeatureGroupIdAndName(parentFeatureGroup.id, feature.name) val childValue = featureValueDAO.resolveByFeatureGroupIdAndName(childFeatureGroup.id, feature.name) assertThat(parentValue!!.valueInt).isEqualTo(randomInt) assertThat(childValue!!.valueInt).isEqualTo(randomInt) assertThat(featureValueDAO.resolveAllByFeatureGroupId(parentFeatureGroup.id)[0].valueInt).isEqualTo(randomInt) assertThat(featureValueDAO.resolveAllByFeatureGroupId(childFeatureGroup.id)[0].valueInt).isEqualTo(randomInt) } @Test fun `given a featureGroup inheritance, feature values will be overwritten by child`() = runTest { // given val featureNameA = FeatureName.repositoriesMaxCountActiveInt val featureA = resolveFeature(featureNameA) val featureNameB = FeatureName.refreshRateInMinutesLowerLimitInt val featureB = resolveFeature(featureNameB) val randomInt = (Math.random() * 1002).toLong() val otherRandomInt = randomInt + 2 // when featureService.assignFeatureValues(parentFeatureGroup, mapOf(featureNameA to createFeatureValue(randomInt))) featureService.assignFeatureValues(parentFeatureGroup, mapOf(featureNameB to createFeatureValue(randomInt))) featureService.assignFeatureValues(childFeatureGroup, mapOf(featureNameA to createFeatureValue(otherRandomInt))) // then val parentValue = featureValueDAO.resolveByFeatureGroupIdAndName(parentFeatureGroup.id, featureA.name) val childValue = featureValueDAO.resolveByFeatureGroupIdAndName(childFeatureGroup.id, featureA.name) assertThat(parentValue!!.valueInt).isEqualTo(randomInt) assertThat(childValue!!.valueInt).isEqualTo(otherRandomInt) val flatten = { list: List<FeatureValueEntity> -> list.fold(mutableMapOf<String, Long>()) { acc, featureValueEntity -> run { acc[featureDAO.findById(featureValueEntity.featureId).orElseThrow().name] = featureValueEntity.valueInt!! acc } } } val allParent = flatten(featureValueDAO.resolveAllByFeatureGroupId(parentFeatureGroup.id)) assertThat(allParent.size).isEqualTo(2) assertThat(allParent).containsEntry(featureA.name, randomInt) assertThat(allParent).containsEntry(featureB.name, randomInt) val allChild = flatten(featureValueDAO.resolveAllByFeatureGroupId(childFeatureGroup.id)) assertThat(allChild.size).isEqualTo(2) assertThat(allChild).containsEntry(featureA.name, otherRandomInt) assertThat(allChild).containsEntry(featureB.name, randomInt) } private fun createFeatureValue( valueInt: Long ): FeatureValueEntity { val featureValue = FeatureValueEntity() featureValue.valueType = FeatureValueType.number featureValue.valueInt = valueInt return featureValue } private fun resolveFeature(featureName: FeatureName): FeatureEntity { val feature = FeatureEntity() feature.name = featureName.name return featureDAO.findByName(featureName.name) ?: featureDAO.save(feature) } companion object { @Container private val postgres = PostgreSQLContainer("postgres:15") .withDatabaseName("feedless-test") .withUsername("postgres") .withPassword("<PASSWORD>") @JvmStatic @DynamicPropertySource fun registerDynamicProperties(registry: DynamicPropertyRegistry) { registry.add("spring.datasource.url") { "jdbc:tc:postgresql:15://localhost:${postgres.firstMappedPort}/${postgres.databaseName}?TC_REUSABLE=false" } registry.add("spring.datasource.username", postgres::getUsername) registry.add("spring.datasource.password", postgres::getPassword) } } }
15
HTML
25
235
52d57ee229026a5ffa6432e753bbe94328a7149b
6,590
feedless
Apache License 2.0
app/src/main/java/com/apzumi/challenge/data/GitHubRepository.kt
PaulHost
351,137,583
false
null
package com.apzumi.challenge.data import com.apzumi.challenge.data.model.GitHubResponseItem import io.reactivex.Flowable import retrofit2.http.GET interface GitHubRepository { @GET("/repositories?since=25") fun getRepositories(): Flowable<List<GitHubResponseItem>> }
0
Kotlin
0
0
604878f2394ffb58af4a97eda31302e9bab5932c
276
apzumi
MIT License
app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ZipPageLoader.kt
Jays2Kings
175,908,029
false
null
package eu.kanade.tachiyomi.ui.reader.loader import android.os.Build import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder import eu.kanade.tachiyomi.util.system.ImageUtil import rx.Observable import java.io.File import java.nio.charset.StandardCharsets import java.util.zip.ZipEntry import java.util.zip.ZipFile /** * Loader used to load a chapter from a .zip or .cbz file. */ class ZipPageLoader(file: File) : PageLoader() { /** * The zip file to load pages from. */ private val zip = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { ZipFile(file, StandardCharsets.ISO_8859_1) } else { ZipFile(file) } /** * Recycles this loader and the open zip. */ override fun recycle() { super.recycle() zip.close() } /** * Returns an observable containing the pages found on this zip archive ordered with a natural * comparator. */ override fun getPages(): Observable<List<ReaderPage>> { return zip.entries().toList() .filter { !it.isDirectory && ImageUtil.isImage(it.name) { zip.getInputStream(it) } } .sortedWith(Comparator<ZipEntry> { f1, f2 -> f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) }) .mapIndexed { i, entry -> val streamFn = { zip.getInputStream(entry) } ReaderPage(i).apply { stream = streamFn status = Page.READY } } .let { Observable.just(it) } } /** * Returns an observable that emits a ready state unless the loader was recycled. */ override fun getPage(page: ReaderPage): Observable<Int> { return Observable.just( if (isRecycled) { Page.ERROR } else { Page.READY } ) } }
92
null
71
974
928f7553bf800cbbc9006e7242f78741dfd64179
1,989
tachiyomiJ2K
Apache License 2.0
app/src/main/java/com/vladislawfox/scout/domain/sources/UpcomingMoviesSource.kt
vladislawfox
336,657,588
false
null
package com.vladislawfox.scout.domain.sources import androidx.paging.PagingSource import androidx.paging.PagingState import com.vladislawfox.scout.domain.model.Movie import com.vladislawfox.scout.domain.usecases.movies.GetNowPlayingMoviesUseCase import javax.inject.Inject class NowPlayingMoviesSource @Inject constructor( private val getNowPlayingMoviesUseCase: GetNowPlayingMoviesUseCase ) : PagingSource<Int, Movie>() { override fun getRefreshKey(state: PagingState<Int, Movie>): Int? { return 1 } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> { val nextPage = params.key ?: 1 val page = getNowPlayingMoviesUseCase.invoke(nextPage) return LoadResult.Page( data = page.items, prevKey = if(nextPage == 1) null else nextPage - 1, nextKey = nextPage + 1 ) } }
0
Kotlin
0
0
71357bb78e34164eca518230457a77c64a38b9c3
893
Scout
MIT License
advent-of-code-2022/src/main/kotlin/year_2022/Day03.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Runner fun main() { fun getCharScore(ch: Char) = if (ch.isUpperCase()) (ch - 'A' + 1) + 26 else (ch - 'a' + 1) fun MutableMap<Char, Int>.addScore(key: Char) { this[key] = this.getOrDefault(key, 0) + 1 } fun MutableMap<Char, Int>.calculate(minimum: Int): Int { return this.map { if (it.value == minimum) getCharScore(it.key) else 0 }.sum() } fun String.distinctForEach(cb: (Char) -> Unit) = this.toCharArray().distinct().forEach(cb) fun part1(input: List<String>): Int { var result = 0 input.forEach { i -> val dict = mutableMapOf<Char, Int>() i.chunked(i.length / 2).forEach { ruckSack -> ruckSack.distinctForEach { dict.addScore(it) } } result += dict.calculate(2) } return result } Runner.run(::part1, 157) fun part2(input: List<String>): Int { var result = 0 input.chunked(3).forEach { group -> val dict = mutableMapOf<Char, Int>() group.forEach { r -> r.distinctForEach { dict.addScore(it) } } result += dict.calculate(3) } return result } Runner.run(::part2, 70) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
1,260
advent-of-code
Apache License 2.0
app-thunderbird/src/main/kotlin/net/thunderbird/android/provider/TbFeatureThemeProvider.kt
thunderbird
1,326,671
false
{"Kotlin": 4766001, "Java": 2159946, "Shell": 2768, "AIDL": 1946}
package net.thunderbird.android.provider import androidx.compose.runtime.Composable import app.k9mail.core.ui.compose.theme2.thunderbird.ThunderbirdTheme2 import app.k9mail.core.ui.theme.api.FeatureThemeProvider class TbFeatureThemeProvider : FeatureThemeProvider { @Composable override fun WithTheme(content: @Composable () -> Unit) { ThunderbirdTheme2 { content() } } }
846
Kotlin
2467
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
414
thunderbird-android
Apache License 2.0
app/src/main/java/com/dialiax/sweeto/model/OrderDetails.kt
AnimeshNilawar
765,803,067
false
{"Kotlin": 76349}
package com.dialiax.sweeto.model import android.os.Parcel import android.os.Parcelable import java.io.Serializable import java.util.ArrayList class OrderDetails():Serializable { var userUid: String? = null var userName: String? = null var foodNames: MutableList<String>? = null var foodImages: MutableList<String>? = null var foodPrices: MutableList<String>? = null var foodQuantities: MutableList<Int>? = null var address: String? = null var totalPrice: String? = null var phoneNumber: String? = null var orderAccepted: Boolean = false var paymentReceived: Boolean = false var itemPushKey: String? = null var currentTime: Long = 0 constructor(parcel: Parcel) : this() { userUid = parcel.readString() userName = parcel.readString() address = parcel.readString() totalPrice = parcel.readString() phoneNumber = parcel.readString() orderAccepted = parcel.readByte() != 0.toByte() paymentReceived = parcel.readByte() != 0.toByte() itemPushKey = parcel.readString() currentTime = parcel.readLong() } constructor( userId: String, name: String, foodItemsName: ArrayList<String>, foodItemsImage: ArrayList<String>, foodItemsPrice: ArrayList<String>, foodItemsQuantity: ArrayList<Int>, address: String, totalAmount: String, phone: String, time: Long, itemPushKey: String?, b: Boolean, b1: Boolean ) : this(){ this.userUid = userId this.userName = name this.foodNames = foodItemsName this.foodImages = foodItemsImage this.foodPrices = foodItemsPrice this.foodQuantities = foodItemsQuantity this.address = address this.totalPrice = totalAmount this.phoneNumber = phone this.currentTime = time this.itemPushKey = itemPushKey this.orderAccepted = b this.paymentReceived = b1 } fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(userUid) parcel.writeString(userName) parcel.writeString(address) parcel.writeString(totalPrice) parcel.writeString(phoneNumber) parcel.writeByte(if (orderAccepted) 1 else 0) parcel.writeByte(if (paymentReceived) 1 else 0) parcel.writeString(itemPushKey) parcel.writeLong(currentTime) } fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<OrderDetails> { override fun createFromParcel(parcel: Parcel): OrderDetails { return OrderDetails(parcel) } override fun newArray(size: Int): Array<OrderDetails?> { return arrayOfNulls(size) } } }
0
Kotlin
1
2
b84dd6c77be5eb09d26b336f7ca97c1ef1ecbaab
2,817
Sweeto-User-App
MIT License
data/src/main/java/ca/bc/gov/data/datasource/local/entity/specialauthority/SpecialAuthorityEntity.kt
bcgov
414,797,174
false
{"Kotlin": 1368323, "Java": 582146}
package ca.bc.gov.data.datasource.local.entity.specialauthority import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey import ca.bc.gov.common.model.DataSource import ca.bc.gov.data.datasource.local.entity.PatientEntity import java.time.Instant /* * Created by amit_metri on 27,June,2022 */ @Entity( tableName = "special_authority", foreignKeys = [ ForeignKey( entity = PatientEntity::class, parentColumns = ["id"], childColumns = ["patient_id"], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE ) ] ) data class SpecialAuthorityEntity( // Defined own primary key("special_authority_id") because "referenceNumber" is set as nullable from the API specs @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "special_authority_id") val specialAuthorityId: Long = 0, @ColumnInfo(name = "patient_id") val patientId: Long, @ColumnInfo(name = "reference_number") val referenceNumber: String? = null, @ColumnInfo(name = "drug_name") val drugName: String? = null, @ColumnInfo(name = "request_status") val requestStatus: String? = null, @ColumnInfo(name = "prescriber_first_name") val prescriberFirstName: String? = null, @ColumnInfo(name = "prescriber_last_name") val prescriberLastName: String? = null, @ColumnInfo(name = "requested_date") val requestedDate: Instant? = null, @ColumnInfo(name = "effective_date") val effectiveDate: Instant? = null, @ColumnInfo(name = "expiry_date") val expiryDate: Instant? = null, @ColumnInfo(name = "data_source") val dataSource: DataSource = DataSource.BCSC )
7
Kotlin
5
5
dfb942bb07d2eb194e0d4438f45084210dd76d03
1,765
myhealthBC-android
Apache License 2.0
server/src/main/com/broll/gainea/server/core/objects/impl/DemonKnight.kt
Rolleander
253,573,579
false
{"Gradle": 8, "Shell": 3, "Batchfile": 3, "Text": 5, "Java Properties": 3, "Ignore List": 1, "Markdown": 1, "YAML": 1, "XML": 7, "Java": 182, "Kotlin": 344, "INI": 2, "JSON": 1, "JavaScript": 2, "HTML": 1, "CSS": 1}
package com.broll.gainea.server.core.objects.impl import com.broll.gainea.server.core.objects.monster.Monster import com.broll.gainea.server.core.objects.monster.MonsterActivity.OFTEN import com.broll.gainea.server.core.objects.monster.MonsterBehavior.AGGRESSIVE import com.broll.gainea.server.core.player.Player class DemonKnight(owner: Player) : Monster(owner) { init { icon = 93 controllable = false behavior = AGGRESSIVE activity = OFTEN name = "Dämonenkrieger" description = "Unkontrollierbar" setStats(4, 4) } }
0
Kotlin
0
3
ab47587c08ce2884269653a49c8fd8351cc4349f
585
Gainea
MIT License
app/src/main/java/com/robert/banyai/wup/presentation/base/BaseViewHolder.kt
robertbanyai72
272,161,765
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 83, "XML": 31, "Java": 1}
package com.robert.banyai.wup.presentation.base import android.view.View import androidx.recyclerview.widget.RecyclerView abstract class BaseViewHolder<I : AdapterItem>(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun bind(adapterItem: I) }
1
null
1
1
511bf026fac90226889fa09be2e55ae886b2665c
264
w.up_app
Apache License 2.0
src/commonMain/kotlin/WeakReference.kt
tomuvak
520,667,059
false
{"Kotlin": 5166, "Shell": 654}
package com.tomuvak.weakReference /** * A weak reference to the given [target]. The weak reference might be used to _try_ and regain a normal (= strong) * reference to the target through [targetOrNull], which will return the original target if it has not been reclaimed * by garbage collection (something a weak reference does not prevent), or `null` if it has. * * Note: the given [target] must be a reference to a "proper" object, not a primitive value or string. Passing a * primitive value or string results in undefined run-time behavior, including possibly thrown exceptions, depending on * the specific type and platform. */ expect class WeakReference<out T : Any>(target: T) { val targetOrNull: T? }
0
Kotlin
0
1
8f588d7ac95cc8410a833604fb7d101c8b281ec9
717
weak-reference
MIT License
lib/src/main/kotlin/nolambda/stream/cleaningservice/utils/Logger.kt
esafirm
425,140,620
false
null
package nolambda.stream.cleaningservice.utils class SimpleLogger : Logger { companion object { private const val ANSI_RESET = "\u001B[0m" private const val ANSI_GREEN = "\u001B[32m" private const val ANSI_YELLOW = "\u001B[33m" private const val IS_DEBUG = true } override fun logDev(text: String) { if (IS_DEBUG) { println("=> $text") } } override fun logGreen(text: String) { println("$ANSI_GREEN${text}$ANSI_RESET") } override fun logYellow(text: String) { println("$ANSI_YELLOW${text}$ANSI_RESET") } override fun log(text: String) { println(text) } } object NoopLogger : Logger { override fun logDev(text: String) {} override fun logGreen(text: String) {} override fun logYellow(text: String) {} override fun log(text: String) {} } interface Logger { fun logDev(text: String) fun logGreen(text: String) fun logYellow(text: String) fun log(text: String) }
0
Kotlin
1
3
cb092e635741e84fa659867af3227b6fe09900bb
1,026
android-cleaning-service
Apache License 2.0
app/src/main/java/com/dev/bins/daily/activity/BaseActivity.kt
devbins
103,132,563
false
{"Java": 41489, "Kotlin": 19443}
package com.dev.bins.daily.activity import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.transition.Explode import android.transition.Slide import android.view.MenuItem /** * Created by bin on 07/10/2017. */ abstract class BaseActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val explode = Explode() explode.duration = 200 val slide = Slide() slide.duration = 200 window.enterTransition = slide window.exitTransition = explode setContentView(getLayoutId()) init() } abstract fun init() fun initToolbar(toolbar: Toolbar) { initToolbar(toolbar, false) } fun initToolbar(toolbar: Toolbar, back: Boolean) { setSupportActionBar(toolbar) if (back) { supportActionBar!!.setDisplayHomeAsUpEnabled(true) } } abstract fun getLayoutId(): Int override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item!!.itemId == android.R.id.home) { ActivityCompat.finishAfterTransition(this) return true } return super.onOptionsItemSelected(item) } }
1
null
1
1
a949dc22b7d4fad41e7f7970e2886ac51c54dd6c
1,349
Daily
Apache License 2.0
src/main/kotlin/com/ruin/lsp/commands/project/run/MyProjectTaskManager.kt
Ruin0x11
121,824,068
false
null
package com.ruin.lsp.commands.project.run import com.intellij.openapi.compiler.CompileStatusNotification import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pair import com.intellij.task.* import com.intellij.task.impl.AbstractProjectTask import com.intellij.task.impl.ProjectTaskList import com.intellij.task.impl.ProjectTaskManagerImpl import com.intellij.util.Consumer import com.intellij.util.SmartList import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.stream.Collectors /** * Massive workaround to get the CompileContext (list of error/warning locations) from a ProjectTask. */ class MyProjectTaskManager(val project: Project, val callback: CompileStatusNotification) : ProjectTaskManagerImpl(project) { // if only this were protected. private val myDefaultProjectTaskRunner = MyProjectTaskRunner(callback) override fun run(context: ProjectTaskContext, projectTask: ProjectTask, callback: ProjectTaskNotification?) { val toRun = SmartList<Pair<ProjectTaskRunner, Collection<ProjectTask>>>() val taskClassifier = Consumer { tasks: Collection<ProjectTask> -> val toBuild = tasks.stream().collect(Collectors.groupingBy<ProjectTask, ProjectTaskRunner> { aTask -> for (runner in getTaskRunners()) { // TODO: find a way to send CompileContext with custom runners if (runner.canRun(aTask)) return@groupingBy runner } myDefaultProjectTaskRunner }) for (entry in toBuild.entries) { toRun.add(Pair.create(entry.key, entry.value)) } } visitTasks(projectTask as? ProjectTaskList ?: setOf(projectTask), taskClassifier) if (toRun.isEmpty()) { sendSuccessNotify(callback) return } val inProgressCounter = AtomicInteger(toRun.size) val errorsCounter = AtomicInteger() val warningsCounter = AtomicInteger() val abortedFlag = AtomicBoolean(false) val chunkStatusNotification = if (callback == null) null else ProjectTaskNotification { executionResult -> val inProgress = inProgressCounter.decrementAndGet() val allErrors = errorsCounter.addAndGet(executionResult.errors) val allWarnings = warningsCounter.addAndGet(executionResult.warnings) if (executionResult.isAborted) { abortedFlag.set(true) } if (inProgress == 0) { callback.finished(ProjectTaskResult(abortedFlag.get(), allErrors, allWarnings)) } } toRun.forEach { pair -> if (pair.second.isEmpty()) { sendSuccessNotify(chunkStatusNotification) } else { pair.first.run(myProject, context, chunkStatusNotification, pair.second) } } } private fun visitTasks(tasks: Collection<ProjectTask>, consumer: Consumer<Collection<ProjectTask>>) { for (child in tasks) { val taskDependencies: Collection<ProjectTask> = if (child is AbstractProjectTask) { child.dependsOn } else child as? ProjectTaskList ?: setOf(child) visitTasks(taskDependencies, consumer) } consumer.consume(tasks) } private fun sendSuccessNotify(notification: ProjectTaskNotification?) { notification?.finished(ProjectTaskResult(false, 0, 0)) } private fun getTaskRunners(): Array<ProjectTaskRunner> { return ProjectTaskRunner.EP_NAME.extensions } }
24
null
26
322
50e6726d8535b5f00ef507db19272c551a694db4
3,758
intellij-lsp-server
MIT License
app/src/main/java/com/multithread/cocoon/presentation/list/TopStoriesViewHolder.kt
anbioc
313,373,806
false
{"Kotlin": 85851, "Java": 829}
package com.multithread.cocoon.presentation.list import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.multithread.cocoon.R import com.multithread.cocoon.domain.model.TopStoryDomainEntity import com.multithread.cocoon.extension.show import com.multithread.cocoon.presentation.topstories.CallbackParam import com.multithread.cocoon.util.ImageLoader import kotlinx.android.synthetic.main.item_story.view.* class TopStoriesViewHolder constructor( containerView: View, private val callback: (entity: CallbackParam) -> Unit, private val imageLoader: ImageLoader ) : RecyclerView.ViewHolder(containerView) { companion object { fun create( parent: ViewGroup, callback: (entity: CallbackParam) -> Unit, imageLoader: ImageLoader, isFavorite: Boolean ) = if (isFavorite) { TopStoriesViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_story_grid, parent, false), callback, imageLoader ) } else { TopStoriesViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_story, parent, false), callback, imageLoader ) } } fun bind(story: TopStoryDomainEntity.Result) { itemView.setOnClickListener { callback(CallbackParam.Click(story)) } itemView.itemStoryLikeContainer.setOnClickListener { if (story.favorite) { callback(CallbackParam.Dislike(story)) } else { callback(CallbackParam.Like(story)) } } itemView.itemTopStoryIcon.show(story.favorite) itemView.itemStoryTitle.text = story.title itemView.itemStoryDateTime.text = story.updatedDate imageLoader.loadImage( itemView.itemStoryImage, 0, 0, story.imageUrl ) } }
0
Kotlin
0
2
aab440dfa558286f924e90d602bc72265843d618
2,131
FlowCleanMVVM
MIT License
app/src/main/kotlin/com/czbix/v2ex/common/NotificationStatus.kt
RedL0tus
71,426,805
false
null
package com.czbix.v2ex.common import android.app.PendingIntent import android.content.Context import android.content.Intent import android.support.annotation.IntDef import android.support.v4.app.NotificationCompat import android.support.v4.app.NotificationManagerCompat import com.czbix.v2ex.AppCtx import com.czbix.v2ex.R import com.czbix.v2ex.eventbus.BaseEvent.NewUnreadEvent import com.czbix.v2ex.ui.MainActivity import com.czbix.v2ex.util.MiscUtils import com.google.common.eventbus.Subscribe class NotificationStatus internal constructor(private val mContext: Context) { private val mNtfManager: NotificationManagerCompat init { mNtfManager = NotificationManagerCompat.from(mContext) } fun init() { AppCtx.eventBus.register(this) } fun showAppUpdate() { val pendingIntent = PendingIntent.getActivity(mContext, 0, MiscUtils.appUpdateIntent, 0) val builder = NotificationCompat.Builder(mContext).apply { setSmallIcon(R.drawable.ic_update_black_24dp) setTicker(mContext.getString(R.string.ntf_title_app_update)) setContentTitle(mContext.getString(R.string.ntf_title_app_update)) setContentText(mContext.getString(R.string.ntf_desc_new_version_of_app)) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) setAutoCancel(true) setOnlyAlertOnce(true) setLocalOnly(true) setContentIntent(pendingIntent) } mNtfManager.notify(ID_APP_UPDATE, builder.build()) } @Subscribe fun onNewUnread(e: NewUnreadEvent) { if (!e.hasNew()) { cancelNotification(ID_NOTIFICATIONS) return } val intent = Intent(mContext, MainActivity::class.java).apply { putExtra(MainActivity.BUNDLE_GOTO, MainActivity.GOTO_NOTIFICATIONS) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) } val pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0) val builder = NotificationCompat.Builder(mContext).apply { setSmallIcon(R.drawable.ic_notifications_white_24dp) setTicker(mContext.getString(R.string.ntf_title_new_notifications)) setContentTitle(mContext.getString(R.string.ntf_title_new_notifications)) setContentText(mContext.getString(R.string.ntf_desc_from_v2ex)) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) setDefaults(NotificationCompat.DEFAULT_ALL) setNumber(e.mCount) setAutoCancel(true) setOnlyAlertOnce(true) setContentIntent(pendingIntent) } mNtfManager.notify(ID_NOTIFICATIONS, builder.build()) } fun cancelNotification(@NotificationId id: Int) { mNtfManager.cancel(id) } @Retention(AnnotationRetention.SOURCE) @IntDef(ID_NOTIFICATIONS.toLong()) annotation class NotificationId companion object { @JvmStatic val instance: NotificationStatus const val ID_NOTIFICATIONS = 0 const val ID_APP_UPDATE = 1 init { instance = NotificationStatus(AppCtx.instance) } } }
1
null
1
1
dfaeb2ad9f961ff046924e6bfb9cd50e3397f35e
3,222
v2ex-android
Apache License 2.0
src/main/kotlin/no/nav/yrkesskade/meldingmottak/hendelser/JournalfoeringHendelseConsumer.kt
navikt
413,400,372
false
null
package no.nav.yrkesskade.meldingmottak.hendelser import no.nav.joarkjournalfoeringhendelser.JournalfoeringHendelseRecord import no.nav.yrkesskade.meldingmottak.services.JournalfoeringHendelseService import no.nav.yrkesskade.meldingmottak.util.kallMetodeMedCallId import org.springframework.kafka.annotation.KafkaListener import org.springframework.messaging.handler.annotation.Payload import org.springframework.stereotype.Service import javax.transaction.Transactional @Service class JournalfoeringHendelseConsumer( private val journalfoeringHendelseService: JournalfoeringHendelseService ) { @KafkaListener( id = "yrkesskade-melding-mottak", topics = ["\${kafka.topic.aapen-dok-journalfoering}"], containerFactory = "kafkaJournalfoeringHendelseListenerContainerFactory", idIsGroup = false ) @Transactional fun listen(@Payload record: JournalfoeringHendelseRecord) { kallMetodeMedCallId { journalfoeringHendelseService.prosesserJournalfoeringHendelse(record) } } }
1
Kotlin
0
0
6ab936e3d9b2bd55f559bdc282009aada1bd10ca
1,034
yrkesskade-melding-mottak
MIT License
src/main/kotlin/no/nav/tms/brannslukning/alert/VarselHendelseSubscribers.kt
navikt
743,413,887
false
{"Kotlin": 101241, "CSS": 8770, "Dockerfile": 148}
package no.nav.tms.brannslukning.alert import no.nav.tms.kafka.application.JsonMessage import no.nav.tms.kafka.application.Subscriber import no.nav.tms.kafka.application.Subscription class EksterntVarselStatusSubscriber( private val alertRepository: AlertRepository, ) : Subscriber() { override fun subscribe(): Subscription = Subscription .forEvent("eksternStatusOppdatert") .withFields("varselId", "status") .withValue("appnavn", "tms-brannslukning") override suspend fun receive(jsonMessage: JsonMessage) { alertRepository.updateEksternStatus(jsonMessage["varselId"].asText(), jsonMessage["status"].asText()) } } class VarselInaktivertSubscriber( private val alertRepository: AlertRepository, ) : Subscriber() { override fun subscribe(): Subscription = Subscription .forEvent("inaktivert") .withValue("appnavn", "tms-brannslukning") .withFields("varselId") override suspend fun receive(jsonMessage: JsonMessage) { alertRepository.setVarselLest(jsonMessage["varselId"].asText()) } }
6
Kotlin
1
0
0cc54d21c6c27b1c7c787a569de52aa834632985
1,088
tms-brannslukning
MIT License
core/src/main/java/com/aliumujib/artic/di/modules/CacheModule.kt
aliumujib
210,103,091
false
{"Kotlin": 448725}
/* * Copyright 2020 Abdul-Mujeeb Aliu * * 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.aliumujib.artic.di.modules import android.content.Context import androidx.room.Room import com.aliumujib.artic.cache.impl.ArticlesCacheImpl import com.aliumujib.artic.cache.impl.SettingsCacheImpl import com.aliumujib.artic.cache.room.ArticlesDao import com.aliumujib.artic.data.repositories.articles.cache.IArticlesCache import com.aliumujib.artic.cache.room.DBClass import com.aliumujib.artic.data.repositories.settings.cache.ISettingsCache import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class CacheModule { @Singleton @Provides fun providesArticlesCache(articlesCache: ArticlesCacheImpl): IArticlesCache { return articlesCache } @Singleton @Provides fun providesSettingsCache(settingsCache: SettingsCacheImpl): ISettingsCache { return settingsCache } @Singleton @Provides fun providesArticlesDao(dBClass: DBClass): ArticlesDao { return dBClass.articlesDao() } @Singleton @Provides fun providesDB(context: Context): DBClass { return Room.databaseBuilder( context.applicationContext, DBClass::class.java, "artic_database" ).fallbackToDestructiveMigration().build() } }
0
Kotlin
6
47
ad986536632f532d0d24aa3847bdef33ab7a5d16
1,855
Artic
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/CircleO.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.CircleO: ImageVector get() { if (_circleO != null) { return _circleO!! } _circleO = Builder(name = "CircleO", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(12.0f, 0.0f) curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f) reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f) reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f) reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f) close() moveTo(12.0f, 22.0f) curveToRelative(-5.514f, 0.0f, -10.0f, -4.486f, -10.0f, -10.0f) reflectiveCurveTo(6.486f, 2.0f, 12.0f, 2.0f) reflectiveCurveToRelative(10.0f, 4.486f, 10.0f, 10.0f) reflectiveCurveToRelative(-4.486f, 10.0f, -10.0f, 10.0f) close() moveTo(12.0f, 5.75f) curveToRelative(-2.757f, 0.0f, -5.0f, 2.243f, -5.0f, 5.0f) verticalLineToRelative(2.5f) curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f) reflectiveCurveToRelative(5.0f, -2.243f, 5.0f, -5.0f) verticalLineToRelative(-2.5f) curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f) close() moveTo(15.0f, 13.25f) curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f) reflectiveCurveToRelative(-3.0f, -1.346f, -3.0f, -3.0f) verticalLineToRelative(-2.5f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) reflectiveCurveToRelative(3.0f, 1.346f, 3.0f, 3.0f) verticalLineToRelative(2.5f) close() } } .build() return _circleO!! } private var _circleO: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,778
icons
MIT License
src/main/kotlin/org/sirekanyan/rknfreebot/command/Command.kt
sirekanian
707,761,741
false
{"Kotlin": 25193}
package org.sirekanyan.rknfreebot.command import org.sirekanyan.rknfreebot.Controller import org.telegram.telegrambots.meta.api.objects.Message fun interface Command { fun execute(controller: Controller, message: Message): Boolean }
0
Kotlin
0
0
57ce3785ee296f6b7f9f94b5826fb1f147119353
240
rknfreebot
MIT License
modules/core/src/main/java/de/deutschebahn/bahnhoflive/ui/station/timetable/TrainMessages.kt
dbbahnhoflive
267,806,942
false
null
/* * SPDX-FileCopyrightText: 2020 DB Station&Service AG <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ package de.deutschebahn.bahnhoflive.ui.station.timetable import de.deutschebahn.bahnhoflive.backend.ris.model.TrainInfo import de.deutschebahn.bahnhoflive.backend.ris.model.TrainMovementInfo class TrainMessages(private val trainInfo: TrainInfo, val trainMovementInfo: TrainMovementInfo?) { data class TrainMessage( val message: String, val severity: IssueSeverity = IssueSeverity.WARNING ) fun hasMessages() = messages.isNotEmpty() val messages = trainMovementInfo?.run { if (isTrainMovementCancelled) { listOf(TrainMessage("Dieser Zug fällt heute aus.")) } else { listOfNotNull( trainInfo.replacementTrainMessage(trainMovementInfo.lineIdentifier).toTrainMessage(), platformMessage.toTrainMessage(), delayMessage.toTrainMessage(IssueSeverity.WARNING_TEXT_ONLY), addedStationsMessage.toTrainMessage(), missingStationsMessage.toTrainMessage(), qosMessages.toTrainMessage(), additionalTrainMessage.toTrainMessage(), splitMessage.toTrainMessage(IssueSeverity.INFO), distantEndpointMessage.toTrainMessage(IssueSeverity.WARNING_TEXT_ONLY) ) } } ?: listOf() companion object { fun String?.toTrainMessage(severity: IssueSeverity = IssueSeverity.WARNING) = takeUnless { it.isNullOrEmpty() || it == "null" } ?.let { TrainMessage(it, severity) } } }
1
null
4
33
78bcee88dbf6aae9ded15998ac3c0448549c0b60
1,643
dbbahnhoflive-android
Apache License 2.0
modules/core/src/main/java/de/deutschebahn/bahnhoflive/ui/station/timetable/TrainMessages.kt
dbbahnhoflive
267,806,942
false
null
/* * SPDX-FileCopyrightText: 2020 DB Station&Service AG <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ package de.deutschebahn.bahnhoflive.ui.station.timetable import de.deutschebahn.bahnhoflive.backend.ris.model.TrainInfo import de.deutschebahn.bahnhoflive.backend.ris.model.TrainMovementInfo class TrainMessages(private val trainInfo: TrainInfo, val trainMovementInfo: TrainMovementInfo?) { data class TrainMessage( val message: String, val severity: IssueSeverity = IssueSeverity.WARNING ) fun hasMessages() = messages.isNotEmpty() val messages = trainMovementInfo?.run { if (isTrainMovementCancelled) { listOf(TrainMessage("Dieser Zug fällt heute aus.")) } else { listOfNotNull( trainInfo.replacementTrainMessage(trainMovementInfo.lineIdentifier).toTrainMessage(), platformMessage.toTrainMessage(), delayMessage.toTrainMessage(IssueSeverity.WARNING_TEXT_ONLY), addedStationsMessage.toTrainMessage(), missingStationsMessage.toTrainMessage(), qosMessages.toTrainMessage(), additionalTrainMessage.toTrainMessage(), splitMessage.toTrainMessage(IssueSeverity.INFO), distantEndpointMessage.toTrainMessage(IssueSeverity.WARNING_TEXT_ONLY) ) } } ?: listOf() companion object { fun String?.toTrainMessage(severity: IssueSeverity = IssueSeverity.WARNING) = takeUnless { it.isNullOrEmpty() || it == "null" } ?.let { TrainMessage(it, severity) } } }
1
null
4
33
78bcee88dbf6aae9ded15998ac3c0448549c0b60
1,643
dbbahnhoflive-android
Apache License 2.0
app/src/main/java/com/android/skip/WhitelistActivity.kt
GuoXiCheng
506,451,823
false
{"Kotlin": 130289, "TypeScript": 12715, "JavaScript": 289}
package com.android.skip import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.android.skip.compose.FlatButton import com.android.skip.compose.RowContent import com.android.skip.compose.ScaffoldPage import com.android.skip.dataclass.AppInfo import com.android.skip.manager.WhitelistManager import com.android.skip.utils.DataStoreUtils import com.google.accompanist.drawablepainter.rememberDrawablePainter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class WhitelistActivity : BaseActivity() { @Composable override fun ProvideContent() { WhitelistInterface(onBackClick = { finish() }) } } @Composable fun WhitelistInterface(onBackClick: () -> Unit) { val context = LocalContext.current val packageManager = context.packageManager val appInfoList = remember { mutableStateListOf<AppInfo>() } val scope = rememberCoroutineScope() LaunchedEffect(Unit) { scope.launch(Dispatchers.IO) { val installedApps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA) val nonSystemApps = installedApps.filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) == 0 } val apps = nonSystemApps.map { app -> AppInfo( appName = app.loadLabel(packageManager).toString(), packageName = app.packageName, appIcon = app.loadIcon(packageManager), checked = mutableStateOf( DataStoreUtils.getSyncData( WHITELIST_DOT + app.packageName, false ) ) ) }.sortedWith(compareByDescending { it.checked.value }) withContext(Dispatchers.Main) { appInfoList.addAll(apps) } } } ScaffoldPage( barTitle = stringResource(id = R.string.whitelist), onBackClick = onBackClick, content = { LazyColumn { items(appInfoList.size) { index -> FlatButton(content = { RowContent( title = appInfoList[index].appName, subTitle = appInfoList[index].packageName, { Icon( painter = rememberDrawablePainter(drawable = appInfoList[index].appIcon), contentDescription = null, tint = Color.Unspecified ) }, checked = appInfoList[index].checked.value, { appInfoList[index].checked.value = it val key = WHITELIST_DOT + appInfoList[index].packageName if (it) DataStoreUtils.putSyncData( key, true ) else DataStoreUtils.removeSync(key) WhitelistManager.setWhitelist(scope, context) } ) }) } } }) }
23
Kotlin
77
2,212
7d0f5c0155431e4cfe4a5de99de0efd9c0b14a44
3,993
SKIP
MIT License
app/src/main/java/com/drs/dseller/feature_onboarding/presentation/screens/signup/SignUpBody.kt
raaja-sn
704,140,729
false
{"Kotlin": 307720}
@file:OptIn(ExperimentalMaterial3Api::class) package com.drs.dseller.feature_onboarding.presentation.screens.signup import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.withStyle import com.drs.dseller.R import com.drs.dseller.core.ui_elements.GreenCircularProgressIndicator import com.drs.dseller.core.ui_elements.buttons.RoundCorneredButton import com.drs.dseller.core.ui_elements.text_fields.FormTextField import com.drs.dseller.feature_onboarding.presentation.states.RegisterUserState import com.drs.dseller.ui.theme.AppTypography import com.drs.dseller.ui.theme.Black80 import com.drs.dseller.ui.theme.Green40 import com.drs.dseller.ui.theme.Grey80 @Composable fun SignUpScreenBody( state: RegisterUserState, usernameChangeListener:(String) -> Unit, phoneChangedListener:(String) ->Unit, emailChangeListener:(String) -> Unit, passwordChangeListener:(String) -> Unit, signUpListener:()->Unit, loginListener:()->Unit ){ val scrollableState = rememberScrollState() Column( modifier = Modifier .fillMaxWidth() .verticalScroll(scrollableState) .padding(horizontal = dimensionResource(id = R.dimen.twenty_five_dp)), horizontalAlignment = Alignment.Start ) { val parentModifier = remember{ Modifier } Spacer( modifier = Modifier.height(dimensionResource(id = R.dimen.twenty_five_dp)) ) Image( modifier = parentModifier .size(dimensionResource(id = R.dimen.fifty_fifty_dp)) .align(Alignment.CenterHorizontally), painter = painterResource(id = R.drawable.dseller_logo_orange), contentDescription = stringResource(id = R.string.description_logo) ) Spacer( modifier = parentModifier.height(dimensionResource(id = R.dimen.one_twenty_dp)) ) Text( modifier = parentModifier .padding(vertical = dimensionResource(R.dimen.ten_dp)), text = stringResource(R.string.signup_title), style = AppTypography.headlineMedium, color = Black80 ) Text( modifier = parentModifier .padding(vertical = dimensionResource(R.dimen.five_dp)) .padding(bottom = dimensionResource(id = R.dimen.thirty_dp)), text = stringResource(R.string.signup_title_info), style = AppTypography.bodyLarge, color = Grey80 ) FormTextField( parentModifier .fillMaxWidth(), stringResource(id = R.string.signup_name), true, state.name, textChangeCallback = usernameChangeListener ) FormTextField( parentModifier .fillMaxWidth(), stringResource(id = R.string.signup_phone), true, state.phoneNumber, KeyboardType.Number, phoneChangedListener ) FormTextField( parentModifier .fillMaxWidth(), stringResource(id = R.string.signup_email), true, state.email, KeyboardType.Email, emailChangeListener ) FormTextField( parentModifier .fillMaxWidth(), stringResource(id = R.string.signup_password), true, state.password, KeyboardType.Password, passwordChangeListener ) TermsText(modifier = parentModifier) RoundCorneredButton( buttonText = stringResource(id = R.string.signup_title), modifier = parentModifier .fillMaxWidth() .padding(top = dimensionResource(id = R.dimen.twenty_dp)), isEnabled = !state.isRegistering, clickCallback = signUpListener ) GreenCircularProgressIndicator( modifier = parentModifier .align(Alignment.CenterHorizontally), isVisible = state.isRegistering ) LoginText( modifier = parentModifier .align(Alignment.CenterHorizontally), loginListener ) } } @Composable fun TermsText( modifier:Modifier, ){ val termsText = stringResource(id = R.string.signup_terms_info) Text( text = buildAnnotatedString { append(termsText.substring(0,31)) withStyle( SpanStyle( color = Green40 ) ){ append(termsText.substring(31,48)) } append(termsText.substring(48,52)) withStyle( SpanStyle( color = Green40 ) ){ append(termsText.substring(52,termsText.length)) } }, style = AppTypography.bodySmall, color = Grey80 ) } @Composable fun LoginText( modifier: Modifier, loginCallback:() -> Unit ) { val loginInfoText = stringResource(id = R.string.signup_login_info) Text( modifier = modifier .clickable { loginCallback() } .padding( top = dimensionResource(id = R.dimen.twenty_dp), bottom = dimensionResource(id = R.dimen.thirty_dp) ), text = buildAnnotatedString { append("$loginInfoText ") withStyle( SpanStyle( color = Green40 ) ) { append(stringResource(id = R.string.login_title)) } }, style = AppTypography.titleSmall, color = Black80 ) }
0
Kotlin
0
0
6fa26d3c90205bcf31fa8aebba26b3659799fbda
6,797
DSeller-Android
MIT License
src/main/kotlin/br/com/zup/edu/pixkeymanagergrpc/KeyTypeEnum.kt
emersondevelops
385,436,995
true
{"Kotlin": 81135}
package br.com.zupacademy.nicolecatarina.pixkey import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator import org.hibernate.validator.internal.constraintvalidators.hv.br.CPFValidator enum class KeyType { CPF { override fun validate(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } if (!chave.matches("[0-9]+".toRegex())) { return false } return CPFValidator().run { initialize(null) isValid(chave, null) } } }, PHONE { override fun validate(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } return chave.matches("^\\+[1-9][0-9]\\d{1,14}\$".toRegex()) } }, EMAIL { override fun validate(chave: String?): Boolean { if (chave.isNullOrBlank()) { return false } return EmailValidator().run { initialize(null) isValid(chave, null) } } }, RANDOM { override fun validate(chave: String?) = chave.isNullOrBlank() }; abstract fun validate(chave: String?): Boolean }
0
Kotlin
0
1
4f8c991eb4a62335f1842dd22c4cfa2e3e1da7e6
1,305
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/com/alexeyodinochenko/tinkoffservice/dto/StocksDto.kt
GuardianOfPC
576,609,848
false
{"Kotlin": 9999}
package com.alexeyodinochenko.tinkoffservice.dto import com.alexeyodinochenko.tinkoffservice.model.Stock data class StocksDto( val stocks: List<Stock> )
1
Kotlin
0
0
8afb55ae4194472673c45543313de9a072222688
158
tinkoff-stock-service
Apache License 2.0
core/archive/src/main/kotlin/mihon/core/archive/ArchiveEntry.kt
mihonapp
743,704,912
false
{"Kotlin": 2940843}
package mihon.core.archive class ArchiveEntry( val name: String, val isFile: Boolean, )
72
Kotlin
447
9,867
f3a2f566c8a09ab862758ae69b43da2a2cd8f1db
97
mihon
Apache License 2.0
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/cryptostore/db/CryptoFileStoreImporter.kt
matrix-org
24,635,052
false
null
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package org.matrix.androidsdk.crypto.cryptostore.db import android.content.Context import io.realm.Realm import io.realm.RealmList import io.realm.kotlin.where import org.matrix.androidsdk.core.Log import org.matrix.androidsdk.crypto.cryptostore.MXFileCryptoStore import org.matrix.androidsdk.crypto.cryptostore.db.model.* import org.matrix.androidsdk.crypto.cryptostore.db.query.getOrCreate import org.matrix.androidsdk.rest.model.login.Credentials /** * This class migrate the legacy FileCryptoStore to the Realm DB */ internal class CryptoFileStoreImporter(private val enableFileEncryption: Boolean, private val context: Context, private val credentials: Credentials) : Realm.Transaction { override fun execute(realm: Realm) { // Create a FileCryptoStore val fileCryptoStore = MXFileCryptoStore(enableFileEncryption) fileCryptoStore.initWithCredentials(context, credentials) if (fileCryptoStore.hasData()) { Log.d(LOG_TAG, "Importing data...") val start = System.currentTimeMillis() fileCryptoStore.open() // Metadata importMetaData(fileCryptoStore, realm) // Rooms importRooms(fileCryptoStore, realm) // Users importUsers(fileCryptoStore, realm) // Outgoing room key requests importOutgoingRoomKeyRequests(fileCryptoStore, realm) // Incoming room key requests importIncomingRoomKeyRequests(fileCryptoStore, realm) // Olm sessions importOlmSessions(fileCryptoStore, realm) // Inbound Sessions importInboundGroupSessions(fileCryptoStore, realm) fileCryptoStore.close() Log.d(LOG_TAG, "Importing data done in " + (System.currentTimeMillis() - start) + "ms") } else { // Already migrated, or new account Log.d(LOG_TAG, "No data to import") } // At last fileCryptoStore.deleteStore() } private fun importMetaData(fileCryptoStore: MXFileCryptoStore, realm: Realm) { Log.d(LOG_TAG, "Importing metadata") realm.createObject(CryptoMetadataEntity::class.java, credentials.getUserId()).apply { deviceId = fileCryptoStore.deviceId backupVersion = null // TODO deviceSyncToken = fileCryptoStore. putOlmAccount(fileCryptoStore.account) globalBlacklistUnverifiedDevices = fileCryptoStore.globalBlacklistUnverifiedDevices } } private fun importRooms(fileCryptoStore: MXFileCryptoStore, realm: Realm) { // Create CryptoRoomEntity in DB fileCryptoStore.roomsAlgorithms?.entries ?.also { Log.d(LOG_TAG, "Importing ${it.size} rooms") } ?.forEach { entry -> CryptoRoomEntity.getOrCreate(realm, entry.key).apply { algorithm = entry.value } } // Set flag blacklistUnverifiedDevices fileCryptoStore.roomsListBlacklistUnverifiedDevices .also { Log.d(LOG_TAG, "Setting ${it.size} room blacklistUnverifiedDevices flags to true") } .forEach { realm.where<CryptoRoomEntity>() .equalTo(CryptoRoomEntityFields.ROOM_ID, it) .findFirst() ?.blacklistUnverifiedDevices = true } } private fun importUsers(fileCryptoStore: MXFileCryptoStore, realm: Realm) { fileCryptoStore.allUsersDevices?.map?.entries ?.also { Log.d(LOG_TAG, "Importing ${it.size} users") } ?.forEach { userIdToDevices -> // Keys are user id realm.createObject(UserEntity::class.java, userIdToDevices.key).apply { devices = RealmList() userIdToDevices.value.entries.forEach { deviceIdToDevice -> devices.add( DeviceInfoEntity.getOrCreate(realm, userIdToDevices.key, deviceIdToDevice.value.deviceId).apply { deviceId = deviceIdToDevice.key identityKey = deviceIdToDevice.value.identityKey() putDeviceInfo(deviceIdToDevice.value) } ) } } } fileCryptoStore.deviceTrackingStatuses ?.also { Log.d(LOG_TAG, "Importing ${it.size} device tracking status") } ?.forEach { entry -> realm.where<UserEntity>() .equalTo(UserEntityFields.USER_ID, entry.key) .findFirst() ?.deviceTrackingStatus = entry.value } } private fun importOutgoingRoomKeyRequests(fileCryptoStore: MXFileCryptoStore, realm: Realm) { fileCryptoStore.outgoingRoomKeyRequests ?.also { Log.d(LOG_TAG, "Importing ${it.size} OutgoingRoomKeyRequests") } ?.forEach { entry -> realm.createObject(OutgoingRoomKeyRequestEntity::class.java, entry.value.mRequestId).apply { putRecipients(entry.value.mRecipients) putRequestBody(entry.value.mRequestBody) state = entry.value.mState.ordinal cancellationTxnId = entry.value.mCancellationTxnId } } } private fun importIncomingRoomKeyRequests(fileCryptoStore: MXFileCryptoStore, realm: Realm) { fileCryptoStore.pendingIncomingRoomKeyRequests ?.also { Log.d(LOG_TAG, "Importing ${it.size} IncomingRoomKeyRequests") } ?.forEach { entry -> realm.createObject(IncomingRoomKeyRequestEntity::class.java).apply { requestId = entry.mRequestId userId = entry.mUserId deviceId = entry.mDeviceId putRequestBody(entry.mRequestBody) } } } private fun importOlmSessions(fileCryptoStore: MXFileCryptoStore, realm: Realm) { fileCryptoStore.olmSessions ?.also { Log.d(LOG_TAG, "Importing ${it.size} olmSessions") } ?.forEach { deviceKeyToMap -> deviceKeyToMap.value.forEach { olmSessionIdToOlmSession -> realm.createObject(OlmSessionEntity::class.java, OlmSessionEntity.createPrimaryKey(olmSessionIdToOlmSession.key, deviceKeyToMap.key)) .apply { deviceKey = deviceKeyToMap.key sessionId = olmSessionIdToOlmSession.key putOlmSession(olmSessionIdToOlmSession.value) lastReceivedMessageTs = 0 } } } } private fun importInboundGroupSessions(fileCryptoStore: MXFileCryptoStore, realm: Realm) { fileCryptoStore.inboundGroupSessions .also { Log.d(LOG_TAG, "Importing ${it.size} InboundGroupSessions") } .forEach { realm.createObject(OlmInboundGroupSessionEntity::class.java, OlmInboundGroupSessionEntity.createPrimaryKey(it.mSession.sessionIdentifier(), it.mSenderKey)).apply { sessionId = it.mSession.sessionIdentifier() senderKey = it.mSenderKey putInboundGroupSession(it) } } } // Add this two methods to allow multiple sessions override fun hashCode() = 99 override fun equals(other: Any?) = other is CryptoFileStoreImporter companion object { private const val LOG_TAG = "CryptoFileStoreImporter" } }
31
null
142
373
68165b6ddbbea51524b5c7e6192d4ae4a0083ad3
9,123
matrix-android-sdk
Apache License 2.0
VejdirektoratetSDK/src/test/java/dk/vejdirektoratet/vejdirektoratetsdk/UtilsTest.kt
Vejdirektoratet
212,273,818
false
null
/** * * VejdirektoratetSDK * * Created by <NAME> on 2019-11-21. * Copyright © 2019 Vejdirektoratet. All rights reserved. */ package dk.vejdirektoratet.vejdirektoratetsdk import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import dk.vejdirektoratet.vejdirektoratetsdk.entity.MapEntity import dk.vejdirektoratet.vejdirektoratetsdk.utils.Utils import java.util.Date import kotlin.test.Test import kotlin.test.assertFailsWith import kotlin.test.asserter class UtilsTest { @Test fun `dateFromIso8601String() - Should throw IllegalDateFormatException if the date string has an invalid format`() { val invalidDateString0 = "" val invalidDateString1 = "2019-8-15T06:02:44.000" assertFailsWith<IllegalDateFormatException> { Utils.dateFromIso8601String(invalidDateString0) } assertFailsWith<IllegalDateFormatException> { Utils.dateFromIso8601String(invalidDateString1) } } @Test fun `dateFromIso8601String() - Should return a Date object generated from the date string`() { val dateString = "2019-08-15T06:02:44.000+0000" val expectedTimestamp = 1565848964000 val date = Utils.dateFromIso8601String(dateString) asserter.assertTrue("Should be of type Date", date is Date) asserter.assertEquals("Should have the correct timestamp", expectedTimestamp, date.time) } @Test fun `VDBoundsToLatLngBounds() - Should convert a VDBounds to a LatLngBounds`() { val southWestLat = 55.1231 val southWestLng = 10.12314 val southWest = VDLatLng(southWestLat, southWestLng) val northEastLat = 57.6532 val northEastLng = 12.54321 val northEast = VDLatLng(northEastLat, northEastLng) val vdBounds = VDBounds(southWest, northEast) val latLngBounds = Utils.vdBoundsToLatLngBounds(vdBounds) asserter.assertTrue("Should be of type LatLngBounds", latLngBounds is LatLngBounds) asserter.assertEquals("Should have the correct latitude for southWest", vdBounds.southWest.lat, latLngBounds.southwest.latitude) asserter.assertEquals("Should have the correct longitude for southWest", vdBounds.southWest.lng, latLngBounds.southwest.longitude) asserter.assertEquals("Should have the correct latitude for northEast", vdBounds.northEast.lat, latLngBounds.northeast.latitude) asserter.assertEquals("Should have the correct longitude for northEast", vdBounds.northEast.lng, latLngBounds.northeast.longitude) } @Test fun `vdLatLngToLatLng() - Should convert a VDLatLng to a LatLng`() { val vdLatLng = VDLatLng(55.1231, 10.12314) val latLng = Utils.vdLatLngToLatLng(vdLatLng) asserter.assertTrue("Should be of type LatLng", latLng is LatLng) asserter.assertEquals("Should have the correct latitude", vdLatLng.lat, latLng.latitude) asserter.assertEquals("Should have the correct longitude", vdLatLng.lng, latLng.longitude) } @Test fun `mapTypeFromString() - Should correctly map a string to a MapType`() { val mapTypeMarker = Utils.mapTypeFromString(Constants.MAP_TYPE_MARKER) val mapTypePolyline = Utils.mapTypeFromString(Constants.MAP_TYPE_POLYLINE) val mapTypePolygon = Utils.mapTypeFromString(Constants.MAP_TYPE_POLYGON) val mapTypeSomethingElse = Utils.mapTypeFromString("somethingElse") asserter.assertEquals("Should be the MapType MARKER", MapEntity.MapType.MARKER, mapTypeMarker) asserter.assertEquals("Should be the MapType POLYLINE", MapEntity.MapType.POLYLINE, mapTypePolyline) asserter.assertEquals("Should be the MapType POLYGON", MapEntity.MapType.POLYGON, mapTypePolygon) asserter.assertEquals("Should be the MapType UNKNOWN", MapEntity.MapType.UNKNOWN, mapTypeSomethingElse) } @Test fun `latLngBoundsToVDBounds() - Should convert a LatLngBound to a VDBounds`() { val southWestLat = 55.1231 val southWestLng = 10.12314 val southWest = LatLng(southWestLat, southWestLng) val northEastLat = 57.6532 val northEastLng = 12.54321 val northEast = LatLng(northEastLat, northEastLng) val latLngBounds = LatLngBounds(southWest, northEast) val vdBounds = Utils.latLngBoundsToVDBounds(latLngBounds) asserter.assertTrue("Should be of type LatLngBounds", vdBounds is VDBounds) asserter.assertEquals("Should have the correct latitude for southWest", latLngBounds.southwest.latitude, vdBounds.southWest.lat) asserter.assertEquals("Should have the correct longitude for southWest", latLngBounds.southwest.longitude, vdBounds.southWest.lng) asserter.assertEquals("Should have the correct latitude for northEast", latLngBounds.northeast.latitude, vdBounds.northEast.lat) asserter.assertEquals("Should have the correct longitude for northEast", latLngBounds.northeast.longitude, vdBounds.northEast.lng) } }
0
Kotlin
0
3
c2c4f7a633a1ee25b33c047a694033e867699441
4,990
sdk-android
MIT License
Kernl.Consumer/src/test/kotlin/nocache/impl/NoCacheMultiNullableParamPrimitiveReturnTest.kt
mattshoe
825,957,770
false
{"Kotlin": 344588, "Shell": 1045}
package nocache.impl import org.mattshoe.shoebox.kernl.runtime.cache.nocache.NoCacheKernl import kernl.org.mattshoe.shoebox.kernl.nocache.NoCacheMultiNullableParamPrimitiveReturnKernl import nocache.NoCacheScenariosTest // Multiple nullable different primitive parameters, primitive return class NoCacheMultiNullableParamPrimitiveReturnTest: NoCacheScenariosTest<NoCacheMultiNullableParamPrimitiveReturnKernl.Params, Int>() { override fun repository(): NoCacheKernl<NoCacheMultiNullableParamPrimitiveReturnKernl.Params, Int> { return NoCacheMultiNullableParamPrimitiveReturnKernl.Factory { id, bar -> (id?.toInt() ?: 0) + (bar ?: 0) } } override val testData = mapOf( NoCacheMultiNullableParamPrimitiveReturnKernl.Params("42", 1) to 43, NoCacheMultiNullableParamPrimitiveReturnKernl.Params("96", 4) to 100, NoCacheMultiNullableParamPrimitiveReturnKernl.Params(null, null) to 0 ) }
10
Kotlin
1
9
9682fcafeb1dccd468443e1265eab55c05757e52
951
kernl
Apache License 2.0
app/src/main/java/com/totallytim/randomreminders/database/Reminder.kt
OmanMkII
261,074,632
false
null
package com.totallytim.randomreminders.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.totallytim.randomreminders.fromCalendar import java.util.* /** * The Reminder database: a collection of the user's reminders that hold information about what the * reminder is, as well as the next occurrence of it and the frequency of it. */ @Entity(tableName = "reminders_table") data class Reminder( /** * The generated primary key. */ @PrimaryKey(autoGenerate = true) var keyID: Long, /** * The name of this reminder (non-unique). */ @ColumnInfo(name = "reminder_name") val name: String = "", /** * The frequency with which this reminder will recur. */ @ColumnInfo(name = "frequency") var frequency: Long = 0L, /** * The variance from the mean at which this occurs, that is: * * NEXT_OCCURRENCE = NOW + T(frequency +/- Range(variance)) */ @ColumnInfo(name = "variance") var variance: Long = 0L, /** * The next time this reminder instance will occur. */ @ColumnInfo(name = "next_occurrence") var nextOccurrence: Long? = fromCalendar(Calendar.getInstance()), /** * Additional information about this reminder that will be presented when triggered. */ @ColumnInfo(name = "description") var description: String? = null)
0
Kotlin
0
0
f736ab6a05b3ada6f51a5c1e0a7d0d5abf2a11c0
1,548
random-reminders
Apache License 2.0
src/main/kotlin/com/github/jk1/ytplugin/timeTracker/actions/StopTrackerAction.kt
JetBrains
48,642,890
false
null
package com.github.jk1.ytplugin.timeTracker.actions import com.github.jk1.ytplugin.ComponentAware import com.github.jk1.ytplugin.logger import com.github.jk1.ytplugin.rest.TimeTrackerRestClient import com.github.jk1.ytplugin.tasks.NoYouTrackRepositoryException import com.github.jk1.ytplugin.tasks.YouTrackServer import com.github.jk1.ytplugin.timeTracker.TrackerNotification import com.github.jk1.ytplugin.ui.YouTrackPluginIcons import com.github.jk1.ytplugin.whenActive import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager import java.util.* class StopTrackerAction : AnAction( "Stop Work Timer", "Stop tracking and post spent time to the current issue", YouTrackPluginIcons.YOUTRACK_STOP_TIME_TRACKER) { override fun actionPerformed(event: AnActionEvent) { event.whenActive { project -> stopTimer(project) } } override fun update(event: AnActionEvent) { val project = event.project if (project != null) { val timer = ComponentAware.of(event.project!!).timeTrackerComponent event.presentation.isEnabled = timer.isRunning event.presentation.isVisible = (timer.isManualTrackingEnable || timer.isAutoTrackingEnable) if (timer.isAutoTrackingEnable){ event.presentation.icon = YouTrackPluginIcons.YOUTRACK_POST_FROM_TIME_TRACKER event.presentation.description = "Post spent time to the current issue and continue tracking" event.presentation.text = "Post Time To Server" } else { event.presentation.icon = YouTrackPluginIcons.YOUTRACK_STOP_TIME_TRACKER event.presentation.description = "Stop tracking and post spent time to the current issue" event.presentation.text = "Stop Work Timer" } } } fun stopTimer(project: Project) { val trackerNote = TrackerNotification() val timer = ComponentAware.of(project).timeTrackerComponent val repo: YouTrackServer? try { repo = ComponentAware.of(project).taskManagerComponent.getActiveYouTrackRepository() logger.debug("YouTrack server integration is configured") } catch (e: NoYouTrackRepositoryException){ logger.debug("YouTrack server integration is not configured yet") return } try { timer.stop() val bar = WindowManager.getInstance().getStatusBar(project) bar?.removeWidget("Time Tracking Clock") if (timer.recordedTime == "0") trackerNote.notify("Spent time shorter than 1 minute is excluded from time tracking", NotificationType.WARNING) else { try { TimeTrackerRestClient(repo).postNewWorkItem(timer.issueId, timer.recordedTime, timer.type, timer.comment, (Date().time).toString()) trackerNote.notify("Work timer stopped, spent time added to" + " ${timer.issueIdReadable}", NotificationType.INFORMATION) ComponentAware.of(project).issueWorkItemsStoreComponent[repo].update(repo) val store: PropertiesComponent = PropertiesComponent.getInstance(project) store.saveFields(timer) } catch (e: Exception) { logger.warn("Time tracking might not be enabled") trackerNote.notify("Could not record time: time tracking is disabled", NotificationType.WARNING) } } } catch (e: IllegalStateException) { logger.warn("Time tracking exception: ${e.message}") trackerNote.notify("Could not stop time tracking: timer is not started", NotificationType.WARNING) } } }
26
null
16
56
210e10ec993ae44fa0472bed9705dc9aad5ec9e2
4,087
youtrack-idea-plugin
Apache License 2.0
cvs-batch/src/main/kotlin/com/yapp/cvs/job/crawl/cu/CUProductCollectorTasklet.kt
YAPP-Github
634,125,354
false
null
package com.yapp.cvs.job.crawl.cu import com.yapp.cvs.domain.collect.ProductRawDataVO import com.yapp.cvs.domain.collect.application.ProductDataProcessor import com.yapp.cvs.domain.enums.RetailerType import com.yapp.cvs.support.CUProductCollectSupport import com.yapp.cvs.support.JsoupHandler import com.yapp.cvs.support.ProductCategoryRule import com.yapp.cvs.support.ProductDataParser import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.batch.core.StepContribution import org.springframework.batch.core.scope.context.ChunkContext import org.springframework.batch.core.step.tasklet.Tasklet import org.springframework.batch.repeat.RepeatStatus open class CUProductCollectorTasklet( private val productDataProcessor: ProductDataProcessor, ) : Tasklet { override fun execute(contribution: StepContribution, chunkContext: ChunkContext): RepeatStatus { val cuProductCollectSupport = CUProductCollectSupport.values().filter { it.promotionType == null } cuProductCollectSupport.forEach { saveProductData(collectRawData(it)) } return RepeatStatus.FINISHED } protected fun collectRawData(category: CUProductCollectSupport): List<ProductRawDataVO> { log.info("Target Category : ${category.productCategoryType?.displayName ?: category.name}") val productCollections = mutableListOf<ProductRawDataVO>() var pageIndex = 1 do { val document = JsoupHandler.doFormPost( category.url, mapOf("pageIndex" to pageIndex.toString(),) ) val body = document.body() val productElements = body.getElementsByClass("prod_list") productElements.forEach { productRawElement -> val title = productRawElement.getElementsByClass("name").text() val price = productRawElement.getElementsByClass("price").text() val imgURL = productRawElement.getElementsByClass("prod_img").attr("src") productCollections.add( ProductRawDataVO( name = ProductDataParser.parseProductName(title), brandName = ProductDataParser.parseBrandName(title), price = ProductDataParser.parsePrice(price), categoryType = category.productCategoryType ?: ProductCategoryRule.parse(title), barcode = ProductDataParser.parseProductCode(imgURL) ?: "", imageUrl = imgURL, retailerType = RetailerType.CU, isPbProduct = category.isPbProduct ) ) } pageIndex++ } while (productElements.size > 0) return productCollections } private fun saveProductData(productRawDataVOList: List<ProductRawDataVO>) { log.info("${productRawDataVOList.size}건 저장") productRawDataVOList.forEach { productDataProcessor.saveProduct(it) } } companion object { private val log: Logger = LoggerFactory.getLogger(this::class.java) } }
5
Kotlin
0
7
9610f8c6e3c2579a88195c17ea4401aac992f1ae
3,170
pyunlee-server
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/coronatest/migration/PCRTestMigration.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.coronatest.migration import dagger.Reusable import de.rki.coronawarnapp.coronatest.server.CoronaTestResult import de.rki.coronawarnapp.coronatest.type.PersonalCoronaTest import de.rki.coronawarnapp.coronatest.type.RegistrationToken import de.rki.coronawarnapp.coronatest.type.pcr.PCRCoronaTest import de.rki.coronawarnapp.storage.TracingSettings import de.rki.coronawarnapp.submission.SubmissionSettings import de.rki.coronawarnapp.util.CWADebug import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import timber.log.Timber import javax.inject.Inject @Reusable class PCRTestMigration @Inject constructor( private val submissionSettings: SubmissionSettings, private val tracingSettings: TracingSettings, ) { private val mutex = Mutex() private var isMigrating: Boolean = false @Suppress("DEPRECATION") suspend fun startMigration(): Set<PersonalCoronaTest> = mutex.withLock { if (isMigrating) throw IllegalStateException("Migration already in progress") isMigrating = true Timber.tag(TAG).i("startMigration()") val token: RegistrationToken? = submissionSettings.registrationTokenMigration if (token == null) { Timber.tag(TAG).d("Nothing to migrate, token was null.") return emptySet() } else { Timber.tag(TAG).i("Migrating token %s", token) } val devicePairingSuccessfulAt = submissionSettings.devicePairingSuccessfulAtMigration Timber.tag(TAG).v("devicePairingSuccessfulAt=%s", devicePairingSuccessfulAt) if (devicePairingSuccessfulAt == null) { if (CWADebug.isDeviceForTestersBuild) { throw IllegalStateException("Can't have registration token without device pairing timestamp !?") } return emptySet() } val isAllowedToSubmitKeys = submissionSettings.isAllowedToSubmitKeysMigration Timber.tag(TAG).v("isAllowedToSubmitKeys=%s", isAllowedToSubmitKeys) val isSubmissionSuccessful = submissionSettings.isSubmissionSuccessfulMigration Timber.tag(TAG).v("isSubmissionSuccessful=%s", isSubmissionSuccessful) val hasViewedTestResult = submissionSettings.hasViewedTestResultMigration Timber.tag(TAG).v("hasViewedTestResult=%s", hasViewedTestResult) val hasGivenConsent = submissionSettings.hasGivenConsentMigration Timber.tag(TAG).v("hasGivenConsent=%s", hasGivenConsent) // TODO per test ? val testResultNotificationSent = tracingSettings.isTestResultAvailableNotificationSentMigration Timber.tag(TAG).v("testResultNotificationSent=%s", testResultNotificationSent) val legacyPCRTest = PCRCoronaTest( identifier = LEGACY_IDENTIFIER, registrationToken = token, registeredAt = devicePairingSuccessfulAt, lastUpdatedAt = devicePairingSuccessfulAt, testResult = when (isAllowedToSubmitKeys) { true -> CoronaTestResult.PCR_POSITIVE else -> CoronaTestResult.PCR_OR_RAT_PENDING }, testResultReceivedAt = devicePairingSuccessfulAt, isSubmitted = isSubmissionSuccessful, isViewed = hasViewedTestResult, isAdvancedConsentGiven = hasGivenConsent, isResultAvailableNotificationSent = testResultNotificationSent, ) return setOf(legacyPCRTest).also { Timber.tag(TAG).d("Offering converted legacy CoronaTest: %s", it) } } suspend fun finishMigration() = mutex.withLock { if (!isMigrating) return@withLock isMigrating = false Timber.tag(TAG).i("finishMigration()") submissionSettings.deleteLegacyTestData() tracingSettings.deleteLegacyTestData() } companion object { private const val TAG = "CoronaTestMigration" /** * We only use this for identification, needs to be guaranteed different from any non-legacy identifiers. */ private const val LEGACY_IDENTIFIER = "qrcode-pcr-legacy" } }
6
null
516
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
4,130
cwa-app-android
Apache License 2.0
shared/src/commonMain/kotlin/ui/mainScreen/NavigationDrawer.kt
Markable97
658,889,189
false
null
package ui.mainScreen import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import data.divisions.DivisionDisplayData @Composable fun DrawerHeader() { Column( modifier = Modifier.padding(top = 20.dp, start = 16.dp) ) { Text( text = "Любительская футбольная лига", fontSize = 16.sp, fontWeight = FontWeight.Medium ) Text( text = "Восточная лига" ) } } @Composable fun DrawerBody( itemsMenu: List<DivisionDisplayData>, modifier: Modifier = Modifier, selectDivision: DivisionDisplayData?, onItemClick: (DivisionDisplayData) -> Unit ) { val selectedItem = remember { mutableStateOf(selectDivision) } LazyColumn(modifier) { items(itemsMenu) { item -> val isItemSelect = item == selectedItem.value val isSelectedColor = if (isItemSelect) Color(0xC195C9BF) else Color.Transparent Box( modifier = Modifier .fillMaxWidth() .clickable { selectedItem.value = item onItemClick.invoke(item) } .background(isSelectedColor) .padding(16.dp), contentAlignment = Alignment.CenterStart ) { val fontWeight = if (isItemSelect) FontWeight.Bold else FontWeight.Normal Text( text = item.name, fontWeight = fontWeight ) } } } }
0
Kotlin
0
1
01b18bf170eb206ffdf27bf71e7bcf6f62ab1e78
2,360
SportCommunityKMM
Apache License 2.0
app/src/main/java/petrov/ivan/bsc/ui/listParty/features/FragmentListPartyModule.kt
peiwal
289,732,500
false
null
package petrov.ivan.bsc.ui.listParty.features import dagger.Module import dagger.Provides import petrov.ivan.bsc.ui.adapters.PartyAdapter @Module class FragmentListPartyModule(private val itemClickListener: PartyAdapter.PartyListener) { @Provides @FragmentListPartyScope fun partyAdapter(): PartyAdapter { return PartyAdapter(itemClickListener) } }
0
Kotlin
0
0
dd61a1334130025e58409b559995c943a801323c
376
BSC_test
MIT License
app/src/main/kotlin/com/mstoyanov/musiclessons/model/Lesson.kt
mstoyanovca
121,074,676
false
{"Kotlin": 114541}
package com.mstoyanov.musiclessons.model import androidx.room.* import androidx.room.ForeignKey.Companion.CASCADE import com.mstoyanov.musiclessons.global.Functions.formatter import java.io.Serializable import java.time.LocalTime @Entity( tableName = "lesson", foreignKeys = [ForeignKey( entity = Student::class, parentColumns = arrayOf("student_id"), childColumns = arrayOf("student_owner_id"), onDelete = CASCADE )], indices = [Index(value = ["student_owner_id"])] ) data class Lesson( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "lesson_id") var lessonId: Long, @TypeConverters(WeekdayConverter::class) var weekday: Weekday, @ColumnInfo(name = "time_from") @TypeConverters(LocalTimeConverter::class) var timeFrom: LocalTime, @ColumnInfo(name = "time_to") @TypeConverters(LocalTimeConverter::class) var timeTo: LocalTime, @ColumnInfo(name = "student_owner_id") var studentId: Long, @Ignore var student: Student ) : Comparable<Lesson>, Serializable { constructor() : this( lessonId = 0L, weekday = Weekday.MONDAY, timeFrom = LocalTime.parse("16:00", formatter), timeTo = LocalTime.parse("16:30", formatter), studentId = 0L, student = Student() ) override fun compareTo(other: Lesson): Int { return when { timeFrom.compareTo(other.timeFrom) != 0 -> timeFrom.compareTo(other.timeFrom) timeTo.compareTo(other.timeTo) != 0 -> timeTo.compareTo(other.timeTo) student.firstName.compareTo( other.student.firstName, ignoreCase = true ) != 0 -> student.firstName.compareTo(other.student.firstName, ignoreCase = true) else -> student.lastName.compareTo(other.student.lastName, ignoreCase = true) } } }
0
Kotlin
1
0
0219f81ef221ae85f96a6329dc8c1358f75dccb8
1,848
music-lessons
MIT License
flow-preferences-tests/src/androidTest/java/com/fredporciuncula/flow/preferences/tests/StringSetPreferenceTest.kt
tfcporciuncula
216,426,553
false
null
package com.tfcporciuncula.tests import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Test @ExperimentalCoroutinesApi class StringSetPreferenceTest : BaseTest() { @Test fun testDefaultValues() { val preference1 = flowSharedPreferences.getStringSet("key", defaultValue = setOf("a, b")) assertThat(preference1.get()).isEqualTo(setOf("a, b")) val preference2 = flowSharedPreferences.getStringSet("key", defaultValue = setOf("x", "y", "a")) assertThat(preference2.get()).isEqualTo(setOf("x", "y", "a")) } @Test fun testSettingValues() { val preference = flowSharedPreferences.getStringSet("key") preference.set(setOf("bla", "bla")) assertThat(preference.get()).isEqualTo(setOf("bla")) runBlocking { preference.setAndCommit(emptySet()) assertThat(preference.get()).isEqualTo(emptySet<String>()) } } }
0
null
18
243
0b0d8250e51f4328239b75b46f0f80367247d92b
961
flow-preferences
Apache License 2.0
app/src/test/java/iced/egret/palette/CollectionUnitTest.kt
anticobalt
189,680,733
false
null
package iced.egret.palette import iced.egret.palette.model.Folder import iced.egret.palette.model.Picture import org.junit.Test class CollectionUnitTest { private val name = "a name" private val path = "a/path/to/a name" @Test fun folderInit() { var folder = Folder(name, path) assert(folder.name == name) assert(folder.path == path) assert(folder.folders.isEmpty()) assert(folder.pictures.isEmpty()) val subFolders = arrayListOf( Folder("a", "path/to/a"), Folder("b", "/a/path/to/b") ) folder = Folder(name, path, subFolders = subFolders) assert(folder.folders == subFolders) assert(folder.pictures.isEmpty()) } @Test fun folderAddChildren() { val folder = Folder(name, path) val subFolder = Folder("z", "antipath/to/z") val subFolders = arrayListOf( Folder("a", "path/to/a"), Folder("b", "a/path/to/b") ) val picture = Picture("name", "whats/in/a/name") val pictures = arrayListOf( Picture("here.jpg", "/destination/here.jpg"), Picture("here.png", "source/here.png"), Picture("here.gif", "/redirect/to/here.gif") ) // one folder assert(subFolder !in folder.folders) folder.addFolder(subFolder) assert(subFolder in folder.folders) // many folders assert(folder.folders.intersect(subFolders).isEmpty()) folder.addFolders(subFolders) assert(folder.folders.intersect(subFolders).size == subFolders.size) assert(subFolder in folder.folders) // one picture assert(picture !in folder.pictures) folder.addPicture(picture) assert(picture in folder.pictures) // many pictures assert(folder.pictures.intersect(pictures).isEmpty()) folder.addPictures(pictures) assert(folder.pictures.intersect(pictures).size == pictures.size) assert(picture in folder.pictures) } @Test fun folderSizes() { val folder = Folder(name, path) val subFolders = arrayListOf( Folder("a", "path/to/a"), Folder("b", "a/path/to/b") ) val pictures = arrayListOf( Picture("here.jpg", "/destination/here.jpg"), Picture("here.png", "source/here.png"), Picture("here.gif", "/redirect/to/here.gif") ) var recursiveSize = 0 assert(folder.isEmpty()) assert(!(folder.isNotEmpty())) assert(folder.size == 0) assert(folder.totalSize == 0) folder.addFolders(subFolders) assert(folder.size == subFolders.size) for (f: Folder in subFolders) { recursiveSize += f.totalSize } assert(folder.totalSize == recursiveSize) folder.addPictures(pictures) assert(folder.size == subFolders.size + pictures.size) assert(folder.totalSize == recursiveSize + pictures.size) } }
3
Kotlin
0
1
7c2ec61c1472e83b00b198696b17a7afa185b48c
3,103
palette
Apache License 2.0
plugin-bazel/src/main/kotlin/org/jetbrains/bazel/debug/configuration/StarlarkDebugConfigurationState.kt
JetBrains
826,262,028
false
{"Kotlin": 3064918, "Starlark": 370388, "Java": 165158, "Scala": 37245, "Python": 34754, "Lex": 17493, "Dockerfile": 8674, "Shell": 7379, "HTML": 1310, "Rust": 680, "Go": 428, "C++": 113}
package org.jetbrains.bazel.debug.configuration import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.project.Project import kotlinx.coroutines.CompletableDeferred import org.jetbrains.bsp.protocol.AnalysisDebugResult import org.jetbrains.plugins.bsp.run.BspProcessHandler class StarlarkDebugConfigurationState( val project: Project, val target: String, environment: ExecutionEnvironment, ) : CommandLineState(environment) { // allows passing execution results (both successful and exceptional) to BspProcessHandler from outside val futureProxy = CompletableDeferred<AnalysisDebugResult>() override fun startProcess(): BspProcessHandler = BspProcessHandler(futureProxy).apply { startNotify() } }
2
Kotlin
18
45
1d79484cfdf8fc31d3a4b214655e857214071723
820
hirschgarten
Apache License 2.0
arch/NetworkLayer/fake/src/main/java/module/network/fake/FakeNetworkDataSource.kt
KellyZ
640,846,392
false
null
package module.network.fake import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import module.network.api.NetworkDataSource import module.network.fake.util.FakeAssetManager import module.network.model.NetworkChangeList import module.network.model.NetworkNewsResource import module.network.model.NetworkTopic import module.network.model.unsplash.UnsplashPhotoResponse import javax.inject.Inject class FakeNetworkDataSource @Inject constructor( private val assets: FakeAssetManager, private val networkJson: Json ) : NetworkDataSource { private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO companion object { private const val NEWS_ASSET = "news.json" private const val TOPICS_ASSET = "topics.json" } override suspend fun getTopics(ids: List<String>?): List<NetworkTopic> = withContext(ioDispatcher) { assets.open(TOPICS_ASSET).use(networkJson::decodeFromStream) } override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> = withContext(ioDispatcher) { assets.open(NEWS_ASSET).use(networkJson::decodeFromStream) } override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> { return getTopics().mapToChangeList(NetworkTopic::id) } override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> { return getNewsResources().mapToChangeList(NetworkNewsResource::id) } override suspend fun searchUnsplashPhotos( query: String, page: Int, perPage: Int ): UnsplashPhotoResponse { TODO("Not yet implemented") } } private fun <T> List<T>.mapToChangeList( idGetter: (T) -> String, ) = mapIndexed { index, item -> NetworkChangeList( id = idGetter(item), changeListVersion = index, isDelete = false ) }
0
Kotlin
0
0
41f00715f73e08fa899139b10427e8cb0be9a1e0
2,053
AndroidModulesSample
Apache License 2.0
app/src/main/java/cz/ikem/dci/zscanner/persistence/SendJobDao.kt
ikem-cz
183,602,578
false
null
package cz.ikem.dci.zscanner.persistence import androidx.lifecycle.LiveData import androidx.room.* @Dao interface SendJobDao { @Query("select * from send_jobs order by timestamp desc") fun getAll(): LiveData<List<SendJob>> @Query("select * from send_jobs order by timestamp desc") fun getAllSync(): List<SendJob> @Insert fun insert(sendJob: SendJob) @Update fun update(sendJob: SendJob) @Delete fun delete(sendJob: SendJob) //@Query("update send_jobs set internal_done_tasks = internal_done_tasks + 1 where instance_id = :correlationId") //fun incrementDone(correlationId: String) @Query("delete from send_jobs where instance_id = :correlationId") fun deleteByInstanceId(correlationId: String) @Query("delete from send_jobs") fun deleteAll() @Query("select * from send_jobs where instance_id = :id") fun getByIdSync(id: String): SendJob @Transaction fun insertInTransaction(sendJob: SendJob) { insert(sendJob) } @Transaction fun deleteMultipleByInstanceIds(ids: List<String>) { ids.forEach { deleteByInstanceId(it) } } //@Transaction //fun incrementDoneInTransaction(correlationId: String) { // incrementDone(correlationId) //} @Transaction fun setPartialJobDoneTag(jobId: String, donetag: String) { val job = getByIdSync(jobId) val done = job.intDoneTasks if (!done.contains(donetag)) { job.intDoneTasks = listOf(done, listOf(donetag)).flatten() update(job) } } }
1
Kotlin
0
2
c1a5d7a449f3fed3da429bda154428ecdb4a8d42
1,598
zscanner-android
MIT License
src/main/java/com/hip/akka/ActorCacheBuilder.kt
hip-property
137,079,682
false
{"Kotlin": 38020}
/*- * =========================================================BeginLicense * Akka Spring utils * . * Copyright (C) 2018 HiP Property * . * 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. * ===========================================================EndLicense */ package com.hip.akka import akka.actor.ActorRef import akka.actor.PoisonPill import akka.actor.TypedActor.self import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.google.common.cache.LoadingCache import com.google.common.cache.RemovalNotification import com.hip.utils.log /** * A cache of actors, which will correctly shut down (with a posion pill) * the actor when evicted. */ class ActorCacheBuilder<K>(val maxSize: Int, val creator: (K) -> ActorRef) { constructor(creator: (K) -> ActorRef) : this(maxSize = 10000, creator = creator) fun build(): LoadingCache<K, ActorRef> { return CacheBuilder.newBuilder() .maximumSize(maxSize.toLong()) .removalListener<K, ActorRef> { notification: RemovalNotification<K, ActorRef> -> log().info("Cached actor for key ${notification.key} has been evicted, and will be shut down") notification.value.tell(PoisonPill.getInstance(), ActorRef.noSender()) } .build(object : CacheLoader<K, ActorRef>() { override fun load(key: K): ActorRef { return creator(key) } }) } }
0
Kotlin
0
0
c683c6046caa3f7a9e525f5579454ea561d7bb10
1,957
akka-spring
Apache License 2.0