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/main/com/doitintl/blaster/deleters/SQLInstanceDeleter.kt | doitintl | 406,397,049 | false | {"Kotlin": 84699, "Java": 16989, "Shell": 4648, "Dockerfile": 468, "Python": 412} | package com.doitintl.blaster.deleters
import com.doitintl.blaster.deleter.BaseDeleter
import com.doitintl.blaster.shared.Constants.CLOUD_BLASTER
import com.doitintl.blaster.shared.Constants.ID
import com.doitintl.blaster.shared.Constants.PROJECT
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.sqladmin.SQLAdmin
class SQLInstanceDeleter : BaseDeleter() {
override val pathPatterns: Array<String>
get() = arrayOf("//cloudsql.googleapis.com/projects/{PROJECT}/instances/{ID}")
override fun doDelete(p: Map<String, String>) {
val response = createSqlAdminService().instances().delete(p[PROJECT], p[ID]).execute()
}
private fun createSqlAdminService(): SQLAdmin {
var cred = GoogleCredential.getApplicationDefault()
if (cred.createScopedRequired()) {
cred = cred.createScoped(listOf("https://www.googleapis.com/auth/cloud-platform"))
}
return SQLAdmin.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), cred)
.setApplicationName(CLOUD_BLASTER).build()
}
} | 3 | Kotlin | 3 | 22 | ce769661dfca7915037330db7ff782c5fef2a97b | 1,271 | CloudBlaster | Apache License 2.0 |
src/main/kotlin/com/terraformation/backend/search/field/TimestampField.kt | terraware | 323,722,525 | false | null | package com.terraformation.backend.search.field
import com.terraformation.backend.search.FieldNode
import com.terraformation.backend.search.SearchFilterType
import com.terraformation.backend.search.SearchTable
import java.time.Instant
import java.time.format.DateTimeParseException
import java.util.EnumSet
import org.jooq.Condition
import org.jooq.TableField
import org.jooq.impl.DSL
/** Search field for columns that have full timestamps. */
class TimestampField(
override val fieldName: String,
override val databaseField: TableField<*, Instant?>,
override val table: SearchTable,
) : SingleColumnSearchField<Instant>() {
override val localize: Boolean
get() = false
override val supportedFilterTypes: Set<SearchFilterType>
get() = EnumSet.of(SearchFilterType.Exact, SearchFilterType.Range)
override fun getCondition(fieldNode: FieldNode): Condition {
val instantValues =
try {
fieldNode.values.map { if (it != null) Instant.parse(it) else null }
} catch (e: DateTimeParseException) {
throw IllegalArgumentException(
"Timestamps must be in RFC 3339 format (example: 2021-05-28T18:45:30Z)")
}
val nonNullInstants = instantValues.filterNotNull()
return when (fieldNode.type) {
SearchFilterType.Exact ->
DSL.or(
listOfNotNull(
if (nonNullInstants.isNotEmpty()) databaseField.`in`(nonNullInstants) else null,
if (fieldNode.values.any { it == null }) databaseField.isNull else null,
))
SearchFilterType.ExactOrFuzzy,
SearchFilterType.Fuzzy ->
throw IllegalArgumentException("Fuzzy search not supported for timestamps")
SearchFilterType.PhraseMatch ->
throw IllegalArgumentException("Phrase match not supported for timestamps")
SearchFilterType.Range -> rangeCondition(instantValues)
}
}
// Timestamp values are always machine-readable.
override fun raw(): SearchField? = null
}
| 16 | null | 1 | 9 | a1596396e04e6175e0be1f7ac05fc18f2cc555cc | 2,012 | terraware-server | Apache License 2.0 |
app/src/test/kotlin/no/nav/tiltakspenger/vedtak/routes/kvp/KvpRoutesTest.kt | navikt | 487,246,438 | false | {"Kotlin": 1005976, "Shell": 1318, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.vedtak.routes.kvp
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.URLProtocol
import io.ktor.http.contentType
import io.ktor.http.path
import io.ktor.server.routing.routing
import io.ktor.server.testing.testApplication
import io.ktor.server.util.url
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import no.nav.tiltakspenger.common.TestApplicationContext
import no.nav.tiltakspenger.felles.Saksbehandler
import no.nav.tiltakspenger.libs.common.Rolle
import no.nav.tiltakspenger.libs.common.Roller
import no.nav.tiltakspenger.objectmothers.førstegangsbehandlingUavklart
import no.nav.tiltakspenger.vedtak.clients.defaultObjectMapper
import no.nav.tiltakspenger.vedtak.routes.behandling.BEHANDLING_PATH
import no.nav.tiltakspenger.vedtak.routes.behandling.vilkår.SamletUtfallDTO
import no.nav.tiltakspenger.vedtak.routes.behandling.vilkår.kvp.KVPVilkårDTO
import no.nav.tiltakspenger.vedtak.routes.behandling.vilkår.kvp.KildeDTO
import no.nav.tiltakspenger.vedtak.routes.behandling.vilkår.kvp.KvpSaksopplysningDTO
import no.nav.tiltakspenger.vedtak.routes.behandling.vilkår.kvp.kvpRoutes
import no.nav.tiltakspenger.vedtak.routes.defaultRequest
import no.nav.tiltakspenger.vedtak.routes.dto.PeriodeDTO
import no.nav.tiltakspenger.vedtak.routes.dto.toDTO
import no.nav.tiltakspenger.vedtak.routes.jacksonSerialization
import no.nav.tiltakspenger.vedtak.tilgang.InnloggetSaksbehandlerProvider
import org.junit.jupiter.api.Test
class KvpRoutesTest {
private val mockInnloggetSaksbehandlerProvider = mockk<InnloggetSaksbehandlerProvider>()
private val objectMapper: ObjectMapper = defaultObjectMapper()
private val periodeBrukerHarKvpEtterEndring = PeriodeDTO(fraOgMed = "2023-01-01", tilOgMed = "2023-01-03")
private val saksbehandler =
Saksbehandler(
"Q123456",
"Superman",
"<EMAIL>",
Roller(listOf(Rolle.SAKSBEHANDLER, Rolle.SKJERMING, Rolle.STRENGT_FORTROLIG_ADRESSE)),
)
@Test
fun `test at endepunkt for henting og lagring av kvp fungerer`() = runTest {
every { mockInnloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(any()) } returns saksbehandler
with(TestApplicationContext()) {
val tac = this
val sak = this.førstegangsbehandlingUavklart(
saksbehandler = saksbehandler,
)
val behandlingId = sak.førstegangsbehandling.id
testApplication {
application {
jacksonSerialization()
routing {
kvpRoutes(
innloggetSaksbehandlerProvider = mockInnloggetSaksbehandlerProvider,
kvpVilkårService = tac.førstegangsbehandlingContext.kvpVilkårService,
behandlingService = tac.førstegangsbehandlingContext.behandlingService,
auditService = tac.personContext.auditService,
)
}
}
// Sjekk at man kan kjøre Get
defaultRequest(
HttpMethod.Get,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
).apply {
status shouldBe HttpStatusCode.OK
val kvpVilkår = objectMapper.readValue<KVPVilkårDTO>(bodyAsText())
kvpVilkår.avklartSaksopplysning.periodeMedDeltagelse.periode shouldNotBe periodeBrukerHarKvpEtterEndring
}
// Sjekk at man kan oppdatere data om kvp
defaultRequest(
HttpMethod.Post,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
) {
setBody(bodyEndreKvp(periodeBrukerHarKvpEtterEndring, true))
}.apply {
status shouldBe HttpStatusCode.Created
}
// Hent data
defaultRequest(
HttpMethod.Get,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
).apply {
status shouldBe HttpStatusCode.OK
contentType() shouldBe ContentType.parse("application/json; charset=UTF-8")
val kvpVilkår = objectMapper.readValue<KVPVilkårDTO>(bodyAsText())
// sjekker at endringen har skjedd
kvpVilkår.avklartSaksopplysning.kilde shouldBe KildeDTO.SAKSBEHANDLER
kvpVilkår.avklartSaksopplysning.periodeMedDeltagelse.periode shouldBe periodeBrukerHarKvpEtterEndring
}
}
}
}
@Test
fun `test at endring av kvp ikke endrer søknadsdata`() = runTest {
every { mockInnloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(any()) } returns saksbehandler
lateinit var originalDatoForKvpFraSøknaden: KvpSaksopplysningDTO
with(TestApplicationContext()) {
val tac = this
val sak = this.førstegangsbehandlingUavklart(
saksbehandler = saksbehandler,
)
val behandlingId = sak.førstegangsbehandling.id
testApplication {
application {
jacksonSerialization()
routing {
kvpRoutes(
innloggetSaksbehandlerProvider = mockInnloggetSaksbehandlerProvider,
kvpVilkårService = tac.førstegangsbehandlingContext.kvpVilkårService,
behandlingService = tac.førstegangsbehandlingContext.behandlingService,
auditService = tac.personContext.auditService,
)
}
}
defaultRequest(
HttpMethod.Get,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
).apply {
status shouldBe HttpStatusCode.OK
val kvpVilkår = objectMapper.readValue<KVPVilkårDTO>(bodyAsText())
originalDatoForKvpFraSøknaden = kvpVilkår.søknadSaksopplysning
}
defaultRequest(
HttpMethod.Post,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
) {
setBody(bodyEndreKvp(periodeBrukerHarKvpEtterEndring, true))
}.apply {
status shouldBe HttpStatusCode.Created
}
defaultRequest(
HttpMethod.Get,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
).apply {
status shouldBe HttpStatusCode.OK
contentType() shouldBe ContentType.parse("application/json; charset=UTF-8")
val kvpVilkår = objectMapper.readValue<KVPVilkårDTO>(bodyAsText())
// sjekker at ikke originale
kvpVilkår.søknadSaksopplysning shouldBe originalDatoForKvpFraSøknaden
}
}
}
}
@Test
fun `test at samlet utfall for kvp blir IKKE_OPPFYLT om bruker går på kvp i vurderingsperioden`() = runTest {
every { mockInnloggetSaksbehandlerProvider.krevInnloggetSaksbehandler(any()) } returns saksbehandler
with(TestApplicationContext()) {
val tac = this
val sak = this.førstegangsbehandlingUavklart(
saksbehandler = saksbehandler,
)
val behandlingId = sak.førstegangsbehandling.id
testApplication {
application {
jacksonSerialization()
routing {
kvpRoutes(
innloggetSaksbehandlerProvider = mockInnloggetSaksbehandlerProvider,
kvpVilkårService = tac.førstegangsbehandlingContext.kvpVilkårService,
behandlingService = tac.førstegangsbehandlingContext.behandlingService,
auditService = tac.personContext.auditService,
)
}
}
val vurderingsperiodeDTO = sak.førstegangsbehandling.vurderingsperiode.toDTO()
defaultRequest(
HttpMethod.Get,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
).apply {
status shouldBe HttpStatusCode.OK
val kvpVilkår = objectMapper.readValue<KVPVilkårDTO>(bodyAsText())
kvpVilkår.samletUtfall shouldBe SamletUtfallDTO.OPPFYLT
}
val bodyKvpDeltarIHelePerioden = bodyEndreKvp(vurderingsperiodeDTO, deltar = true)
defaultRequest(
HttpMethod.Post,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
) {
setBody(bodyKvpDeltarIHelePerioden)
}.apply {
status shouldBe HttpStatusCode.Created
}
defaultRequest(
HttpMethod.Get,
url {
protocol = URLProtocol.HTTPS
path("$BEHANDLING_PATH/$behandlingId/vilkar/kvp")
},
).apply {
status shouldBe HttpStatusCode.OK
contentType() shouldBe ContentType.parse("application/json; charset=UTF-8")
val kvpVilkår = objectMapper.readValue<KVPVilkårDTO>(bodyAsText())
kvpVilkår.samletUtfall shouldBe SamletUtfallDTO.IKKE_OPPFYLT
}
}
}
}
private fun bodyEndreKvp(
periodeDTO: PeriodeDTO,
deltar: Boolean,
): String {
val deltarString = if (deltar) "true" else "false"
return """
{
"ytelseForPeriode": [
{
"periode": {
"fraOgMed": "${periodeDTO.fraOgMed}",
"tilOgMed": "${periodeDTO.tilOgMed}"
},
"deltar": $deltarString
}
],
"årsakTilEndring": "FEIL_I_INNHENTET_DATA"
}
""".trimIndent()
}
}
| 8 | Kotlin | 0 | 1 | d51a5a99224ac15fe23c378541494504ca346cc2 | 11,589 | tiltakspenger-vedtak | MIT License |
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/omsorgsopptjening/repository/UtfallDb.kt | navikt | 593,529,397 | false | null | package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening.repository
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening.model.*
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type",
)
internal sealed class VilkårsvurderingUtfallDb {
object EllerAvslått : VilkårsvurderingUtfallDb()
object EllerInnvilget : VilkårsvurderingUtfallDb()
object OgAvslått : VilkårsvurderingUtfallDb()
object OgInnvilget : VilkårsvurderingUtfallDb()
data class VilkårAvslag(val henvisning: Set<JuridiskHenvisningDb>) : VilkårsvurderingUtfallDb()
data class VilkårInnvilget(val henvisning: Set<JuridiskHenvisningDb>) : VilkårsvurderingUtfallDb()
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type",
)
internal sealed class BehandlingsutfallDb {
object AutomatiskGodskrivingAvslagUtenOppgave : BehandlingsutfallDb()
object AutomatiskGodskrivingAvslagMedOppgave : BehandlingsutfallDb()
object AutomatiskGodskrivingInnvilget : BehandlingsutfallDb()
}
internal fun BehandlingUtfall.toDb(): BehandlingsutfallDb {
return when (this) {
AutomatiskGodskrivingUtfall.AvslagMedOppgave -> {
BehandlingsutfallDb.AutomatiskGodskrivingAvslagMedOppgave
}
AutomatiskGodskrivingUtfall.AvslagUtenOppgave -> {
BehandlingsutfallDb.AutomatiskGodskrivingAvslagUtenOppgave
}
AutomatiskGodskrivingUtfall.Innvilget -> {
BehandlingsutfallDb.AutomatiskGodskrivingInnvilget
}
}
}
internal fun VilkårsvurderingUtfall.toDb(): VilkårsvurderingUtfallDb {
return when (this) {
is EllerAvslått -> {
VilkårsvurderingUtfallDb.EllerAvslått
}
is EllerInnvilget -> {
VilkårsvurderingUtfallDb.EllerInnvilget
}
is OgAvslått -> {
VilkårsvurderingUtfallDb.OgAvslått
}
is OgInnvilget -> {
VilkårsvurderingUtfallDb.OgInnvilget
}
is VilkårsvurderingUtfall.Innvilget.Vilkår -> {
VilkårsvurderingUtfallDb.VilkårInnvilget(henvisning = henvisninger.toDb())
}
is VilkårsvurderingUtfall.Avslag.Vilkår -> {
VilkårsvurderingUtfallDb.VilkårAvslag(henvisning = henvisninger.toDb())
}
}
}
internal fun VilkårsvurderingUtfallDb.toDomain(): VilkårsvurderingUtfall {
return when (this) {
is VilkårsvurderingUtfallDb.EllerAvslått -> {
EllerAvslått
}
is VilkårsvurderingUtfallDb.EllerInnvilget -> {
EllerInnvilget
}
is VilkårsvurderingUtfallDb.OgAvslått -> {
OgAvslått
}
is VilkårsvurderingUtfallDb.OgInnvilget -> {
OgInnvilget
}
is VilkårsvurderingUtfallDb.VilkårAvslag -> {
VilkårsvurderingUtfall.Avslag.Vilkår(henvisninger = henvisning.toDomain())
}
is VilkårsvurderingUtfallDb.VilkårInnvilget -> {
VilkårsvurderingUtfall.Innvilget.Vilkår(henvisninger = henvisning.toDomain())
}
}
}
internal fun BehandlingsutfallDb.toDomain(): BehandlingUtfall {
return when (this) {
is BehandlingsutfallDb.AutomatiskGodskrivingAvslagUtenOppgave -> {
AutomatiskGodskrivingUtfall.AvslagUtenOppgave
}
is BehandlingsutfallDb.AutomatiskGodskrivingInnvilget -> {
AutomatiskGodskrivingUtfall.Innvilget
}
is BehandlingsutfallDb.AutomatiskGodskrivingAvslagMedOppgave -> {
AutomatiskGodskrivingUtfall.AvslagMedOppgave
}
}
}
| 0 | Kotlin | 0 | 0 | 2993c63491257a02ac6c5eb7cacc034152ecfa91 | 3,818 | omsorgsopptjening-bestem-pensjonsopptjening | MIT License |
src/main/kotlin/juuxel/adorn/block/renderer/TradingStationRenderer.kt | modindex | 199,925,686 | true | {"Kotlin": 234308, "Java": 9514, "Shell": 297} | package juuxel.adorn.block.renderer
import com.mojang.blaze3d.platform.GlStateManager
import juuxel.adorn.block.entity.TradingStationBlockEntity
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.minecraft.client.MinecraftClient
import net.minecraft.client.render.block.entity.BlockEntityRenderer
import net.minecraft.client.render.model.json.ModelTransformation
import net.minecraft.item.ItemStack
import net.minecraft.text.LiteralText
import net.minecraft.text.Text
import net.minecraft.text.TranslatableText
import net.minecraft.util.Formatting
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.hit.HitResult
@Environment(EnvType.CLIENT)
class TradingStationRenderer : BlockEntityRenderer<TradingStationBlockEntity>() {
override fun render(be: TradingStationBlockEntity, x: Double, y: Double, z: Double, tickDelta: Float, i: Int) {
super.render(be, x, y, z, tickDelta, i)
val hitResult = renderManager.hitResult
val lookingAtBlock = hitResult != null &&
hitResult.type == HitResult.Type.BLOCK &&
be.pos == (hitResult as BlockHitResult).blockPos
val trade = be.trade
if (!trade.isEmpty()) {
GlStateManager.pushMatrix()
GlStateManager.translated(x + 0.5, y + 1.2, z + 0.5)
val playerAge = MinecraftClient.getInstance().player.age
GlStateManager.pushMatrix()
GlStateManager.rotatef((playerAge + tickDelta) * SELLING_ROTATION_MULTIPLIER, 0f, 1f, 0f)
GlStateManager.scalef(0.6f, 0.6f, 0.6f)
GlStateManager.translatef(0f, 0.3f, 0f)
val itemRenderer = MinecraftClient.getInstance().itemRenderer
itemRenderer.renderItem(trade.selling, ModelTransformation.Type.FIXED)
GlStateManager.popMatrix()
/*if (lookingAtBlock) {
GlStateManager.rotatef((playerAge + tickDelta) * PRICE_ROTATION_MULTIPLIER, 0f, 1f, 0f)
GlStateManager.translatef(0.55f, 0f, 0f)
itemRenderer.renderItem(trade.price, ModelTransformation.Type.GROUND)
}*/
GlStateManager.popMatrix()
}
if (lookingAtBlock) {
disableLightmap(true)
for ((row, text) in getLabelRows(be).withIndex()) {
renderName(be, text, x, y + 0.9 - 0.25 * row, z, 12)
}
disableLightmap(false)
}
}
private fun getLabelRows(be: TradingStationBlockEntity): Sequence<String> =
sequence {
yield(TranslatableText(
"block.adorn.trading_station.label.1",
be.ownerName.copy().formatted(Formatting.GOLD)
))
if (!be.trade.isEmpty()) {
yield(
TranslatableText(
"block.adorn.trading_station.label.2",
be.trade.selling.toTextComponentWithCount()
)
)
yield(
TranslatableText(
"block.adorn.trading_station.label.3",
be.trade.price.toTextComponentWithCount()
)
)
}
}.map(Text::asFormattedString)
private fun ItemStack.toTextComponentWithCount(): Text =
LiteralText("${count}x ").append(toHoverableText())
companion object {
private const val SELLING_ROTATION_MULTIPLIER = 1.2f
//private const val PRICE_ROTATION_MULTIPLIER = -2.5f
}
}
| 0 | Kotlin | 0 | 0 | 9941d7de7de66fc1dce4edeb29e3b2dcd78e0c2f | 3,552 | Adorn | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/FishHook.kt | walter-juan | 868,046,028 | false | {"Kotlin": 20416825} | package com.woowla.compose.icon.collections.tabler.tabler.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.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.FishHook: ImageVector
get() {
if (_fishHook != null) {
return _fishHook!!
}
_fishHook = Builder(name = "FishHook", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.0f, 9.0f)
verticalLineToRelative(6.0f)
arcToRelative(5.0f, 5.0f, 0.0f, false, true, -10.0f, 0.0f)
verticalLineToRelative(-4.0f)
lineToRelative(3.0f, 3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.0f, 7.0f)
moveToRelative(-2.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, -4.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.0f, 5.0f)
verticalLineToRelative(-2.0f)
}
}
.build()
return _fishHook!!
}
private var _fishHook: ImageVector? = null
| 0 | Kotlin | 0 | 1 | b037895588c2f62d069c724abe624b67c0889bf9 | 2,481 | compose-icon-collections | MIT License |
app/src/main/java/com/nikola/jakshic/dagger/profile/ProfileFragment.kt | rohitnotes | 343,577,504 | true | {"Kotlin": 198124} | package com.nikola.jakshic.dagger.profile
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import coil.load
import coil.transform.CircleCropTransformation
import com.nikola.jakshic.dagger.R
import com.nikola.jakshic.dagger.common.Status
import com.nikola.jakshic.dagger.util.DotaUtil
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.activity_profile.*
import kotlinx.android.synthetic.main.toolbar_profile.*
@AndroidEntryPoint
class ProfileFragment : Fragment(R.layout.activity_profile) {
private val viewModel by viewModels<ProfileViewModel>()
private val args by navArgs<ProfileFragmentArgs>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val id = args.accountId
// Change the color of the progress bar
progressBar.indeterminateDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY)
viewModel.getProfile(id)
viewModel.profile.observe(viewLifecycleOwner) {
if (it != null) {
imgPlayerAvatar.load(it.avatarUrl) {
transformations(CircleCropTransformation())
}
val medal = DotaUtil.getMedal(requireContext(), it.rankTier, it.leaderboardRank)
val stars = DotaUtil.getStars(requireContext(), it.rankTier, it.leaderboardRank)
imgRankMedal.load(medal)
imgRankStars.load(stars)
val name = if (TextUtils.isEmpty(it.name)) it.personaName else it.name
collapsingToolbar.title = name
tvPlayerName.text = name
tvLeaderboardRank.text = if (it.leaderboardRank != 0L) it.leaderboardRank.toString() else null
tvPlayerId.text = it.id.toString()
tvPlayerGames.text = resources.getString(R.string.player_games, (it.wins + it.losses) as Long) // lint is throwing `wrong argument type for formatting argument` error
tvPlayerWins.text = resources.getString(R.string.player_wins, it.wins as Long) // lint is throwing `wrong argument type for formatting argument` error
tvPlayerLosses.text = resources.getString(R.string.player_losses, it.losses as Long) // lint is throwing `wrong argument type for formatting argument` error
val winRate = (it.wins.toDouble() / (it.wins + it.losses)) * 100
tvPlayerWinRate.text = resources.getString(R.string.player_winrate, winRate as Double) // lint is throwing `wrong argument type for formatting argument` error
}
}
viewModel.bookmark.observe(viewLifecycleOwner) {
with(btnFollow) {
if (it == null) {
text = getString(R.string.follow)
setTextColor(ContextCompat.getColor(requireContext(), android.R.color.white))
background = ContextCompat.getDrawable(requireContext(), R.drawable.button_toolbar_follow_inactive)
} else {
text = getString(R.string.unfollow)
setTextColor(ContextCompat.getColor(requireContext(), R.color.colorAccent))
background = ContextCompat.getDrawable(requireContext(), R.drawable.button_toolbar_follow_active)
}
}
}
viewModel.status.observe(viewLifecycleOwner) {
when (it) {
Status.LOADING -> {
btnRefresh.isEnabled = false
btnRefresh.visibility = View.GONE
progressBar.visibility = View.VISIBLE
}
else -> {
btnRefresh.visibility = View.VISIBLE
progressBar.visibility = View.GONE
btnRefresh.isEnabled = true
}
}
}
btnRefresh.setOnClickListener { viewModel.fetchProfile(id) }
val medalDialog = MedalDialog()
imgRankMedal.setOnClickListener { if (!medalDialog.isAdded) medalDialog.show(childFragmentManager, null) }
// Toolbar is drawn over the medal and refresh button, so we need to register clicks
// on the toolbar and then pass them to the proper views.
toolbar.setOnTouchListener { v, event ->
if (event.action != MotionEvent.ACTION_DOWN) return@setOnTouchListener false
val refreshX = toolbar.width - btnRefresh.width
val medalMarginLeft = (imgRankMedal.layoutParams as ConstraintLayout.LayoutParams).leftMargin
val medalMarginTop = (imgRankMedal.layoutParams as ConstraintLayout.LayoutParams).topMargin
val medalWidth = imgRankMedal.width
if (event.x >= refreshX && btnRefresh.isEnabled) btnRefresh.callOnClick()
if (event.y >= medalMarginTop && event.x >= medalMarginLeft && event.x <= (medalWidth + medalMarginLeft)) imgRankMedal.callOnClick()
false
}
btnFollow.setOnClickListener {
if (viewModel.bookmark.value == null)
viewModel.addToBookmark(id)
else {
viewModel.removeFromBookmark(id)
}
}
viewPager.offscreenPageLimit = 2
viewPager.adapter = ProfilePagerAdapter(requireContext(), childFragmentManager)
tabLayout.setupWithViewPager(viewPager)
}
} | 0 | null | 0 | 0 | 2d509ad54190e5c51cd7650c1ebd8d77a6040abb | 5,741 | dagger | MIT License |
shared/src/commonMain/kotlin/assets/composable/AssetItem.kt | amdevprojects | 685,035,772 | false | null | package assets.composable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import assets.model.Asset
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
@Composable
fun AssetItem(asset: Asset) {
Column(modifier = Modifier.background(Color.White).padding(2.dp), horizontalAlignment = Alignment.CenterHorizontally) {
KamelImage(
asyncPainterResource(asset.url),
contentDescription = null
)
Text(text = asset.asset_id)
}
} | 0 | Kotlin | 0 | 0 | 55dd62007683dcf83edd7ee7104f4674a2150b95 | 829 | ComposeKMMPOC | Apache License 2.0 |
src/test/kotlin/no/nav/familie/ef/sak/api/gui/VurderingControllerTest.kt | blommish | 359,371,467 | false | null | package no.nav.familie.ef.sak.api.gui
import no.nav.familie.ef.sak.OppslagSpringRunnerTest
import no.nav.familie.ef.sak.api.dto.OppdaterVilkårsvurderingDto
import no.nav.familie.ef.sak.api.dto.SvarPåVurderingerDto
import no.nav.familie.ef.sak.api.dto.VilkårDto
import no.nav.familie.ef.sak.api.dto.VilkårsvurderingDto
import no.nav.familie.ef.sak.regler.SvarId
import no.nav.familie.ef.sak.repository.domain.BehandlingType
import no.nav.familie.ef.sak.repository.domain.Stønadstype
import no.nav.familie.ef.sak.repository.domain.VilkårType
import no.nav.familie.ef.sak.service.BehandlingService
import no.nav.familie.ef.sak.service.FagsakService
import no.nav.familie.ef.sak.service.GrunnlagsdataService
import no.nav.familie.kontrakter.ef.søknad.SøknadMedVedlegg
import no.nav.familie.kontrakter.ef.søknad.Testsøknad
import no.nav.familie.kontrakter.felles.Ressurs
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.web.client.exchange
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
internal class VurderingControllerTest : OppslagSpringRunnerTest() {
@Autowired lateinit var behandlingService: BehandlingService
@Autowired lateinit var fagsakService: FagsakService
@Autowired lateinit var grunnlagsdataService: GrunnlagsdataService
@BeforeEach
fun setUp() {
headers.setBearerAuth(lokalTestToken)
}
@Test
internal fun `skal hente vilkår`() {
val respons: ResponseEntity<Ressurs<VilkårDto>> = opprettInngangsvilkår()
assertThat(respons.statusCode).isEqualTo(HttpStatus.OK)
assertThat(respons.body.status).isEqualTo(Ressurs.Status.SUKSESS)
assertThat(respons.body.data).isNotNull
}
@Test
internal fun `oppdaterVilkår - skal sjekke att behandlingId som blir sendt inn er lik den som finnes i vilkårsvurderingen`() {
val opprettetVurdering = opprettInngangsvilkår().body.data!!
val fagsak = fagsakService.hentEllerOpprettFagsakMedBehandlinger("0", Stønadstype.OVERGANGSSTØNAD)
val behandling = behandlingService.opprettBehandling(BehandlingType.FØRSTEGANGSBEHANDLING, fagsak.id)
val oppdaterVilkårsvurdering = lagOppdaterVilkårsvurdering(opprettetVurdering, VilkårType.FORUTGÅENDE_MEDLEMSKAP)
.copy(behandlingId = behandling.id)
validerSjekkPåBehandlingId(oppdaterVilkårsvurdering, "vilkar")
}
@Test
internal fun `nullstillVilkår - skal sjekke att behandlingId som blir sendt inn er lik den som finnes i vilkårsvurderingen`() {
val opprettetVurdering = opprettInngangsvilkår().body.data!!
val fagsak = fagsakService.hentEllerOpprettFagsakMedBehandlinger("0", Stønadstype.OVERGANGSSTØNAD)
val behandling = behandlingService.opprettBehandling(BehandlingType.FØRSTEGANGSBEHANDLING, fagsak.id)
val nullstillVurdering = OppdaterVilkårsvurderingDto(opprettetVurdering.vurderinger.first().id, behandling.id)
validerSjekkPåBehandlingId(nullstillVurdering, "nullstill")
}
private fun validerSjekkPåBehandlingId(request: Any, path: String) {
val respons: ResponseEntity<Ressurs<VilkårsvurderingDto>> =
restTemplate.exchange(localhost("/api/vurdering/$path"),
HttpMethod.POST,
HttpEntity(request, headers))
assertThat(respons.statusCode).isEqualTo(HttpStatus.BAD_REQUEST)
assertThat(respons.body!!.frontendFeilmelding).isEqualTo("BehandlingId er feil, her har noe gått galt")
}
@Test
internal fun `skal oppdatere vurderingen for FORUTGÅENDE_MEDLEMSKAP som har ett spørsmål som vi setter til JA`() {
val opprettetVurdering = opprettInngangsvilkår().body.data!!
val oppdatertVilkårsvarMedJa = lagOppdaterVilkårsvurdering(opprettetVurdering, VilkårType.FORUTGÅENDE_MEDLEMSKAP)
val respons: ResponseEntity<Ressurs<VilkårsvurderingDto>> =
restTemplate.exchange(localhost("/api/vurdering/vilkar"),
HttpMethod.POST,
HttpEntity(oppdatertVilkårsvarMedJa, headers))
assertThat(respons.statusCode).isEqualTo(HttpStatus.OK)
assertThat(respons.body.status).isEqualTo(Ressurs.Status.SUKSESS)
assertThat(respons.body.data?.id).isEqualTo(oppdatertVilkårsvarMedJa.id)
}
private fun lagOppdaterVilkårsvurdering(opprettetVurdering: VilkårDto, vilkårType: VilkårType): SvarPåVurderingerDto {
return opprettetVurdering.vurderinger.first { it.vilkårType == vilkårType }.let {
lagOppdaterVilkårsvurderingMedSvarJa(it)
}
}
private fun lagOppdaterVilkårsvurderingMedSvarJa(it: VilkårsvurderingDto) =
SvarPåVurderingerDto(id = it.id,
behandlingId = it.behandlingId,
delvilkårsvurderinger = it.delvilkårsvurderinger.map {
it.copy(vurderinger = it.vurderinger.map { vurderingDto ->
vurderingDto.copy(svar = SvarId.JA)
})
})
private fun opprettInngangsvilkår(): ResponseEntity<Ressurs<VilkårDto>> {
val søknad = SøknadMedVedlegg(Testsøknad.søknadOvergangsstønad, emptyList())
val fagsak = fagsakService.hentEllerOpprettFagsakMedBehandlinger(søknad.søknad.personalia.verdi.fødselsnummer.verdi.verdi,
Stønadstype.OVERGANGSSTØNAD)
val behandling = behandlingService.opprettBehandling(BehandlingType.FØRSTEGANGSBEHANDLING, fagsak.id)
behandlingService.lagreSøknadForOvergangsstønad(søknad.søknad, behandling.id, fagsak.id, "1234")
grunnlagsdataService.hentEndringerIRegistergrunnlag(behandling.id)
return restTemplate.exchange(localhost("/api/vurdering/${behandling.id}/vilkar"),
HttpMethod.GET,
HttpEntity<Any>(headers))
}
} | 1 | null | 1 | 1 | 0e850df593c82a910c68c2393e6d2f30fc49eaa7 | 6,382 | familie-ef-sak | MIT License |
app/src/main/java/xyz/godi/budgetmanager/db/ExpensesDb.kt | zularizal | 178,556,279 | false | null | package xyz.godi.budgetmanager.db
import androidx.room.Database
import androidx.room.RoomDatabase
import xyz.godi.expenses.data.Expense
import xyz.godi.expenses.db.DailyExpenseDao
@Database(
entities = [Expense::class],
version = 1,
exportSchema = false
)
abstract class ExpensesDb: RoomDatabase() {
abstract fun dailyExpenseDao(): DailyExpenseDao
companion object {
const val DATABASE_NAME = "expenses_manager.db"
}
} | 0 | Kotlin | 0 | 2 | a2a1d45f1fd597a8f78d098f178d2f4ef071d18d | 466 | Expense-manager | Apache License 2.0 |
app/src/main/java/ca/on/hojat/gamenews/core/domain/entities/Company.kt | hojat72elect | 574,228,468 | false | null | package ca.on.hojat.gamenews.core.domain.entities
data class Company(
val id: Int,
val name: String,
val websiteUrl: String,
val logo: Image?,
val developedGames: List<Int>,
) {
val hasLogo: Boolean
get() = (logo != null)
val hasDevelopedGames: Boolean
get() = developedGames.isNotEmpty()
}
| 0 | null | 8 | 4 | b1c07551e90790ee3d273bc4c0ad3a5f97f71202 | 338 | GameHub | MIT License |
subprojects/assemble/build-metrics/src/test/kotlin/com/avito/android/plugin/build_metrics/runtime/JvmMetricsSenderStub.kt | avito-tech | 230,265,582 | false | null | package com.avito.android.plugin.build_metrics.runtime
import com.avito.android.plugin.build_metrics.internal.runtime.HeapInfo
import com.avito.android.plugin.build_metrics.internal.runtime.JvmMetricsSender
import com.avito.android.plugin.build_metrics.internal.runtime.LocalVm
internal class JvmMetricsSenderStub : JvmMetricsSender {
val sendInvocations = mutableListOf<Pair<LocalVm, HeapInfo>>()
override fun send(vm: LocalVm, heapInfo: HeapInfo) {
sendInvocations.add(vm to heapInfo)
}
}
| 8 | Kotlin | 41 | 353 | c4e3170ffd74b1b33000334dd35b84ae21ad78ae | 515 | avito-android | MIT License |
app/src/main/java/com/example/simplerxapp/models/dto/SubjectResponseDto.kt | CycoByte | 872,479,871 | false | {"Kotlin": 49145} | package com.example.simplerxapp.models.dto
import com.example.simplerxapp.models.SubjectModel
data class SubjectResponseDto(
override val _embedded: Embedded
): ApiBaseResponse<SubjectResponseDto.Embedded> {
data class Embedded(
val subjects: List<SubjectModel>
)
} | 0 | Kotlin | 0 | 0 | 2a924900a048b42ad16185fd50ccbdd2844c7fdb | 287 | sample-rxkotlin-langs | MIT License |
Halachic Times/locations/src/main/java/com/github/times/location/bing/BingResponse.kt | pnemonic78 | 121,489,129 | false | {"Kotlin": 915819, "Java": 140420, "HTML": 5998, "Shell": 73} | /*
* Copyright 2012, <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.
*/
package com.github.times.location.bing
import android.net.Uri
import com.google.gson.annotations.SerializedName
/**
* Root object for Bing address JSON response.
*
* @author <NAME>
*/
class BingResponse {
@SerializedName("authenticationResultCode")
var authenticationResultCode: String? = null
@SerializedName("brandLogoUri")
var brandLogoUri: Uri? = null
@SerializedName("copyright")
var copyright: String? = null
@SerializedName("resourceSets")
var resourceSets: List<ResourceSet>? = null
@SerializedName("statusCode")
var statusCode = 0
@SerializedName("statusDescription")
var statusDescription: String? = null
@SerializedName("traceId")
var traceId: String? = null
class ResourceSet {
@SerializedName("estimatedTotal")
var estimatedTotal = 0
@SerializedName("resources")
var resources: List<BingResource>? = null
}
companion object {
const val STATUS_OK = 200
}
} | 43 | Kotlin | 2 | 9 | e84bb48cbc39c548042482459b5d6bed35a6fe80 | 1,586 | HalachicTimes | Apache License 2.0 |
compiler/src/main/kotlin/io/github/aplcornell/viaduct/circuitanalysis/AnalysisProvider.kt | apl-cornell | 169,159,978 | false | {"Kotlin": 1117382, "Java": 43793, "C++": 13898, "Lex": 12293, "Python": 11983, "Dockerfile": 1951, "Makefile": 1762, "SWIG": 1212, "Shell": 950} | package io.github.aplcornell.viaduct.circuitanalysis
import io.github.aplcornell.viaduct.syntax.circuit.ProgramNode
interface AnalysisProvider<Analysis> {
/**
* Returns the [Analysis] instance for [program].
* The returned instance is cached for efficiency, so calling [get] again on [program] will
* return the same instance.
*/
fun get(program: ProgramNode): Analysis
}
| 31 | Kotlin | 4 | 20 | 567491fdcfd313bf287b8cdd374e80f1e005ac62 | 402 | viaduct | MIT License |
app/src/main/java/torille/fi/lurkforreddit/data/SubredditDao.kt | Briseus | 82,205,094 | false | {"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 6, "Kotlin": 90, "XML": 57, "Java": 2} | package torille.fi.lurkforreddit.data
import android.arch.persistence.room.*
import io.reactivex.Flowable
import torille.fi.lurkforreddit.data.models.view.Subreddit
@Dao
interface SubredditDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(subreddit: Subreddit)
@Update
fun update(subreddit: Subreddit)
@Delete
fun delete(subreddit: Subreddit)
@Query("DELETE FROM subreddits")
fun deleteAllSubreddits()
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(subreddit: List<Subreddit>)
@Query("SELECT * FROM subreddits")
fun getSubreddits(): Flowable<List<Subreddit>>
}
| 1 | Kotlin | 0 | 2 | 3473b8c91c64d7f13862c7aaf8a75f7c8d1914d0 | 649 | Lurker | MIT License |
lib/src/androidTest/java/com/flexcode/multiselectcalendar/calendar/ExampleInstrumentedTest.kt | Felix-Kariuki | 708,437,440 | false | {"Kotlin": 46622} | package com.flexcode.multiselectcalendar.calendar
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
public class ExampleInstrumentedTest {
@Test
public fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.flexcode.multiselectcalendar.calendar.test", appContext.packageName)
}
}
| 5 | Kotlin | 0 | 5 | 55b4a8889f7d2209552a5b4e27850d5b5330c98e | 727 | MultiSelectCalendar | Apache License 2.0 |
VivaCoronia/app/src/main/java/de/tudarmstadt/iptk/foxtrot/vivacoronia/dataStorage/QuizGameDao.kt | ckuessner | 313,282,198 | false | null | package de.tudarmstadt.iptk.foxtrot.vivacoronia.dataStorage
import androidx.room.*
import de.tudarmstadt.iptk.foxtrot.vivacoronia.dataStorage.entities.QuizGame
@Dao
interface QuizGameDao {
@Insert
fun insert(game: QuizGame)
@Update
fun update(game: QuizGame)
@Delete
fun delete(game: QuizGame)
@Query("SELECT * FROM quiz_game_table WHERE finishedAt == -1")
fun getActive(): List<QuizGame>
@Query("SELECT * FROM quiz_game_table WHERE finishedAt > 0 ORDER BY finishedAt DESC")
fun getFinished(): List<QuizGame>
@Query("SELECT * FROM quiz_game_table WHERE gameId = :gameId")
fun getGame(gameId: String): QuizGame?
} | 0 | Kotlin | 0 | 0 | 779a0382c2a3f06ed57f23b25777985bf80db5b8 | 667 | vivacoronia-frontend | Apache License 2.0 |
app/src/main/java/com/stellarcontainersfsm/features/stock/model/NewStockListResponseModel.kt | DebashisINT | 756,252,499 | false | {"Kotlin": 14218175, "Java": 1004755} | package com.stellarcontainersfsm.features.stock.model
import com.stellarcontainersfsm.base.BaseResponse
/**
* Created by Saikat on 17-09-2019.
*/
class NewStockListResponseModel : BaseResponse() {
var stock_list: ArrayList<StockListDataModel>? = null
} | 0 | Kotlin | 0 | 0 | afb97c29d93fc5bd8668cd16d2525947ad51b8a5 | 261 | StellarContainersFSM | Apache License 2.0 |
app/src/main/kotlin/cn/tongdun/android/beans/DetailsItemBean.kt | trustdecision | 577,570,869 | false | {"Kotlin": 92009, "C++": 9704, "Java": 2257, "C": 1249, "CMake": 884} | package cn.tongdun.android.beans
data class DetailsItemBean(
val name: String, val value: String
)
| 2 | Kotlin | 38 | 343 | 172d2a745ce0f1ca2cb3aed4717818913760856e | 105 | trustdevice-android | MIT License |
src/org/chorusmc/chorus/menus/drop/actions/insert/EnchantmentName.kt | franga2000 | 246,333,834 | true | {"Kotlin": 324702, "CSS": 90948, "Java": 50010, "JavaScript": 19888} | package org.chorusmc.chorus.menus.drop.actions.insert
import org.chorusmc.chorus.minecraft.McClass
import org.chorusmc.chorus.settings.SettingsBuilder
/**
* @author Gio
*/
class EnchantmentName : EnumNameAction(McClass("Enchantment").cls) {
init {
SettingsBuilder.addAction("4.Minecraft.0.Server_version", Runnable {
enumClass = McClass("Enchantment").cls
})
}
} | 0 | null | 0 | 0 | fb0faa7277e90242c9f16ba7174baf18bed24e6f | 403 | chorus | Apache License 2.0 |
backend/src/main/kotlin/ase/athlete_view/common/sanitization/Sanitizer.kt | bastianferch | 753,047,760 | false | {"Kotlin": 895253, "TypeScript": 217992, "HTML": 75240, "Python": 44465, "SCSS": 25875, "JavaScript": 9353, "Dockerfile": 1329, "Shell": 203} | package ase.athlete_view.common.sanitization
import io.github.oshai.kotlinlogging.KotlinLogging
import ase.athlete_view.domain.activity.pojo.entity.Interval
import ase.athlete_view.domain.activity.pojo.entity.PlannedActivity
import ase.athlete_view.domain.activity.pojo.entity.Step
import ase.athlete_view.domain.authentication.dto.AthleteRegistrationDTO
import ase.athlete_view.domain.authentication.dto.TrainerRegistrationDTO
import ase.athlete_view.domain.notification.pojo.entity.Notification
import ase.athlete_view.domain.time_constraint.pojo.dto.DailyTimeConstraintDto
import ase.athlete_view.domain.time_constraint.pojo.dto.TimeConstraintDto
import ase.athlete_view.domain.time_constraint.pojo.dto.WeeklyTimeConstraintDto
import ase.athlete_view.domain.user.pojo.dto.AthleteDTO
import ase.athlete_view.domain.user.pojo.dto.TrainerDTO
import ase.athlete_view.domain.zone.pojo.dto.ZoneDto
import ase.athlete_view.domain.zone.pojo.entity.Zone
import org.owasp.html.PolicyFactory
import org.owasp.html.Sanitizers
import org.springframework.stereotype.Service
@Service
class Sanitizer {
val log = KotlinLogging.logger {}
fun sanitizeText(text: String): String {
log.trace { "S | sanitizeText($text)" }
// only allow non-dangerous tags
val policy: PolicyFactory = Sanitizers.FORMATTING
return policy.sanitize(text)
}
fun sanitizeNotification(notification: Notification): Notification {
log.trace { "S | sanitizeNotification($notification)" }
var newBody: String? = null
if (notification.body != null) {
newBody = sanitizeText(notification.body!!)
}
return Notification(
notification.id,
notification.recipient,
notification.read,
notification.timestamp,
sanitizeText(notification.header),
newBody,
notification.link);
/*-
* #%L
* athlete_view
* %%
* Copyright (C) 2023 - 2024 TU Wien INSO ASE GROUP 5 WS2023
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
}
fun sanitizeAthleteRegistrationDTO(athleteDto: AthleteRegistrationDTO): AthleteRegistrationDTO {
log.trace { "S | sanitizeAthleteRegistrationDTO($athleteDto)" }
return athleteDto.copy(
name = sanitizeText(athleteDto.name!!),
country = athleteDto.country?.let { sanitizeText(it) },
zip = athleteDto.zip?.let { sanitizeText(it) }
)
}
fun sanitizeAthleteDto(athleteDTO: AthleteDTO): AthleteDTO {
log.trace { "S | sanitizeAthleteDto($athleteDTO)" }
return AthleteDTO(
id = athleteDTO.id,
email = athleteDTO.email,
name = sanitizeText(athleteDTO.name),
country = athleteDTO.country?.let { sanitizeText(it) },
zip = athleteDTO.zip?.let { sanitizeText(it) },
dob = athleteDTO.dob,
height = athleteDTO.height,
weight = athleteDTO.weight,
trainer = athleteDTO.trainer,
trainerToBe = athleteDTO.trainerToBe,
token = athleteDTO.token,
userType = athleteDTO.userType,
)
}
fun sanitizeTrainerDTO(trainerDTO: TrainerDTO): TrainerDTO {
log.trace { "S | sanitizeTrainerDTO($trainerDTO)" }
return TrainerDTO(
id = trainerDTO.id,
email = trainerDTO.email,
name = sanitizeText(trainerDTO.name),
country = trainerDTO.country?.let { sanitizeText(it) },
zip = trainerDTO.zip?.let { sanitizeText(it) },
code = trainerDTO.code,
token = trainerDTO.token,
userType = trainerDTO.userType,
athletes = trainerDTO.athletes,
unacceptedAthletes = trainerDTO.unacceptedAthletes,
)
}
fun sanitizeTrainerRegistrationDTO(trainerDTO: TrainerRegistrationDTO): TrainerRegistrationDTO {
log.trace { "S | sanitizeTrainerRegistrationDTO($trainerDTO)" }
return trainerDTO.copy(
name = sanitizeText(trainerDTO.name!!),
country = trainerDTO.country?.let { sanitizeText(it) },
zip = trainerDTO.zip?.let { sanitizeText(it) }
)
}
fun sanitizePlannedActivity(plannedActivity: PlannedActivity): PlannedActivity {
log.trace { "S | sanitizePlannedActivity($plannedActivity)" }
var newNote: String? = null;
if (plannedActivity.note != null) {
newNote = sanitizeText(plannedActivity.note!!)
}
return PlannedActivity(
id = plannedActivity.id,
name = sanitizeText(plannedActivity.name),
type = plannedActivity.type,
interval = plannedActivity.interval,
withTrainer = plannedActivity.withTrainer,
template = plannedActivity.template,
note = newNote,
date = plannedActivity.date,
estimatedDuration = plannedActivity.estimatedDuration,
load = plannedActivity.load,
createdBy = plannedActivity.createdBy,
createdFor = plannedActivity.createdFor,
activity = plannedActivity.activity
)
}
fun sanitizeStep(step: Step): Step {
log.trace { "S | sanitizeStep($step)" }
if (step.note == null) return step;
val newStep = step.copy()
newStep.note = sanitizeText(step.note!!)
return newStep;
}
fun sanitizeTimeConstraintDto(timeConstraintDto: TimeConstraintDto): TimeConstraintDto {
log.trace { "S | sanitizeTimeConstraintDto($timeConstraintDto)" }
if (timeConstraintDto is DailyTimeConstraintDto) {
return DailyTimeConstraintDto(
id = timeConstraintDto.id,
isBlacklist = timeConstraintDto.isBlacklist,
title = sanitizeText(timeConstraintDto.title),
startTime = timeConstraintDto.startTime,
endTime = timeConstraintDto.endTime
)
} else if (timeConstraintDto is WeeklyTimeConstraintDto) {
return WeeklyTimeConstraintDto(
id = timeConstraintDto.id,
isBlacklist = timeConstraintDto.isBlacklist,
title = sanitizeText(timeConstraintDto.title),
constraint = timeConstraintDto.constraint
)
} else {
return TimeConstraintDto(
id = timeConstraintDto.id,
isBlacklist = timeConstraintDto.isBlacklist,
title = sanitizeText(timeConstraintDto.title),
)
}
}
fun sanitizeZoneDTO(zoneDto: ZoneDto): ZoneDto {
log.trace { "S | sanitizeZoneDTO($zoneDto)" }
return ZoneDto(
id = zoneDto.id,
name = sanitizeText(zoneDto.name),
fromBPM = zoneDto.fromBPM,
toBPM = zoneDto.toBPM,
)
}
}
| 0 | Kotlin | 0 | 3 | bb6edd91d50f4944948d194f2b300ec9d2ec818a | 7,932 | AthleteView | MIT License |
base/src/commonTest/kotlin/utils/ContainsAnyTests.kt | splendo | 191,371,940 | false | {"Kotlin": 6494822, "Swift": 172024, "Shell": 1514} | /*
Copyright 2021 Splendo Consulting B.V. The Netherlands
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 utils
import com.splendo.kaluga.base.utils.containsAny
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ContainsAnyTests {
@Test
fun containsNone() {
val input = setOf(1, 2, 3)
val match = setOf(4, 5, 6)
assertFalse(input.containsAny(match))
}
@Test
fun containsAll() {
val input = listOf(1, 2, 3)
val match = listOf(1, 2, 3)
assertTrue(input.containsAny(match))
}
@Test
fun containsAny() {
val input = listOf(1, 2, 3)
val match = listOf(3, 2)
assertTrue(input.containsAny(match))
}
@Test
fun emptyCollectionContainsNothing() {
val input = emptyList<Int>()
val match = listOf(1, 2, 3)
assertFalse(input.containsAny(match))
}
@Test
fun anyCollectionDoesNotContainsEmpty() {
val input = listOf(1, 2, 3)
val match = emptyList<Int>()
assertFalse(input.containsAny(match))
}
}
| 87 | Kotlin | 7 | 315 | 4094d5625a4cacb851b313d4e96bce6faac1c81f | 1,638 | kaluga | Apache License 2.0 |
android/features/login/login_domain/src/main/java/com/iprayforgod/login_domain/entities/inputs/ForgotPwdInput.kt | devrath | 507,511,543 | false | {"Kotlin": 219977, "Java": 712} | package com.iprayforgod.login_domain.entities.inputs
data class ForgotPwdInput(val email: String)
| 0 | Kotlin | 4 | 18 | 060080c93dc97279603be3efe5a228eadc71f41a | 99 | droid-pure-kotlin-application | Apache License 2.0 |
src/main/kotlin/com/mineinabyss/idofront/serialization/SerializableItemStack.kt | ReyADayer | 379,520,997 | true | {"Kotlin": 89351} | package com.mineinabyss.idofront.serialization
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Damageable
/**
* A wrapper for [ItemStack] that uses [kotlinx.serialization](https://github.com/Kotlin/kotlinx.serialization).
* Allows for easy-to-use serialization to JSON (or YAML with kaml).
*
* Currently missing many things spigot's item serialization contains, but way cleaner to use!
*/
//TODO this should be a custom serializer, not wrapper
@Serializable
data class SerializableItemStack(
@SerialName("type") var type: Material,
@SerialName("amount") var amount: Int = 1,
@SerialName("custom-model-data") var customModelData: Int? = null,
@SerialName("display-name") var displayName: String? = null,
@SerialName("localized-name") var localizedName: String? = null,
@SerialName("unbreakable") var unbreakable: Boolean? = null,
@SerialName("lore") var lore: String? = null,
@SerialName("damage") var damage: Int? = null
) {
fun toItemStack(applyTo: ItemStack = ItemStack(type)) = applyTo.apply {
val meta = itemMeta ?: return@apply
type = [email protected]
customModelData?.let { meta.setCustomModelData(it) }
displayName?.let { meta.setDisplayName(it) }
localizedName?.let { meta.setLocalizedName(it) }
unbreakable?.let { meta.isUnbreakable = it }
lore?.let { meta.lore = it.split("\n") }
if (this is Damageable) [email protected]?.let { damage = it }
itemMeta = meta
}
}
/**
* Converts an [ItemStack] to [SerializableItemStack]
*
* @see SerializableItemStack
*/
fun ItemStack.toSerializable(): SerializableItemStack {
return with(itemMeta) {
SerializableItemStack(
type,
amount,
if (this?.hasCustomModelData() == true) this.customModelData else null,
this?.displayName,
this?.localizedName,
this?.isUnbreakable,
this?.lore?.joinToString(separator = "\n"),
(this as? Damageable)?.damage
)
}
}
| 0 | null | 0 | 0 | 8f982691e26cb9419e3a6b03f53948f9ee560c53 | 2,203 | Idofront | MIT License |
app/src/main/java/xyz/teamgravity/composerecipeapp/presentation/theme/Theme.kt | raheemadamboev | 357,501,676 | false | null | package xyz.teamgravity.composerecipeapp.presentation.theme
import android.annotation.SuppressLint
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
@SuppressLint("ConflictingOnColor")
private val LightThemeColors = lightColors(
primary = Blue600,
primaryVariant = Blue400,
onPrimary = Black2,
secondary = Color.White,
secondaryVariant = Teal300,
onSecondary = Color.Black,
error = RedErrorDark,
onError = RedErrorLight,
background = Grey1,
onBackground = Color.Black,
surface = Color.White,
onSurface = Black2,
)
private val DarkThemeColors = darkColors(
primary = Blue700,
primaryVariant = Color.White,
onPrimary = Color.White,
secondary = Black1,
onSecondary = Color.White,
error = RedErrorLight,
background = Color.Black,
onBackground = Color.White,
surface = Black1,
onSurface = Color.White,
)
@Composable
fun AppTheme(
darkTheme: Boolean,
content: @Composable () -> Unit
) {
MaterialTheme(
colors = if (darkTheme) DarkThemeColors else LightThemeColors,
typography = QuickSandTypography,
shapes = AppShapes
) {
content()
}
} | 0 | Kotlin | 0 | 0 | 25f680d1a93a58540c69e07f2ad4c01a89a45f42 | 1,344 | jetpack-compose-recipe-app | Apache License 2.0 |
app/src/main/java/edu/uoc/avalldeperas/eatsafe/favorites/data/FavoritesRepositoryImpl.kt | avalldeperas | 767,722,753 | false | {"Kotlin": 279197} | package edu.uoc.avalldeperas.eatsafe.favorites.data
import android.util.Log
import com.google.firebase.Firebase
import com.google.firebase.firestore.firestore
import com.google.firebase.firestore.snapshots
import com.google.firebase.firestore.toObjects
import edu.uoc.avalldeperas.eatsafe.favorites.domain.model.FavoritePlace
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class FavoritesRepositoryImpl @Inject constructor() : FavoritesRepository {
private val favoritesRef = Firebase.firestore.collection("favorites")
override fun getFavoritesByUser(userId: String): Flow<List<FavoritePlace>> {
Log.d("avb", "getFavoritesByUser: userid = $userId")
return try {
favoritesRef.whereEqualTo(USER_ID, userId)
.snapshots()
.map { it.toObjects<FavoritePlace>() }
} catch (e: Exception) {
Log.d("avb", "getFavoritesByUser: exception = ${e.message}")
emptyFlow()
}
}
override fun getFavoritesByPlaceAndUser(
placeId: String,
userId: String,
): Flow<List<FavoritePlace>> {
Log.d("avb", "getFavoritesByPlaceAndUser: placeId = $placeId, userid = $userId")
return try {
favoritesRef.whereEqualTo(PLACE_ID, placeId).whereEqualTo(USER_ID, userId).snapshots()
.map { it.toObjects<FavoritePlace>() }
} catch (e: Exception) {
Log.d("avb", "getFavoritesByPlaceAndUser: exception = ${e.message}")
emptyFlow()
}
}
override suspend fun save(favorite: FavoritePlace): Boolean {
return try {
val document = favoritesRef.document()
favorite.favoriteId = document.id
document.set(favorite).await()
true
} catch (e: Exception) {
Log.e("avb", "save favorite exception: ${e.message}")
false
}
}
override suspend fun delete(favorite: FavoritePlace): Boolean {
Log.d("avb", "deleting favorite: $favorite")
return try {
favoritesRef.document(favorite.favoriteId).delete().await()
true
} catch (e: Exception) {
Log.e("avb", "delete favorite exception: ${e.message}")
false
}
}
companion object {
const val USER_ID = "userId"
const val PLACE_ID = "placeId"
}
}
| 2 | Kotlin | 0 | 1 | bea2e59bdb80779ae7cac19f4e3ed85ad7b285d3 | 2,506 | EatSafe | Creative Commons Attribution 4.0 International |
compiler-plugin/src/main/java/io/mths/kava/compiler/frontend/k2/resolve/FirTypeRef.kt | MerlinTHS | 598,539,841 | false | null | package io.mths.kava.compiler.frontend.k2.resolve
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.types.FirTypeRef
/**
* Replaces receivers typeRef with [typeRef] and
* returns the receiver.
*/
context (FirSession)
infix fun <Type : FirExpression> Type.resolvedAs(
typeRef: FirTypeRef
): Type = apply {
replaceTypeRef(typeRef)
} | 0 | Kotlin | 0 | 0 | 5d038afd21c7099a47eb889422dbdb4b34926d0f | 426 | KavaCompilerPlugin | Apache License 2.0 |
app/src/main/kotlin/org/eclipse/kuksa/testapp/extension/UriExtension.kt | eclipse-kuksa | 687,949,615 | false | {"Kotlin": 408240, "Java": 6763, "Shell": 2409} | /*
* Copyright (c) 2023 Contributors to the Eclipse Foundation
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*
*/
package org.eclipse.kuksa.testapp.extension
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import java.io.FileNotFoundException
fun Uri.fetchFileName(context: Context): String? {
var fileName: String? = null
val cursor = context.contentResolver.query(this, null, null, null, null)
cursor?.use {
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (cursor.moveToFirst()) {
fileName = cursor.getString(nameIndex)
}
}
return fileName
}
@Throws(FileNotFoundException::class)
fun Uri.readAsText(context: Context): String {
val contentResolver = context.contentResolver
return contentResolver.openInputStream(this)?.use {
it.reader().readText()
} ?: error("Could not read file from uri")
}
| 19 | Kotlin | 1 | 2 | a03cf49b66d9f2116474cabdd5741f21a0511926 | 1,502 | kuksa-android-sdk | Apache License 2.0 |
src/main/kotlin/com/dotori/v2/domain/mainpage/presentation/dto/res/BoardAlarmResDto.kt | Team-Ampersand | 569,110,809 | false | {"Kotlin": 421826, "Shell": 827} | package com.dotori.v2.domain.mainpage.presentation.dto.res
import com.dotori.v2.domain.board.presentation.data.dto.BoardDto
data class BoardAlarmResDto(
val content: List<BoardDto>
) | 2 | Kotlin | 3 | 15 | 6647b1f03ae7424af188d0003ad7025f992dca11 | 188 | Dotori-server-V2 | Apache License 2.0 |
app/src/main/java/com/example/festunavigator/data/repository/RecordsImpl.kt | theCWBGroup | 780,532,969 | false | {"Kotlin": 175318} | package com.example.festunavigator.data.repository
import com.example.festunavigator.data.data_source.Database
import com.example.festunavigator.data.model.Record
import com.example.festunavigator.domain.repository.RecordsRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class RecordsImpl @Inject constructor(
private val database: Database
): RecordsRepository {
private val dao = database.recordsDao
override suspend fun insertRecord(record: Record) {
dao.insertRecord(record)
}
override fun getRecords(time: Long, limit: Int): Flow<List<Record>> {
return dao.getRecords(time, limit)
}
override fun getRecords(): Flow<List<Record>> {
return dao.getRecords()
}
} | 0 | Kotlin | 1 | 0 | 079bf0571e5d2aa8a1bbc0ebfaae99c070a4231d | 750 | VisioMateNavigator | MIT License |
src/main/kotlin/org/rust/lang/core/macros/MacroExpansionTask.kt | orium | 128,264,562 | true | {"Kotlin": 9733503, "Rust": 154200, "Python": 103484, "HTML": 21126, "Lex": 12335, "Java": 688, "Shell": 377, "RenderScript": 120} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoUtil
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import org.rust.RsTask
import org.rust.lang.core.crate.CratePersistentId
import org.rust.lang.core.macros.MacroExpansionFileSystem.FSItem
import org.rust.lang.core.macros.MacroExpansionFileSystem.TrustedRequestor
import org.rust.lang.core.psi.RsPsiManager
import org.rust.lang.core.resolve2.*
import org.rust.openapiext.*
import org.rust.stdext.HashCode
import org.rust.stdext.mapToSet
import java.io.IOException
/**
* Overview of macro expansion process:
* Macros are expanded during [CrateDefMap] building and saved to [MacroExpansionSharedCache].
* Among with that we statically generate names of expansion files (`<mixHash>_<order>.rs`).
* [MacroExpansionTask] creates and deletes needed expansion files based on [CrateDefMap.expansionNameToMacroCall].
* Expansions are taken from [MacroExpansionSharedCache].
*
* Linking with PSI is done using [MacroIndex].
*
*
* Here is typical path of expansion file:
* "/rust_expanded_macros/<random_project_id>/<crate_id>/a/b/<mix_hash>_<order>.rs"
* List of methods that rely on such path format:
* - [DefCollector.recordExpansionFileName]
* - [expansionNameToPath]
* - [VirtualFile.extractMixHashAndMacroStorageVersion]
* - [MacroExpansionServiceImplInner.getDefMapForExpansionFile]
* - [MacroExpansionTask.collectExistingFiles]
*/
class MacroExpansionTask(
project: Project,
private val modificationTracker: SimpleModificationTracker,
private val lastUpdatedMacrosAt: MutableMap<CratePersistentId, Long>,
private val projectDirectoryName: String,
override val taskType: RsTask.TaskType,
) : Task.Backgroundable(project, "Expanding Rust macros", /* canBeCancelled = */ false),
RsTask {
private val expansionFileSystem: MacroExpansionFileSystem = MacroExpansionFileSystem.getInstance()
private val defMapService = project.defMapService
override fun run(indicator: ProgressIndicator) {
indicator.checkCanceled()
indicator.isIndeterminate = false
val subTaskIndicator = indicator.toThreadSafeProgressIndicator()
val start1 = System.currentTimeMillis()
val allDefMaps = try {
indicator.text = "Preparing resolve data"
defMapService.updateDefMapForAllCratesWithWriteActionPriority(subTaskIndicator)
} catch (e: ProcessCanceledException) {
throw e
}
val start2 = System.currentTimeMillis()
val elapsed1 = start2 - start1
MACRO_LOG.debug("Finished building DefMaps for all crates in $elapsed1 ms")
indicator.text = "Save macro expansions"
updateMacrosFiles(allDefMaps)
val elapsed2 = System.currentTimeMillis() - start2
MACRO_LOG.debug("Finished macro expansion task in $elapsed2 ms")
}
private class FileCreation(
val crate: CratePersistentId,
val expansionName: String,
val content: String,
val ranges: RangeMap,
)
private class FileDeletion(
val crate: CratePersistentId,
val expansionName: String,
val file: FSItem.FSFile,
)
private data class FileAttributes(
val path: MacroExpansionVfsBatch.Path,
val rangeMap: RangeMap,
)
private fun updateMacrosFiles(allDefMaps: List<CrateDefMap>) {
val contentRoot = "/$MACRO_EXPANSION_VFS_ROOT/$projectDirectoryName"
val batch = MacroExpansionVfsBatch(contentRoot)
val hasStaleExpansions = deleteStaleExpansions(allDefMaps, batch)
val defMaps = allDefMaps.filter {
lastUpdatedMacrosAt[it.crate] != it.timestamp
}
if (!hasStaleExpansions && defMaps.isEmpty()) return
val files = collectFilesForCreationAndDeletion(defMaps)
val singleChangeApplied = !batch.hasChanges
&& files.first.size == 1
&& files.second.size == 1
&& applySingleChange(contentRoot, files.first.single(), files.second.single())
if (!singleChangeApplied) {
val filesToWriteAttributes = createOrDeleteNeededFiles(files, batch)
applyBatchAndWriteAttributes(batch, filesToWriteAttributes)
}
for (defMap in defMaps) {
lastUpdatedMacrosAt[defMap.crate] = defMap.timestamp
}
}
private fun collectFilesForCreationAndDeletion(defMaps: List<CrateDefMap>): Pair<List<FileCreation>, List<FileDeletion>> {
val expansionSharedCache = MacroExpansionSharedCache.getInstance()
val pendingFileWrites = mutableListOf<FileCreation>()
val pendingFileDeletions = mutableListOf<FileDeletion>()
for (defMap in defMaps) {
val existingFiles = collectExistingFiles(defMap.crate)
val requiredExpansions = defMap.expansionNameToMacroCall
val filesToDelete = existingFiles.keys - requiredExpansions.keys
val filesToCreate = requiredExpansions.keys - existingFiles.keys
for (expansionName in filesToCreate) {
/**
* Note that we don't use expansion text here, and ideally shouldn't load expansion at all.
* Expansion text is provided in [MacroExpansionFileSystem.contentsToByteArray].
*/
val mixHash = extractMixHashFromExpansionName(expansionName)
val expansion = expansionSharedCache.getExpansionIfCached(mixHash)?.ok() ?: continue
val ranges = expansion.ranges
pendingFileWrites += FileCreation(defMap.crate, expansionName, expansion.text, ranges)
}
for (fileName in filesToDelete) {
val file = existingFiles.getValue(fileName)
pendingFileDeletions += FileDeletion(defMap.crate, fileName, file)
}
}
return pendingFileWrites to pendingFileDeletions
}
/** An optimization for single macro change (i.e. typing in a macro call) */
private fun applySingleChange(
contentRoot: String,
singleWrite: FileCreation,
singleDeletion: FileDeletion
): Boolean {
val oldPath = "$contentRoot/${singleDeletion.crate}/${expansionNameToPath(singleDeletion.expansionName)}"
val newPath = "$contentRoot/${singleWrite.crate}/${expansionNameToPath(singleWrite.expansionName)}"
val lastSlash = newPath.lastIndexOf('/')
if (lastSlash == -1) error("unreachable")
val newParentPath = newPath.substring(0, lastSlash)
val newName = newPath.substring(lastSlash + 1)
return invokeAndWaitIfNeeded {
val root = MacroExpansionFileSystem.getInstance().findFileByPath("/")!!
val oldFile = MacroExpansionFileSystem.getInstance().findFileByPath(oldPath)
?: return@invokeAndWaitIfNeeded false
val oldPsiFile = oldFile.toPsiFile(project) ?: return@invokeAndWaitIfNeeded false
val (nearestNewParentFile, segmentsToCreate) = root.findNearestExistingFile(newParentPath)
runWriteAction {
try {
var newFileParent = nearestNewParentFile
for (segment in segmentsToCreate) {
newFileParent = newFileParent.createChildDirectory(TrustedRequestor, segment)
}
RsPsiManager.withIgnoredPsiEvents(oldPsiFile) {
if (newFileParent != oldFile.parent) {
oldFile.move(TrustedRequestor, newFileParent)
} else {
MoveToTheSameDir.hit()
}
oldFile.rename(TrustedRequestor, newName)
}
val doc = FileDocumentManager.getInstance().getCachedDocument(oldFile)
if (doc == null) {
oldFile.getOutputStream(TrustedRequestor).use {
it.write(singleWrite.content.toByteArray())
}
} else {
UndoUtil.disableUndoFor(doc)
CommandProcessor.getInstance().runUndoTransparentAction {
doc.setText(singleWrite.content)
}
UndoUtil.enableUndoFor(doc)
MacroExpansionFileSystem.withAllowedWriting(oldFile) {
FileDocumentManager.getInstance().saveDocument(doc)
}
}
oldFile.writeRangeMap(singleWrite.ranges)
} catch (e: IOException) {
MACRO_LOG.error(e)
return@runWriteAction false
}
if (isUnitTestMode && runSyncInUnitTests) {
// In unit tests macro expansion task works synchronously, so we have to
// commit the document synchronously too
val doc = FileDocumentManager.getInstance().getCachedDocument(oldFile)
if (doc != null) {
PsiDocumentManager.getInstance(project).commitDocument(doc)
}
}
modificationTracker.incModificationCount()
true
}
}
}
private fun createOrDeleteNeededFiles(
files: Pair<List<FileCreation>, List<FileDeletion>>,
batch: MacroExpansionVfsBatch
): List<FileAttributes> {
val filesToWriteAttributes = mutableListOf<FileAttributes>()
for (fileCreation in files.first) {
val path = batch.createFile(fileCreation.crate, fileCreation.expansionName, fileCreation.content, implicit = true)
filesToWriteAttributes += FileAttributes(path, fileCreation.ranges)
}
for (fileDeletion in files.second) {
batch.deleteFile(fileDeletion.file)
}
return filesToWriteAttributes
}
private fun applyBatchAndWriteAttributes(batch: MacroExpansionVfsBatch, files: List<FileAttributes>) {
if (!batch.hasChanges) return
batch.applyToVfs(false) {
for ((path, ranges) in files) {
val virtualFile = path.toVirtualFile() ?: continue
virtualFile.writeRangeMap(ranges)
}
modificationTracker.incModificationCount()
}
}
private fun collectExistingFiles(crate: CratePersistentId): Map<String, FSItem.FSFile> {
val path = "/$MACRO_EXPANSION_VFS_ROOT/$projectDirectoryName/$crate"
val rootDirectory = expansionFileSystem.getDirectory(path) ?: return emptyMap()
return rootDirectory
.copyChildren().asSequence().filterIsInstance<FSItem.FSDir>() // first level directories
.flatMap { it.copyChildren() }.filterIsInstance<FSItem.FSDir>() // second level directories
.flatMap { it.copyChildren() }.filterIsInstance<FSItem.FSFile>() // actual files
.associateBy { it.name }
}
private fun deleteStaleExpansions(allDefMaps: List<CrateDefMap>, batch: MacroExpansionVfsBatch): Boolean {
val crates = allDefMaps.mapToSet { it.crate.toString() }
lastUpdatedMacrosAt.entries.removeIf { (crate, _) ->
crate.toString() !in crates
}
val path = "/$MACRO_EXPANSION_VFS_ROOT/$projectDirectoryName"
val root = expansionFileSystem.getDirectory(path) ?: return false
root.copyChildren()
.filterIsInstance<FSItem.FSDir>()
.filter { it.name !in crates }
.ifEmpty { return false }
.forEach { batch.deleteFile(it) }
return true
}
override val waitForSmartMode: Boolean
get() = true
override val progressBarShowDelay: Int
get() = when (taskType) {
RsTask.TaskType.MACROS_UNPROCESSED -> 0
else -> 2000
}
override val runSyncInUnitTests: Boolean
get() = true
object MoveToTheSameDir: Testmark()
}
// "<mixHash>_<order>.rs" → "<mixHash>"
fun extractMixHashFromExpansionName(name: String): HashCode {
testAssert { name.endsWith(".rs") && name.contains('_') }
val index = name.indexOf('_')
check(index != -1)
val mixHash = name.substring(0, index)
return HashCode.fromHexString(mixHash)
}
| 0 | Kotlin | 0 | 0 | 08043a654dc4e80119f8bdb7c73247f1816de411 | 13,021 | intellij-rust | MIT License |
recycler_view/src/main/java/com/yaman/recycler_view/generic_recycler_views/core/adapters/GenericAdapterPagination.kt | Yamanaswal | 685,417,811 | false | {"Kotlin": 83009} | package com.yaman.recycler_view.generic_recycler_views.core.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.yaman.recycler_view.generic_recycler_views.core.view_holders.BaseItemCallback
import com.yaman.recycler_view.generic_recycler_views.core.view_holders.BaseViewHolder
import kotlin.math.min
/** Generic Adapter For Homogenous Recycler View with Pagination */
abstract class GenericAdapterPagination<T : Any>(
@LayoutRes val layoutId: Int,
private val loadMoreListener: (currentPage: Int) -> Unit // Callback to load more data
) : ListAdapter<T, BaseViewHolder<T>>(BaseItemCallback<T>()) {
private var currentPage: Int = 0
private var items = mutableListOf<T>()
private var isLoading = false
abstract fun onBindViewHold(holder: BaseViewHolder<T>, position: Int)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T> {
val binding = DataBindingUtil.inflate<ViewDataBinding>(
LayoutInflater.from(parent.context),
layoutId,
parent,
false
)
return BaseViewHolder(binding)
}
override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
onBindViewHold(holder, position)
}
override fun getItemViewType(position: Int) = layoutId
override fun getItemCount(): Int {
return items.size
}
/* Required for pagination to work */
fun setRecyclerViewScrollListener(recyclerView: RecyclerView) {
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager
if (layoutManager != null && !isLoading) {
val visibleItemCount = layoutManager.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItemPosition =
(layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition()
?: 0
if (visibleItemCount + firstVisibleItemPosition >= totalItemCount && firstVisibleItemPosition >= 0 && !isLoading) {
isLoading = true
loadMoreListener.invoke(currentPage)
}
}
}
})
}
// Load initial data (first page)
fun updateInitialData(list: MutableList<T>, pageSize: Int) {
val initialData = list.subList(0, min(pageSize, list.size))
currentPage = 0
items.clear()
items.addAll(initialData)
}
fun addMoreList(list: MutableList<T>, pageSize: Int, currentPage: Int) {
this.currentPage = currentPage + 1
val startIndex = this.currentPage * pageSize
val endIndex = min(startIndex + pageSize, list.size) // Ensure endIndex doesn't exceed data size
// Load more data
if (startIndex < list.size) {
val newData = list.subList(startIndex, endIndex)
val insertPosition = items.size // Position where new items will be inserted
this.items.addAll(newData)
notifyItemRangeInserted(insertPosition, newData.size)
}
// Reset isLoading flag
isLoading = false
}
override fun getItem(position: Int): T {
return items[position]
}
fun addItem(position: Int) {
items.removeAt(position)
}
fun removeItem(position: Int) {
items.removeAt(position)
}
}
| 0 | Kotlin | 0 | 0 | 7498a31a82b28bdd37bc7f5faca551e86bac03ee | 3,932 | MultipleModuleApp | MIT License |
nfcofflinetransfer/src/main/java/com/ul/ims/gmdl/nfcofflinetransfer/model/ApduResponse.kt | NeoTim | 303,771,349 | true | {"Kotlin": 1437450, "Java": 3058} | /*
* Copyright (C) 2019 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
*
* 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.ul.ims.gmdl.nfcofflinetransfer.model
import java.io.ByteArrayOutputStream
class ApduResponse private constructor(
val dataField: ByteArray?,
val sw1sw2: ByteArray
) {
fun encode(): ByteArray {
val outputStream = ByteArrayOutputStream()
dataField?.let {
outputStream.write(it)
}
outputStream.write(sw1sw2)
return outputStream.toByteArray()
}
fun getSw2() = sw1sw2[1]
class Builder {
private var dataField: ByteArray? = null
private var sw1sw2: ByteArray = byteArrayOf(0x00, 0x00)
fun decode(response: ByteArray) = apply {
if (response.size > 2) {
dataField = response.copyOfRange(0, response.size - 2)
}
sw1sw2 = response.copyOfRange(response.size - 2, response.size)
}
fun setResponse(dataField: ByteArray?, sw1sw2: ByteArray) = apply {
this.dataField = dataField
this.sw1sw2 = sw1sw2
}
fun build(): ApduResponse {
return ApduResponse(
dataField,
sw1sw2
)
}
}
} | 0 | null | 0 | 0 | 4c8ac13424959a3c3b7a870ed0436b1c958151df | 1,758 | mdl-ref-apps | Apache License 2.0 |
app/src/main/java/com/mwalagho/ferdinand/runningapp/other/SortType.kt | ferdinandmwal123 | 315,910,069 | false | null | package com.mwalagho.ferdinand.runningapp.other
enum class SortType {
DATE, RUNNING_TIME, AVG_SPEED, DISTANCE, CALORIES_BURNED
} | 0 | Kotlin | 0 | 0 | f4e824673ba86a38e96916bd3bbd94e3511fc44d | 133 | RunningAppKotlin | MIT License |
correlation/core/serialization/json/src/main/kotlin/org/sollecitom/chassis/correlation/core/serialization/json/access/origin/client/info/AgentJsonSerde.kt | sollecitom | 669,483,842 | false | {"Kotlin": 868904, "Java": 30834} | package org.sollecitom.chassis.correlation.core.serialization.json.access.origin.client.info
import org.json.JSONObject
import org.sollecitom.chassis.core.domain.naming.Name
import org.sollecitom.chassis.json.utils.getStringOrNull
import org.sollecitom.chassis.json.utils.jsonSchemaAt
import org.sollecitom.chassis.json.utils.serde.JsonSerde
import org.sollecitom.chassis.json.utils.serde.getValueOrNull
import org.sollecitom.chassis.json.utils.serde.setValue
import org.sollecitom.chassis.web.client.info.domain.Agent
import org.sollecitom.chassis.web.client.info.domain.Version
private object AgentJsonSerde : JsonSerde.SchemaAware<Agent> {
private const val SCHEMA_LOCATION = "correlation/access/origin/client/info/Agent.json"
override val schema by lazy { jsonSchemaAt(SCHEMA_LOCATION) }
override fun serialize(value: Agent) = JSONObject().apply {
value.className?.value?.let { put(Fields.CLASS_NAME, it) }
value.name?.value?.let { put(Fields.NAME, it) }
value.version?.let { setValue(Fields.VERSION, it, Version.jsonSerde) }
}
override fun deserialize(json: JSONObject): Agent {
val className = json.getStringOrNull(Fields.CLASS_NAME)?.let(::Name)
val name = json.getStringOrNull(Fields.NAME)?.let(::Name)
val version = json.getValueOrNull(Fields.VERSION, Version.jsonSerde)
return Agent(className, name, version)
}
private object Fields {
const val CLASS_NAME = "class-name"
const val NAME = "name"
const val VERSION = "version"
}
}
val Agent.Companion.jsonSerde: JsonSerde.SchemaAware<Agent> get() = AgentJsonSerde | 0 | Kotlin | 0 | 2 | d11bf12bc66105bbf7edd35d01fbbadc200c3ee8 | 1,641 | chassis | MIT License |
app/src/main/java/com/precopia/david/lists/view/authentication/AuthLogic.kt | DavidPrecopia | 150,194,957 | false | null | package com.precopia.david.lists.view.authentication
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.precopia.david.lists.common.subscribeCompletable
import com.precopia.david.lists.util.ISchedulerProviderContract
import com.precopia.david.lists.util.UtilExceptions
import com.precopia.david.lists.view.authentication.IAuthContract.LogicEvents
import com.precopia.david.lists.view.authentication.IAuthContract.ViewEvents
import com.precopia.domain.repository.IRepositoryContract
import io.reactivex.rxjava3.disposables.CompositeDisposable
class AuthLogic(private val viewModel: IAuthContract.ViewModel,
private val userRepo: IRepositoryContract.UserRepository,
private val disposable: CompositeDisposable,
private val schedulerProvider: ISchedulerProviderContract) :
ViewModel(),
IAuthContract.Logic {
private val viewEventLiveData = MutableLiveData<ViewEvents>()
override fun onEvent(event: LogicEvents) {
when (event) {
is LogicEvents.OnStart -> onStart(event.signOut)
LogicEvents.SignInSuccessful -> signInSuccessful()
LogicEvents.SignInCancelled -> signInCancelled()
is LogicEvents.SignInFailed -> signInFailed(event.errorCode)
LogicEvents.VerifyEmailButtonClicked -> verifyEmailButtonClicked()
}
}
override fun observe(): LiveData<ViewEvents> = viewEventLiveData
private fun onStart(signOut: Boolean) {
when {
signOut -> signOut()
userRepo.userVerified -> viewEventLiveData.value =
ViewEvents.OpenMainView
userRepo.signedOut -> viewEventLiveData.value =
ViewEvents.SignIn(viewModel.signInRequestCode)
userRepo.hasEmail && userRepo.emailVerified.not() -> verifyEmail()
else -> UtilExceptions.throwException(IllegalStateException())
}
}
private fun signInSuccessful() {
when (userRepo.hasEmail && userRepo.emailVerified.not()) {
true -> verifyEmail()
false -> with(viewEventLiveData) {
value = ViewEvents.DisplayMessage(viewModel.msgSignInSucceed)
value = ViewEvents.OpenMainView
}
}
}
private fun signInCancelled() {
finish(viewModel.msgSignInCanceled)
}
private fun signInFailed(errorCode: Int) {
finish(viewModel.getMsgSignInError(errorCode))
}
private fun signOut() {
// Need to re-set state in case the user
// signs-in with an unverified email.
viewModel.emailVerificationSent = false
disposable.add(subscribeCompletable(
userRepo.signOut(),
{ signOutSucceeded() },
{ signOutFailed(it) },
schedulerProvider
))
}
private fun signOutSucceeded() {
with(viewEventLiveData) {
value = ViewEvents.DisplayMessage(viewModel.msgSignOutSucceed)
value = ViewEvents.SignIn(viewModel.signInRequestCode)
}
}
private fun signOutFailed(e: Throwable) {
UtilExceptions.throwException(e)
with(viewEventLiveData) {
value = ViewEvents.DisplayMessage(viewModel.msgSignOutFailed)
value = ViewEvents.OpenMainView
}
}
private fun verifyEmailButtonClicked() {
viewEventLiveData.value = ViewEvents.HideEmailSentMessage
verifyEmail()
}
private fun verifyEmail() {
when (viewModel.emailVerificationSent) {
true -> disposable.add(subscribeCompletable(
userRepo.reloadUser(),
{ successfullyReloadedUser() },
{ failedToReloadUser(it) },
schedulerProvider
))
false -> disposable.add(subscribeCompletable(
userRepo.sendVerificationEmail(),
{ successfullySentEmail() },
{ failedToSendEmail(it) },
schedulerProvider
))
}
}
private fun successfullyReloadedUser() {
when (userRepo.emailVerified) {
true -> with(viewEventLiveData) {
value = ViewEvents.HideEmailSentMessage
value = ViewEvents.DisplayMessage(viewModel.msgSignInSucceed)
value = ViewEvents.OpenMainView
}
false -> viewEventLiveData.value =
ViewEvents.DisplayEmailSentMessage(userRepo.email!!)
}
}
private fun failedToReloadUser(e: Throwable) {
UtilExceptions.throwException(e)
viewEventLiveData.value = ViewEvents.SignIn(viewModel.signInRequestCode)
}
private fun successfullySentEmail() {
viewModel.emailVerificationSent = true
viewEventLiveData.value = ViewEvents.DisplayEmailSentMessage(userRepo.email!!)
}
private fun failedToSendEmail(e: Throwable) {
UtilExceptions.throwException(e)
finish(viewModel.msgSignInError)
}
private fun finish(displayMessage: String) {
disposable.clear()
with(viewEventLiveData) {
value = ViewEvents.DisplayMessage(displayMessage)
value = ViewEvents.FinishView
}
}
override fun onCleared() {
disposable.clear()
super.onCleared()
}
}
| 0 | Kotlin | 2 | 4 | 1b6cb87b308d74920e38652172d3dfcd96fdb652 | 5,459 | Lists | Apache License 2.0 |
app/src/main/java/digital/wup/superhero/data/model/Image.kt | wupdigital | 121,959,686 | false | {"Gradle": 3, "Java Properties": 3, "XML": 74, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 2, "Kotlin": 45} | package digital.wup.superhero.data.model
import com.google.gson.annotations.SerializedName
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
data class Image(
@SerializedName("path")
var path: String,
@SerializedName("extension")
var extension: String
)
| 1 | null | 1 | 1 | 92401a92bd1b3465494fad4972fad4bad98a5c37 | 311 | kotlin-superhero-app | Apache License 2.0 |
raft/src/main/kotlin/com/github/mattisonchao/exception/InfiniteCountDownException.kt | mattisonchao | 314,711,331 | false | null | package com.github.mattisonchao.exception
class InfiniteCountDownException(override val message: String?) : RuntimeException(message)
| 0 | Kotlin | 0 | 1 | 66c0c6eef9cedd3f439cc8930ad5d0ee2dbedf4f | 135 | raftsman | Apache License 2.0 |
app/src/main/java/com/example/cetl/model/team/TeamList.kt | Bhavyansh03-tech | 840,319,498 | false | {"Kotlin": 596261} | package com.example.cetl.model.team
data class TeamList(
var teamId: String? = "",
var inviteCode: String? = "",
var teamBanner: String? = "",
var teamLogo: String? = "",
var teamName: String? = "",
var description: String? = "",
var creatorUid: String? = "",
var teamGame: String? = "",
var country: String? = "",
var city: String? = "",
var date: String? = "",
var teamFinishes: Long? = null,
var memberCount: Long? = null
) {
constructor(): this("","", "", "", "", "", "","", "", "", "", null, null)
} | 0 | Kotlin | 0 | 0 | ea288888f95b0465b4af79d26ce2b5baa1258c61 | 561 | CETL | MIT License |
app-quality-insights/ui/testSrc/com/android/tools/idea/insights/ui/actions/AppInsightsDisplayRefreshTimestampActionTest.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2022 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.tools.idea.insights.ui.actions
import com.android.tools.idea.concurrency.SupervisorJob
import com.android.tools.idea.insights.InsightsFakeClock
import com.android.tools.idea.insights.ui.Timestamp
import com.android.tools.idea.insights.ui.TimestampState
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.MoreExecutors
import com.intellij.testFramework.DisposableRule
import java.time.Duration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.yield
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AppInsightsDisplayRefreshTimestampActionTest {
@get:Rule val disposableRule = DisposableRule()
private lateinit var scope: CoroutineScope
private lateinit var timestamp: MutableSharedFlow<Timestamp>
private lateinit var action: AppInsightsDisplayRefreshTimestampAction
private lateinit var clock: InsightsFakeClock
@Before
fun setUp() {
clock = InsightsFakeClock()
scope =
CoroutineScope(
MoreExecutors.directExecutor().asCoroutineDispatcher() +
SupervisorJob(disposableRule.disposable)
)
timestamp = MutableSharedFlow()
action = AppInsightsDisplayRefreshTimestampAction(timestamp, clock, scope)
}
private suspend fun waitUntil(condition: () -> Boolean) {
withTimeout(1000) {
while (!condition()) {
yield()
}
}
}
@Test
fun `display refreshing in progress`() {
runBlocking {
assertThat(action.displayText).isEqualTo("Last refreshed: never")
timestamp.emit(Timestamp(null, TimestampState.UNAVAILABLE))
waitUntil { action.displayText == "Refreshing..." }
}
}
@Test
fun `display last refreshed`() {
runBlocking {
assertThat(action.displayText).isEqualTo("Last refreshed: never")
timestamp.emit(Timestamp(clock.instant(), TimestampState.ONLINE))
waitUntil { action.displayText == "Last refreshed: right now" }
// Check "text being updated" when time advances.
clock.advanceTimeBy(Duration.ofSeconds(1).toMillis())
assertThat(action.displayText).isEqualTo("Last refreshed: moments ago")
// Check "text being updated" when time advances.
clock.advanceTimeBy(Duration.ofMinutes(2).toMillis())
assertThat(action.displayText).isEqualTo("Last refreshed: 2 minutes ago")
}
}
@Test
fun `display offline`() {
runBlocking {
assertThat(action.displayText).isEqualTo("Last refreshed: never")
timestamp.emit(Timestamp(clock.instant(), TimestampState.ONLINE))
waitUntil { action.displayText == "Last refreshed: right now" }
clock.advanceTimeBy(Duration.ofMinutes(2).toMillis())
assertThat(action.displayText).isEqualTo("Last refreshed: 2 minutes ago")
timestamp.emit(Timestamp(null, TimestampState.UNAVAILABLE))
waitUntil { action.displayText == "Refreshing..." }
timestamp.emit(Timestamp(null, TimestampState.OFFLINE))
waitUntil { action.displayText == "Currently offline. Last refreshed: 2 minutes ago" }
}
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 3,862 | android | Apache License 2.0 |
src/main/kotlin/com/rose/gateway/bot/extensions/whitelist/WhitelistArguments.kt | nicholasgrose | 377,028,896 | false | null | package com.rose.gateway.bot.extensions.whitelist
import com.kotlindiscord.kord.extensions.commands.Arguments
import com.kotlindiscord.kord.extensions.commands.converters.impl.string
import dev.kord.common.annotation.KordPreview
@OptIn(KordPreview::class)
class WhitelistArguments : Arguments() {
val username by string("username", "The user to modify the whitelist status of.")
}
| 0 | Kotlin | 0 | 1 | 641b737d623f89394f8ced6fc5a450fc7d2a6d2e | 387 | Gateway | MIT License |
src/day22/Day22.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day22
import java.io.File
import kotlin.reflect.KFunction3
fun main() {
val input = File("src/day22/input.txt").readText().split("\n\n")
val tiles = mutableSetOf<Pair<Int, Int>>()
val walls = mutableSetOf<Pair<Int, Int>>()
input[0].split("\n").forEachIndexed { row, s ->
s.toList().forEachIndexed { column, c ->
when (c) {
'.' -> tiles.add(Pair(column + 1, row + 1))
'#' -> walls.add(Pair(column + 1, row + 1))
}
}
}
val directions = input[1].toList().fold(emptyList<Any>()) { acc, c ->
when (c) {
'L' -> acc + 'L'
'R' -> acc + 'R'
else -> if (acc.isNotEmpty() && acc.last() is Int) (acc.dropLast(1) + ((acc.last() as Int * 10) + c.toString()
.toInt())) else (acc + c.toString().toInt())
}
}
println(solve(tiles, walls, directions, ::flatWrap))
println(solve(tiles, walls, directions, ::cubeWrap))
}
private fun solve(
tiles: Set<Pair<Int, Int>>,
walls: Set<Pair<Int, Int>>,
directions: List<Any>,
wrap: KFunction3<Set<Pair<Int, Int>>, Set<Pair<Int, Int>>, State, State>
): Int {
var state = State(tiles.filter { it.second == 1 }.minByOrNull { it.first }!!, 0)
val deltas = listOf(Pair(1, 0), Pair(0, 1), Pair(-1, 0), Pair(0, -1))
directions.forEach { direction ->
when (direction) {
'L' -> state = State(state.coord, (state.facing - 1).mod(deltas.size))
'R' -> state = State(state.coord, (state.facing + 1).mod(deltas.size))
else -> for (i in 1..direction as Int) {
var nextState = State(
Pair(
state.coord.first + deltas[state.facing].first,
state.coord.second + deltas[state.facing].second
), state.facing
)
if (nextState.coord !in (walls + tiles)) {
nextState = wrap(tiles, walls, nextState)
}
if (nextState.coord in walls) break
state = nextState
}
}
}
return state.password()
}
data class State(val coord: Pair<Int, Int>, val facing: Int) {
fun password() = 4 * coord.first + 1000 * coord.second + facing
}
private fun flatWrap(tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, state: State): State {
return State(when (state.facing) {
0 -> (tiles + walls).filter { it.second == state.coord.second }.minByOrNull { it.first }!!
1 -> (tiles + walls).filter { it.first == state.coord.first }.minByOrNull { it.second }!!
2 -> (tiles + walls).filter { it.second == state.coord.second }.maxByOrNull { it.first }!!
3 -> (tiles + walls).filter { it.first == state.coord.first }.maxByOrNull { it.second }!!
else -> throw IllegalStateException()
}, state.facing
)
}
private fun cubeWrap(tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, state: State): State {
return when (state.facing) {
0 -> {
when (state.coord.second) {
in 1..50 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.maxByOrNull { it.first }!!, 2)
}
in 51..100 -> {
State((tiles + walls).filter { it.first == 50 + state.coord.second }.maxByOrNull { it.second }!!, 3)
}
in 101..150 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.maxByOrNull { it.first }!!, 2)
}
else -> {
State((tiles + walls).filter { it.first == state.coord.second - 100 }.maxByOrNull { it.second }!!, 3)
}
}
}
1 -> {
when (state.coord.first) {
in 1..50 -> {
State((tiles + walls).filter { it.first == 100 + state.coord.first }.minByOrNull { it.second }!!, 1)
}
in 51..100 -> {
State((tiles + walls).filter { it.second == 100 + state.coord.first }.maxByOrNull { it.first }!!, 2)
}
else -> {
State((tiles + walls).filter { it.second == state.coord.first - 50 }.maxByOrNull { it.first }!!, 2)
}
}
}
2 -> {
when (state.coord.second) {
in 1..50 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.minByOrNull { it.first }!!, 0)
}
in 51..100 -> {
State((tiles + walls).filter { it.first == state.coord.second - 50 }.minByOrNull { it.second }!!, 1)
}
in 101..150 -> {
State((tiles + walls).filter { it.second == 151 - state.coord.second }.minByOrNull { it.first }!!, 0)
}
else -> {
State((tiles + walls).filter { it.first == state.coord.second - 100 }.minByOrNull { it.second }!!, 1)
}
}
}
3 -> {
when (state.coord.first) {
in 1..50 -> {
State((tiles + walls).filter { it.second == 50 + state.coord.first }.minByOrNull { it.first }!!, 0)
}
in 51..100 -> {
State((tiles + walls).filter { it.second == 100 + state.coord.first }.minByOrNull { it.first }!!, 0)
}
else -> {
State((tiles + walls).filter { it.first == state.coord.first - 100 }.maxByOrNull { it.second }!!, 3)
}
}
}
else -> throw IllegalStateException()
}
} | 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 5,790 | advent-of-code-2022 | MIT License |
ClassTimeTable-android/app/src/main/java/com/example/classtimetable/AlarmReceiver.kt | MBP16 | 356,158,037 | false | {"Swift": 164542, "C": 142761, "Kotlin": 17391, "C++": 6576, "Python": 4041, "JavaScript": 3917, "Java": 749} | package com.example.classtimetable
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import java.util.*
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationIntent = Intent(context, MainActivity::class.java)
notificationIntent.flags = (Intent.FLAG_ACTIVITY_CLEAR_TOP
or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pendingI = PendingIntent.getActivity(
context, 0,
notificationIntent, 0
)
val builder = NotificationCompat.Builder(context, "default")
val builder2 = NotificationCompat.Builder(context, "default2")
//OREO API 26 이상에서는 채널 필요
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setSmallIcon(R.drawable.main_icon) //mipmap 사용시 Oreo 이상에서 시스템 UI 에러남
val channelName = "시작/끝 종"
val description = "수업시간 시작/끝, 조회, 종례시 과목/선생님 이름/쉬는시간/점심시간등의 내용을 담은 알림"
val importance = NotificationManager.IMPORTANCE_HIGH //소리와 알림메시지를 같이 보여줌
val channel = NotificationChannel("Class_Bell", channelName, importance)
channel.description = description
notificationManager?.createNotificationChannel(channel)
}
else builder.setSmallIcon(R.drawable.main_icon) // Oreo 이하에서 mipmap 사용하지 않으면 Couldn't create icon: StatusBarIcon 에러남
builder.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setTicker("{Time to watch some cool stuff!}")
.setContentTitle("\uD83D\uDD14조회시간이에요\uD83D\uDD14")
.setContentText("아침조회 시간입니다. 출석체크를 하고 선생님의 말씀을 들어보세요")
.setContentInfo("INFO")
.setContentIntent(pendingI)
builder2.setSmallIcon(R.drawable.main_icon) // Oreo 이하에서 mipmap 사용하지 않으면 Couldn't create icon: StatusBarIcon 에러남
builder2.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setTicker("{Time to watch some cool stuff!}")
.setContentTitle("\uD83D\uDD141교시 수업 시작할 시간이에요\uD83D\uDD14")
.setContentText("아침조회 시간입니다. 출석체크를 하고 선생님의 말씀을 들어보세요")
.setContentInfo("INFO")
.setContentIntent(pendingI)
if (notificationManager != null) {
// 노티피케이션 동작시킴
notificationManager.notify(1234, builder.build())
notificationManager.notify(123, builder2.build())
val nextNotifyTime = Calendar.getInstance()
// 내일 같은 시간으로 알람시간 결정
nextNotifyTime.add(Calendar.DATE, 1)
// Preference에 설정한 값 저장
val editor = context.getSharedPreferences("daily alarm", Context.MODE_PRIVATE).edit()
editor.putLong("nextNotifyTime", nextNotifyTime.timeInMillis)
editor.apply()
}
}
} | 0 | Swift | 0 | 1 | 24207893faeee3852a327f637d11548fd69f86da | 3,454 | old_projects | MIT License |
app/src/main/java/com/kylecorry/trail_sense/shared/permissions/IsPersistentForegroundRequired.kt | kylecorry31 | 215,154,276 | false | null | package com.kylecorry.trail_sense.shared.permissions
import android.content.Context
import com.kylecorry.andromeda.core.specifications.Specification
import com.kylecorry.trail_sense.navigation.paths.infrastructure.BacktrackIsEnabled
import com.kylecorry.trail_sense.navigation.paths.infrastructure.BacktrackRequiresForeground
import com.kylecorry.trail_sense.weather.infrastructure.WeatherMonitorIsEnabled
import com.kylecorry.trail_sense.weather.infrastructure.WeatherMonitorRequiresForeground
class IsBatteryExemptionRequired(
private val areForegroundServicesRestricted: Specification<Context> = AreForegroundServicesRestricted(),
private val areForegroundServicesRequired: Specification<Context> = foregroundRequired
) : Specification<Context>() {
override fun isSatisfiedBy(value: Context): Boolean {
if (!areForegroundServicesRestricted.isSatisfiedBy(value)) {
return false
}
return areForegroundServicesRequired.isSatisfiedBy(value)
}
companion object {
private val backtrack = BacktrackIsEnabled().and(BacktrackRequiresForeground())
private val weather = WeatherMonitorIsEnabled().and(WeatherMonitorRequiresForeground())
private val foregroundRequired = backtrack.or(weather)
}
} | 377 | Kotlin | 42 | 634 | 39571218460c862aae56fd0fc75932e70b58ebba | 1,277 | Trail-Sense | MIT License |
src/main/kotlin/io/github/ludorival/kotlintdd/BasePattern.kt | ludorival | 435,224,771 | false | null | package io.github.ludorival.kotlintdd
open class BasePattern<R1 : WithContext, R2 : WithContext, R3 : WithContext>(
private val assumption: R1,
private val action: R2,
private val assertion: R3
) {
class AssumptionContext<T, R1 : WithContext, R2 : WithContext, R3 : WithContext> internal constructor(
private val pattern: BasePattern<R1, R2, R3>,
key: String,
result: T
) :
Context<T>(result, key) {
internal fun <V> chainAct(key: String, block: R2.(T) -> V) =
chain(ActContext(pattern, key, pattern.actionReceiver(this).block(result)))
infix fun <V> and(block: R1.(T) -> V): AssumptionContext<V, R1, R2, R3> =
chain(AssumptionContext(pattern, "AND", pattern.assumptionReceiver(this).block(result)))
internal fun <V> chainAssert(key: String, block: R3.(T) -> V) =
chain(AssertContext(pattern, key, pattern.assertionReceiver(this).block(result)))
}
class ActContext<T, R1 : WithContext, R2 : WithContext, R3 : WithContext> internal constructor(
private val pattern: BasePattern<R1, R2, R3>,
key: String,
result: T
) :
Context<T>(result, key) {
infix fun <V> and(block: R2.(T) -> V): ActContext<V, R1, R2, R3> =
chain(ActContext(pattern, "AND", pattern.actionReceiver(this).block(result)))
internal fun <V> chainAssert(key: String, block: R3.(T) -> V) =
chain(AssertContext(pattern, key, pattern.assertionReceiver(this).block(result)))
}
class AssertContext<T, R1 : WithContext, R2 : WithContext, R3 : WithContext> internal constructor(
private val pattern: BasePattern<R1, R2, R3>,
key: String,
result: T
) :
Context<T>(result, key) {
infix fun <V> and(block: R3.(T) -> V): AssertContext<V, R1, R2, R3> =
chain(AssertContext(pattern, "AND", pattern.assertionReceiver(this).block(result)))
}
private fun <T> assumptionReceiver(context: Context<T>): R1 = assumption.apply { with(context) }
private fun <T> actionReceiver(context: Context<T>): R2 = action.apply { with(context) }
private fun <T> assertionReceiver(context: Context<T>): R3 = assertion.apply { with(context) }
fun <V> assume(key: String, block: R1.() -> V): AssumptionContext<V, R1, R2, R3> =
AssumptionContext(this, key, assumptionReceiver(Context.EMPTY_CONTEXT).block())
fun <V> act(key: String, block: R2.() -> V): ActContext<V, R1, R2, R3> =
ActContext(this, key, actionReceiver(Context.EMPTY_CONTEXT).block())
}
| 6 | Kotlin | 0 | 6 | fddc39afe845eb2e6648eb1e9015fe511232e13e | 2,599 | kotlin-tdd | MIT License |
src/test/kotlin/io/snyk/plugin/services/download/CliDownloaderTest.kt | snyk | 117,852,067 | false | null | package io.snyk.plugin.services.download
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import io.snyk.plugin.cli.Platform
import io.snyk.plugin.mockCliDownload
import io.snyk.plugin.pluginSettings
import io.snyk.plugin.services.SnykApplicationSettingsStateService
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import junit.framework.TestCase.fail
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
class CliDownloaderTest {
@Before
fun setUp() {
unmockkAll()
mockkStatic("io.snyk.plugin.UtilsKt")
every { pluginSettings() } returns SnykApplicationSettingsStateService()
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun `calculateSha256 should verify the SHA of a given file and return false if no match`() {
val filePath = "src/test/resources/dummy-binary"
val expectedSha = "2b418a5d0573164b4f93188fc94de0332fc0968e7a8439b01f530a4cdde1dcf2"
val bytes = Files.readAllBytes(File(filePath).toPath())
assertEquals(expectedSha, CliDownloader().calculateSha256(bytes))
}
@Test
fun `should refer to snyk static website as base url`() {
assertEquals("https://static.snyk.io", CliDownloader.BASE_URL)
}
@Test
fun `should download version information from base url`() {
assertEquals("${CliDownloader.BASE_URL}/cli/latest/version", CliDownloader.LATEST_RELEASES_URL)
}
@Test
fun `should download cli information from base url`() {
assertEquals(
"${CliDownloader.BASE_URL}/cli/latest/${Platform.current().snykWrapperFileName}",
CliDownloader.LATEST_RELEASE_DOWNLOAD_URL
)
}
@Test
fun `should download sha256 from base url`() {
assertEquals(
"${CliDownloader.BASE_URL}/cli/latest/${Platform.current().snykWrapperFileName}.sha256",
CliDownloader.SHA256_DOWNLOAD_URL
)
}
@Test
fun `should not delete file if checksum verification fails`() {
val testFile = Files.createTempFile("test", "test").toFile()
testFile.deleteOnExit()
val dummyContent = "test test test".toByteArray()
Files.write(testFile.toPath(), dummyContent)
val cut = CliDownloader()
val expectedSha = cut.calculateSha256("wrong sha".toByteArray())
mockCliDownload()
every { pluginSettings() } returns SnykApplicationSettingsStateService()
try {
cut.downloadFile(testFile, expectedSha, mockk(relaxed = true))
fail("Should have thrown ChecksumVerificationException")
} catch (e: ChecksumVerificationException) {
assertTrue("testFile should still exist, as $e was thrown", testFile.exists())
} finally {
testFile.delete()
}
}
}
| 8 | null | 36 | 50 | ff350e02fcf3b26756be9c8b704ddae366ba066c | 2,948 | snyk-intellij-plugin | Apache License 2.0 |
fastscroller-core/src/commonMain/kotlin/oikvpqya/compose/fastscroller/ScrollbarAdapter.kt | oikvpqya | 818,143,301 | false | {"Kotlin": 57425} | /*
* Copyright 2024 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 oikvpqya.compose.fastscroller
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
/**
* Defines how to scroll the scrollable component and how to display a scrollbar for it.
*
* The values of this interface are typically in pixels, but do not have to be.
* It's possible to create an adapter with any scroll range of `Double` values.
*/
expect interface ScrollbarAdapter {
// We use `Double` values here in order to allow scrolling both very large (think LazyList with
// millions of items) and very small (think something whose natural coordinates are less than 1)
// content.
/**
* Scroll offset of the content inside the scrollable component.
*
* For example, a value of `100` could mean the content is scrolled by 100 pixels from the
* start.
*/
val scrollOffset: Double
/**
* The size of the scrollable content, on the scrollable axis.
*/
val contentSize: Double
/**
* The size of the viewport, on the scrollable axis.
*/
val viewportSize: Double
/**
* Instantly jump to [scrollOffset].
*
* @param scrollOffset target offset to jump to, value will be coerced to the valid
* scroll range.
*/
suspend fun scrollTo(scrollOffset: Double)
}
/**
* Create and [remember] [ScrollbarAdapter] for
* scrollable container with the given instance [ScrollState].
*/
@Composable
expect fun rememberScrollbarAdapter(
scrollState: ScrollState
): ScrollbarAdapter
/**
* Create and [remember] [ScrollbarAdapter] for
* lazy scrollable container with the given instance [LazyListState].
*/
@Composable
expect fun rememberScrollbarAdapter(
scrollState: LazyListState,
): ScrollbarAdapter
/**
* Create and [remember] [ScrollbarAdapter] for lazy grid with
* the given instance of [LazyGridState].
*/
@Composable
expect fun rememberScrollbarAdapter(
scrollState: LazyGridState,
): ScrollbarAdapter
/**
* ScrollbarAdapter for Modifier.verticalScroll and Modifier.horizontalScroll
*
* [scrollState] is instance of [ScrollState] which is used by scrollable component
*/
expect fun ScrollbarAdapter(scrollState: ScrollState): ScrollbarAdapter
/**
* ScrollbarAdapter for lazy lists.
*
* [scrollState] is instance of [LazyListState] which is used by scrollable component
*/
expect fun ScrollbarAdapter(scrollState: LazyListState): ScrollbarAdapter
/**
* ScrollbarAdapter for lazy grids.
*
* [scrollState] is instance of [LazyGridState] which is used by scrollable component
*/
expect fun ScrollbarAdapter(scrollState: LazyGridState): ScrollbarAdapter
| 0 | Kotlin | 0 | 0 | 979eca1c9fe066be9e0552413148d1137ea2ea03 | 3,408 | fastscroller-compose-multiplatform | Apache License 2.0 |
app/src/main/java/uoc/cbonache/tfg/ui/main/MainActivity.kt | cbonacheuoc | 109,753,411 | true | {"Kotlin": 144808, "Java": 6706} | package uoc.cbonache.tfg.ui.main
import android.content.Intent
import uoc.cbonache.tfg.R
import uoc.cbonache.tfg.ui.Navigator
import uoc.cbonache.tfg.ui.base.BaseActivity
import javax.inject.Inject
/**
* @author cbonache
*/
class MainActivity : BaseActivity(), MainView {
@Inject lateinit var presenter: MainPresenter
@Inject lateinit var navigator: Navigator
override fun onRequestLayout(): Int = R.layout.activity_main
override fun onViewLoaded() {
presenter.getToken()
}
override fun navigateToShippingList() {
navigator.navigateToShippingList(this, arrayListOf(Intent.FLAG_ACTIVITY_CLEAR_TOP))
finish()
}
override fun navigateToLoginActivity() {
navigator.navigateToLoginActivity(this)
finish()
}
}
| 0 | Kotlin | 0 | 1 | c6c3cdc87eb96aaf179a6442111371aebe0a80dc | 789 | Transpdroid-Android-App | Apache License 2.0 |
app/src/main/java/com/domatix/yevbes/nucleus/generic/callbacs/views/OnViewShortClickListener.kt | sm2x | 234,568,179 | true | {"Kotlin": 782306} | package com.domatix.yevbes.nucleus.generic.callbacs.views
import android.view.View
interface OnViewShortClickListener {
fun onShortClick(view: View)
} | 0 | null | 0 | 0 | 237e9496b5fb608f543e98111269da9b91a06ed3 | 156 | nucleus | MIT License |
main/src/main/kotlin/us/wedemy/eggeum/android/main/ui/CafeImageFragment.kt | Wedemy | 615,061,021 | false | null | /*
* Designed and developed by Wedemy 2023.
*
* Licensed under the MIT.
* Please see full license: https://github.com/Wedemy/eggeum-android/blob/main/LICENSE
*/
package us.wedemy.eggeum.android.main.ui
import android.os.Bundle
import android.view.View
import dagger.hilt.android.AndroidEntryPoint
import us.wedemy.eggeum.android.common.ui.BaseFragment
import us.wedemy.eggeum.android.main.databinding.FragmentCafeImageBinding
import us.wedemy.eggeum.android.main.ui.adapter.CafeImageAdapter
@AndroidEntryPoint
class CafeImageFragment : BaseFragment<FragmentCafeImageBinding>() {
private val cafeImageAdapter by lazy {
CafeImageAdapter { _ -> run {} }
}
override fun getViewBinding() = FragmentCafeImageBinding.inflate(layoutInflater)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.rvCafeImage.apply {
setHasFixedSize(true)
adapter = cafeImageAdapter
}
}
}
| 9 | Kotlin | 0 | 6 | dca83db50e53f614b31fbea03d1340d665325315 | 982 | eggeum-android | MIT License |
viewmodel/MyApplication/app/src/main/java/com/example/edgarng/myapplication/vip/VIPDto.kt | EdgarNg1024 | 167,693,302 | true | {"Kotlin": 18680} | package com.example.edgarng.myapplication.vip
import java.util.*
data class VIPDto(var userName: String, var deadlineDate: Date) | 0 | Kotlin | 5 | 1 | 7b611d3cf833f7056888ec41fe38dc2851f2ac70 | 130 | kaixue-docs | MIT License |
shared/src/commonMain/kotlin/app/prasan/spacexwiki/contract/IRepository.kt | prasannajeet | 501,365,727 | false | {"Kotlin": 93649, "Swift": 4553, "Ruby": 1762} | package app.prasan.spacexwiki.contract
import app.prasan.spacexwiki.models.dao.CompanyInfo
import kotlinx.coroutines.flow.Flow
/**
* Designated repository contract
* @author Prasan
* @since 1.0
*/
interface IRepository {
suspend fun getSpaceXCompanyInfo(forceRefresh: Boolean): Flow<Result<CompanyInfo>>
} | 1 | Kotlin | 0 | 3 | 66f49350d84a5f6643f8fed94d115daa4a036402 | 315 | SpaceX_Wiki_KMM_iOS_Android | MIT License |
emojipicker/src/main/java/com/github/apeun/gidaechi/emojipicker/core/network/EmojiRemoteDataSource.kt | apeun-gidaechi | 873,390,004 | false | {"Kotlin": 26840} | package com.github.apeun.gidaechi.emojipicker.core.network
import com.github.apeun.gidaechi.emojipicker.core.network.response.EmojiResponse
import kotlinx.coroutines.flow.Flow
interface EmojiRemoteDataSource {
suspend fun getEmojiAll(): Flow<List<EmojiResponse>>
} | 0 | Kotlin | 0 | 1 | b1d7108777b95fddbca7499f8e59ff212674f4ad | 271 | emojipicker | Apache License 2.0 |
libs/rest/rest-client/src/main/kotlin/net/corda/rest/client/auth/credentials/BasicAuthCredentials.kt | corda | 346,070,752 | false | {"Kotlin": 20475899, "Java": 321378, "Smarty": 115617, "Shell": 54666, "Groovy": 30246, "PowerShell": 6509, "TypeScript": 5826, "Solidity": 2024} | package net.corda.httprpc.client.auth.credentials
data class BasicAuthCredentials(val username: String, val password: String) : CredentialsProvider {
override fun getCredentials(): Any {
return this
}
}
| 82 | Kotlin | 7 | 61 | 1f146ffd2d65f6198929109ae0d02e78c0549e20 | 220 | corda-runtime-os | Apache License 2.0 |
src/main/kotlin/io/github/itsflicker/itsbotbridge/ItsBotBridge.kt | FlickerProjects | 544,714,039 | false | null | package io.github.itsflicker.itsbotbridge
import taboolib.common.io.newFile
import taboolib.common.platform.Plugin
import taboolib.common.platform.function.getDataFolder
import taboolib.expansion.setupPlayerDatabase
import taboolib.module.configuration.Config
import taboolib.module.configuration.Configuration
object ItsBotBridge : Plugin() {
@Config
lateinit var conf: Configuration
private set
override fun onEnable() {
if (conf.getBoolean("database.enabled")) {
setupPlayerDatabase(conf.getConfigurationSection("database")!!, conf.getString("database.table")!!)
} else {
setupPlayerDatabase(newFile(getDataFolder(), "data.db"))
}
}
} | 0 | Kotlin | 0 | 0 | 65d332288bc1fc190a4aacd2bf7566a8d1414e60 | 714 | ItsBotBridge | Creative Commons Zero v1.0 Universal |
core/src/main/kotlin/io/timemates/backend/authorization/types/value/AccessHash.kt | timemates | 575,534,781 | false | {"Kotlin": 355697, "Dockerfile": 859} | package io.timemates.backend.authorization.types.value
import io.timemates.backend.validation.FailureMessage
import io.timemates.backend.validation.SafeConstructor
import io.timemates.backend.validation.ValidationFailureHandler
import io.timemates.backend.validation.reflection.wrapperTypeName
@JvmInline
value class AccessHash private constructor(val string: String) {
companion object : SafeConstructor<AccessHash, String>() {
override val displayName: String by wrapperTypeName()
const val SIZE = 128
context(ValidationFailureHandler)
override fun create(value: String): AccessHash {
return when (value.length) {
0 -> onFail(io.timemates.backend.validation.FailureMessage.ofBlank())
SIZE -> AccessHash(value)
else -> onFail(io.timemates.backend.validation.FailureMessage.ofSize(SIZE))
}
}
}
} | 16 | Kotlin | 1 | 8 | 6c1c51f3395d8d656fabc04cd7b98a4b567c27e6 | 919 | backend | MIT License |
app/src/main/java/com/mohandass/botforge/settings/viewmodel/SettingsViewModel.kt | L4TTiCe | 611,975,837 | false | null | // SPDX-FileCopyrightText: 2023 <NAME> (L4TTiCe)
//
// SPDX-License-Identifier: MIT
package com.mohandass.botforge.settings.viewmodel
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.auth.AuthCredential
import com.mohandass.botforge.R
import com.mohandass.botforge.auth.services.AccountService
import com.mohandass.botforge.common.services.Analytics
import com.mohandass.botforge.common.services.Logger
import com.mohandass.botforge.common.services.snackbar.SnackbarManager
import com.mohandass.botforge.common.services.snackbar.SnackbarMessage
import com.mohandass.botforge.common.services.snackbar.SnackbarMessage.Companion.toSnackbarMessageWithAction
import com.mohandass.botforge.settings.model.PreferredHeader
import com.mohandass.botforge.settings.model.PreferredTheme
import com.mohandass.botforge.settings.service.PreferencesDataStore
import com.mohandass.botforge.settings.service.SharedPreferencesService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* ViewModel for the Settings screen
*
* Handles various settings for the app, such as preferred theme, API key, Account, etc.
*/
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val accountService: AccountService,
private val sharedPreferencesService: SharedPreferencesService,
private val preferencesDataStore: PreferencesDataStore,
private val logger: Logger,
private val analytics: Analytics,
) : ViewModel() {
fun getApiKey(): String = sharedPreferencesService.getApiKey()
fun setApiKey(value: String) {
logger.log(TAG, "setApiKey()")
sharedPreferencesService.setAPIKey(value)
SnackbarManager.showMessage(R.string.api_key_saved)
}
fun updateImageGenerationEnabled(value: Boolean) {
logger.log(TAG, "updateImageGenerationEnabled() value: $value")
viewModelScope.launch {
preferencesDataStore.setEnableImageGeneration(value)
analytics.logIsImageGenerationEnabled(value)
}
}
fun getCurrentUser() = accountService.currentUser
fun getDisplayName() = accountService.displayName
// Usage
val usageTokens = mutableStateOf(sharedPreferencesService.getUsageTokens())
val usageImageSmallCount = mutableStateOf(sharedPreferencesService.getUsageImageSmallCount())
val usageImageMediumCount = mutableStateOf(sharedPreferencesService.getUsageImageMediumCount())
val usageImageLargeCount = mutableStateOf(sharedPreferencesService.getUsageImageLargeCount())
fun resetUsage() {
logger.log(TAG, "resetUsageTokens()")
sharedPreferencesService.resetUsage()
SnackbarManager.showMessage(R.string.usage_tokens_reset)
usageTokens.value = sharedPreferencesService.getUsageTokens()
usageImageSmallCount.value = sharedPreferencesService.getUsageImageSmallCount()
usageImageMediumCount.value = sharedPreferencesService.getUsageImageMediumCount()
usageImageLargeCount.value = sharedPreferencesService.getUsageImageLargeCount()
}
fun updateTheme(preferredTheme: PreferredTheme) {
logger.log(TAG, "updateTheme() preferredTheme: $preferredTheme")
viewModelScope.launch {
preferencesDataStore.updateTheme(preferredTheme)
analytics.logPreferredTheme(preferredTheme)
}
}
fun updateDynamicColor(value: Boolean) {
logger.log(TAG, "updateDynamicColor() value: $value")
viewModelScope.launch {
preferencesDataStore.setDynamicColor(value)
analytics.logIsDynamicColorEnabled(value)
}
}
fun updatePreferredHeader(value: PreferredHeader) {
logger.log(TAG, "updatePreferredHeader() value: $value")
viewModelScope.launch {
preferencesDataStore.setPreferredHeader(value)
analytics.logIsMinimalHeaderEnabled(value == PreferredHeader.MINIMAL_HEADER)
}
}
fun clearSyncInfo() {
logger.log(TAG, "clearLastSyncTime()")
viewModelScope.launch {
preferencesDataStore.clearLastSuccessfulSync()
preferencesDataStore.setLastModerationIndexProcessed(0)
}
}
fun setUserGeneratedContent(value: Boolean) {
logger.log(TAG, "setUserGeneratedContent() value: $value")
viewModelScope.launch {
preferencesDataStore.setUserGeneratedContent(value)
analytics.logIsUgcEnabled(value)
}
}
fun setShakeToClear(value: Boolean) {
logger.log(TAG, "setShakeToClear() value: $value")
viewModelScope.launch {
preferencesDataStore.setShakeToClear(value)
analytics.logIsShakeToClearEnabled(value)
}
}
fun setShakeToClearSensitivity(value: Float) {
logger.log(TAG, "setShakeToClearSensitivity() value: $value")
viewModelScope.launch {
preferencesDataStore.setShakeToClearSensitivity(value)
analytics.logShakeToClearSensitivity(value)
}
}
val isAnalyticsEnabled: Boolean
get() = !sharedPreferencesService.getAnalyticsOptOut()
fun setAnalyticsEnabled(value: Boolean) {
logger.log(TAG, "setAnalyticsEnabled() value: $value")
viewModelScope.launch {
sharedPreferencesService.setAnalyticsOptOut(!value)
analytics.logIsAnalyticsEnabled(value)
}
}
fun setAutoGenerateChatTitle(value: Boolean) {
logger.log(TAG, "setAutoGenerateChatTitle() value: $value")
viewModelScope.launch {
preferencesDataStore.setAutoGenerateChatTitle(value)
analytics.logIsAutoGenerateChatTitleEnabled(value)
}
}
fun regenerateDisplayName() {
logger.log(TAG, "regenerateDisplayName()")
viewModelScope.launch {
accountService.generateAndSetDisplayName()
analytics.logNameChanged()
}
}
fun onGoogleSignIn(credential: AuthCredential, onSuccess: () -> Unit) {
viewModelScope.launch {
try {
accountService.linkWithCredential(credential)
analytics.logLinkedWithGoogle()
SnackbarManager.showMessage(R.string.account_linked)
onSuccess()
} catch (e: Exception) {
SnackbarManager.showMessage(
SnackbarMessage.StringSnackbar(
e.message ?: "Error linking account"
)
)
}
}
}
fun signOut(onSuccess: () -> Unit) {
viewModelScope.launch {
accountService.signOut()
onSuccess()
}
}
fun deleteAccount(onSuccess: () -> Unit) {
viewModelScope.launch {
try {
accountService.deleteAccount()
SnackbarManager.showMessage(R.string.delete_account_success)
onSuccess()
} catch (e: Exception) {
e.toSnackbarMessageWithAction(R.string.sign_out) {
signOut(onSuccess)
}.let { message ->
SnackbarManager.showMessage(message)
}
}
}
}
companion object {
private const val TAG = "SettingsViewModel"
}
}
| 1 | Kotlin | 0 | 27 | 3025ea313d99028c3a796a493b6f35279ee2b6b5 | 7,391 | BotForge | MIT License |
src/main/kotlin/model/EventInfo.kt | westy92 | 579,845,743 | false | {"Kotlin": 27100} | package model
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Information about an Event
*/
data class EventInfo(
override val id: String,
override val name: String,
override val url: String,
/**
* Whether this Event is unsafe for children or viewing at work
*/
val adult: Boolean,
/**
* The Event's Alternate Names
*/
@JsonProperty("alternate_names")
val alternateNames: List<AlternateName>,
/**
* The Event's hashtags
*/
val hashtags: List<String>?,
/**
* The Event's images
*/
val image: ImageInfo?,
/**
* The Event's sources
*/
val sources: List<String>?,
/**
* The Event's description
*/
val description: RichText?,
/**
* How to observe the Event
*/
@JsonProperty("how_to_observe")
val howToObserve: RichText?,
/**
* Patterns defining when the Event is observed
*/
val patterns: List<Pattern>?,
/**
* The Event's founders
*/
val founders: List<FounderInfo>?,
/**
* The Event Occurrences (when it occurs)
*/
val occurrences: List<Occurrence>?,
) : Event
| 0 | Kotlin | 0 | 2 | 481253c8b2dafaf8a206b8e04b410136d583f81d | 1,173 | holiday-event-api-java | MIT License |
src/main/kotlin/day2.kt | bfrengley | 318,716,410 | false | null | package aoc2020.day2
import aoc2020.util.loadTextResource
fun main(args: Array<String>) {
val lines = loadTextResource("/day2.txt").lines()
// part 1
print("Part 1: ")
println(lines.count { validate(it) { rule, pass -> rule.checkV1(pass) } })
// part 2
print("Part 2: ")
println(lines.count { validate(it) { rule, pass -> rule.checkV2(pass) } })
}
data class Rule(val letter: Char, val min: Int, val max: Int) {
fun checkV1(pass: String) = pass.count { it == letter } in min..max
fun checkV2(pass: String) =
(pass[min - 1] == letter && pass[max - 1] != letter) ||
(pass[max - 1] == letter && pass[min - 1] != letter)
}
fun validate(line: String, check: (Rule, String) -> Boolean): Boolean {
val rule = line.substringBefore(':').trim()
val pass = line.substringAfter(':').trim()
return check(parseRule(rule), pass)
}
fun parseRule(rule: String): Rule {
val dashIdx = rule.indexOf('-')
val spaceIdx = rule.indexOf(' ')
val letter = rule[spaceIdx + 1]
val min = rule.substring(0 until dashIdx).toInt()
val max = rule.substring(dashIdx + 1 until spaceIdx).toInt()
return Rule(letter, min, max)
}
| 0 | Kotlin | 0 | 0 | 088628f585dc3315e51e6a671a7e662d4cb81af6 | 1,198 | aoc2020 | ISC License |
core/src/main/kotlin/com/libktx/core/screen/LoadingScreen.kt | ihalsh | 342,684,581 | false | null | package com.libktx.core.screen
import com.badlogic.ashley.core.PooledEngine
import com.badlogic.gdx.Gdx.input
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.libktx.core.Game
import com.libktx.core.utils.ImageAssets.Atlas
import com.libktx.core.utils.MusicAssets.Rain
import com.libktx.core.utils.SoundAssets.Drop
import kotlinx.coroutines.launch
import ktx.app.KtxScreen
import ktx.assets.async.AssetStorage
import ktx.async.KtxAsync
import ktx.graphics.use
class LoadingScreen(private val game: Game,
private val assets: AssetStorage,
private val batch: Batch,
private val renderer: ShapeRenderer,
private val font: BitmapFont,
private val camera: OrthographicCamera,
private val engine: PooledEngine) : KtxScreen {
override fun show() {
loadAssets()
}
override fun render(delta: Float) {
batch.use(camera.apply { update() }) { batch ->
font.run {
draw(batch, "Welcome to Drop!!! ", 100f, 150f)
if (assets.progress.isFinished) {
draw(batch, "Tap anywhere to begin!", 100f, 100f)
processInput()
} else draw(batch, "Loading assets...", 100f, 100f)
}
}
}
private fun loadAssets() {
KtxAsync.initiate()
val atlas = assets.loadAsync<TextureAtlas>(Atlas.path)
val dropSound = assets.loadAsync<Sound>(Drop.path)
val rainMusic = assets.loadAsync<Music>(Rain.path)
KtxAsync.launch {
game.addScreen(GameScreen(dropImage = atlas.await().findRegion("drop"),
bucketImage = atlas.await().findRegion("bucket"),
dropSound = dropSound.await(),
rainMusic = rainMusic.await(),
batch = batch, renderer = renderer, font = font, camera = camera, engine = engine))
}
}
private fun processInput() {
if (input.isTouched) {
game.setScreen<GameScreen>()
game.removeScreen<LoadingScreen>()
dispose()
}
}
} | 0 | Kotlin | 0 | 0 | 95279f16931cb0d57f3b8d3165ef1c3db9fa322c | 2,448 | SimpleKtxGame | Apache License 2.0 |
app/src/test/java/com/duckduckgo/app/email/AppEmailManagerTest.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.app.email
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import app.cash.turbine.*
import com.duckduckgo.app.email.AppEmailManager.Companion.DUCK_EMAIL_DOMAIN
import com.duckduckgo.app.email.AppEmailManager.Companion.UNKNOWN_COHORT
import com.duckduckgo.app.email.api.EmailAlias
import com.duckduckgo.app.email.api.EmailService
import com.duckduckgo.app.email.db.EmailDataStore
import com.duckduckgo.app.email.sync.*
import com.duckduckgo.app.pixels.AppPixelName.EMAIL_DISABLED
import com.duckduckgo.app.pixels.AppPixelName.EMAIL_ENABLED
import com.duckduckgo.app.statistics.pixels.Pixel
import com.duckduckgo.common.test.CoroutineTestRule
import com.duckduckgo.sync.settings.api.SyncSettingsListener
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.*
@FlowPreview
@RunWith(AndroidJUnit4::class)
class AppEmailManagerTest {
@get:Rule
var coroutineRule = CoroutineTestRule()
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private val mockEmailService: EmailService = mock()
private val mockEmailDataStore: EmailDataStore = FakeEmailDataStore()
private val mockSyncSettingsListener = mock<SyncSettingsListener>()
private val emailSyncableSetting = EmailSync(mockEmailDataStore, mockSyncSettingsListener, mock())
private val mockPixel: Pixel = mock()
lateinit var testee: AppEmailManager
@Before
fun setup() {
testee = AppEmailManager(
mockEmailService,
mockEmailDataStore,
emailSyncableSetting,
coroutineRule.testDispatcherProvider,
TestScope(),
mockPixel,
)
}
@Test
fun whenFetchAliasFromServiceThenStoreAliasAddingDuckDomain() = runTest {
mockEmailDataStore.emailToken = "token"
whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias("test"))
testee.getAlias()
assertEquals("test$DUCK_EMAIL_DOMAIN", mockEmailDataStore.nextAlias)
}
@Test
fun whenFetchAliasFromServiceAndTokenDoesNotExistThenDoNothing() = runTest {
mockEmailDataStore.emailToken = null
testee.getAlias()
verify(mockEmailService, never()).newAlias(any())
}
@Test
fun whenFetchAliasFromServiceAndAddressIsBlankThenStoreNull() = runTest {
mockEmailDataStore.emailToken = "token"
whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias(""))
testee.getAlias()
assertNull(mockEmailDataStore.nextAlias)
}
@Test
fun whenGetAliasThenReturnNextAlias() = runTest {
givenNextAliasExists()
assertEquals("alias", testee.getAlias())
}
@Test
fun whenGetAliasIfNextAliasDoesNotExistThenReturnNull() {
assertNull(testee.getAlias())
}
@Test
fun whenGetAliasThenClearNextAlias() {
testee.getAlias()
assertNull(mockEmailDataStore.nextAlias)
}
@Test
fun whenIsSignedInAndTokenDoesNotExistThenReturnFalse() {
mockEmailDataStore.emailUsername = "username"
mockEmailDataStore.nextAlias = "alias"
assertFalse(testee.isSignedIn())
}
@Test
fun whenIsSignedInAndUsernameDoesNotExistThenReturnFalse() {
mockEmailDataStore.emailToken = "token"
mockEmailDataStore.nextAlias = "alias"
assertFalse(testee.isSignedIn())
}
@Test
fun whenIsSignedInAndTokenAndUsernameExistThenReturnTrue() {
mockEmailDataStore.emailToken = "token"
mockEmailDataStore.emailUsername = "username"
assertTrue(testee.isSignedIn())
}
@Test
fun whenStoreCredentialsThenGenerateNewAlias() = runTest {
mockEmailDataStore.emailToken = "token"
whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias(""))
testee.storeCredentials("token", "username", "cohort")
verify(mockEmailService).newAlias(any())
}
@Test
fun whenStoreCredentialsThenNotifySyncableSetting() = runTest {
mockEmailDataStore.emailToken = "token"
whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias(""))
testee.storeCredentials("token", "username", "cohort")
verify(mockSyncSettingsListener).onSettingChanged(emailSyncableSetting.key)
}
@Test
fun whenStoreCredentialsThenSendPixel() = runTest {
mockEmailDataStore.emailToken = "token"
whenever(mockEmailService.newAlias(any())).thenReturn(EmailAlias(""))
testee.storeCredentials("token", "username", "cohort")
verify(mockPixel).fire(EMAIL_ENABLED)
}
@Test
fun whenStoreCredentialsThenCredentialsAreStoredInDataStore() {
testee.storeCredentials("token", "username", "cohort")
assertEquals("username", mockEmailDataStore.emailUsername)
assertEquals("token", mockEmailDataStore.emailToken)
assertEquals("cohort", mockEmailDataStore.cohort)
}
@Test
fun whenStoreCredentialsIfCredentialsWereCorrectlyStoredThenIsSignedInChannelSendsTrue() = runTest {
testee.storeCredentials("token", "username", "cohort")
assertTrue(testee.signedInFlow().first())
}
@Test
fun whenStoreCredentialsIfCredentialsAreBlankThenIsSignedInChannelSendsFalse() = runTest {
testee.storeCredentials("", "", "cohort")
assertFalse(testee.signedInFlow().first())
}
@Test
fun whenSignedOutThenClearEmailDataAndAliasIsNull() {
testee.signOut()
assertNull(mockEmailDataStore.emailUsername)
assertNull(mockEmailDataStore.emailToken)
assertNull(mockEmailDataStore.nextAlias)
assertNull(testee.getAlias())
}
@Test
fun whenSignedOutThenNotifySyncableSetting() {
testee.signOut()
verify(mockSyncSettingsListener).onSettingChanged(emailSyncableSetting.key)
}
@Test
fun whenSignedOutThenSendPixel() {
testee.signOut()
verify(mockPixel).fire(EMAIL_DISABLED)
}
@Test
fun whenSignedOutThenIsSignedInChannelSendsFalse() = runTest {
testee.signOut()
assertFalse(testee.signedInFlow().first())
}
@Test
fun whenGetEmailAddressThenDuckEmailDomainIsAppended() {
mockEmailDataStore.emailUsername = "username"
assertEquals("username$DUCK_EMAIL_DOMAIN", testee.getEmailAddress())
}
@Test
fun whenGetCohortThenReturnCohort() {
mockEmailDataStore.cohort = "cohort"
assertEquals("cohort", testee.getCohort())
}
@Test
fun whenGetCohortIfCohortIsNullThenReturnUnknown() {
mockEmailDataStore.cohort = null
assertEquals(UNKNOWN_COHORT, testee.getCohort())
}
@Test
fun whenGetCohortIfCohortIsEmtpyThenReturnUnknown() {
mockEmailDataStore.cohort = ""
assertEquals(UNKNOWN_COHORT, testee.getCohort())
}
@Test
fun whenIsEmailFeatureSupportedAndEncryptionCanBeUsedThenReturnTrue() {
(mockEmailDataStore as FakeEmailDataStore).canUseEncryption = true
assertTrue(testee.isEmailFeatureSupported())
}
@Test
fun whenGetLastUsedDateIfNullThenReturnEmpty() {
assertEquals("", testee.getLastUsedDate())
}
@Test
fun whenGetLastUsedDateIfNotNullThenReturnValueFromStore() {
mockEmailDataStore.lastUsedDate = "2021-01-01"
assertEquals("2021-01-01", testee.getLastUsedDate())
}
@Test
fun whenIsEmailFeatureSupportedAndEncryptionCannotBeUsedThenReturnFalse() {
(mockEmailDataStore as FakeEmailDataStore).canUseEncryption = false
assertFalse(testee.isEmailFeatureSupported())
}
@Test
fun whenGetUserDataThenDataReceivedCorrectly() {
val expected = JSONObject().apply {
put(AppEmailManager.TOKEN, "token")
put(AppEmailManager.USERNAME, "user")
put(AppEmailManager.NEXT_ALIAS, "nextAlias")
}.toString()
mockEmailDataStore.emailToken = "token"
mockEmailDataStore.emailUsername = "user"
mockEmailDataStore.nextAlias = "<EMAIL>"
assertEquals(expected, testee.getUserData())
}
@Test
fun whenSyncableSettingNotifiesChangeThenRefreshEmailState() = runTest {
testee.signedInFlow().test {
assertFalse(awaitItem())
emailSyncableSetting.save("{\"username\":\"email\",\"personal_access_token\":\"token\"}")
assertTrue(awaitItem())
cancelAndIgnoreRemainingEvents()
}
}
private fun givenNextAliasExists() {
mockEmailDataStore.nextAlias = "alias"
}
class TestEmailService : EmailService {
override suspend fun newAlias(authorization: String): EmailAlias = EmailAlias("alias")
}
}
class FakeEmailDataStore : EmailDataStore {
override var emailToken: String? = null
override var nextAlias: String? = null
override var emailUsername: String? = null
override var cohort: String? = null
override var lastUsedDate: String? = null
var canUseEncryption: Boolean = false
override fun canUseEncryption(): Boolean = canUseEncryption
}
| 0 | Kotlin | 0 | 0 | 54351d039b85138a85cbfc7fc3bd5bc53637559f | 9,534 | DuckDuckGo | Apache License 2.0 |
java/sui-security/src/main/java/ru/sui/suisecurity/security/JwtTokenProvider.kt | mbuyakov | 174,821,817 | false | {"TypeScript": 672905, "Java": 191967, "Kotlin": 158752, "PLpgSQL": 48243, "JavaScript": 19879, "Less": 14088, "Smarty": 830, "Shell": 774, "Dockerfile": 57} | package ru.sui.suisecurity.security
import io.jsonwebtoken.*
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.cache.annotation.Cacheable
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.WebAuthenticationDetails
import org.springframework.stereotype.Component
import ru.sui.suisecurity.exception.SessionException
import ru.sui.suisecurity.extension.clientIp
import ru.sui.suisecurity.session.Session
import ru.sui.suisecurity.session.SessionManager
import ru.sui.suisecurity.utils.VALIDATE_TOKEN_CACHE
import ru.sui.suisecurity.utils.getRequest
import java.util.*
private const val SESSION_KEY = "__sui_session"
private val log = KotlinLogging.logger { }
@Component
class JwtTokenProvider {
@Autowired
private lateinit var sessionManager: SessionManager
@Value("\${jwtSecret}")
private val jwtSecret: String? = null
@Value("\${jwtExpiration}")
private val jwtExpiration: Int = 0
fun generateToken(authentication: Authentication): String {
val userPrincipal = authentication.principal as UserPrincipal
val now = Date()
val expiryDate = Date(now.time + jwtExpiration)
val sessionId = UUID.randomUUID()
val userId = userPrincipal.user.id!!
val remoteAddress = kotlin.runCatching { getRequest().clientIp }.getOrNull()
sessionManager.createSession(Session(
id = sessionId,
userId = userId,
expiryDate = expiryDate,
remoteAddress = remoteAddress
))
return Jwts.builder()
.setSubject(userId.toString())
.setIssuedAt(Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.claim(SESSION_KEY, sessionId)
.compact()
}
fun getUserIdFromJWT(token: String): Long {
return Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.body
.subject
.toLong()
}
fun getSessionIdFromJWT(token: String): UUID {
return UUID.fromString(Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).body[SESSION_KEY] as String)
}
@Cacheable(VALIDATE_TOKEN_CACHE)
fun validateToken(authToken: String, updateActivity: Boolean = true): Boolean {
log.debug { "Call validateToken with token $authToken" }
try {
sessionManager.checkSession(getSessionIdFromJWT(authToken), updateActivity)
return true
} catch (ex: SignatureException) {
log.error("Invalid JWT signature")
} catch (ex: MalformedJwtException) {
log.error("Invalid JWT token")
} catch (ex: ExpiredJwtException) {
log.error("Expired JWT token")
} catch (ex: UnsupportedJwtException) {
log.error("Unsupported JWT token")
} catch (ex: IllegalArgumentException) {
log.error("JWT claims string is empty.")
} catch (ex: Exception) {
log.error(ex.message, ex)
}
return false
}
}
| 1 | TypeScript | 1 | 5 | 3048f84a18e730ece2f16a1223c82c863edabf38 | 3,285 | SUI.CORE | Apache License 2.0 |
app/src/main/java/com/kaya/currency/core/use_case/UseCase.kt | ata-kaya | 681,869,811 | false | null | package com.kaya.currency.core.use_case
abstract class UseCase<T> {
abstract fun execute(): T
} | 0 | Kotlin | 0 | 0 | 7fdebff16bcd3b99389eb1a90fac52ab531ac77a | 100 | Currency-MVVM-Test | MIT License |
skellig-junit-runner/src/test/kotlin/org/skellig/runner/DefaultSkelligRunnerTest.kt | skellig-framework | 263,021,995 | false | null | package org.skellig.runner
import org.junit.runner.RunWith
import org.skellig.runner.annotation.SkelligOptions
import org.skellig.runner.config.TestSkelligContext
@RunWith(SkelligRunner::class)
@SkelligOptions(features = ["feature"],
testSteps = ["feature", "org.skellig.runner.stepdefs"],
context = TestSkelligContext::class)
class DefaultSkelligRunnerTest | 4 | Kotlin | 0 | 1 | dcbd3e8007ccbf07cbf68d8e5f92f5cfb969ea5a | 375 | skellig-core | Apache License 2.0 |
config/src/commonMain/kotlin/lexi/builder/FileAppenderConfigurationBuilder.kt | aSoft-Ltd | 592,348,487 | false | {"Kotlin": 42859} | @file:JsExport
package lexi.builder
import kotlinx.JsExport
import kotlin.jvm.JvmOverloads
class FileAppenderConfigurationBuilder @JvmOverloads constructor(
internal var directory: String? = null,
enabled: Boolean = false,
) : AppenderConfigurationBuilder(null, enabled) {
fun directory(path: String) {
directory = path
}
} | 0 | Kotlin | 0 | 0 | 09c8b878733bb887fa18cc0fc43611d60a7493a2 | 350 | lexi | MIT License |
src/main/kotlin/eece513/client/PrintStreamPresenter.kt | kierse | 177,887,071 | false | null | package eece513.client
import java.io.PrintStream
/**
* This class processes [GrepClient.Server.Response]'s and prints them
* to the given [out] and [err] PrintStream's. Instances of this class
* can be used to print results out to the console.
*/
class PrintStreamPresenter(
private val out: PrintStream, private val err: PrintStream
) : GrepClient.Presenter {
override fun displayResponse(response: GrepClient.Server.Response) {
when (response) {
is GrepClient.Server.Response.Result -> printStdOut(response)
is GrepClient.Server.Response.Error -> printStdErr(response)
}
}
override fun displayHelp(msg: String) = err.println(msg)
private fun printStdOut(response: GrepClient.Server.Response.Result) {
for (line in response.result) {
out.println("${response.name}:$line")
}
}
private fun printStdErr(response: GrepClient.Server.Response.Error) {
for (line in response.result) {
err.println("${response.name}:$line")
}
}
} | 0 | Kotlin | 0 | 0 | e1e3b01978993e580c7b28ee54c87f726275c9ec | 1,064 | distributed-grep | MIT License |
app/src/main/java/com/psimao/rtcplayground/presentation/home/dial/DialFragment.kt | psimao | 140,693,237 | false | {"Kotlin": 77228} | package com.psimao.rtcplayground.presentation.home.dial
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.psimao.rtcplayground.R
import com.psimao.rtcplayground.data.model.User
import com.psimao.rtcplayground.presentation.call.CallActivity
import com.psimao.rtcplayground.presentation.socket.SocketService
import kotlinx.android.synthetic.main.fragment_dial.*
import kotlinx.android.synthetic.main.item_chat_message.view.*
import kotlinx.android.synthetic.main.item_user.view.*
import org.koin.android.ext.android.inject
import java.util.*
class DialFragment : Fragment(), DialView {
companion object {
val TAG: String = DialFragment::class.java.name
}
private val presenter: DialPresenter by inject()
private val adapter: OnlineUserAdapter by lazy { OnlineUserAdapter() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_dial, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.create(this)
recyclerViewOnlineUsers.layoutManager = LinearLayoutManager(context)
recyclerViewOnlineUsers.adapter = adapter
adapter.onItemSelected = {
presenter.onUserSelected(it)
}
}
override fun onStart() {
super.onStart()
if (!SocketService.isConnected) {
showNotConnected()
}
}
override fun onDestroy() {
super.onDestroy()
presenter.destroy()
}
override fun updateOnlineUsersList(onlineUsers: List<User>) {
Handler(context?.mainLooper).post {
textNotConnected.visibility = View.GONE
adapter.updateDataSet(onlineUsers)
}
}
override fun showCallView(targetId: String, targetAlias: String) {
startActivity(CallActivity.createIntentForInitiator(context!!, targetId, targetAlias))
}
override fun showNotConnected() {
adapter.clear()
textNotConnected.visibility = View.VISIBLE
}
inner class OnlineUserAdapter : RecyclerView.Adapter<OnlineUserAdapter.ViewHolder>() {
private val onlineUsers: ArrayList<User> = ArrayList()
private val random: Random = Random()
var onItemSelected: ((User) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false))
}
override fun getItemCount(): Int = onlineUsers.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(onlineUsers[position]) {
holder.itemView.textViewUserAlias.text = alias
holder.itemView.textViewUserId.text = id
val red = random.nextInt(255)
val green = random.nextInt(255)
val blue = random.nextInt(255)
holder.itemView.imageUser.backgroundTintList = ColorStateList.valueOf(Color.rgb(red, green, blue))
holder.itemView.setOnClickListener {
onItemSelected?.invoke(this)
}
}
}
fun updateDataSet(users: List<User>) {
onlineUsers.clear()
onlineUsers.addAll(users)
notifyDataSetChanged()
}
fun clear() {
onlineUsers.clear()
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
} | 3 | Kotlin | 0 | 1 | faa65d49b6fc2a84498b7e3c272748ad6bbe4637 | 3,961 | rtcplayground | MIT License |
src/main/java/com/nifcloud/mbaas/core/NCMBQuery.kt | NIFCLOUD-mbaas | 447,844,303 | false | null | /*
* Copyright 2017-2021 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
*
* 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.nifcloud.mbaas.core
import com.nifcloud.mbaas.core.NCMBDateFormat.getIso8601
import kotlinx.serialization.json.JSON
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import org.json.JSONArray
/**
* NCMBQuery is used to search data from NIFCLOUD mobile backend
*/
//プライベートコンストラクターとしてcompanion object内にあるfor〇〇メソッドを用いて、インスタンスを取得する
class NCMBQuery<T : NCMBObject> private constructor(val mClassName: String, val service:NCMBServiceInterface<T>){
private var mWhereConditions: JSONObject = JSONObject()
private var mCountCondition: Int = 0
private var order: List<String> = ArrayList()
var limit: Int = 0 // default value is 0 (valid limit value is 1 to 1000)
set(value) {
if (value < 1 || value >1000 ) {
throw NCMBException(
NCMBException.GENERIC_ERROR,
"Need to set limit value from 1 to 1000"
)
}
}
var skip: Int = 0 // default value is 0 (valid skip value is >0 )
set(value) {
if (value < 0 ) {
throw NCMBException(
NCMBException.GENERIC_ERROR,
"Need to set skip value > 0"
)
}
}
companion object {
fun forObject(className: String): NCMBQuery<NCMBObject> {
return NCMBQuery<NCMBObject>(className, NCMBObjectService())
}
}
/**
* search data from NIFCLOUD mobile backend
* @return NCMBObject(include extend class) list of search result
* @throws NCMBException exception sdk internal or NIFCLOUD mobile backend
*/
@Throws(NCMBException::class)
fun find(): List<T> {
return service.find(mClassName, query)
}
/**
* search data from NIFCLOUD mobile backend asynchronously
* @param callback executed callback after data search
*/
fun findInBackground(findCallback: NCMBCallback) {
service.findInBackground(mClassName, query, findCallback)
}
/**
* get total number of search result from NIFCLOUD mobile backend
* @return total number of search result
* @throws NCMBException exception sdk internal or NIFCLOUD mobile backend
*/
@Throws(NCMBException::class)
fun count(): Int {
mCountCondition = 1
return service.count(mClassName, query)
}
/**
* get total number of search result from NIFCLOUD mobile backend asynchronously
* @param callback executed callback after data search
*/
fun countInBackground(countCallback: NCMBCallback) {
mCountCondition = 1
service.countInBackground(mClassName, query, countCallback)
}
/**
* get current search condition
* @return current search condition
*/
val query: JSONObject
get() {
val query = JSONObject()
if (mWhereConditions.length() > 0) {
query.put(NCMBQueryConstants.REQUEST_PARAMETER_WHERE, mWhereConditions)
}
if (mCountCondition > 0) {
query.put(NCMBQueryConstants.REQUEST_PARAMETER_COUNT,1)
}
if (limit > 0 ) {
query.put(NCMBQueryConstants.REQUEST_PARAMETER_LIMIT, limit)
}
if (skip > 0 ) {
query.put(NCMBQueryConstants.REQUEST_PARAMETER_SKIP, skip)
}
if (order.size > 0) {
query.put("order", order.joinToString(separator = "," ))
}
return query
}
@Throws(JSONException::class)
private fun convertConditionValue(value: Any): Any {
return if (value is Date) {
val dateJson = JSONObject("{'__type':'Date'}")
val df: SimpleDateFormat = getIso8601()
dateJson.put("iso", df.format(value as Date))
dateJson
} else {
value
}
}
/**
* set the conditions to search the data that matches the value of the specified key.
* NOTICE that if this search condition is set, you can not set other search condition for this key.
* OR if this search condition is set last, other set search condition for same key will be overwrite.
* @param key field name to set the conditions
* @param value condition value
*/
fun whereEqualTo(key: String, value: Any) {
try {
mWhereConditions.put(key, convertConditionValue(value) )
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that does not match the value of the specified key
* @param key field name to set the conditions
* @param value condition value
*/
fun whereNotEqualTo(key: String, value: Any) {
try {
mWhereConditions.put(key, addSearchCondition(key, "\$ne" , value))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data by ascending order with specified field name (key)
* @param key field name for order by ascending
*/
fun addOrderByAscending(key: String) {
if(key != "") {
order += key
}
}
/**
* set the conditions to search the data that greater than the value of the specified key
* @param key field name to set the conditions
* @param value condition value
*/
fun whereGreaterThan(key: String, value: Any) {
try {
mWhereConditions.put(key,addSearchCondition(key, "\$gt", value))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that less than the value of the specified key
* @param key field name to set the conditions
* @param value condition value
*/
fun whereLessThan(key: String, value: Any) {
try {
mWhereConditions.put(key,addSearchCondition(key, "\$lt", value))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that greater than or equal to the value of the specified key
* @param key field name to set the conditions
* @param value condition value
*/
fun whereGreaterThanOrEqualTo(key: String, value: Any) {
try {
mWhereConditions.put(key,addSearchCondition(key, "\$gte", value))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that less than or equal to the value of the specified key
* @param key field name to set the conditions
* @param value condition value
*/
fun whereLessThanOrEqualTo(key: String, value: Any) {
try {
mWhereConditions.put(key,addSearchCondition(key, "\$lte", value))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
//Add new search condition (new 'operand' and 'value') for 'key', and return added search Condition for key
internal fun addSearchCondition(key: String, operand: String, value: Any):JSONObject {
var newCondition = JSONObject()
if (mWhereConditions.has(key)) {
val currentCondition = mWhereConditions[key]
if (currentCondition is JSONObject) {
newCondition = currentCondition
}
else {
throw NCMBException(NCMBException.GENERIC_ERROR, "Cannot set other search condition for key which already set whereEqualTo search condition")
}
}
newCondition.put(operand, convertConditionValue(value))
return newCondition
}
/**
* set the conditions to search the data by descending order with specified field name (key)
* @param key field name for order by ascending
*/
fun addOrderByDescending(key: String) {
if(key != "") {
order += "-"+key
}
}
/**
* set the conditions to search the data that contains value of the specified key
* @param key field name to set the conditions
* @param objects condition objects
*/
fun whereContainedIn(key: String, objects: Collection<Any>) {
try {
mWhereConditions.put(key,addSearchConditionArray(key, "\$in", objects))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that contains elements of array in the specified key
* @param key field name to set the conditions (search field must be Array type field)
* @param elements condition elements in the specified key array
*/
fun whereContainedInArray(key: String, objects: Collection<Any>) {
try {
mWhereConditions.put(key,addSearchConditionArray(key, "\$inArray", objects))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that contains elements of array in the specified key
* @param key field name to set the conditions (search field must be Array type field)
* @param elements condition elements in the specified key array
*/
fun whereNotContainedInArray(key: String, objects: Collection<Any>) {
try {
mWhereConditions.put(key,addSearchConditionArray(key, "\$ninArray", objects))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that not contains value of the specified key
* @param key field name to set the conditions
* @param objects condition objects
*/
fun whereNotContainedIn(key: String, objects: Collection<Any>) {
try {
mWhereConditions.put(key,addSearchConditionArray(key, "\$nin", objects))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* set the conditions to search the data that contains all elements of array in the specified key
* @param Arraykey field name to set the conditions (search field must be Array type field)
* @param elements condition elements in the specified key array
*/
fun whereContainsAll(key: String, elements: Collection<Any>) {
try {
mWhereConditions.put(key,addSearchConditionArray(key, "\$all", elements))
} catch (e: JSONException) {
throw NCMBException(e)
}
}
/**
* Constructor
* @param className class name string for search data
*/
init {
mWhereConditions = JSONObject()
}
//Add new search condition (new 'operand' and 'value') for 'key', and return added search Condition for key
internal fun addSearchConditionArray(key: String, operand: String, objects: Collection<Any>):JSONObject {
var newCondition = JSONObject()
if (mWhereConditions.has(key)) {
val currentCondition = mWhereConditions[key]
if (currentCondition is JSONObject) {
newCondition = currentCondition
}
else {
throw NCMBException(NCMBException.GENERIC_ERROR, "Cannot set other search condition for key which already set whereEqualTo search condition")
}
}
val array = JSONArray()
for (value in objects) {
array.put(convertConditionValue(value))
}
newCondition.put(operand, array)
return newCondition
}
}
| 6 | Kotlin | 0 | 0 | cb2cf4283cbef22cfe154ea616f04ad6e34396e0 | 12,285 | ncmb_kotlin | Apache License 2.0 |
shared/features/details/src/commonMain/kotlin/com/dee/details/presentation/MovieDetailsViewModel.kt | deeheinhtet | 776,096,363 | false | {"Kotlin": 98395, "Swift": 15749} | package com.dee.details.presentation
import com.dee.core.BaseViewModel
import com.dee.common.mapToErrorDisplay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import modules.moviedetails.domain.MovieDetailsDisplay
import com.dee.details.domain.MovieDetailsUseCase
/**
* Created by <NAME>
*/
class MovieDetailsViewModel(private val movieDetailsUseCase: MovieDetailsUseCase) :
BaseViewModel() {
override val inputs = MovieDetailsInputs()
override val outputs = MovieDetailsOutputs()
private val _movieDetails = MutableStateFlow<MovieDetailsDisplay?>(null)
inner class MovieDetailsInputs : BaseInputs() {
fun onGetMovieDetails(id: String) = getMovieDetails(id)
}
inner class MovieDetailsOutputs : BaseOutputs() {
val movieDetails: StateFlow<MovieDetailsDisplay?>
get() = _movieDetails
}
private fun getMovieDetails(id: String) {
scope.launch {
movieDetailsUseCase(id)
.onStart { inputs.emitLoading(true) }
.onCompletion { inputs.emitLoading(false) }
.catch { inputs.emitError(it.mapToErrorDisplay()) }
.collectLatest {
_movieDetails.value = it
}
}
}
}
| 0 | Kotlin | 5 | 44 | 460fa93dae6162332280c1a515e2875a6efbf599 | 1,495 | TheMovie | MIT License |
core/src/main/java/com/bigwic/employeeluas/core/utils/AppUtils.kt | WicMan101 | 451,754,424 | false | {"Kotlin": 28093} | package com.bigwic.employeeluas.core.utils
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.util.Log
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
class AppUtils(private val context: Context) {
fun isNetworkAvailable(): Boolean {
var hasConnection = false
val connectivityManager = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities = connectivityManager
.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
hasConnection = true
}
}
}
return hasConnection
}
@SuppressLint("SimpleDateFormat")
fun formatToReadableDate(createdDate: String): String {
val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val formatter = SimpleDateFormat("dd/MM/yyyy HH:mm")
return formatter.format(parser.parse(createdDate))
}
// Bit of a long way round method.
// Passing in Calendar in order to make the method testable.
fun isEvening(currentTime: Calendar): Boolean {
val fromTime = Calendar.getInstance()
fromTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(12))
fromTime.set(Calendar.MINUTE, Integer.valueOf(0))
val toTime = Calendar.getInstance()
toTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(23))
toTime.set(Calendar.MINUTE, Integer.valueOf(59))
toTime.set(Calendar.SECOND, Integer.valueOf(59))
return currentTime.after(fromTime) && currentTime.before(toTime)
}
} | 0 | Kotlin | 0 | 0 | ca5f03a0c7969137533b40a641e46e2c2c8299a5 | 2,005 | employee-luas | MIT License |
price/src/main/kotlin/de/richargh/springkotlinhexagonal/domain/Greeter.kt | Richargh | 165,030,359 | false | null | package de.richargh.springkotlinhexagonal.domain
class Greeter{
fun sayHello() = "Hello"
} | 0 | Kotlin | 0 | 1 | f91b0de43d49dc596daeccc8fc0c929e65eb0de9 | 95 | spring-kotlin-hexagonal | MIT License |
example-android/src/main/java/com/komoju/android/ui/screens/store/FakeItemDetailScreen.kt | degica | 851,401,843 | false | {"Kotlin": 266785, "JavaScript": 1844} | package com.komoju.android.ui.screens.store
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.Image
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.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import cafe.adriel.voyager.core.model.rememberNavigatorScreenModel
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.komoju.android.R
import com.komoju.android.sdk.KomojuSDK
import com.komoju.android.sdk.canProcessPayment
import com.komoju.android.ui.theme.KomojuDarkGreen
data class FakeItemDetailScreen(private val index: Int) : Screen {
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val backPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
val screenModel = navigator.rememberNavigatorScreenModel { FakeStoreScreenModel() }
val uiState by screenModel.uiState.collectAsStateWithLifecycle()
val item by remember { derivedStateOf { uiState.items[index] } }
val komojuSDKConfiguration by screenModel.komojuSDKConfiguration.collectAsStateWithLifecycle()
val komojuPaymentLauncher = rememberLauncherForActivityResult(KomojuSDK.KomojuPaymentResultContract) {
screenModel.onKomojuPaymentCompleted()
navigator.push(if (it.isSuccessFul) FakeOrderSuccessScreen() else FakeOrderFailedScreen())
}
LaunchedEffect(komojuSDKConfiguration) {
val configuration = komojuSDKConfiguration
if (configuration.canProcessPayment()) {
komojuPaymentLauncher.launch(configuration)
}
}
Box {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(state = rememberScrollState()),
) {
Box {
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.padding(8.dp)
.clip(RoundedCornerShape(24.dp)),
painter = painterResource(item.imageID),
contentDescription = "",
)
Icon(
modifier = Modifier
.padding(16.dp)
.clip(CircleShape)
.clickable {
backPressedDispatcher?.onBackPressed()
}
.background(Color.LightGray.copy(alpha = .2f), CircleShape)
.padding(12.dp)
.align(Alignment.TopStart),
imageVector = Icons.AutoMirrored.Rounded.ArrowBack,
contentDescription = "",
tint = Color.DarkGray,
)
Icon(
modifier = Modifier
.padding(16.dp)
.clip(CircleShape)
.clickable {
screenModel.onItemChanged(item.copy(isFavorite = item.isFavorite.not()))
}
.background(Color.LightGray.copy(alpha = .2f), CircleShape)
.padding(12.dp)
.align(Alignment.TopEnd),
imageVector = if (item.isFavorite) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = "",
tint = if (item.isFavorite) Color.Red else Color.DarkGray,
)
}
Text(
"¥" + item.price + ".00",
fontSize = 18.sp,
color = Color.Black,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(vertical = 4.dp, horizontal = 16.dp),
)
Text(
stringResource(item.name),
fontSize = 20.sp,
color = Color.Black,
fontWeight = FontWeight.Medium,
lineHeight = 16.sp,
modifier = Modifier.padding(horizontal = 15.dp),
)
Text(
stringResource(R.string.model) + ": " + item.model + ", " + stringResource(item.color),
fontSize = 14.sp,
color = Color.Gray,
fontWeight = FontWeight.Normal,
modifier = Modifier.padding(horizontal = 16.dp),
)
Spacer(modifier = Modifier.height(16.dp))
Text(
stringResource(item.description),
fontSize = 12.sp,
color = Color.Gray,
fontWeight = FontWeight.Normal,
modifier = Modifier
.padding(horizontal = 16.dp)
.weight(1f),
lineHeight = 16.sp,
)
Button(
colors = ButtonDefaults.buttonColors(containerColor = KomojuDarkGreen),
onClick = {
screenModel.onBuyClicked(item)
},
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
) {
Text(
stringResource(R.string.buy_this_item),
)
}
}
if (uiState.isCreatingSession) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray.copy(alpha = .1f))
.clickable {},
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
}
}
}
}
| 0 | Kotlin | 0 | 4 | 28e708a0a4c253537509001ef5823172c5a02a55 | 8,029 | komoju-mobile-sdk | MIT License |
composeApp/src/androidMain/kotlin/com/ixidev/jtsalat/JtSalatApp.kt | ixiDev | 807,871,390 | false | {"Kotlin": 88024, "Swift": 594} | package com.ixidev.jtsalat
import android.app.Application
import com.ixidev.jtsalat.di.koinModules
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
class JtSalatApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@JtSalatApp)
modules(koinModules)
}
}
} | 0 | Kotlin | 0 | 2 | 6d850e1d3099b352164f5144bd9626ac60d2a987 | 469 | JtSalat | Apache License 2.0 |
app/src/main/java/com/hillpark/hillpark/utils/DbUtils.kt | 0adik0 | 437,355,255 | false | {"Kotlin": 201941, "Java": 22343} | package com.hillpark.hillpark.utils
class DbUtils {
} | 0 | Kotlin | 0 | 0 | fb5519d9169a5d1185439df79a5da802e727fc87 | 54 | Hillpark | Apache License 2.0 |
src/Day17.kt | wgolyakov | 572,463,468 | false | null | fun main() {
val rocks = listOf(
listOf(
"####"
),
listOf(
".#.",
"###",
".#.",
),
listOf(
"..#",
"..#",
"###",
),
listOf(
"#",
"#",
"#",
"#",
),
listOf(
"##",
"##",
),
)
fun emptyChamber() = mutableListOf(
StringBuilder("+-------+"),
)
fun addLayers(chamber: MutableList<StringBuilder>, n: Int) {
if (n >= 0) {
for (i in 0 until n)
chamber.add(0, StringBuilder("|.......|"))
} else {
for (i in 0 until -n)
chamber.removeAt(0)
}
}
fun drawRock(chamber: MutableList<StringBuilder>, rock: List<String>, x: Int, y: Int, color: Char = '#') {
for (i in rock.indices) {
val rockLayer = rock[i]
val chamberLayer = chamber[y + i]
for (j in rockLayer.indices)
if (rockLayer[j] != '.') chamberLayer[x + j] = color
}
}
fun eraseRock(chamber: MutableList<StringBuilder>, rock: List<String>, x: Int, y: Int) =
drawRock(chamber, rock, x, y, '.')
fun emptySpace(chamber: MutableList<StringBuilder>, rock: List<String>, x: Int, y: Int): Boolean {
for (i in rock.indices) {
val rockLayer = rock[i]
val chamberLayer = chamber[y + i]
for (j in rockLayer.indices)
if (rockLayer[j] != '.' && chamberLayer[x + j] != '.') return false
}
return true
}
fun moveRock(chamber: MutableList<StringBuilder>, rock: List<String>, x: Int, y: Int, dx: Int, dy: Int): Boolean {
eraseRock(chamber, rock, x, y)
return if (emptySpace(chamber, rock, x + dx, y + dy)) {
drawRock(chamber, rock, x + dx, y + dy)
true
} else {
drawRock(chamber, rock, x, y)
false
}
}
fun part1(jets: String): Int {
val chamber = emptyChamber()
var towerY = chamber.size - 1
var j = 0
for (r in 0 until 2022) {
val rock = rocks[r % rocks.size]
val newLayersCount = 3 - towerY + rock.size
addLayers(chamber, newLayersCount)
towerY += newLayersCount
var x = 3
var y = 0
drawRock(chamber, rock, x, y)
while (true) {
val jet = jets[j++ % jets.length]
val dx = if (jet == '<') -1 else 1
if (moveRock(chamber, rock, x, y, dx, 0))
x += dx
if (moveRock(chamber, rock, x, y, 0, 1))
y++
else
break
}
if (y < towerY) towerY = y
}
return chamber.size - towerY - 1
}
fun part2(jets: String): Long {
val chamber = emptyChamber()
val maxChamberSaveSize = 1000000
var towerY = chamber.size - 1
var towerSize = 0L
val towerStat = mutableMapOf<Int, MutableList<Pair<Long, Long>>>()
val rockStat = mutableMapOf<Int, MutableList<Pair<Long, Long>>>()
var j = 0L
for (r in 0 until 1000000000000) {
if (r % rocks.size == 0L) {
val jMod = (j % jets.length).toInt()
val towerList = towerStat.getOrPut(jMod) { mutableListOf() }
val lastTowerSize = if (towerList.isNotEmpty()) towerList.last().first else 0L
val dt = towerSize - lastTowerSize
towerList.add(towerSize to dt)
val rockList = rockStat.getOrPut(jMod) { mutableListOf() }
val lastRock = if (rockList.isNotEmpty()) rockList.last().first else 0L
val dr = r - lastRock
rockList.add(r to dr)
if (towerList.size >= 3 && rockList.size >= 3) {
if ((1000000000000 - r) % dr == 0L) {
return towerSize + ((1000000000000 - r) / dr) * dt
}
}
}
val rock = rocks[(r % rocks.size).toInt()]
val newLayersCount = 3 - towerY + rock.size
addLayers(chamber, newLayersCount)
towerY += newLayersCount
var x = 3
var y = 0
drawRock(chamber, rock, x, y)
while (true) {
val jet = jets[(j++ % jets.length).toInt()]
val dx = if (jet == '<') -1 else 1
if (moveRock(chamber, rock, x, y, dx, 0))
x += dx
if (moveRock(chamber, rock, x, y, 0, 1))
y++
else
break
}
if (y < towerY) {
towerSize += towerY - y
towerY = y
}
while (chamber.size > maxChamberSaveSize) chamber.removeLast()
}
return towerSize
}
val testInput = readFile("Day17_test")
check(part1(testInput) == 3068)
check(part2(testInput) == 1514285714288)
val input = readFile("Day17")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 4,044 | advent-of-code-2022 | Apache License 2.0 |
core/src/main/kotlin/com/malinskiy/marathon/execution/strategy/SortingStrategy.kt | cdsap | 134,924,816 | true | {"Kotlin": 300576, "JavaScript": 33573, "CSS": 29044, "HTML": 2224, "Shell": 964} | package com.malinskiy.marathon.execution.strategy
import com.malinskiy.marathon.analytics.metrics.MetricsProvider
import com.malinskiy.marathon.test.Test
import java.util.Comparator
interface SortingStrategy {
fun process(metricsProvider: MetricsProvider): Comparator<Test>
}
| 1 | Kotlin | 0 | 1 | ce6648774cd47c87f074ebdfdacbbcf781bdfdd4 | 282 | marathon | Apache License 2.0 |
next/kmp/app/electronApp/src/jsMain/kotlin/org.dweb_browser.js_backend/state_compose/autoSyncOperationFromClient.kt | BioforestChain | 594,577,896 | false | {"Kotlin": 3614368, "TypeScript": 823236, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16888, "Shell": 13534, "JavaScript": 4011, "Svelte": 3504, "CSS": 818} | package org.dweb_browser.js_backend.state_compose
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import org.dweb_browser.js_backend.view_model.ViewModelSocket
import org.dweb_browser.js_common.network.socket.SocketData
import org.dweb_browser.js_common.state_compose.ComposeFlow
/**
* 通过从客户端发送过来的操作
*/
fun ComposeFlow.StateComposeFlow<*, *, *>.autoSyncOperationFromClient(
viewModelSocket: ViewModelSocket
) {
viewModelSocket.onData {
val socketData = Json.decodeFromString<SocketData>(it)
console.log("socketData.composeFlowId", socketData.composeFlowId, id)
when (socketData.composeFlowId) {
id -> CoroutineScope(Dispatchers.Default).launch {
val operationValueContainer =
operationFlowCore.serialization.decodeFromString(socketData.data)
console.log(
"emitByClient", operationValueContainer.value, operationValueContainer.emitType
)
emitByClient(operationValueContainer.value, operationValueContainer.emitType)
}
}
}
}
/**
* 通过从客户端发送过来的操作
*/
fun ComposeFlow.ListComposeFlow<*, *, *>.autoSyncOperationFromClient(
viewModelSocket: ViewModelSocket
) {
viewModelSocket.onData {
val socketData = Json.decodeFromString<SocketData>(it)
when (socketData.composeFlowId) {
id -> CoroutineScope(Dispatchers.Default).launch {
val operationValueContainer =
operationFlowCore.serialization.decodeFromString(socketData.data)
emitByClient(operationValueContainer.value, operationValueContainer.emitType)
}
else -> {}
}
}
} | 62 | Kotlin | 4 | 15 | e7525ec3daebda888e462b722625ec004f073ff4 | 1,817 | dweb_browser | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/AnimationNodeOneShot.kt | ShalokShalom | 343,354,086 | true | {"Kotlin": 516486, "GDScript": 294955, "C++": 262753, "C#": 11670, "CMake": 2060, "Shell": 1628, "C": 959, "Python": 75} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName")
package godot
import godot.AnimationNodeOneShot
import godot.annotation.GodotBaseType
import godot.core.TransferContext
import godot.core.VariantType.BOOL
import godot.core.VariantType.DOUBLE
import godot.core.VariantType.JVM_INT
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.util.VoidPtr
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
@GodotBaseType
open class AnimationNodeOneShot : AnimationNode() {
open var autorestart: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_AUTORESTART, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(value) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_AUTORESTART, NIL)
}
open var autorestartDelay: Double
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_AUTORESTART_DELAY, DOUBLE)
return TransferContext.readReturnValue(DOUBLE, false) as Double
}
set(value) {
TransferContext.writeArguments(DOUBLE to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_AUTORESTART_DELAY, NIL)
}
open var autorestartRandomDelay: Double
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_AUTORESTART_RANDOM_DELAY, DOUBLE)
return TransferContext.readReturnValue(DOUBLE, false) as Double
}
set(value) {
TransferContext.writeArguments(DOUBLE to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_AUTORESTART_RANDOM_DELAY, NIL)
}
open var fadeinTime: Double
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_FADEIN_TIME, DOUBLE)
return TransferContext.readReturnValue(DOUBLE, false) as Double
}
set(value) {
TransferContext.writeArguments(DOUBLE to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_FADEIN_TIME, NIL)
}
open var fadeoutTime: Double
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_FADEOUT_TIME, DOUBLE)
return TransferContext.readReturnValue(DOUBLE, false) as Double
}
set(value) {
TransferContext.writeArguments(DOUBLE to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_FADEOUT_TIME, NIL)
}
open var sync: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_SYNC,
BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(value) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_SYNC,
NIL)
}
override fun __new(): VoidPtr =
TransferContext.invokeConstructor(ENGINECLASS_ANIMATIONNODEONESHOT)
open fun getMixMode(): AnimationNodeOneShot.MixMode {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_GET_MIX_MODE,
LONG)
return AnimationNodeOneShot.MixMode.values()[TransferContext.readReturnValue(JVM_INT) as Int]
}
open fun setMixMode(mode: Long) {
TransferContext.writeArguments(LONG to mode)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_ANIMATIONNODEONESHOT_SET_MIX_MODE,
NIL)
}
enum class MixMode(
id: Long
) {
MIX_MODE_BLEND(0),
MIX_MODE_ADD(1);
val id: Long
init {
this.id = id
}
companion object {
fun from(value: Long) = values().single { it.id == value }
}
}
companion object {
final const val MIX_MODE_ADD: Long = 1
final const val MIX_MODE_BLEND: Long = 0
}
}
| 0 | null | 0 | 1 | 7b9b195de5be4a0b88b9831c3a02f9ca06aa399c | 4,618 | godot-jvm | MIT License |
client/src/commonTest/kotlin/com/github/mustafaozhan/ccc/client/viewmodel/CurrenciesViewModelTest.kt | narakai | 343,746,570 | true | {"Kotlin": 235341, "Swift": 40106, "HTML": 797} | /*
* Copyright (c) 2021 <NAME>. All rights reserved.
*/
package com.github.mustafaozhan.ccc.client.viewmodel
import com.github.mustafaozhan.ccc.client.base.BaseViewModelTest
import com.github.mustafaozhan.ccc.client.model.Currency
import com.github.mustafaozhan.ccc.common.di.getDependency
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CurrenciesViewModelTest : BaseViewModelTest<CurrenciesViewModel>() {
override val viewModel: CurrenciesViewModel by lazy {
koin.getDependency(CurrenciesViewModel::class)
}
@Test
fun filterList() {
val euro = Currency("EUR", "Euro", "€")
val dollar = Currency("USD", "American Dollar", "$")
val originalList = mutableListOf<Currency>().apply {
add(euro)
add(dollar)
}
with(viewModel) {
data.unFilteredList = originalList
filterList("USD")
assertTrue(state.value.currencyList.contains(dollar))
data.unFilteredList = originalList
filterList("Euro")
assertTrue(state.value.currencyList.contains(euro))
data.unFilteredList = originalList
filterList("$")
assertTrue(state.value.currencyList.contains(dollar))
data.unFilteredList = originalList
filterList("asdasd")
assertTrue(state.value.currencyList.isEmpty())
data.unFilteredList = originalList
filterList("o")
assertEquals(2, state.value.currencyList.size)
}
}
@Test
fun hideSelectionVisibility() {
viewModel.hideSelectionVisibility()
assertEquals(false, viewModel.state.value.selectionVisibility)
}
@Test
fun queryGetUpdatedOnFilteringList() {
val query = "query"
viewModel.filterList(query)
assertEquals(query, viewModel.data.query)
}
// Event
@Test
fun onItemLongClick() = with(viewModel) {
val currentValue = viewModel.state.value.selectionVisibility
event.onItemLongClick()
assertEquals(!currentValue, viewModel.state.value.selectionVisibility)
}
@Test
fun updateAllCurrenciesState() {
assertEquals(Unit, viewModel.event.updateAllCurrenciesState(true))
assertEquals(Unit, viewModel.event.updateAllCurrenciesState(false))
}
@Test
fun onItemClick() {
val currency = Currency("EUR", "Euro", "€")
assertEquals(Unit, viewModel.event.onItemClick(currency))
}
// @Test
// fun onCloseClick() = runTest {
// viewModel.event.onCloseClick()
// assertEquals(CurrenciesEffect.Back, viewModel.effect.first())
// assertEquals("", viewModel.data.query)
// }
//
// @Test
// fun onDoneClick() = runTest {
// viewModel.event.onDoneClick()
// assertEquals(CurrenciesEffect.FewCurrency, viewModel.effect.first())
// }
}
| 0 | null | 0 | 0 | 7535e4b2a11b10c7ad30ad3d7926a464ded42b3f | 2,944 | CCC | Apache License 2.0 |
sample/src/main/java/com/xavijimenezmulet/shapesforjetpackcompose/ui/screens/AllScreen.kt | xavijimenezmulet | 663,193,932 | false | null | package com.xavijimenezmulet.shapesforjetpackcompose.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xavijimenezmulet.shapesforjetpackcompose.ui.common.Shapes
/**
* @author xavierjimenez
* @since 20/7/23
* @email <EMAIL>
*/
@Composable
fun AllScreen(
paddingValues: PaddingValues,
list: List<Shapes>,
text: String
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = text,
fontWeight = FontWeight.Bold,
fontSize = 30.sp,
color = Color.Black,
textAlign = TextAlign.Center
)
LazyVerticalGrid(
modifier = Modifier
.fillMaxSize(),
columns = GridCells.Fixed(2)
) {
items(list.size) { item ->
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.padding(16.dp)
.size(100.dp)
.clip(list[item].shape)
.background(Color.Red),
contentAlignment = Alignment.Center
) {
Text(
list[item].title,
fontWeight = FontWeight.Bold,
fontSize = list[item].textSize.sp
)
}
}
}
}
}
}
| 0 | Kotlin | 4 | 15 | 77e44f49b8a6672c29fd53e5289d5b806b1bf39c | 2,653 | shapes-for-jetpackcompose | Apache License 2.0 |
src/main/kotlin/cu/suitetecsa/sdk/nauta/ConnectApi.kt | suitetecsa | 489,622,656 | false | {"Kotlin": 116270, "HTML": 37720} | package cu.suitetecsa.sdk.nauta
import cu.suitetecsa.sdk.nauta.core.PortalManager.Connect
import cu.suitetecsa.sdk.nauta.core.PortalManager.User
import cu.suitetecsa.sdk.nauta.core.exceptions.*
import cu.suitetecsa.sdk.nauta.core.extensions.toSeconds
import cu.suitetecsa.sdk.nauta.domain.model.*
import cu.suitetecsa.sdk.nauta.domain.model.Recharge
import cu.suitetecsa.sdk.nauta.domain.model.ResultType.Failure
import cu.suitetecsa.sdk.nauta.domain.model.ResultType.Success
import cu.suitetecsa.sdk.nauta.domain.model.Transfer
import cu.suitetecsa.sdk.nauta.scraper.ConnectPortalScraper
import cu.suitetecsa.sdk.nauta.scraper.ConnectPortalScraperImpl
import cu.suitetecsa.sdk.nauta.scraper.UserPortalScraper
import cu.suitetecsa.sdk.nauta.scraper.UserPortalScrapperImpl
import cu.suitetecsa.sdk.nauta.util.*
import cu.suitetecsa.sdk.network.Action
import cu.suitetecsa.sdk.network.HttpResponse
import cu.suitetecsa.sdk.network.JsoupPortalCommunicator
import cu.suitetecsa.sdk.network.PortalCommunicator
import cu.suitetecsa.sdk.util.ExceptionHandler
import kotlin.math.ceil
import cu.suitetecsa.sdk.nauta.util.Recharge as ActionRecharge
import cu.suitetecsa.sdk.nauta.util.Transfer as ActionTransfer
class ConnectApi(
private val portalCommunicator: PortalCommunicator,
private val connectPortalScraper: ConnectPortalScraper,
private val userPortalCommunicator: PortalCommunicator,
private val userPortalScraper: UserPortalScraper
) {
private var username = ""
private var password = ""
private var actionLogin = ""
private var wlanUserIp = ""
private var csrfHw = ""
private var csrf = ""
private var attributeUUID = ""
private val notLoggedInExceptionHandler = ExceptionHandler
.builder(NotLoggedInException::class.java)
.build()
var isNautaHome: Boolean = false
private set
val isConnected: ResultType<Boolean>
get() {
return portalCommunicator.performAction(CheckConnection()) {
connectPortalScraper.parseCheckConnections(it.text ?: "")
}
}
var dataSession: DataSession = DataSession("", "", "", "")
val remainingTime: ResultType<Long>
get() {
return portalCommunicator.performAction(
LoadUserInformation(
username = username,
wlanUserIp = wlanUserIp,
csrfHw = csrfHw,
attributeUUID = attributeUUID,
portal = Connect
)
) { it.text?.toSeconds() ?: 0L }
}
val connectInformation: ResultType<NautaConnectInformation>
get() {
if (username.isBlank() || password.isBlank()) throw LoginException("username and password are required")
if (csrfHw.isBlank()) init()
return portalCommunicator.performAction(
LoadUserInformation(
username = username,
password = <PASSWORD>,
wlanUserIp = wlanUserIp,
csrfHw = csrfHw,
portal = Connect
)
) {
connectPortalScraper.parseNautaConnectInformation(it.text ?: "")
}
}
private fun init() {
when (val landingResult = portalCommunicator.performAction(CheckConnection()) {
connectPortalScraper.parseActionForm(it.text ?: "")
}) {
is Failure -> throw landingResult.throwable
is Success -> {
val (action, data) = landingResult.result
when (val loginResult = portalCommunicator.performAction(GetPage(action, data)) {
connectPortalScraper.parseActionForm(it.text ?: "")
}) {
is Failure -> throw loginResult.throwable
is Success -> {
val (loginAction, loginData) = loginResult.result
wlanUserIp = data["wlanuserip"] ?: ""
csrfHw = loginData["CSRFHW"] ?: ""
actionLogin = loginAction
}
}
}
}
}
fun setCredentials(username: String, password: String) {
this.username = username
this.password = <PASSWORD>
}
fun connect(): ResultType<String> {
val loginExceptionHandler = ExceptionHandler.builder(LoginException::class.java).build()
when (val it = isConnected) {
is Failure -> return Failure(
loginExceptionHandler.handleException(
"Failed to connect",
listOf(it.throwable.message ?: "")
)
)
is Success -> if (it.result) return Failure(
loginExceptionHandler.handleException(
"Fail to connect",
listOf("Already connected")
)
)
}
if (username.isBlank() || password.isBlank())
return Failure(
loginExceptionHandler.handleException(
"Fail to connect",
listOf("username and password are required")
)
)
init()
portalCommunicator.performAction(
Login(
csrf = csrfHw,
wlanUserIp = wlanUserIp,
username = username,
password = <PASSWORD>,
portal = Connect
)
) {
try {
connectPortalScraper.parseAttributeUUID(it.text ?: "")
} catch (exc: LoadInfoException) {
""
}
}.also {
return when (it) {
is Failure -> return it
is Success -> {
if (it.result.isBlank()) Failure(
loginExceptionHandler.handleException(
"Fail to connect",
listOf("Unknown error")
)
)
else {
dataSession = DataSession(username, csrfHw, wlanUserIp, it.result)
Success("Connected")
}
}
}
}
}
fun disconnect(): ResultType<String> {
val logoutExceptionHandler = ExceptionHandler.builder(LogoutException::class.java).build()
isConnected.also {
when (it) {
is Failure -> return Failure(
logoutExceptionHandler.handleException(
"Failed to disconnect",
listOf(it.throwable.message ?: "Unknown exception")
)
)
is Success -> {
portalCommunicator.performAction(
Logout(
username,
wlanUserIp,
csrfHw,
attributeUUID
)
) { response ->
connectPortalScraper.isSuccessLogout(response.text ?: "")
}.also { logoutResult ->
return when (logoutResult) {
is Failure -> Failure(
logoutExceptionHandler.handleException(
"Failed to disconnect",
listOf(logoutResult.throwable.message ?: "Unknown exception")
)
)
is Success -> if (!logoutResult.result) Failure(
logoutExceptionHandler.handleException(
"Failed to disconnect",
listOf("")
)
)
else {
dataSession = DataSession("", "", "", "")
Success("Disconnected")
}
}
}
}
}
}
}
val captchaImage: ResultType<ByteArray>
get() = userPortalCommunicator.performAction(GetCaptcha) { it.content ?: ByteArray(0) }
val userInformation: ResultType<NautaUser>
get() {
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get user information",
listOf("You are not logged in")
)
return userPortalCommunicator.performAction(LoadUserInformation(portal = User)) {
userPortalScraper.parseNautaUser(it.text ?: "")
}
}
private fun loadCsrf(action: Action) {
when (val csrfResult =
userPortalCommunicator.performAction("https://www.portal.nauta.cu${action.csrfUrl() ?: action.url()}") {
userPortalScraper.parseCsrfToken(it.text ?: "")
}) {
is Failure -> throw csrfResult.throwable
is Success -> {
csrf = userPortalScraper.parseCsrfToken(csrfResult.result)
}
}
}
fun login(captchaCode: String): ResultType<NautaUser> {
val preAction = Login(
username = username,
password = <PASSWORD>,
captchaCode = captchaCode,
portal = User
)
if (csrf.isBlank()) loadCsrf(preAction)
val action =
Login(
csrf = csrf,
username = username,
password = <PASSWORD>,
captchaCode = captchaCode,
portal = User
)
return userPortalCommunicator.performAction(action) {
val user =
userPortalScraper.parseNautaUser(
it.text ?: "",
ExceptionHandler.builder(LoginException::class.java).build()
)
isNautaHome = !user.offer.isNullOrEmpty()
user
}
}
fun topUp(rechargeCode: String): ResultType<NautaUser> {
val preAction = ActionRecharge(rechargeCode = rechargeCode)
if (csrf.isBlank()) return Failure(
notLoggedInExceptionHandler.handleException(
"Failed to top up",
listOf("You are not logged in")
)
)
loadCsrf(preAction)
val action = ActionRecharge(csrf = csrf, rechargeCode = rechargeCode)
return when (val result = userPortalCommunicator.performAction(action) {
userPortalScraper.parseErrors(
it.text ?: "",
"Failed to top up",
ExceptionHandler.builder(RechargeException::class.java).build()
)
}) {
is Failure -> throw result.throwable
is Success -> userInformation
}
}
fun transferFunds(amount: Float, destinationAccount: String?): ResultType<NautaUser> {
val preAction = ActionTransfer(amount = amount, destinationAccount = destinationAccount, password = <PASSWORD>)
if (csrf.isBlank()) return Failure(
notLoggedInExceptionHandler.handleException(
"Failed to transfer funds",
listOf("You are not logged in")
)
)
loadCsrf(preAction)
val action =
ActionTransfer(csrf = csrf, amount = amount, destinationAccount = destinationAccount, password = <PASSWORD>)
return when (val result = userPortalCommunicator.performAction(action) {
userPortalScraper.parseErrors(it.text ?: "")
}) {
is Failure -> throw result.throwable
is Success -> userInformation
}
}
fun changePassword(newPassword: String): ResultType<String> {
val preAction = ChangePassword(
oldPassword = <PASSWORD>,
newPassword = <PASSWORD>
)
if (csrf.isBlank()) return Failure(
notLoggedInExceptionHandler.handleException(
"Failed to change password",
listOf("You are not logged in")
)
)
loadCsrf(preAction)
val action = ChangePassword(
csrf = csrf,
oldPassword = <PASSWORD>,
newPassword = <PASSWORD>
)
return when (val result = userPortalCommunicator.performAction(action) {
userPortalScraper.parseErrors(it.text ?: "")
}) {
is Failure -> throw result.throwable
is Success -> Success(newPassword)
}
}
fun changeEmailPassword(oldPassword: String, newPassword: String): ResultType<String> {
val preAction = ChangePassword(
oldPassword = <PASSWORD>,
newPassword = <PASSWORD>,
changeMail = true
)
if (csrf.isBlank()) return Failure(
notLoggedInExceptionHandler.handleException(
"Failed to change email password",
listOf("You are not logged in")
)
)
loadCsrf(preAction)
val action =
ChangePassword(
csrf = csrf,
oldPassword = <PASSWORD>,
newPassword = <PASSWORD>,
changeMail = true
)
return when (val result = userPortalCommunicator.performAction(action) {
userPortalScraper.parseErrors(it.text ?: "")
}) {
is Failure -> throw result.throwable
is Success -> Success(newPassword)
}
}
fun getConnectionsSummary(year: Int, month: Int): ResultType<ConnectionsSummary> {
val preAction = GetSummary(
year = year,
month = month,
type = ActionType.Connections
)
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get connections summary",
listOf("You are not logged in")
)
loadCsrf(preAction)
val action = GetSummary(
csrf = csrf,
year = year,
month = month,
type = ActionType.Connections
)
return userPortalCommunicator.performAction(action) {
userPortalScraper.parseConnectionsSummary(it.text ?: "")
}
}
fun getRechargesSummary(year: Int, month: Int): ResultType<RechargesSummary> {
val preAction = GetSummary(
year = year,
month = month,
type = ActionType.Recharges
)
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get connections summary",
listOf("You are not logged in")
)
loadCsrf(preAction)
val action = GetSummary(
csrf = csrf,
year = year,
month = month,
type = ActionType.Recharges
)
return userPortalCommunicator.performAction(action) {
userPortalScraper.parseRechargesSummary(it.text ?: "")
}
}
fun getTransfersSummary(year: Int, month: Int): ResultType<TransfersSummary> {
val preAction = GetSummary(
year = year,
month = month,
type = ActionType.Transfers
)
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get transfers summary",
listOf("You are not logged in")
)
loadCsrf(preAction)
val action = GetSummary(
csrf = csrf,
year = year,
month = month,
type = ActionType.Transfers
)
return userPortalCommunicator.performAction(action) {
userPortalScraper.parseTransfersSummary(it.text ?: "")
}
}
fun getQuotesPaidSummary(year: Int, month: Int): ResultType<QuotesPaidSummary> {
val preAction = GetSummary(
year = year,
month = month,
type = ActionType.QuotesPaid
)
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get quotes paid summary",
listOf("You are not logged in")
)
loadCsrf(preAction)
val action = GetSummary(
csrf = csrf,
year = year,
month = month,
type = ActionType.QuotesPaid
)
return userPortalCommunicator.performAction(action) {
userPortalScraper.parseQuotesPaidSummary(it.text ?: "")
}
}
@JvmOverloads
fun getConnections(
connectionsSummary: ConnectionsSummary,
large: Int = 0,
reversed: Boolean = false
): ResultType<List<Connection>> {
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get connections",
listOf("You are not logged in")
)
val internalLarge = if (large == 0) connectionsSummary.count else large
if (connectionsSummary.count != 0) {
val action = GetActions(
connectionsSummary.count,
connectionsSummary.yearMonthSelected,
internalLarge,
reversed,
ActionType.Connections
)
return getActions(action) {
val connects = userPortalScraper.parseConnections(it.text ?: "")
if (reversed) connects.reversed() else connects
}
}
return Success(emptyList())
}
@JvmOverloads
fun getRecharges(
rechargesSummary: RechargesSummary,
large: Int = 0,
reversed: Boolean = false
): ResultType<List<Recharge>> {
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get recharges",
listOf("You are not logged in")
)
val internalLarge = if (large == 0) rechargesSummary.count else large
if (rechargesSummary.count != 0) {
val action = GetActions(
rechargesSummary.count,
rechargesSummary.yearMonthSelected,
internalLarge,
reversed,
ActionType.Connections
)
return getActions(action) {
val recharges = userPortalScraper.parseRecharges(it.text ?: "")
if (reversed) recharges.reversed() else recharges
}
}
return Success(emptyList())
}
@JvmOverloads
fun getTransfers(
transfersSummary: TransfersSummary,
large: Int = 0,
reversed: Boolean = false
): ResultType<List<Transfer>> {
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get transfers",
listOf("You are not logged in")
)
val internalLarge = if (large == 0) transfersSummary.count else large
if (transfersSummary.count != 0) {
val action = GetActions(
transfersSummary.count,
transfersSummary.yearMonthSelected,
internalLarge,
reversed,
ActionType.Connections
)
return getActions(action) {
val transfers = userPortalScraper.parseTransfers(it.text ?: "")
if (reversed) transfers.reversed() else transfers
}
}
return Success(emptyList())
}
@JvmOverloads
fun getQuotesPaid(
quotesPaidSummary: QuotesPaidSummary,
large: Int = 0,
reversed: Boolean = false
): ResultType<List<QuotePaid>> {
if (csrf.isBlank()) throw notLoggedInExceptionHandler.handleException(
"Failed to get quotes paid",
listOf("You are not logged in")
)
val internalLarge = if (large == 0) quotesPaidSummary.count else large
if (quotesPaidSummary.count != 0) {
val action = GetActions(
quotesPaidSummary.count,
quotesPaidSummary.yearMonthSelected,
internalLarge,
reversed,
ActionType.Connections
)
return getActions(action) {
val quotesPaid = userPortalScraper.parseQuotesPaid(it.text ?: "")
if (reversed) quotesPaid.reversed() else quotesPaid
}
}
return Success(emptyList())
}
private fun <T> getActions(
action: Action,
transform: (HttpResponse) -> List<T>
): ResultType<List<T>> {
val large = action.large()
val count = action.count()
val reversed = action.reversed()
val yearMonthSelected = action.yearMonthSelected()
val url = action.url()
val actionList = mutableListOf<T>()
val internalLarge = if (large == 0 || large > count) count else large
if (count != 0) {
val totalPages = ceil(count.toDouble() / 14.0).toInt()
var currentPage = if (reversed) totalPages else 1
val rest = if (reversed || currentPage == totalPages) totalPages % 14 else 0
while ((actionList.size - rest) < internalLarge && (currentPage in 1..totalPages)) {
val page = if (currentPage != 1) currentPage else null
val currentUrl = "$url$yearMonthSelected/$count${page?.let { "/$it" } ?: ""}"
when (val result = portalCommunicator.performAction(currentUrl, transform = transform)) {
is Failure -> return Failure(result.throwable)
is Success -> {
actionList.addAll(result.result)
}
}
currentPage += if (reversed) -1 else 1
}
}
return Success(actionList.take(internalLarge))
}
class Builder {
private var portalCommunicator: PortalCommunicator? = null
private var connectPortalScraper: ConnectPortalScraper? = null
private var userPortalCommunicator: PortalCommunicator? = null
private var userPortalScraper: UserPortalScraper? = null
fun connectPortalCommunicator(communicator: PortalCommunicator): Builder {
portalCommunicator = communicator
return this
}
fun connectPortalScraper(scraper: ConnectPortalScraper): Builder {
connectPortalScraper = scraper
return this
}
fun userPortalCommunicator(communicator: PortalCommunicator): Builder {
userPortalCommunicator = communicator
return this
}
fun userPortalScraper(scraper: UserPortalScraper): Builder {
userPortalScraper = scraper
return this
}
fun build(): ConnectApi {
return ConnectApi(
portalCommunicator = portalCommunicator ?: JsoupPortalCommunicator.Builder().build(),
connectPortalScraper = connectPortalScraper ?: ConnectPortalScraperImpl.builder().build(),
userPortalCommunicator = userPortalCommunicator ?: JsoupPortalCommunicator.Builder().build(),
userPortalScraper = userPortalScraper ?: UserPortalScrapperImpl()
)
}
}
companion object {
fun builder(): Builder {
return Builder()
}
}
} | 1 | Kotlin | 1 | 6 | 6d921c163bde8104de4fcfe70f210355f7cda5e7 | 23,467 | suitetecsa-sdk-kotlin | MIT License |
drm-backend/src/main/kotlin/moe/_47saikyo/drm/backend/dao/impl/UserDaoImpl.kt | Smileslime47 | 738,883,139 | false | {"Kotlin": 243069, "Vue": 73384, "Java": 49135, "TypeScript": 25030, "Solidity": 18621, "CSS": 1622, "Dockerfile": 774, "Shell": 511, "HTML": 390} | package moe._47saikyo.drm.backend.dao.impl
import moe._47saikyo.drm.backend.dao.UserDao
import moe._47saikyo.drm.backend.mapper.UserTable
import moe._47saikyo.drm.core.domain.User
import org.jetbrains.exposed.exceptions.ExposedSQLException
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.transaction
/**
* UserDao实现
*
* @author 刘一邦
* @since 2024/01/20
*/
class UserDaoImpl : UserDao {
override suspend fun getUser(where: SqlExpressionBuilder.() -> Op<Boolean>): User? =
transaction { UserTable.select(where).map(UserTable::resultRowToUser).singleOrNull() }
override suspend fun getUsers(): List<User> =
transaction { UserTable.selectAll().map(UserTable::resultRowToUser) }
override suspend fun insertUser(user: User): User? =
transaction {
try {
UserTable.insert(UserTable.getStatementBinder(user)).resultedValues?.singleOrNull()
?.let(UserTable::resultRowToUser)
} catch (e: ExposedSQLException) {
null
}
}
override suspend fun updateUser(user: User): Boolean =
transaction { UserTable.update({ UserTable.id eq user.id }, null, UserTable.getStatementBinder(user)) > 0 }
override suspend fun deleteUser(user: User): Boolean =
transaction { UserTable.deleteWhere { id eq user.id } > 0 }
} | 0 | Kotlin | 0 | 4 | e0053b3b1e81e049c6869e4a0f52bfdfb2bcbacb | 1,444 | Digital-Rights-Management | MIT License |
components/src/main/java/dev/medzik/android/components/ui/LoadingIndicator.kt | M3DZIK | 698,762,035 | false | {"Kotlin": 92610} | package dev.medzik.android.components.ui
import androidx.compose.animation.core.*
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* Loading indicator that animates three dots in a row.
*
* @param animating whether the indicator should be animating.
* @param modifier the [Modifier] to be applied to the indicator
* @param color the [Color] of the dots
* @param indicatorSpacing spacing between the dots
*/
@Composable
fun LoadingIndicator(
animating: Boolean,
modifier: Modifier = Modifier,
color: Color = MaterialTheme.colorScheme.primary,
indicatorSpacing: Dp = 4.dp
) {
val animatedValues =
List(3) { index ->
var animatedValue by remember(animating) { mutableFloatStateOf(0f) }
LaunchedEffect(animating) {
if (animating) {
animate(
initialValue = 8 / 2f,
targetValue = -8 / 2f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = 300),
repeatMode = RepeatMode.Reverse,
initialStartOffset = StartOffset(300 / 3 * index)
)
) { value, _ -> animatedValue = value }
}
}
animatedValue
}
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically
) {
animatedValues.forEach { animatedValue ->
LoadingDot(
modifier = Modifier
.padding(horizontal = indicatorSpacing)
.width(8.dp)
.aspectRatio(1f)
.offset(y = animatedValue.dp),
color = color
)
}
}
}
@Preview
@Composable
fun LoadingIndicatorPreview() {
LoadingIndicator(
animating = true,
modifier = Modifier.padding(8.dp)
)
}
| 1 | Kotlin | 0 | 1 | d3d214c4532be17e523cc9bf9ccb9cd4337ca51e | 2,276 | android-utils | MIT License |
app/src/main/kotlin/com/kondenko/pocketwaka/screens/main/MainActivity.kt | mezentsev | 139,961,954 | true | {"Kotlin": 113269, "Java": 828, "Makefile": 168} | package com.kondenko.pocketwaka.screens.main
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.kondenko.pocketwaka.R
import com.kondenko.pocketwaka.screens.auth.AuthActivity
import com.kondenko.pocketwaka.screens.stats.FragmentStats
import com.kondenko.pocketwaka.utils.report
import com.kondenko.pocketwaka.utils.transaction
import io.reactivex.subjects.PublishSubject
import org.koin.android.ext.android.inject
class MainActivity : AppCompatActivity(), MainView {
private val tagStats = "stats"
private val presenter: MainActivityPresenter by inject()
private val refreshEvents = PublishSubject.create<Any>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onStart() {
super.onStart()
presenter.attach(this)
}
override fun onStop() {
presenter.detach()
super.onStop()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main_activity_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_logout -> presenter.logout()
R.id.action_refresh -> refreshEvents.onNext(Any())
}
return super.onOptionsItemSelected(item)
}
override fun showLoginScreen() {
val intent = Intent(this, AuthActivity::class.java)
startActivity(intent)
finish()
}
override fun showStats() {
val statsFragment = FragmentStats()
statsFragment.subscribeToRefreshEvents(refreshEvents)
setFragment(statsFragment, tagStats)
}
override fun showError(throwable: Throwable?, messageStringRes: Int?) {
throwable?.report()
Toast.makeText(this, R.string.error_refreshing_token, Toast.LENGTH_LONG).show()
}
override fun onLogout() {
finish()
startActivity(Intent(this, AuthActivity::class.java))
}
private fun setFragment(fragment: Fragment, tag: String) {
if (supportFragmentManager.findFragmentByTag(tag) == null) {
supportFragmentManager.transaction {
replace(R.id.container, fragment, tag)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 5461af8f58ccd5aee8a8e70c4bccdf8013f5a7d3 | 2,497 | pocketwaka | MIT License |
libs/pandautils/src/main/java/com/instructure/pandautils/features/calendar/BaseCalendarFragment.kt | instructure | 179,290,947 | false | {"Kotlin": 16415961, "Dart": 4454406, "HTML": 185120, "Ruby": 35686, "Java": 24752, "Shell": 19157, "Groovy": 11717, "JavaScript": 9505, "Objective-C": 7431, "Python": 2438, "CSS": 1356, "Swift": 807, "Dockerfile": 112} | /*
* Copyright (C) 2024 - present Instructure, 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.
*/
@file:OptIn(ExperimentalFoundationApi::class)
package com.instructure.pandautils.features.calendar
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.instructure.canvasapi2.utils.pageview.PageView
import com.instructure.interactions.FragmentInteractions
import com.instructure.interactions.Navigation
import com.instructure.interactions.router.Route
import com.instructure.pandautils.R
import com.instructure.pandautils.analytics.SCREEN_VIEW_CALENDAR
import com.instructure.pandautils.analytics.ScreenView
import com.instructure.pandautils.features.calendar.composables.CalendarScreen
import com.instructure.pandautils.features.calendar.filter.CalendarFilterFragment
import com.instructure.pandautils.features.inbox.list.filter.ContextFilterFragment
import com.instructure.pandautils.interfaces.NavigationCallbacks
import com.instructure.pandautils.utils.ThemePrefs
import com.instructure.pandautils.utils.ViewStyler
import com.instructure.pandautils.utils.collectOneOffEvents
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
@ScreenView(SCREEN_VIEW_CALENDAR)
@PageView(url = "calendar")
class CalendarFragment : Fragment(), NavigationCallbacks, FragmentInteractions {
private val viewModel: CalendarViewModel by viewModels()
@Inject
lateinit var sharedViewModel: CalendarSharedEvents
@Inject
lateinit var calendarRouter: CalendarRouter
@OptIn(ExperimentalFoundationApi::class)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
applyTheme()
viewLifecycleOwner.lifecycleScope.collectOneOffEvents(viewModel.events, ::handleAction)
viewLifecycleOwner.lifecycleScope.collectOneOffEvents(sharedViewModel.events, ::handleSharedViewModelAction)
return ComposeView(requireActivity()).apply {
setContent {
val uiState by viewModel.uiState.collectAsState()
val actionHandler = { action: CalendarAction -> viewModel.handleAction(action) }
CalendarScreen(title(), uiState, actionHandler) {
calendarRouter.openNavigationDrawer()
}
}
}
}
private fun handleAction(action: CalendarViewModelAction) {
when (action) {
is CalendarViewModelAction.OpenAssignment -> calendarRouter.openAssignment(action.canvasContext, action.assignmentId)
is CalendarViewModelAction.OpenDiscussion -> calendarRouter.openDiscussion(action.canvasContext, action.discussionId)
is CalendarViewModelAction.OpenQuiz -> calendarRouter.openQuiz(action.canvasContext, action.htmlUrl)
is CalendarViewModelAction.OpenCalendarEvent -> calendarRouter.openCalendarEvent(action.canvasContext, action.eventId)
is CalendarViewModelAction.OpenToDo -> calendarRouter.openToDo(action.plannerItem)
is CalendarViewModelAction.OpenCreateToDo -> calendarRouter.openCreateToDo(action.initialDateString)
CalendarViewModelAction.OpenFilters -> {
val calendarFilterFragment = CalendarFilterFragment.newInstance()
calendarFilterFragment.show(requireActivity().supportFragmentManager, ContextFilterFragment::javaClass.name)
}
is CalendarViewModelAction.OpenCreateEvent -> calendarRouter.openCreateEvent(action.initialDateString)
}
}
private fun handleSharedViewModelAction(action: SharedCalendarAction) {
when (action) {
is SharedCalendarAction.RefreshDays -> action.days.forEach {
viewModel.handleAction(CalendarAction.RefreshDay(it))
}
is SharedCalendarAction.RefreshCalendar -> viewModel.handleAction(CalendarAction.RefreshCalendar)
is SharedCalendarAction.FiltersClosed -> {
applyTheme()
if (action.changed) {
viewModel.handleAction(CalendarAction.FiltersRefreshed)
}
}
else -> {}
}
}
override val navigation: Navigation?
get() = activity as? Navigation
override fun title(): String = getString(R.string.calendar)
override fun applyTheme() {
ViewStyler.setStatusBarDark(requireActivity(), ThemePrefs.primaryColor)
calendarRouter.attachNavigationDrawer()
}
override fun getFragment(): Fragment? {
return this
}
override fun onHandleBackPressed(): Boolean {
return false
}
companion object {
fun newInstance(route: Route) = CalendarFragment()
fun makeRoute() = Route(CalendarFragment::class.java, null)
}
} | 7 | Kotlin | 98 | 127 | ca6e2aeaeedb851003af5497e64c22e02dbf0db8 | 5,752 | canvas-android | Apache License 2.0 |
app/src/main/java/xyz/sachil/essence/fragment/vh/NoMoreStateViewHolder.kt | sachil | 52,771,681 | false | null | package xyz.sachil.essence.fragment.vh
import androidx.recyclerview.widget.RecyclerView
import xyz.sachil.essence.databinding.RecyclerItemStateNoMoreBinding
class NoMoreStateViewHolder(private val viewBinding: RecyclerItemStateNoMoreBinding) :
RecyclerView.ViewHolder(viewBinding.root) {
companion object {
const val ITEM_TYPE_STATE_NO_MORE = 0x02
}
} | 0 | Kotlin | 0 | 0 | ae80cdd14529844cbb539ffe01edddd3e6c696a7 | 373 | Essence | Apache License 2.0 |
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/UserLock.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.fontawesomeicons.solid
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 compose.icons.fontawesomeicons.SolidGroup
public val SolidGroup.UserLock: ImageVector
get() {
if (_userLock != null) {
return _userLock!!
}
_userLock = Builder(name = "UserLock", defaultWidth = 640.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 640.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(224.0f, 256.0f)
arcTo(128.0f, 128.0f, 0.0f, true, false, 96.0f, 128.0f)
arcToRelative(128.0f, 128.0f, 0.0f, false, false, 128.0f, 128.0f)
close()
moveTo(320.0f, 320.0f)
arcToRelative(63.08f, 63.08f, 0.0f, false, true, 8.1f, -30.5f)
curveToRelative(-4.8f, -0.5f, -9.5f, -1.5f, -14.5f, -1.5f)
horizontalLineToRelative(-16.7f)
arcToRelative(174.08f, 174.08f, 0.0f, false, true, -145.8f, 0.0f)
horizontalLineToRelative(-16.7f)
arcTo(134.43f, 134.43f, 0.0f, false, false, 0.0f, 422.4f)
lineTo(0.0f, 464.0f)
arcToRelative(48.0f, 48.0f, 0.0f, false, false, 48.0f, 48.0f)
horizontalLineToRelative(280.9f)
arcToRelative(63.54f, 63.54f, 0.0f, false, true, -8.9f, -32.0f)
close()
moveTo(608.0f, 288.0f)
horizontalLineToRelative(-32.0f)
verticalLineToRelative(-80.0f)
arcToRelative(80.0f, 80.0f, 0.0f, false, false, -160.0f, 0.0f)
verticalLineToRelative(80.0f)
horizontalLineToRelative(-32.0f)
arcToRelative(32.0f, 32.0f, 0.0f, false, false, -32.0f, 32.0f)
verticalLineToRelative(160.0f)
arcToRelative(32.0f, 32.0f, 0.0f, false, false, 32.0f, 32.0f)
horizontalLineToRelative(224.0f)
arcToRelative(32.0f, 32.0f, 0.0f, false, false, 32.0f, -32.0f)
lineTo(640.0f, 320.0f)
arcToRelative(32.0f, 32.0f, 0.0f, false, false, -32.0f, -32.0f)
close()
moveTo(496.0f, 432.0f)
arcToRelative(32.0f, 32.0f, 0.0f, true, true, 32.0f, -32.0f)
arcToRelative(32.0f, 32.0f, 0.0f, false, true, -32.0f, 32.0f)
close()
moveTo(528.0f, 288.0f)
horizontalLineToRelative(-64.0f)
verticalLineToRelative(-80.0f)
arcToRelative(32.0f, 32.0f, 0.0f, false, true, 64.0f, 0.0f)
close()
}
}
.build()
return _userLock!!
}
private var _userLock: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,395 | compose-icons | MIT License |
idea/tests/testData/quickfix/inlineClassConstructorNotValParameter/var.kt | JetBrains | 278,369,660 | false | null | // "Change to val" "true"
inline class Foo(<caret>var x: Int) | 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 61 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/luckyweather/android/LuckyWeatherApplication.kt | Luke-chu | 513,820,778 | false | null | package com.luckyweather.android
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
/**
* 由于从ViewModel层开始就不再持有Activity的引用了,因此经常会出现“缺Context”的情况
* 可以用如下技术,给LuckyWeather提供一种全局获取Context的方式
*/
class LuckyWeatherApplication: Application() {
companion object{
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
//在彩云天气获取到的令牌
const val TOKEN = "bv7oPkU410u9RSwZ"
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
} | 1 | Kotlin | 0 | 0 | 284fd96d312ecbb286dda87bf0e4dec76fba2afe | 566 | LuckyWeather | Apache License 2.0 |
app/src/main/java/com/matrix/autoreply/ui/adapters/ContactMessageAdapter.kt | it5prasoon | 373,158,816 | false | null | package com.matrix.autoreply.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.matrix.autoreply.databinding.MessageItemBinding
import java.text.SimpleDateFormat
import java.util.*
class ContactMessageAdapter :
ListAdapter<Pair<String?, Long>, ContactMessageAdapter.MessageViewHolder>(MessageDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
val binding = MessageItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MessageViewHolder(binding)
}
override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
val message = getItem(position)
holder.bind(message)
}
inner class MessageViewHolder(private val binding: MessageItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(message: Pair<String?, Long>) {
binding.messageTextView.text = message.first
binding.timestamp.text = convertTimestampToTime(message.second)
}
}
private class MessageDiffCallback : DiffUtil.ItemCallback<Pair<String?, Long>>() {
override fun areItemsTheSame(oldItem: Pair<String?, Long>, newItem: Pair<String?, Long>): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Pair<String?, Long>, newItem: Pair<String?, Long>): Boolean {
return oldItem == newItem
}
}
private fun convertTimestampToTime(timestamp: Long): String {
val date = Date(timestamp)
val dateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
return dateFormat.format(date)
}
}
| 0 | Kotlin | 5 | 25 | 166387e95ab95924f0515d4326c57fc7f10e611c | 1,847 | Auto-Reply-Android | MIT License |
app/src/main/java/com/nicoapps/cooktime/ui/screens/recipe/edit/appbar/ViewRecipeAppBottomBarActions.kt | andremn | 758,641,451 | false | {"Kotlin": 185045} | package com.nicoapps.cooktime.ui.screens.recipe.edit.appbar
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.nicoapps.cooktime.ui.components.recipe.StarredRecipeIcon
import com.nicoapps.cooktime.ui.defaultTransitionSpec
@Composable
fun ViewRecipeAppBottomBarActions(
modifier: Modifier = Modifier,
isEditing: Boolean,
isStarred: Boolean,
onEditClick: () -> Unit,
onDeleteClick: () -> Unit,
onStarClick: () -> Unit,
onEditDoneClick: () -> Unit,
onEditCancelClick: () -> Unit
) {
AnimatedContent(
targetState = isEditing,
label = "viewRecipeAppBottomBarActionsAnimation",
transitionSpec = { defaultTransitionSpec() }
) { editing ->
Row(
modifier = modifier
) {
if (editing) {
IconButton(
onClick = { onEditDoneClick() }
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = "Localized description"
)
}
IconButton(
onClick = { onEditCancelClick() }
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Localized description"
)
}
} else {
IconButton(onClick = { onEditClick() }) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = "Localized description",
)
}
IconButton(onClick = { onDeleteClick() }) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Localized description",
)
}
IconButton(
onClick = { onStarClick() }) {
StarredRecipeIcon(
isStarred = isStarred
)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 389af6b6dffccd88ddbf4a434a090fa7c1a65e6a | 2,611 | cooktime | MIT License |
foodbanks/src/main/java/com/yuriisurzhykov/foodbanks/di/data/FavoritesModule.kt | yuriisurzhykov | 524,002,724 | false | {"Kotlin": 274520, "Java": 1023} | package com.yuriisurzhykov.foodbanks.di.data
import com.yuriisurzhykov.foodbanks.data.favorites.FavoriteCacheDataStore
import com.yuriisurzhykov.foodbanks.data.favorites.FavoritesDao
import com.yuriisurzhykov.foodbanks.data.favorites.FavoritesRepository
import com.yuriisurzhykov.foodbanks.data.favorites.PointToFavoriteMapper
import com.yuriisurzhykov.foodbanks.data.point.cache.PointsCacheDataSource
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class FavoritesModule {
@Provides
@Singleton
fun provideFavoriteCacheDataStore(dao: FavoritesDao): FavoriteCacheDataStore {
return FavoriteCacheDataStore.Base(dao)
}
@Provides
@Singleton
fun provideFavoritesRepository(
mapper: PointToFavoriteMapper,
cache: PointsCacheDataSource,
favoriteCache: FavoriteCacheDataStore,
favoritesDao: FavoritesDao
): FavoritesRepository {
return FavoritesRepository.Base(
mapper, cache, favoriteCache, favoritesDao
)
}
} | 1 | Kotlin | 0 | 2 | f9b12ffa6dafe283dc8738e7f0eeb0328f7f547b | 1,160 | PointDetector | MIT License |
app/src/main/java/com/example/foodike/presentation/home/components/FoodikeBottomNavigation.kt | gautam84 | 528,051,224 | false | {"Kotlin": 259631} | /**
*
* MIT License
*
* Copyright (c) 2023 Gautam Hazarika
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**/
package com.example.foodike.presentation.home.components
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.contentColorFor
import androidx.compose.material.primarySurface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun FoodikeBottomNavigation(
modifier: Modifier = Modifier,
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
elevation: Dp = BottomNavigationDefaults.Elevation,
content: @Composable RowScope.() -> Unit
) {
Surface(
color = backgroundColor,
contentColor = contentColor,
elevation = elevation,
modifier = modifier,
shape = RoundedCornerShape(percent = 50)
) {
Row(
Modifier
// .fillMaxWidth()
.height(BottomNavigationHeight)
.selectableGroup(),
horizontalArrangement = Arrangement.SpaceBetween,
content = content
)
}
}
object BottomNavigationDefaults {
val Elevation = 8.dp
}
private val BottomNavigationHeight = 56.dp | 0 | Kotlin | 6 | 36 | 333eacf966eef7e04cad88277d1d2221ca80f77e | 2,621 | Foodike | MIT License |
common/src/commonMain/kotlin/com/artemchep/keyguard/common/service/justgetmydata/impl/JustGetMyDataServiceImpl.kt | AChep | 669,697,660 | false | {"Kotlin": 5516822, "HTML": 45876} | package com.artemchep.keyguard.common.service.justgetmydata.impl
import arrow.core.partially1
import com.artemchep.keyguard.common.io.attempt
import com.artemchep.keyguard.common.io.bind
import com.artemchep.keyguard.common.io.effectMap
import com.artemchep.keyguard.common.io.sharedSoftRef
import com.artemchep.keyguard.common.model.FileResource
import com.artemchep.keyguard.common.service.justgetmydata.JustGetMyDataService
import com.artemchep.keyguard.common.service.justgetmydata.JustGetMyDataServiceInfo
import com.artemchep.keyguard.common.service.text.TextService
import com.artemchep.keyguard.common.service.text.readFromResourcesAsText
import com.artemchep.keyguard.common.service.tld.TldService
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.kodein.di.DirectDI
import org.kodein.di.instance
@Serializable
data class JustGetMyDataEntity(
val name: String,
@SerialName("domains")
val domains: Set<String> = emptySet(),
val url: String? = null,
val difficulty: String? = null,
val notes: String? = null,
val email: String? = null,
@SerialName("email_subject")
val emailSubject: String? = null,
@SerialName("email_body")
val emailBody: String? = null,
)
fun JustGetMyDataEntity.toDomain(
additionalDomain: String?,
) = kotlin.run {
val newDomains = if (additionalDomain != null) {
domains + additionalDomain
} else {
domains
}
JustGetMyDataServiceInfo(
name = name,
domains = newDomains,
url = url,
difficulty = difficulty,
notes = notes,
email = email,
emailSubject = emailSubject,
emailBody = emailBody,
)
}
class JustGetMyDataServiceImpl(
private val textService: TextService,
private val tldService: TldService,
private val json: Json,
) : JustGetMyDataService {
companion object {
private const val TAG = "JustGetMyDataService"
}
private val hostRegex = "://(.*@)?([^/]+)".toRegex()
private val listIo = ::loadJustGetMyDataRawData
.partially1(textService)
.effectMap { jsonString ->
val entities = json.decodeFromString<List<JustGetMyDataEntity>>(jsonString)
val models = entities
.map { entity ->
val host = entity.url
?.let { url ->
val result = hostRegex.find(url)
result?.groupValues?.getOrNull(2) // get the host
}
val domain = host?.let {
tldService.getDomainName(host)
.attempt()
.bind()
.getOrNull()
}
entity.toDomain(
additionalDomain = domain,
)
}
models
}
.sharedSoftRef(TAG)
constructor(
directDI: DirectDI,
) : this(
textService = directDI.instance(),
tldService = directDI.instance(),
json = directDI.instance(),
)
override fun get() = listIo
}
private suspend fun loadJustGetMyDataRawData(
textService: TextService,
) = textService.readFromResourcesAsText(FileResource.justGetMyData)
| 66 | Kotlin | 31 | 995 | 557bf42372ebb19007e3a8871e3f7cb8a7e50739 | 3,378 | keyguard-app | Linux Kernel Variant of OpenIB.org license |
module_mine/src/main/java/com/yang/module_mine/repository/MineRepository.kt | jlglyyx | 517,636,450 | false | null | package com.yang.module_mine.repository
import com.yang.lib_common.base.repository.BaseRepository
import com.yang.lib_common.remote.di.response.MResult
import com.yang.lib_common.room.entity.UserInfoData
import com.yang.module_mine.api.MineApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
/**
* @ClassName: Repository
* @Description:
* @Author: yxy
* @Date: 2022/7/14 11:36
*/
class MineRepository @Inject constructor(private val mainApi: MineApi) :BaseRepository(){
suspend fun getA():String{
return withContext(Dispatchers.IO) {
mainApi.getA()
}
}
suspend fun getUserInfo(id:String): MResult<UserInfoData> {
return withContextIO {
mainApi.getUserInfo(id)
}
}
} | 0 | Kotlin | 0 | 0 | 54160737d8ce5b9f0755837a50da101ccce24e5b | 802 | SHelp | Apache License 2.0 |
playground/sandbox-compose/src/main/kotlin/com/sdds/playground/sandbox/textfield/TextFieldDefaults.kt | salute-developers | 765,665,583 | false | {"Kotlin": 1537506} | package com.sdds.playground.sandbox.textfield
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.shape.CornerBasedShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.sdds.compose.uikit.CoreTextField
import com.sdds.compose.uikit.CoreTextField.HelperTextPosition
import com.sdds.compose.uikit.CoreTextField.LabelPosition
import com.sdds.compose.uikit.ScrollBarConfig
import com.sdds.compose.uikit.adjustBy
import com.sdds.playground.sandbox.chip.SandboxEmbeddedChip
import com.sdds.playground.sandbox.textfield.SandboxTextField.InputState
import com.sdds.playground.sandbox.tokens.compose.StylesSaluteTheme
/**
* Цвета текстового поля
*/
@Stable
internal interface SandboxTextFieldColors {
/**
* Цвет значения текстового поля
*
* @param state состояние текстового поля
* @param isClear текстовое поле с фоном или без фона
*/
@Composable
fun valueColor(state: InputState, isClear: Boolean): State<Color>
/**
* Цвет контента в начале
*
* @param state состояние текстового поля
* @param isClear текстовое поле с фоном или без фона
*/
@Composable
fun startContentColor(state: InputState, isClear: Boolean): State<Color>
/**
* Цвет фона текстового поля
*
* @param state состояние текстового поля
*/
@Composable
fun backgroundColor(state: InputState): State<Color>
/**
* Цвет разделителя текстового поля в состоянии без фона
*
* @param state состояние текстового поля
*/
@Composable
fun dividerColor(state: InputState): State<Color>
/**
* Цвет заглушки текстового поля
*
* @param state состояние текстового поля
* @param isClear текстовое поле с фоном или без фона
*/
@Composable
fun placeholderColor(state: InputState, isClear: Boolean): State<Color>
/**
* Цвет лейбла текстового поля
*
* @param state состояние текстового поля
* @param type тип лейбла
*/
@Composable
fun labelColor(state: InputState, type: LabelPosition): State<Color>
/**
* Цвет иконки в начале текстового поля
*
* @param state состояние текстового поля
*/
@Composable
fun leadingIconColor(state: InputState): State<Color>
/**
* Цвет иконки в конце текстового поля
*
* @param state состояние текстового поля
*/
@Composable
fun trailingIconColor(state: InputState, disabledAlpha: Float): State<Color>
/**
* Цвет подписи текстового поля
*
* @param state состояние текстового поля
*/
@Composable
fun captionColor(state: InputState): State<Color>
@Composable
fun optionalColor(): State<Color>
/**
* Цвет курсора текстового поля
*
* @param state состояние текстового поля
*/
@Composable
fun cursorColor(state: InputState): State<Color>
}
/**
* Текстовые стили поля
*/
@Stable
internal interface SandboxTextFieldStyles {
/**
* Текстовый стиль внешнего лейбла
* @param size размер текстового поля
* @param colors цвета текстового поля
* @param inputState состояние текстового поля
*/
@Composable
fun outerLabelStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
): State<TextStyle>
@Composable
fun outerOptionalStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
): State<TextStyle>
/**
* Текстовый стиль внутреннего лейбла
* @param size размер текстового поля
* @param inputState cостояние текстового поля
* @param isEmpty true, если поле пустое
* @param colors цвета текстового поля
*/
@Composable
fun innerLabelStyle(
size: SandboxTextField.Size,
inputState: InputState,
isEmpty: Boolean,
colors: SandboxTextFieldColors,
): State<TextStyle>
@Composable
fun innerOptionalStyle(
size: SandboxTextField.Size,
inputState: InputState,
isEmpty: Boolean,
colors: SandboxTextFieldColors,
): State<TextStyle>
/**
* Текстовый стиль значения поля
* @param size размер текстового поля
* @param colors цвета текстового поля
* @param inputState состояние текстового поля
* @param isClear текстовое поле с фоном или без фона
*/
@Composable
fun valueStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
isClear: Boolean,
): State<TextStyle>
/**
* Текстовый стиль подписи поля
* @param size размер текстового поля
* @param colors цвета текстового поля
* @param inputState состояние текстового поля
*/
@Composable
fun captionStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
): State<TextStyle>
@Composable
fun counterStyle(
size: SandboxTextField.Size,
): State<TextStyle>
/**
* Текстовый стиль заглушки поля
* @param size размер текстового поля
* @param colors цвета текстового поля
* @param inputState состояние текстового поля
* @param isClear текстовое поле с фоном или без фона
*/
@Composable
fun placeholderStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
isClear: Boolean,
): State<TextStyle>
}
/**
* Значения по-умолчанию текстового поля
*/
@Immutable
internal object TextFieldDefaults {
@Composable
fun scrollBarConfig(isClear: Boolean): ScrollBarConfig? =
if (isClear) {
null
} else {
ScrollBarConfig(
indicatorThickness = 1.dp,
indicatorColor = StylesSaluteTheme.colors.surfaceDefaultTransparentTertiary,
backgroundColor = StylesSaluteTheme.colors.surfaceDefaultTransparentPrimary,
padding = PaddingValues(top = 18.dp, end = 2.dp, bottom = 36.dp),
)
}
@Composable
fun fieldAppearance(
isClear: Boolean,
colors: SandboxTextFieldColors,
inputState: InputState,
size: SandboxTextField.Size,
hasDivider: Boolean,
): CoreTextField.FieldAppearance {
return if (!isClear) {
CoreTextField.FieldAppearance.Solid(
backgroundColor = colors.backgroundColor(state = inputState).value,
shape = textFieldShapeFor(size),
)
} else {
CoreTextField.FieldAppearance.Clear(
dividerColor = if (hasDivider) {
colors.dividerColor(inputState).value
} else {
Color.Transparent
},
dividerThickness = 1.dp,
)
}
}
@Composable
fun SandboxTextField.FieldType.toFieldType(
labelPosition: LabelPosition,
position: CoreTextField.DotBadge.Position,
hasLabel: Boolean,
optionalText: String,
size: SandboxTextField.Size,
fieldAppearance: CoreTextField.FieldAppearance,
): CoreTextField.FieldType {
return when (this) {
SandboxTextField.FieldType.Optional -> CoreTextField.FieldType.Optional(
optionalText = optionalText,
)
SandboxTextField.FieldType.Required -> CoreTextField.FieldType.Required(
dotBadge = dotBadge(labelPosition, position, hasLabel, size, fieldAppearance),
)
}
}
@Composable
private fun dotBadge(
labelPosition: LabelPosition,
position: CoreTextField.DotBadge.Position,
hasLabel: Boolean,
size: SandboxTextField.Size,
fieldAppearance: CoreTextField.FieldAppearance,
): CoreTextField.DotBadge {
return when {
labelPosition == LabelPosition.Outer && hasLabel -> {
val horizontalPadding: Dp
val verticalPadding: Dp
if (position == CoreTextField.DotBadge.Position.Start) {
horizontalPadding = 6.dp
verticalPadding = 0.dp
} else {
horizontalPadding = 4.dp
verticalPadding = if (size == SandboxTextField.Size.XS) 2.dp else 4.dp
}
CoreTextField.DotBadge(
size = 6.dp,
color = StylesSaluteTheme.colors.surfaceDefaultNegative,
position = position,
horizontalPadding = horizontalPadding,
verticalPadding = verticalPadding,
)
}
fieldAppearance is CoreTextField.FieldAppearance.Clear -> {
CoreTextField.DotBadge(
size = if (size == SandboxTextField.Size.S || size == SandboxTextField.Size.XS) {
6.dp
} else {
8.dp
},
color = StylesSaluteTheme.colors.surfaceDefaultNegative,
position = position,
horizontalPadding = if (size == SandboxTextField.Size.XS) {
4.dp
} else {
6.dp
},
)
}
else -> CoreTextField.DotBadge(
size = if (size == SandboxTextField.Size.S || size == SandboxTextField.Size.XS) {
6.dp
} else {
8.dp
},
color = StylesSaluteTheme.colors.surfaceDefaultNegative,
position = position,
)
}
}
fun chipSize(size: SandboxTextField.Size): SandboxEmbeddedChip.Size {
return when (size) {
SandboxTextField.Size.L -> SandboxEmbeddedChip.Size.L
SandboxTextField.Size.M -> SandboxEmbeddedChip.Size.M
SandboxTextField.Size.S -> SandboxEmbeddedChip.Size.S
SandboxTextField.Size.XS -> SandboxEmbeddedChip.Size.XS
}
}
@Composable
fun chipContainerShape(size: SandboxTextField.Size): CornerBasedShape {
return when (size) {
SandboxTextField.Size.L -> StylesSaluteTheme.shapes.roundS
SandboxTextField.Size.M -> StylesSaluteTheme.shapes.roundXs
SandboxTextField.Size.S -> StylesSaluteTheme.shapes.roundXxs
SandboxTextField.Size.XS -> StylesSaluteTheme.shapes.roundXxs.adjustBy(all = (-2).dp)
}
}
fun chipHeight(size: SandboxTextField.Size): Dp {
return when (size) {
SandboxTextField.Size.L -> SandboxEmbeddedChip.Size.L.height
SandboxTextField.Size.M -> SandboxEmbeddedChip.Size.M.height
SandboxTextField.Size.S -> SandboxEmbeddedChip.Size.S.height
SandboxTextField.Size.XS -> SandboxEmbeddedChip.Size.XS.height
}
}
fun boxMinHeight(size: SandboxTextField.Size): Dp {
return when (size) {
SandboxTextField.Size.L -> 56.dp
SandboxTextField.Size.M -> 48.dp
SandboxTextField.Size.S -> 40.dp
SandboxTextField.Size.XS -> 32.dp
}
}
fun coreTextFieldPaddings(
size: SandboxTextField.Size,
labelPosition: LabelPosition,
helperTextPosition: HelperTextPosition,
singleLine: Boolean,
isClear: Boolean,
): CoreTextField.Paddings {
return CoreTextField.Paddings(
boxPaddingStart = startContentPadding(size, isClear),
boxPaddingEnd = endContentPadding(size, isClear),
boxPaddingTop = textTopPadding(size, labelPosition),
boxPaddingBottom = textBottomPadding(size, labelPosition, singleLine, isClear),
labelPadding = if (labelPosition == LabelPosition.Outer) {
outerLabelBottomPadding(size, isClear)
} else {
innerLabelToValuePadding(size)
},
helperTextPadding = if (helperTextPosition == HelperTextPosition.Outer || isClear) {
helperTextTopOuterPadding(size)
} else {
helperTextInnerTopPadding(size)
},
optionalPadding = 4.dp,
startContentEndPadding = startIconMargin(size),
endContentStartPadding = endIconMargin(size),
chipsPadding = 6.dp,
chipsSpacing = 2.dp,
keepDotBadgeStartPadding = null,
)
}
private fun textTopPadding(size: SandboxTextField.Size, labelPosition: LabelPosition): Dp {
return if (labelPosition == LabelPosition.Inner) {
when (size) {
SandboxTextField.Size.L -> 9.dp
SandboxTextField.Size.M -> 6.dp
SandboxTextField.Size.S -> 4.dp
SandboxTextField.Size.XS -> 8.dp
}
} else {
when (size) {
SandboxTextField.Size.L -> 16.dp
SandboxTextField.Size.M -> 12.dp
SandboxTextField.Size.S -> 8.dp
SandboxTextField.Size.XS -> 8.dp
}
}
}
private fun textBottomPadding(
size: SandboxTextField.Size,
labelPosition: LabelPosition,
singleLine: Boolean,
isClear: Boolean,
): Dp {
return if (singleLine || isClear) {
singleLineTextTopPadding(size, labelPosition)
} else {
when (size) {
SandboxTextField.Size.L -> 12.dp
SandboxTextField.Size.M -> 12.dp
SandboxTextField.Size.S -> 12.dp
SandboxTextField.Size.XS -> 8.dp
}
}
}
private fun singleLineTextTopPadding(
size: SandboxTextField.Size,
labelPosition: LabelPosition,
): Dp {
return if (labelPosition == LabelPosition.Inner) {
when (size) {
SandboxTextField.Size.L -> 9.dp
SandboxTextField.Size.M -> 6.dp
SandboxTextField.Size.S -> 4.dp
SandboxTextField.Size.XS -> 8.dp
}
} else {
when (size) {
SandboxTextField.Size.L -> 16.dp
SandboxTextField.Size.M -> 12.dp
SandboxTextField.Size.S -> 8.dp
SandboxTextField.Size.XS -> 8.dp
}
}
}
private fun startIconMargin(size: SandboxTextField.Size): Dp =
when (size) {
SandboxTextField.Size.L -> 8.dp
SandboxTextField.Size.M -> 6.dp
SandboxTextField.Size.S -> 4.dp
SandboxTextField.Size.XS -> 4.dp
}
private fun endIconMargin(size: SandboxTextField.Size): Dp =
when (size) {
SandboxTextField.Size.L -> 10.dp
SandboxTextField.Size.M -> 8.dp
SandboxTextField.Size.S -> 6.dp
SandboxTextField.Size.XS -> 4.dp
}
private fun startContentPadding(size: SandboxTextField.Size, isClear: Boolean): Dp =
if (isClear) {
0.dp
} else {
when (size) {
SandboxTextField.Size.L -> 16.dp
SandboxTextField.Size.M -> 14.dp
SandboxTextField.Size.S -> 12.dp
SandboxTextField.Size.XS -> 8.dp
}
}
private fun endContentPadding(size: SandboxTextField.Size, isClear: Boolean): Dp =
if (isClear) {
0.dp
} else {
when (size) {
SandboxTextField.Size.L -> 16.dp
SandboxTextField.Size.M -> 14.dp
SandboxTextField.Size.S -> 12.dp
SandboxTextField.Size.XS -> 8.dp
}
}
private fun innerLabelToValuePadding(size: SandboxTextField.Size): Dp =
when (size) {
SandboxTextField.Size.L,
SandboxTextField.Size.M,
-> 2.dp
SandboxTextField.Size.S,
SandboxTextField.Size.XS,
-> 0.dp
}
private fun outerLabelBottomPadding(size: SandboxTextField.Size, isClear: Boolean): Dp =
if (isClear) {
when (size) {
SandboxTextField.Size.L -> 4.dp
SandboxTextField.Size.M -> 4.dp
SandboxTextField.Size.S -> 4.dp
SandboxTextField.Size.XS -> 2.dp
}
} else {
when (size) {
SandboxTextField.Size.L -> 12.dp
SandboxTextField.Size.M -> 10.dp
SandboxTextField.Size.S -> 8.dp
SandboxTextField.Size.XS -> 6.dp
}
}
private fun helperTextTopOuterPadding(size: SandboxTextField.Size): Dp =
when (size) {
SandboxTextField.Size.L,
SandboxTextField.Size.M,
SandboxTextField.Size.S,
SandboxTextField.Size.XS,
-> 4.dp
}
private fun helperTextInnerTopPadding(size: SandboxTextField.Size): Dp =
when (size) {
SandboxTextField.Size.L,
SandboxTextField.Size.M,
SandboxTextField.Size.S,
-> 12.dp
SandboxTextField.Size.XS -> 8.dp
}
@Composable
fun iconSize(size: SandboxTextField.Size): Dp =
when (size) {
SandboxTextField.Size.L,
SandboxTextField.Size.M,
SandboxTextField.Size.S,
-> 24.dp
SandboxTextField.Size.XS -> 16.dp
}
/**
* Цветовые настройки поля
*/
@Composable
fun textFieldColors(): SandboxTextFieldColors = DefaultSandboxTextFieldColors()
/**
* Текстовые стили поля
*/
@Composable
fun textFieldStyles(): SandboxTextFieldStyles = DefaultSandboxTextFieldStyles()
/**
* Форма в зависимости от размера поля [SandboxTextField.Size]
*/
@Composable
fun textFieldShapeFor(size: SandboxTextField.Size) = when (size) {
SandboxTextField.Size.XS -> StylesSaluteTheme.shapes.roundS
SandboxTextField.Size.S -> StylesSaluteTheme.shapes.roundM.adjustBy(all = (-2).dp)
SandboxTextField.Size.M -> StylesSaluteTheme.shapes.roundM
SandboxTextField.Size.L -> StylesSaluteTheme.shapes.roundM.adjustBy(all = 2.dp)
}
}
@Immutable
private class DefaultSandboxTextFieldColors : SandboxTextFieldColors {
@Composable
override fun leadingIconColor(state: InputState): State<Color> {
return rememberUpdatedState(StylesSaluteTheme.colors.textDefaultSecondary)
}
@Composable
override fun trailingIconColor(state: InputState, disabledAlpha: Float): State<Color> {
var color = StylesSaluteTheme.colors.textDefaultSecondary
if (state == InputState.ReadOnly) {
color = color.copy(alpha = color.alpha * disabledAlpha)
}
return rememberUpdatedState(color)
}
@Composable
override fun backgroundColor(state: InputState): State<Color> {
val surfaceAlpha = if (isSystemInDarkTheme()) 0.12f else 0.06f
val readOnlyAlpha = if (isSystemInDarkTheme()) 0.02f else 0.01f
val color = when (state) {
InputState.Normal -> StylesSaluteTheme.colors.surfaceDefaultTransparentPrimary
InputState.Focused -> StylesSaluteTheme.colors.surfaceDefaultTransparentSecondary
InputState.Error -> StylesSaluteTheme.colors.surfaceDefaultNegative.copy(alpha = surfaceAlpha)
InputState.Warning -> StylesSaluteTheme.colors.surfaceDefaultWarning.copy(alpha = surfaceAlpha)
InputState.Success -> StylesSaluteTheme.colors.surfaceDefaultPositive.copy(alpha = surfaceAlpha)
InputState.ReadOnly -> StylesSaluteTheme.colors.surfaceDefaultSolidDefault.copy(alpha = readOnlyAlpha)
}
return rememberUpdatedState(color)
}
@Composable
override fun dividerColor(state: InputState): State<Color> {
val color = when (state) {
InputState.Normal -> StylesSaluteTheme.colors.surfaceDefaultTransparentTertiary
InputState.Focused -> StylesSaluteTheme.colors.surfaceDefaultAccent
InputState.Error -> StylesSaluteTheme.colors.surfaceDefaultNegative
InputState.Warning -> StylesSaluteTheme.colors.surfaceDefaultWarning
InputState.Success -> StylesSaluteTheme.colors.surfaceDefaultPositive
InputState.ReadOnly -> StylesSaluteTheme.colors.surfaceDefaultTransparentPrimary
}
return rememberUpdatedState(color)
}
@Composable
override fun placeholderColor(state: InputState, isClear: Boolean): State<Color> {
return rememberUpdatedState(
if (state == InputState.Focused) {
StylesSaluteTheme.colors.textDefaultTertiary
} else {
if (isClear) {
when (state) {
InputState.Error -> StylesSaluteTheme.colors.textDefaultNegative
InputState.Warning -> StylesSaluteTheme.colors.textDefaultWarning
InputState.Success -> StylesSaluteTheme.colors.textDefaultPositive
else -> StylesSaluteTheme.colors.textDefaultSecondary
}
} else {
StylesSaluteTheme.colors.textDefaultSecondary
}
},
)
}
@Composable
override fun labelColor(state: InputState, type: LabelPosition): State<Color> {
val color = when (type) {
LabelPosition.Outer -> textFieldTextColor(state = state)
LabelPosition.Inner -> StylesSaluteTheme.colors.textDefaultSecondary
}
return rememberUpdatedState(color)
}
@Composable
override fun valueColor(state: InputState, isClear: Boolean): State<Color> {
return if (isClear) {
rememberUpdatedState(
when (state) {
InputState.Error -> StylesSaluteTheme.colors.textDefaultNegative
InputState.Warning -> StylesSaluteTheme.colors.textDefaultWarning
InputState.Success -> StylesSaluteTheme.colors.textDefaultPositive
else -> textFieldTextColor(state)
},
)
} else {
rememberUpdatedState(textFieldTextColor(state = state))
}
}
@Composable
override fun startContentColor(state: InputState, isClear: Boolean): State<Color> {
return if (isClear) {
rememberUpdatedState(
when (state) {
InputState.Error -> StylesSaluteTheme.colors.surfaceDefaultNegative
InputState.Warning -> StylesSaluteTheme.colors.surfaceDefaultWarning
InputState.Success -> StylesSaluteTheme.colors.surfaceDefaultPositive
else -> StylesSaluteTheme.colors.textDefaultSecondary
},
)
} else {
rememberUpdatedState(StylesSaluteTheme.colors.textDefaultSecondary)
}
}
@Composable
override fun cursorColor(state: InputState): State<Color> {
return rememberUpdatedState(StylesSaluteTheme.colors.textDefaultAccent)
}
@Composable
override fun captionColor(state: InputState): State<Color> {
val color = when (state) {
InputState.Normal,
InputState.Focused,
InputState.ReadOnly,
-> StylesSaluteTheme.colors.textDefaultSecondary
InputState.Error -> StylesSaluteTheme.colors.textDefaultNegative
InputState.Warning -> StylesSaluteTheme.colors.textDefaultWarning
InputState.Success -> StylesSaluteTheme.colors.textDefaultPositive
}
return rememberUpdatedState(newValue = color)
}
@Composable
override fun optionalColor(): State<Color> {
return rememberUpdatedState(StylesSaluteTheme.colors.textDefaultTertiary)
}
@Composable
private fun textFieldTextColor(state: InputState) = when (state) {
InputState.ReadOnly -> StylesSaluteTheme.colors.textDefaultSecondary
InputState.Normal,
InputState.Focused,
InputState.Error,
InputState.Warning,
InputState.Success,
-> StylesSaluteTheme.colors.textDefaultPrimary
}
}
@Immutable
private class DefaultSandboxTextFieldStyles : SandboxTextFieldStyles {
@Composable
override fun outerLabelStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
): State<TextStyle> {
return rememberUpdatedState(
textFieldTextStyle(size).copy(
color = colors.labelColor(
state = inputState,
type = LabelPosition.Outer,
).value,
),
)
}
@Composable
override fun outerOptionalStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
): State<TextStyle> {
return rememberUpdatedState(
textFieldTextStyle(size).copy(
color = colors.optionalColor().value,
),
)
}
@Composable
override fun innerLabelStyle(
size: SandboxTextField.Size,
inputState: InputState,
isEmpty: Boolean,
colors: SandboxTextFieldColors,
): State<TextStyle> {
val style =
when (size) {
SandboxTextField.Size.XS -> StylesSaluteTheme.typography.bodyXxsNormal
SandboxTextField.Size.S -> StylesSaluteTheme.typography.bodyXsNormal
SandboxTextField.Size.M -> StylesSaluteTheme.typography.bodyXsNormal
SandboxTextField.Size.L -> StylesSaluteTheme.typography.bodyXsNormal
}
return rememberUpdatedState(
style.copy(
color = colors.labelColor(
state = inputState,
type = LabelPosition.Inner,
).value,
),
)
}
@Composable
override fun innerOptionalStyle(
size: SandboxTextField.Size,
inputState: InputState,
isEmpty: Boolean,
colors: SandboxTextFieldColors,
): State<TextStyle> {
val style =
when (size) {
SandboxTextField.Size.XS -> StylesSaluteTheme.typography.bodyXxsNormal
SandboxTextField.Size.S -> StylesSaluteTheme.typography.bodyXsNormal
SandboxTextField.Size.M -> StylesSaluteTheme.typography.bodyXsNormal
SandboxTextField.Size.L -> StylesSaluteTheme.typography.bodyXsNormal
}
return rememberUpdatedState(
style.copy(
color = colors.optionalColor().value,
),
)
}
@Composable
override fun valueStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
isClear: Boolean,
): State<TextStyle> {
return rememberUpdatedState(
textFieldTextStyle(size).copy(
color = colors.valueColor(inputState, isClear).value,
),
)
}
@Composable
override fun captionStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
): State<TextStyle> {
return rememberUpdatedState(
StylesSaluteTheme.typography.bodyXsNormal.copy(
color = colors.captionColor(inputState).value,
),
)
}
@Composable
override fun counterStyle(size: SandboxTextField.Size): State<TextStyle> {
return rememberUpdatedState(
StylesSaluteTheme.typography.bodyXsNormal.copy(
color = StylesSaluteTheme.colors.textDefaultSecondary,
),
)
}
@Composable
override fun placeholderStyle(
size: SandboxTextField.Size,
colors: SandboxTextFieldColors,
inputState: InputState,
isClear: Boolean,
): State<TextStyle> {
return rememberUpdatedState(
textFieldTextStyle(size).copy(
color = colors.placeholderColor(inputState, isClear).value,
),
)
}
@Composable
private fun textFieldTextStyle(size: SandboxTextField.Size) = when (size) {
SandboxTextField.Size.XS -> StylesSaluteTheme.typography.bodyXsNormal
SandboxTextField.Size.S -> StylesSaluteTheme.typography.bodySNormal
SandboxTextField.Size.M -> StylesSaluteTheme.typography.bodyMNormal
SandboxTextField.Size.L -> StylesSaluteTheme.typography.bodyLNormal
}
}
| 4 | Kotlin | 0 | 1 | f48c90444d32f4c25e25d87570daba44f6312f35 | 29,181 | plasma-android | MIT License |
feature/customer/src/main/java/com/niyaj/customer/details/CustomerDetailsViewModel.kt | skniyajali | 644,752,474 | false | {"Kotlin": 2194063, "Java": 232} | package com.niyaj.customer.details
import androidx.compose.runtime.snapshotFlow
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.niyaj.data.repository.CustomerRepository
import com.niyaj.model.TotalOrderDetails
import com.niyaj.ui.event.UiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class CustomerDetailsViewModel @Inject constructor(
private val customerRepository: CustomerRepository,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val customerId = savedStateHandle.get<Int>("customerId") ?: 0
private val _totalOrders = MutableStateFlow(TotalOrderDetails())
val totalOrders = _totalOrders.asStateFlow()
val customerDetails = snapshotFlow { customerId }.mapLatest {
val data = customerRepository.getCustomerById(it).data
if (data == null) UiState.Empty else UiState.Success(data)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UiState.Loading
)
val orderDetails = snapshotFlow { customerId }.flatMapLatest { customerId ->
customerRepository.getCustomerWiseOrders(customerId).mapLatest { orders ->
if (orders.isEmpty()) UiState.Empty else {
val startDate = orders.first().updatedAt
val endDate = orders.last().updatedAt
val repeatedOrder = orders.groupingBy { it.customerAddress }
.eachCount()
.filter { it.value > 1 }.size
_totalOrders.value = _totalOrders.value.copy(
totalAmount = orders.sumOf { it.totalPrice },
totalOrder = orders.size,
repeatedOrder = repeatedOrder,
datePeriod = Pair(startDate, endDate)
)
UiState.Success(orders)
}
}
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UiState.Loading
)
} | 21 | Kotlin | 0 | 3 | df479a26e0bcd81549ef13a9f5334c39e52a2d0b | 2,399 | PoposRoom | Apache License 2.0 |
app/src/main/java/com/revolgenx/anilib/data/field/home/DiscoverTrendingMediaField.kt | rev0lgenX | 244,410,204 | false | null | package com.revolgenx.anilib.data.field.home
import android.content.Context
import com.revolgenx.anilib.data.field.media.MediaField
import com.revolgenx.anilib.common.preference.getTrendingField
import com.revolgenx.anilib.common.preference.storeTrendingField
class TrendingMediaField : MediaField() {
override var includeStaff: Boolean = true
override var includeStudio: Boolean = true
companion object {
fun create(context: Context) = getTrendingField(context)
}
fun saveTrendingField(context: Context) {
storeTrendingField(context, this)
}
} | 3 | Kotlin | 1 | 24 | 355d2b5510682d869f18e0113453237af8a1f1cc | 589 | AniLib | Apache License 2.0 |
trade-order-service/src/main/kotlin/com/ash/trading/oms/tradeorder/statemachine/event/RemoveTradeFromTradeOrderEvent.kt | ashfrench | 760,910,146 | false | {"Kotlin": 79793} | package com.ash.trading.oms.tradeorder.statemachine.event
import com.ash.trading.oms.model.OrderId
import com.ash.trading.oms.model.WorkedQuantity
data class RemoveTradeFromTradeOrderEvent(
val orderId: OrderId,
val workedQuantity: WorkedQuantity
): OmsTradeOrderEvent
| 0 | Kotlin | 0 | 0 | 2f013569fced2d98404e8cab8222689309ac8ab0 | 279 | trade-oms | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.