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
shared/src/commonMain/kotlin/com/uteke/kmm/feature/productitem/GetProductCachedUseCase.kt
uteke
466,413,830
false
null
package com.uteke.kmm.feature.productitem import com.uteke.kmm.storage.product.ProductDao import com.uteke.kmm.storage.product.ProductLocalModel import kotlinx.coroutines.flow.* class GetProductCachedUseCase( private val productDao: ProductDao ) : GetProductUseCase { override fun invoke(productId: Int): Flow<ProductModel> = flow { emit(productDao.selectById(id = productId).toProductModel()) }.catch { e -> throw GetProductException( message = e.message, cause = e ) } private fun ProductLocalModel.toProductModel() = ProductModel( id = id, title = title, description = description, kind = kind, type = type, images = images, ingredients = ingredients, allergens = allergens ) }
0
Kotlin
0
0
f69e673d1663d22a8cf0ba63cfb56a1ed85b3deb
863
kmm-application
Apache License 2.0
features/imdbmovie/src/main/java/sourceset564/samples/mvvm/feature/imdbmovie/domain/MovieDashboardContract.kt
Source-Set-564
211,533,076
false
null
package sourceset564.samples.mvvm.feature.imdbmovie.domain import id.nz.app.mvppattern.data.model.Movie import id.nz.template.mvvm.core.BaseUseCase /** * Created by Anwar on 11/22/2019. */ interface MovieDashboardContract{ interface UseCase : BaseUseCase<Contract>{ fun getPopular(page : Int) fun getTopRate(page: Int) } interface Contract{ fun onPopularFetched(list: List<Movie>, currentPage : Int, countPage : Int) fun onPopularError(throwable: Throwable) fun onTopRateFetched(list: List<Movie>, currentPage : Int, countPage: Int) fun onTopRateError(throwable: Throwable) } }
0
Kotlin
0
2
59bb69f0f2e3231064fdb516fe29d18af3e07219
652
Android-MVVM-Sample-Kotlin
MIT License
domain/src/main/java/com/puskal/domain/following/GetContentCreatorsUseCase.kt
puskal-khadka
622,175,439
false
null
package com.puskal.domain.following import com.puskal.data.model.ContentCreatorFollowingModel import com.puskal.data.repository.home.FollowingRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject /** * Created by Puskal Khadka on 3/15/2023. */ class GetContentCreatorsUseCase @Inject constructor(private val followingRepository: FollowingRepository) { operator fun invoke(): Flow<List<ContentCreatorFollowingModel>> { return followingRepository.getContentCreatorForFollowing() } }
0
Kotlin
3
26
e0e3c0f9fae50411b034346a720f276692119a90
520
TikTok-Compose
Apache License 2.0
src/main/java/team/_0mods/ecr/common/particle/ECParticleOptions.kt
0mods
830,371,936
false
{"Kotlin": 207186, "Java": 15587}
package team._0mods.ecr.common.particle import com.mojang.brigadier.StringReader import com.mojang.serialization.Codec import com.mojang.serialization.codecs.RecordCodecBuilder import net.minecraft.core.particles.ParticleOptions import net.minecraft.core.particles.ParticleType import net.minecraft.network.FriendlyByteBuf import net.minecraft.util.Mth import net.minecraftforge.registries.ForgeRegistries import team._0mods.ecr.common.init.registry.ECRegistry import java.awt.Color class ECParticleOptions(val color: Color, size: Float, val lifeTime: Int, val resizeSpeed: Float, val physical: Boolean, val removeOnGround: Boolean): ParticleOptions { companion object { @JvmField val CODEC: Codec<ECParticleOptions> = RecordCodecBuilder.create { it.group( Codec.INT.fieldOf("color").forGetter { t -> t.color.rgb }, Codec.FLOAT.fieldOf("size").forGetter { t -> t.size }, Codec.INT.fieldOf("lifetime").forGetter { t -> t.lifeTime }, Codec.FLOAT.fieldOf("resize_speed").forGetter { t -> t.resizeSpeed }, Codec.BOOL.fieldOf("has_physics").forGetter { t -> t.physical }, Codec.BOOL.fieldOf("remove_on_ground").forGetter { t -> t.removeOnGround } ).apply(it, ::ECParticleOptions) } @JvmField val DESERIALIZER = object : ParticleOptions.Deserializer<ECParticleOptions> { override fun fromCommand( particleType: ParticleType<ECParticleOptions>, reader: StringReader ): ECParticleOptions { reader.expect(' '); val r = Mth.clamp(reader.readInt(), 0, 255) reader.expect(' '); val g = Mth.clamp(reader.readInt(), 0, 255) reader.expect(' '); val b = Mth.clamp(reader.readInt(), 0, 255) reader.expect(' '); val size = Mth.clamp(reader.readFloat(), 0.05f, 5f) reader.expect(' '); val lifeTime = reader.readInt() reader.expect(' '); val resizeSpeed = reader.readFloat() reader.expect(' '); val hasPhysics = reader.readBoolean() reader.expect(' '); val removeOnGround = reader.readBoolean() return ECParticleOptions(Color(r, g, b), size, lifeTime, resizeSpeed, hasPhysics, removeOnGround) } override fun fromNetwork( particleType: ParticleType<ECParticleOptions>, buffer: FriendlyByteBuf ): ECParticleOptions { val r = Mth.clamp(buffer.readInt(), 0, 255) val g = Mth.clamp(buffer.readInt(), 0, 255) val b = Mth.clamp(buffer.readInt(), 0, 255) val color = Color(r, g, b) val size = Mth.clamp(buffer.readFloat(), 0.05f, 5f) val lifeTime = buffer.readInt() val speed = buffer.readFloat() val hasPhysics = buffer.readBoolean() val removeOnGround = buffer.readBoolean() return ECParticleOptions(color, size, lifeTime, speed, hasPhysics, removeOnGround) } } } private constructor(rgb: Int, size: Float, lifeTime: Int, resizeSpeed: Float, physical: Boolean, removeOnGround: Boolean): this(Color(rgb), Mth.clamp(size, 0.05f, 5f), lifeTime, resizeSpeed, physical, removeOnGround) val size = Mth.clamp(size, 0.05f, 5f) override fun getType(): ParticleType<*> = ECRegistry.ecParticle.get() override fun writeToNetwork(buffer: FriendlyByteBuf) { buffer.writeInt(color.red) buffer.writeInt(color.green) buffer.writeInt(color.blue) buffer.writeFloat(size) buffer.writeInt(lifeTime) buffer.writeFloat(resizeSpeed) buffer.writeBoolean(physical) buffer.writeBoolean(removeOnGround) } override fun writeToString(): String = "${ForgeRegistries.PARTICLE_TYPES.getKey(this.type)} ${color.red} ${color.green} ${color.blue} $size $lifeTime $resizeSpeed $physical $removeOnGround" }
0
Kotlin
0
0
03e95d001679b90016ea9420d682bc00c0980110
4,079
ECR
MIT License
src/main/kotlin/de/livepoll/api/repository/OpenTextItemAnswerRepository.kt
livepoll
299,668,765
false
null
package de.livepoll.api.repository import de.livepoll.api.entity.db.OpenTextItemAnswer import org.springframework.data.jpa.repository.JpaRepository import javax.transaction.Transactional @Transactional interface OpenTextItemAnswerRepository : JpaRepository<OpenTextItemAnswer, Long>
8
Kotlin
0
3
82a2413f19ecb26f78e39a1920c79450dc4a62da
285
live-poll-api
MIT License
.legacy/app/src/main/java/com/makentoshe/booruchan/AppFileProvider.kt
Makentoshe
147,361,920
false
null
package com.makentoshe.booruchan import androidx.core.content.FileProvider class AppFileProvider: FileProvider()
0
Kotlin
1
6
d0f40fb8011967e212df1f21beb43e4c4ec03356
115
Booruchan
Apache License 2.0
app/src/main/java/de/schwerin/stoppCoronaDE/model/assets/AssetInteractor.kt
Mandarin-Medien
269,321,452
false
null
package at.roteskreuz.stopcorona.model.assets import at.roteskreuz.stopcorona.model.entities.configuration.ApiConfigurationHolder import at.roteskreuz.stopcorona.model.repositories.FilesRepository import at.roteskreuz.stopcorona.skeleton.core.model.helpers.AppDispatchers import com.squareup.moshi.Moshi import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext /** * Interactor that can load and parse bundled assets. */ interface AssetInteractor { /** * Load configuration from bundled JSON. */ suspend fun configuration(): ApiConfigurationHolder } class AssetInteractorImpl( private val appDispatchers: AppDispatchers, private val moshi: Moshi, private val filesRepository: FilesRepository ) : AssetInteractor, CoroutineScope { override val coroutineContext: CoroutineContext get() = appDispatchers.IO override suspend fun configuration(): ApiConfigurationHolder = loadResourceAsJson("configuration") /** * Load json file with name [name] from raw resources into an object of type [T]. * * @param name file name of the resources (not including the extension (.json) */ @Suppress("BlockingMethodInNonBlockingContext") private suspend inline fun <reified T> loadResourceAsJson(name: String): T { return withContext(coroutineContext) { val json: String = filesRepository.loadRawResource(name) val adapter = moshi.adapter(T::class.java) // We try to load precompiled data. If we failed to provide the right data let it crash! adapter.fromJson(json)!! } } }
0
null
0
1
a8a489c25b55cce8b14d60b9afa3fb44cfecab43
1,677
stopp-corona-de-android
Apache License 2.0
app/src/main/java/co/temy/android/ktx/MetricsExtensions.kt
temyco
241,076,714
false
null
package co.temy.android.ktx import android.content.res.Resources import android.util.DisplayMetrics /** * Converts value in pixels into value in device-independent pixels */ fun Int.toDp(): Int { val metrics = Resources.getSystem().displayMetrics return this / (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT) } /** * Converts value in device-independent pixels into value in pixels */ fun Int.toPx(): Int { val metrics = Resources.getSystem().displayMetrics return this * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT) }
5
Kotlin
0
4
30723fe0b814134a2f4d08d85e601f57f1579d05
556
android-ktx
Apache License 2.0
app-alpha/src/main/java/com/github/uragiristereo/mejiboard/data/model/local/download/DownloadInfo.kt
uragiristereo
406,362,024
false
{"Kotlin": 395562}
package com.github.uragiristereo.mejiboard.data.model.local.download data class DownloadInfo( val progress: Float = 0f, val downloaded: Long = 0L, val length: Long = 0L, var path: String = "", var status: String = "idle" )
2
Kotlin
3
72
6f23178dddf36ed4e9382aeef7bb56114903f443
243
Mejiboard
Apache License 2.0
app/src/main/java/com/perraco/yasc/data/api/Routes.kt
perracodex
714,243,421
false
{"Kotlin": 93043}
/* * Copyright (c) 2024 <NAME>. All rights reserved. * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT> */ package com.perraco.yasc.data.api object Routes { const val BASE_JOKES: String = "https://v2.jokeapi.dev" const val BASE_POSTS: String = "https://jsonplaceholder.typicode.com" const val ALBUMS: String = "/albums" const val PHOTOS: String = "/photos" const val POSTS: String = "/posts" const val COMMENTS: String = "/comments" const val JOKES: String = "/joke/Any" }
0
Kotlin
0
1
a848f4c8ca4bbab2d69c115dfbf0a89782fd5df2
572
yasc
MIT License
app/src/main/java/com/andrewm/weatherornot/data/model/forecast/Forecast.kt
moorea
130,636,872
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 63, "Java": 1, "XML": 20}
package com.andrewm.weatherornot.data.model.forecast import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Forecast : RealmObject() { @PrimaryKey open var zip: String? = null open var latitude: Double? = 0.0 open var longitude: Double? = 0.0 open var timezone: String? = null open var currently: Currently? = null open var minutely: Minutely? = null open var hourly: Hourly? = null open var daily: Daily? = null open var alerts: RealmList<Alert>? = null open var flags: Flags? = null }
0
Kotlin
1
0
3350416caf7cf256238d8f8a15f70e75becb65d8
596
weather-or-not
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageadjudicationsapi/entities/IncidentRole.kt
ministryofjustice
416,301,250
false
{"Kotlin": 1560615, "Dockerfile": 1411}
package uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities import jakarta.persistence.Entity import jakarta.persistence.Table @Entity @Table(name = "incident_role") data class IncidentRole( override val id: Long? = null, var roleCode: String?, var associatedPrisonersNumber: String?, var associatedPrisonersName: String?, ) : BaseEntity()
4
Kotlin
0
3
d58e28afdb2e684b9df9aa28011e8e6e545f67e8
364
hmpps-manage-adjudications-api
MIT License
src/main/kotlin/br/com/zup/controller/ListaChavePixController.kt
jhonyrodrigues
384,222,309
true
{"Kotlin": 28425, "Smarty": 2172, "Dockerfile": 166}
package br.com.zup.controller import br.com.zup.ListaChavesRequest import br.com.zup.PixListaChavesServiceGrpc import br.com.zup.response.ChavePixResponse import io.grpc.StatusRuntimeException import io.micronaut.http.HttpResponse import io.micronaut.http.HttpStatus import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.exceptions.HttpStatusException import org.slf4j.LoggerFactory import java.util.* @Controller("/api/v1/clientes/") class ListaChavePixController(private val listaChaveClient: PixListaChavesServiceGrpc.PixListaChavesServiceBlockingStub) { val LOGGER = LoggerFactory.getLogger(this::class.java) @Get("{clienteId}/pix/") fun lista(clienteId: UUID): HttpResponse<Any> { try { LOGGER.info("[$clienteId] - Listando todas as chaves") val pix = listaChaveClient.lista( ListaChavesRequest.newBuilder().setClienteId(clienteId.toString()).build() ) val chaves = pix.chavesList.map { ChavePixResponse(it) } return HttpResponse.ok(chaves) } catch (e: StatusRuntimeException) { throw HttpStatusException(HttpStatus.NOT_FOUND, "Ocorreu um erro ao litar as chaves") } } }
0
Kotlin
0
0
90299b2a3d62aecafc3f38cdb19164e90bf11682
1,268
orange-talents-05-template-pix-keymanager-rest
Apache License 2.0
src/test/kotlin/it/ldsoftware/k8bit/PCSpec.kt
LukeDS-it
243,369,123
false
null
package it.ldsoftware.k8bit import org.assertj.core.api.Assertions.assertThat import org.junit.Test class PCSpec { @Test fun `jump should move the program counter to the specified memory address`() { val subject = Chip8Processor() subject.jumpa(0x520) assertThat(subject.pc).isEqualTo(0x520) } @Test fun `call should move the pc to the specified memory address, remembering the last location`() { val subject = Chip8Processor() subject.call(0x520) assertThat(subject.pc).isEqualTo(0x520) assertThat(subject.stack[subject.sp - 1]).isEqualTo(0x200) } @Test fun `ret should return the execution to where the program called the subroutine`() { val subject = Chip8Processor() subject.call(0x520) subject.ret() assertThat(subject.pc).isEqualTo(0x200) assertThat(subject.sp).isEqualTo(0) } @Test fun `eq should increment the pc if the condition is true`() { val subject = Chip8Processor() val register = 1 val value = 0x20 subject.v[register] = value val remaining = (register shl 8) or value subject.eq(remaining) assertThat(subject.pc).isEqualTo(0x202) } @Test fun `eq should not increment the pc if the condition is false`() { val subject = Chip8Processor() val register = 1 val value = 0x20 subject.v[register] = value val remaining = register shl 8 or 0x21 subject.eq(remaining) assertThat(subject.pc).isEqualTo(0x200) } @Test fun `neq should increment the pc if the condition is false`() { val subject = Chip8Processor() val register = 1 val value = 0x20 subject.v[register] = value val remaining = (register shl 8) or 0x21 subject.neq(remaining) assertThat(subject.pc).isEqualTo(0x202) } @Test fun `neq should not increment the pc if the condition is true`() { val subject = Chip8Processor() val register = 1 val value = 0x20 subject.v[register] = value val remaining = register shl 8 or value subject.neq(remaining) assertThat(subject.pc).isEqualTo(0x200) } @Test fun `eqreg should increment the pc if the two registers have the same value`() { val subject = Chip8Processor() val reg1 = 1 val reg2 = 2 val value = 0x20 subject.v[reg1] = value subject.v[reg2] = value val remaining = (reg1 shl 8) or (reg2 shl 4) subject.eqreg(remaining) assertThat(subject.pc).isEqualTo(0x202) } @Test fun `eqreg should not increment the pc if the two registers do not have the same value`() { val subject = Chip8Processor() val reg1 = 1 val reg2 = 2 val value = 0x20 subject.v[reg1] = value subject.v[reg2] = 0x21 val remaining = (reg1 shl 8) or (reg2 shl 4) subject.eqreg(remaining) assertThat(subject.pc).isEqualTo(0x200) } @Test fun `neqreg should increment the pc if the two registers do not have the same value`() { val subject = Chip8Processor() val reg1 = 1 val reg2 = 2 val value = 0x20 subject.v[reg1] = value subject.v[reg2] = 0x21 val remaining = (reg1 shl 8) or (reg2 shl 4) subject.neqreg(remaining) assertThat(subject.pc).isEqualTo(0x202) } @Test fun `neqreg should not increment the pc if the two registers have the same value`() { val subject = Chip8Processor() val reg1 = 1 val reg2 = 2 val value = 0x20 subject.v[reg1] = value subject.v[reg2] = value val remaining = (reg1 shl 8) or (reg2 shl 4) subject.neqreg(remaining) assertThat(subject.pc).isEqualTo(0x200) } @Test fun `jumpmem should jump the pc with the given value, plus the value in register v0`() { val subject = Chip8Processor() val value = 0x200 subject.v[0] = 0x10 subject.jumpv(value) assertThat(subject.pc).isEqualTo(0x210) } @Test fun `skipKeyEq should skip next instruction if the key in register x is pressed`() { val subject = Chip8Processor() subject.press(0xF) subject.v[3] = 0xF subject.skipKeyEq(3) assertThat(subject.keys[0xF]).isTrue() assertThat(subject.pc).isEqualTo(0x202) } @Test fun `skipKeyEq should not skip next instruction if the key in register x is not pressed`() { val subject = Chip8Processor() subject.press(0xF) subject.v[3] = 0xF subject.skipKeyEq(2) assertThat(subject.keys[0]).isFalse() assertThat(subject.pc).isEqualTo(0x200) } @Test fun `skipKeyNeq should skip next instruction if the key in register x is not pressed`() { val subject = Chip8Processor() subject.press(0xF) subject.v[3] = 0xF subject.skipKeyNeq(2) assertThat(subject.keys[0xF]).isTrue() assertThat(subject.pc).isEqualTo(0x202) } @Test fun `skipKeyNeq should not skip next instruction if the key in register x is pressed`() { val subject = Chip8Processor() subject.press(0xF) subject.v[3] = 0xF subject.skipKeyNeq(3) assertThat(subject.keys[0]).isFalse() assertThat(subject.pc).isEqualTo(0x200) } @Test fun `skipKeyEq should not skip next instruction if the key in register x was released`() { val subject = Chip8Processor() subject.press(0xF) subject.release(0xF) subject.v[3] = 0xF subject.skipKeyEq(3) assertThat(subject.keys[0xF]).isFalse() assertThat(subject.pc).isEqualTo(0x200) } }
0
Kotlin
0
0
1c710884de68266863a0e10c73da1d4cb890875f
5,914
k8bit
MIT License
kotlin/src/test/kotlin/StatementPrinterTests.kt
khoovirajsingh
207,102,392
true
{"Text": 6, "Ignore List": 6, "Markdown": 3, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Java Properties": 1, "Java": 5, "OpenStep Property List": 4, "Swift": 5, "Objective-C": 1, "XML": 4, "Microsoft Visual Studio Solution": 1, "C#": 5, "INI": 3, "Kotlin": 5, "JSON": 13, "JavaScript": 2, "Jest Snapshot": 1, "Python": 2, "CMake": 2, "C++": 7}
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test class StatementPrinterTests { @Test internal fun exampleStatement() { val expected = "Statement for BigCo\n" + " Hamlet: \$650.00 (55 seats)\n" + " As You Like It: \$580.00 (35 seats)\n" + " Othello: \$500.00 (40 seats)\n" + "Amount owed is \$1,730.00\n" + "You earned 47 credits\n" val plays = mapOf( "hamlet" to Play("Hamlet", "tragedy"), "as-like" to Play("As You Like It", "comedy"), "othello" to Play("Othello", "tragedy") ) val invoice = Invoice( "BigCo", listOf( Performance("hamlet", 55), Performance("as-like", 35), Performance("othello", 40) ) ) val statementPrinter = StatementPrinter() val result = statementPrinter.print(invoice, plays) assertEquals(expected, result) } @Test internal fun statementWithNewPlayTypes() { val plays = mapOf( "henry-v" to Play("Henry V", "history"), "as-like" to Play("As You Like It", "pastoral") ) val invoice = Invoice( "BigCo", listOf( Performance("henry-v", 53), Performance("as-like", 55) ) ) val statementPrinter = StatementPrinter() assertThrows(Error::class.java) { statementPrinter.print(invoice, plays) } } }
0
C#
0
0
b1707bc029872594011a579894e66aee49e488da
1,618
Theatrical-Players-Refactoring-Kata
MIT License
src/commonMain/kotlin/fr/misterassm/kronote/api/adapter/RetrieveAdapter.kt
MisterAssm
373,556,385
false
{"Kotlin": 44558}
package fr.misterassm.kronote.api.adapter interface RetrieveAdapter
2
Kotlin
1
5
b2a9ced647c8e6e0fcf7d2f615a1e6f8e36fa6ee
68
pronote-api
MIT License
app/src/main/java/com/ayoprez/sobuu/ui/theme/Theme.kt
AyoPrez
542,163,912
false
{"Kotlin": 531589}
package com.ayoprez.sobuu.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.ViewCompat import com.google.accompanist.systemuicontroller.rememberSystemUiController private val DarkColorScheme = darkColorScheme( primary = DarkGreenSheen, secondary = LightLava, tertiary = DarkVermilion, background = BlackBlue, ) private val LightColorScheme = lightColorScheme( primary = GreenSheen, secondary = DarkLava, tertiary = Vermilion, background = WhiteBlue, /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun SobuuAuthTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val systemUiController = rememberSystemUiController() val view = LocalView.current val window = (view.context as Activity).window val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } if (!view.isInEditMode) { SideEffect { window.statusBarColor = GreenSheen.toArgb() ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme } } systemUiController.setSystemBarsColor( color = colorScheme.primary ) systemUiController.setNavigationBarColor(color = colorScheme.secondary) MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) } @Composable fun SobuuTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val systemUiController = rememberSystemUiController() val view = LocalView.current val window = (view.context as Activity).window val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } if (!view.isInEditMode) { SideEffect { window.statusBarColor = WhiteBlue.toArgb() //ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme } } systemUiController.isStatusBarVisible = true systemUiController.setStatusBarColor( color = WhiteBlue) systemUiController.setSystemBarsColor( color = GreenSheen, darkIcons = true ) MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
0
Kotlin
0
0
d3d9adb6b69abe87c03d94eefcbeaa1c80708f1f
3,528
sobuu
Apache License 2.0
src/buildings/Buildings.kt
kwiecien
145,902,936
false
null
package buildings open class BaseBuildingMaterial { open val numberNeeded: Int = 1 } class Wood : BaseBuildingMaterial() { override val numberNeeded: Int = 4 } class Brick : BaseBuildingMaterial() { override val numberNeeded: Int = 8 } class Building<out T : BaseBuildingMaterial>(private val buildingMaterial: T) { val baseMaterialsNeeded: Int = 100 val actualMaterialsNeeded: Int = buildingMaterial.numberNeeded * baseMaterialsNeeded fun build() = println(buildingMaterial::class.simpleName + actualMaterialsNeeded) } fun <T : BaseBuildingMaterial> Building<T>.isSmallBuilding() { if (actualMaterialsNeeded < 500) println("Small building") else println("Large building") } fun main(args: Array<String>) { Building(Wood()).build() Building(Brick()).isSmallBuilding() }
0
Kotlin
0
0
5b8d468d7863632f6c3e558e8c0c803e1c85e310
816
kotlin-bootcamp-for-programmers
MIT License
src/main/kotlin/no/nav/k9/los/nyoppgavestyring/query/dto/resultat/Oppgavefeltverdi.kt
navikt
238,874,021
false
{"Kotlin": 1525312, "JavaScript": 741, "Shell": 659, "Dockerfile": 343, "PLpgSQL": 167}
package no.nav.k9.los.nyoppgavestyring.query.dto.resultat class Oppgavefeltverdi( val område: String?, val kode: String, val verdi: Any? )
6
Kotlin
0
0
adda314ccc08fe69764403c8e30478787649500d
151
k9-los-api
MIT License
android/app/src/main/java/com/utn/frba/mobile/regalapp/editItem/EditItem.kt
UTN-FRBA-Mobile
542,387,698
false
null
package com.utn.frba.mobile.regalapp.editItem import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.Button import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.utn.frba.mobile.domain.models.ItemModel import com.utn.frba.mobile.regalapp.R import com.utn.frba.mobile.regalapp.addItem.ItemForm @Composable fun EditItem( item: ItemModel?, onNameChange: (String) -> Unit? = {}, onQuantityChange: (String) -> Unit = {}, onPriceChange: (String) -> Unit = {}, onLocationChange: (String) -> Unit = {}, onCoordinatesChange: (lat: Double, lng: Double) -> Unit = {_,_ ->}, onSaveClicked: (item: ItemModel) -> Unit = {}, isLoading: Boolean = false, ) { if (item != null) { Column() { ItemForm( item = item, onNameChange, onQuantityChange, onPriceChange, onLocationChange, onCoordinatesChange, readOnly = isLoading, ) Spacer(modifier = Modifier.height(20.dp)) Button( onClick = { onSaveClicked(item) }, modifier = Modifier.align(alignment = Alignment.CenterHorizontally) ) { Text(text = stringResource(id = R.string.edit)) } if (isLoading) { CircularProgressIndicator( modifier = Modifier.align(alignment = Alignment.CenterHorizontally) ) } } } }
0
Kotlin
0
1
2addb3960108d9baab9a12eaeb1c4bdcc8e7e4c9
1,912
RegalApp
MIT License
kotlin/api/src/main/kotlin/org/diffkt/external/LibraryUtils.kt
facebookresearch
495,505,391
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package org.diffkt.external internal fun loadLib(name: String) { fun getExtension(name: String): String { val os = System.getProperty("os.name") val ext = if (os.contains("Linux", ignoreCase = true)) { ".so" } else if (os.contains("Darwin", ignoreCase = true)) { ".dylib" } else if (os.contains("Mac OS X", ignoreCase = true)) { // for Github container ".dylib" } else if (os.contains("Windows", ignoreCase = true)) { ".dll" } else ".dylib" // default to a mac return ext } val ext = getExtension(name) val libFileName = "${name}$ext" // code inside the try block is adapted from the accepted answer here: // https://stackoverflow.com/questions/4691095/java-loading-dlls-by-a-relative-path-and-hide-them-inside-a-jar try { val input = Thread.currentThread().contextClassLoader.getResourceAsStream(libFileName) ?: throw RuntimeException("Unable to find $libFileName in resources") val buffer = ByteArray(1024) // We copy the lib to a temp file because we were unable to load the lib directly from within a jar when // using the packaged library. val temp = createTempFile("utils/${name}$ext", "") val fos = temp.outputStream() var read = input.read(buffer) while (read != -1) { fos.write(buffer, 0, read) read = input.read(buffer) } fos.close() input.close() System.load(temp.absolutePath) } catch (e: Exception) { throw RuntimeException("Unable to load lib $libFileName: ${e.message}") } }
62
Jupyter Notebook
3
55
710f403719bb89e3bcf00d72e53313f8571d5230
1,888
diffkt
MIT License
AndroidJava/buildSrc/src/main/kotlin/AppConfiguration.kt
alexandrehtrb
134,422,439
false
{"C#": 11886, "Java": 10340, "Kotlin": 2408}
object AppConfiguration { const val compileSdkVersion = 29 const val buildToolsVersion = "29.0.2" const val minSdkVersion = 14 const val targetSdkVersion = 29 const val versionCode = 1 const val versionName = "1.0.0" const val applicationId = "br.alexandrehtrb.iridescentviewapp" const val testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" }
0
C#
7
20
d287043e9e503c502d628a37fff360e532a8ae45
393
IridescentView
MIT License
app/src/main/java/com/nonetxmxy/mmzqfxy/model/response/BanksResBean.kt
AnFxy
623,415,411
false
null
package com.nonetxmxy.mmzqfxy.model.response data class BanksResBean( val WPGaNatDXD: List<String> )
0
Kotlin
0
0
5fa1b0610746a42a8adad1f7da282842356851d1
106
M22
Apache License 2.0
src/main/kotlin/org/nexial/core/SystemVariables.kt
nexiality
123,623,623
false
{"Gradle": 2, "Java Properties": 10, "Text": 26, "Ignore List": 1, "XML": 36, "Markdown": 2, "Shell": 15, "Batchfile": 16, "Java": 432, "INI": 6, "HTML": 17, "JSON": 39, "SQL": 4, "CSS": 2, "JavaScript": 34, "SVG": 1, "Kotlin": 154}
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nexial.core import org.apache.commons.lang3.BooleanUtils import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.math.NumberUtils import kotlin.streams.toList /** * constants repo. to manage/track system variables */ object SystemVariables { // global defaults, to be registered from the definition of each default values private val SYSVARS = mutableMapOf<String, Any?>() private val SYSVARGROUPS = mutableListOf<String>() @JvmStatic fun registerSysVar(name: String): String { if (StringUtils.isNotBlank(name)) SYSVARS[name] = null return name } @JvmStatic fun <T> registerSysVar(name: String, value: T): String { if (StringUtils.isNotBlank(name)) SYSVARS[name] = value return name } @JvmStatic fun registerSysVarGroup(group: String): String { if (StringUtils.isNotBlank(group) && !SYSVARGROUPS.contains(group)) SYSVARGROUPS.add(group) return group } @JvmStatic fun getDefault(name: String) = if (SYSVARS.containsKey(name)) SYSVARS[name].toString() else null @JvmStatic fun getDefaultBool(name: String): Boolean { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return BooleanUtils.toBoolean(SYSVARS[name].toString()) } @JvmStatic fun getDefaultInt(name: String): Int { require(SYSVARS.containsKey(name)) { "No default value configured for '$name'" } return NumberUtils.toInt(SYSVARS[name].toString()) } @JvmStatic fun getDefaultLong(name: String): Long { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return NumberUtils.toLong(SYSVARS[name].toString()) } @JvmStatic fun getDefaultFloat(name: String): Double { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return NumberUtils.toFloat(SYSVARS[name].toString()).toDouble() } @JvmStatic fun getDefaultDouble(name: String): Double { require(SYSVARS.containsKey(name)) { "No default configured for '$name'" } return NumberUtils.toDouble(SYSVARS[name].toString()) } @JvmStatic fun isRegisteredSysVar(name: String): Boolean { if (SYSVARS.containsKey(name)) return true for (group in SYSVARGROUPS) { if (StringUtils.startsWith(name, group)) return true } return false } @JvmStatic fun listSysVars(): List<String> = SYSVARS.keys.stream().sorted().toList() }
0
JavaScript
0
1
ee16530ba5b223d943790f9c7ba36b5db9676e19
3,191
nexial-incubate
Apache License 2.0
fuzzer/fuzzing_output/crashing_tests/verified/objectInstance.kt-690101051.kt
ItsLastDay
102,885,402
false
null
import kotlin.test.assertEquals object Obj { fun foo() = 1 } class A { companion object { fun foo() = 2 } } class B { companion object Factory { fun foo() = 3 } } class C fun box(): String { assertEquals(1, Obj::class.objectInstance!!.foo()) assertEquals(2, A.Companion::class.objectInstance!!.foo()) assertEquals(3, B.Factory::class.objectInstance!!.foo()) assertEquals(null, (C)?::class.objectInstance) assertEquals(null, String::class.objectInstance) assertEquals(Unit, Unit::class.objectInstance) return "OK" }
1
Kotlin
1
6
bb80db8b1383a6c7f186bea95c53faff4c0e0281
527
KotlinFuzzer
MIT License
app/src/main/java/com/evgtrush/toDoKa/domain/models/ToDoKaItem.kt
AgnaWiese
609,940,705
false
null
/* * Copyright (C) 2023. <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evgtrush.toDoKa.domain.models data class ToDoKaItem( val id: Int = 0, val name: String, val bought: Boolean = false, val toDoKaListId: Int = 0, )
1
Kotlin
0
0
668852a8fd4103d4e18efcebf2078ce05c19788b
771
todoka
Apache License 2.0
core/src/commonTest/kotlin/dev/brella/ktornea/spotify/ListMatchers.kt
UnderMybrella
628,495,061
false
null
package dev.brella.ktornea.spotify import io.kotest.matchers.Matcher import io.kotest.matchers.collections.atLeastSize import io.kotest.matchers.equalityMatcher @Suppress("UNCHECKED_CAST") public fun listShouldMatchExactly(a: Any?): Matcher<List<*>> { val sizeMatcher = atLeastSize<Any?>(1) val matcher = if (a is Matcher<*>) a as Matcher<Any?> else equalityMatcher(a) return Matcher { value -> chainMatcherResults( { sizeMatcher.test(value) }, { matcher.test(value[0]) } ) } } @Suppress("UNCHECKED_CAST") public fun listShouldMatchExactly(a: Any?, b: Any?): Matcher<List<*>> { val sizeMatcher = atLeastSize<Any?>(2) val a = if (a is Matcher<*>) a as Matcher<Any?> else equalityMatcher(a) val b = if (b is Matcher<*>) b as Matcher<Any?> else equalityMatcher(b) return Matcher { value -> chainMatcherResults( { sizeMatcher.test(value) }, { a.test(value[0]) }, { b.test(value[1]) } ) } } @Suppress("UNCHECKED_CAST") public fun listShouldMatchExactly(a: Any?, b: Any?, c: Any?): Matcher<List<*>> { val sizeMatcher = atLeastSize<Any?>(3) val a = if (a is Matcher<*>) a as Matcher<Any?> else equalityMatcher(a) val b = if (b is Matcher<*>) b as Matcher<Any?> else equalityMatcher(b) val c = if (c is Matcher<*>) c as Matcher<Any?> else equalityMatcher(c) return Matcher { value -> chainMatcherResults( { sizeMatcher.test(value) }, { a.test(value[0]) }, { b.test(value[1]) }, { c.test(value[2]) } ) } }
0
Kotlin
0
1
b56c46c58629cf28ca1c14c3529615eed925f625
1,721
ktornea-spotify
MIT License
src/commonMain/kotlin/com/adyen/model/transferwebhooks/Amount.kt
tjerkw
733,432,442
false
{"Kotlin": 5043126, "Makefile": 6356}
/** * Transfer webhooks * * Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds. * * The version of the OpenAPI document: 4 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package com.adyen.model.transferwebhooks import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * * * @param currency The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). * @param `value` The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). */ @Serializable data class Amount ( /* The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). */ @SerialName(value = "currency") @Required val currency: kotlin.String, /* The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). */ @SerialName(value = "value") @Required val `value`: kotlin.Long )
0
Kotlin
0
0
2da5aea5519b2dfa84454fe1665e9699edc87507
1,459
adyen-kotlin-multiplatform-api-library
MIT License
app/src/main/java/com/example/mywaycompose/presentation/ui/screen/edit_main_task/state/MainTaskFieldUIState.kt
larkes-cyber
739,078,285
false
{"Kotlin": 573267}
package com.example.mywaycompose.presentation.ui.screen.edit_main_task.state import android.net.Uri data class MainTaskFieldUIState( val titleField:String = "", val iconField:String = "", val imageSrc:Uri? = null )
0
Kotlin
0
1
b329374b9a5f459e75fb30b7a05a726fce065ceb
228
PlannerApp
Apache License 2.0
app-quality-insights/play-vitals/view/testSrc/com/android/tools/idea/vitals/ui/VitalsConnectionSelectorActionTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.vitals.ui import com.android.tools.idea.insights.Selection import com.android.tools.idea.vitals.TEST_CONNECTION_1 import com.android.tools.idea.vitals.TEST_CONNECTION_2 import com.android.tools.idea.vitals.datamodel.VitalsConnection import com.google.common.truth.Truth.assertThat import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.TestActionEvent.createTestEvent import java.awt.Point import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test class VitalsConnectionSelectorActionTest { @get:Rule val applicationRule = ApplicationRule() @Test fun `action updates title when selection changes`() = runTest { val stateFlow = MutableStateFlow(Selection<VitalsConnection>(null, emptyList())) val action = VitalsConnectionSelectorAction(stateFlow, this, {}, { Point() }) val event = createTestEvent() action.update(event) assertThat(event.presentation.text).isEqualTo("No apps available") stateFlow.value = Selection(TEST_CONNECTION_1, listOf(TEST_CONNECTION_1, TEST_CONNECTION_2)) action.update(event) assertThat(event.presentation.text) .isEqualTo("${TEST_CONNECTION_1.displayName} [${TEST_CONNECTION_1.appId}]") } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,921
android
Apache License 2.0
src/main/java/com/fretron/vehicleManager/di/modules/SchemaModule.kt
Vishal1297
321,992,020
false
{"Kotlin": 34583, "Java": 29047}
package com.fretron.vehicleManager.di.modules import dagger.Module import dagger.Provides import org.codehaus.jackson.map.ObjectMapper import javax.inject.Singleton @Module class SchemaModule { @Singleton @Provides fun providesObjectMapper(): ObjectMapper = ObjectMapper() }
1
Kotlin
2
1
2cfb5253e1ccc347f4c2feb7565163f5b304c1d7
290
vehicle-manager
Creative Commons Zero v1.0 Universal
features/movie/src/main/java/com/andhiratobing/moviecompose/movie/movielist/domain/usecase/MovieUseCaseImpl.kt
andhiratobing
443,302,737
false
{"Kotlin": 69028}
package com.andhiratobing.moviecompose.movie.movielist.domain.usecase import com.andhiratobing.moviecompose.movie.movielist.domain.models.MovieDomain import com.andhiratobing.moviecompose.movie.movielist.domain.repositories.MovieRepository import javax.inject.Inject class MovieUseCaseImpl @Inject constructor( private val movieRepository: MovieRepository ) : MovieUseCase { override fun invoke(): List<MovieDomain> { return movieRepository.getMovieList() } }
0
Kotlin
0
1
05495ac44369f5fa11b3b23236f18b65b2241c62
482
movie-compose
Apache License 2.0
JetNews/app/src/main/java/com/example/jetnews/ui/interests/InterestsScreen.kt
yiflylian
248,149,368
true
{"Kotlin": 107313, "Shell": 1102}
/* * Copyright 2019 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui.interests import androidx.compose.Composable import androidx.compose.remember import androidx.compose.state import androidx.ui.core.Clip import androidx.ui.core.Opacity import androidx.ui.core.Text import androidx.ui.foundation.Box import androidx.ui.foundation.SimpleImage import androidx.ui.foundation.VerticalScroller import androidx.ui.foundation.selection.Toggleable import androidx.ui.foundation.shape.corner.RoundedCornerShape import androidx.ui.layout.Column import androidx.ui.layout.Container import androidx.ui.layout.LayoutGravity import androidx.ui.layout.LayoutPadding import androidx.ui.layout.LayoutSize import androidx.ui.layout.Row import androidx.ui.material.Divider import androidx.ui.material.DrawerState import androidx.ui.material.MaterialTheme import androidx.ui.material.Scaffold import androidx.ui.material.ScaffoldState import androidx.ui.material.Tab import androidx.ui.material.TabRow import androidx.ui.material.TopAppBar import androidx.ui.material.ripple.Ripple import androidx.ui.res.imageResource import androidx.ui.tooling.preview.Preview import androidx.ui.unit.dp import com.example.jetnews.R import com.example.jetnews.data.people import com.example.jetnews.data.publications import com.example.jetnews.data.topics import com.example.jetnews.ui.AppDrawer import com.example.jetnews.ui.JetnewsStatus import com.example.jetnews.ui.Screen import com.example.jetnews.ui.VectorImageButton private enum class Sections(val title: String) { Topics("Topics"), People("People"), Publications("Publications") } @Composable fun InterestsScreen(scaffoldState: ScaffoldState = remember { ScaffoldState() }) { Scaffold( scaffoldState = scaffoldState, drawerContent = { AppDrawer( currentScreen = Screen.Interests, closeDrawer = { scaffoldState.drawerState = DrawerState.Closed } ) }, topAppBar = { TopAppBar( title = { Text("Interests") }, navigationIcon = { VectorImageButton(R.drawable.ic_jetnews_logo) { scaffoldState.drawerState = DrawerState.Opened } } ) }, bodyContent = { val (currentSection, updateSection) = state { Sections.Topics } InterestsScreenBody(currentSection, updateSection) } ) } @Composable private fun InterestsScreenBody( currentSection: Sections, updateSection: (Sections) -> Unit ) { val sectionTitles = Sections.values().map { it.title } Column { TabRow(items = sectionTitles, selectedIndex = currentSection.ordinal) { index, title -> Tab( text = { Text(title) }, selected = currentSection.ordinal == index, onSelected = { updateSection(Sections.values()[index]) }) } Container(modifier = LayoutFlexible(1f)) { when (currentSection) { Sections.Topics -> TopicsTab() Sections.People -> PeopleTab() Sections.Publications -> PublicationsTab() } } } } @Composable private fun TopicsTab() { TabWithSections( "Topics", topics ) } @Composable private fun PeopleTab() { TabWithTopics( Sections.People.title, people ) } @Composable private fun PublicationsTab() { TabWithTopics( Sections.Publications.title, publications ) } @Composable private fun TabWithTopics(tabName: String, topics: List<String>) { VerticalScroller { Column(modifier = LayoutPadding(top = 16.dp)) { topics.forEach { topic -> TopicItem( getTopicKey( tabName, "- ", topic ), topic ) TopicDivider() } } } } @Composable private fun TabWithSections( tabName: String, sections: Map<String, List<String>> ) { VerticalScroller { Column { sections.forEach { (section, topics) -> Text( text = section, modifier = LayoutPadding(16.dp), style = (MaterialTheme.typography()).subtitle1) topics.forEach { topic -> TopicItem( getTopicKey( tabName, section, topic ), topic ) TopicDivider() } } } } } @Composable private fun TopicItem(topicKey: String, itemTitle: String) { val image = imageResource(R.drawable.placeholder_1_1) Ripple(bounded = true) { val selected = isTopicSelected(topicKey) val onSelected = { it: Boolean -> selectTopic(topicKey, it) } Toggleable(selected, onSelected) { // TODO(b/150060763): Remove box after "Bug in ripple + modifiers." Box { Row( modifier = LayoutPadding(start = 16.dp, top = 0.dp, end = 16.dp, bottom = 0.dp) ) { Container(modifier = LayoutGravity.Center + LayoutSize(56.dp, 56.dp)) { Clip(RoundedCornerShape(4.dp)) { SimpleImage(image = image) } } Text( text = itemTitle, modifier = LayoutFlexible(1f) + LayoutGravity.Center + LayoutPadding(16.dp), style = (MaterialTheme.typography()).subtitle1 ) SelectTopicButton( modifier = LayoutGravity.Center, selected = selected ) } } } } } @Composable private fun TopicDivider() { Opacity(0.08f) { Divider(LayoutPadding(start = 72.dp, top = 8.dp, end = 0.dp, bottom = 8.dp)) } } private fun getTopicKey(tab: String, group: String, topic: String) = "$tab-$group-$topic" private fun isTopicSelected(key: String) = JetnewsStatus.selectedTopics.contains(key) private fun selectTopic(key: String, select: Boolean) { if (select) { JetnewsStatus.selectedTopics.add(key) } else { JetnewsStatus.selectedTopics.remove(key) } } @Preview @Composable fun PreviewInterestsScreen() { InterestsScreen() } @Preview @Composable private fun PreviewDrawerOpen() { InterestsScreen(scaffoldState = ScaffoldState(drawerState = DrawerState.Opened)) } @Preview @Composable fun PreviewTopicsTab() { TopicsTab() } @Preview @Composable fun PreviewPeopleTab() { PeopleTab() } @Preview @Composable fun PreviewTabWithTopics() { TabWithTopics(tabName = "preview", topics = listOf("Hello", "Compose")) }
0
null
0
1
ed00fb1f7657c74d82f4f6180c30ae6fbea42c1f
7,734
compose-samples
Apache License 2.0
app/src/main/java/com/edgar/movie/demo/widget/CustomDialog.kt
edgardeng
267,626,303
false
null
import android.app.Dialog import android.content.Context import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.Gravity import android.view.View import android.view.WindowManager import android.widget.TextView import com.edgar.movie.R class CustomDialog : Dialog, View.OnClickListener { constructor(context: Context) : super(context) constructor(context: Context, themeResId: Int) : super(context, themeResId) private var mTvTitle: TextView? = null private var mTvMessage: TextView? = null private var mTvCancel: TextView? = null private var mTvConfirm: TextView? = null private var title: String? = null private var message: String? = null private var cancel: String? = null private var confirm: String? = null private var cancelListener: IOnCancelListener? = null private var confirmListener: IOnConfirmListener? = null; private var height = 0 fun setTitle(t: String) { this.title = t } fun setMessage(t: String) { this.message = t } fun setCancel(cancel: String, listener: IOnCancelListener) { this.cancel = cancel; this.cancelListener = listener; } fun setConfirm( confirm: String, listener: IOnConfirmListener) { this.confirm = confirm; this.confirmListener = listener; } override fun onCreate(savedInstanceState: Bundle?) { Log.e("CustomDialog","onCreate") super.onCreate(savedInstanceState); setContentView(R.layout.v_demo_dialog_custom) mTvTitle = findViewById<TextView>(R.id.tv_dialog_custom_title); mTvMessage = findViewById<TextView>(R.id.tv_dialog_custom_message); mTvCancel = findViewById<TextView>(R.id.tv_dialog_custom_cancel); mTvConfirm = findViewById<TextView>(R.id.tv_dialog_custom_confirm); if (!TextUtils.isEmpty(title)) { mTvTitle?.setText(title); } if (!TextUtils.isEmpty(message)) { mTvMessage?.setText(message); } if (!TextUtils.isEmpty(cancel)) { mTvCancel?.setText(cancel); } if (!TextUtils.isEmpty(confirm)) { mTvConfirm?.setText(confirm); } mTvCancel?.setOnClickListener(this); mTvConfirm?.setOnClickListener(this); } override fun show() { window!!.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) window!!.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) if (height == 0){ window!!.attributes.height = 320 } else { window!!.attributes.height = height } window!!.attributes.width = 320 window!!.setGravity(Gravity.CENTER) super.show() } override fun onClick(v: View) { when (v.getId()) { R.id.tv_dialog_custom_cancel -> { cancelListener?.onCancel(this); dismiss(); } R.id.tv_dialog_custom_confirm -> { confirmListener?.onConfirm(this); dismiss(); } } } interface IOnCancelListener { fun onCancel(dialog: CustomDialog); } interface IOnConfirmListener { fun onConfirm(dialog: CustomDialog); } }
0
Kotlin
1
4
d8b3f740d2f564817ac1ffebe000f952cb175361
3,329
good-kotlin-app
MIT License
ComposeFadingEdges/src/main/kotlin/com/gigamole/composefadingedges/content/FadingEdgesContentType.kt
GIGAMOLE
660,667,627
false
null
package com.gigamole.composefadingedges.content import androidx.compose.foundation.ScrollState import androidx.compose.foundation.lazy.LazyListState import com.gigamole.composefadingedges.content.scrollconfig.FadingEdgesScrollConfig import com.gigamole.composefadingedges.fadingEdges import com.gigamole.composefadingedges.fill.FadingEdgesFillType /** * The fading edges content type for [fadingEdges]. * * @see FadingEdgesScrollConfig * @see FadingEdgesFillType * @author GIGAMOLE */ sealed interface FadingEdgesContentType { /** The fading edges for a static content. The fading edges are always fully shown. */ object Static : FadingEdgesContentType /** * The fading edges for a [ScrollState] scrollable content. * * @property scrollState The scrollable container state. * @property scrollConfig The fading edges scroll configuration. */ data class Scroll( val scrollState: ScrollState, val scrollConfig: FadingEdgesScrollConfig = FadingEdgesContentTypeDefaults.ScrollConfig ) : FadingEdgesContentType /** * The fading edges for a [LazyListState] scrollable content. * * @property lazyListState The lazy list state. * @property scrollConfig The fading edges scroll configuration. */ data class LazyList( val lazyListState: LazyListState, val scrollConfig: FadingEdgesScrollConfig = FadingEdgesContentTypeDefaults.ScrollConfig ) : FadingEdgesContentType }
0
Kotlin
0
3
0fae40077606e47ecaabbd419f4b29b39d6ed749
1,483
ComposeFadingEdges
MIT License
app/src/main/java/com/inno/innochat/model/User.kt
noundla
154,170,378
false
null
package com.inno.innochat.model import android.os.Parcel import android.os.Parcelable import io.realm.RealmObject /** * @author <NAME> * */ open class User(var id: String="", var name: String="", var avatar: String="", var isAvailable:Boolean=false, var isCommTo : String = ""): RealmObject(), Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readString(), parcel.readByte() != 0.toByte(), parcel.readString()) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(name) parcel.writeString(avatar) parcel.writeByte(if (isAvailable) 1 else 0) parcel.writeString(isCommTo) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<User> { override fun createFromParcel(parcel: Parcel): User { return User(parcel) } override fun newArray(size: Int): Array<User?> { return arrayOfNulls(size) } } }
1
null
1
1
20f79cfff856d2d4ace3eb81052556e0a573542e
1,200
InnoChat
The Unlicense
bgw-core/src/main/kotlin/tools/aqua/bgw/visual/CompoundVisual.kt
Chasethechicken
403,624,117
true
{"Kotlin": 610676}
/* * Copyright 2021 The BoardGameWork Authors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused", "MemberVisibilityCanBePrivate") package tools.aqua.bgw.visual import tools.aqua.bgw.observable.ObservableArrayList import tools.aqua.bgw.observable.ObservableList /** * A compound visual containing stacked [SingleLayerVisual]s. * * Hint: Each [SingleLayerVisual] besides the bottom should have opacity in order to display all layers properly. * * @constructor Creates a [CompoundVisual] with given children as [List]. * * @param children Children [SingleLayerVisual]s in the order they should be displayed, where the first * [SingleLayerVisual] gets displayed at the bottom of the stack. */ open class CompoundVisual(children: List<SingleLayerVisual>) : Visual() { /** * [ObservableList] for the [children] of this stack. * The first [SingleLayerVisual] gets displayed at the bottom of the stack. * * @see children */ val childrenProperty: ObservableArrayList<SingleLayerVisual> = ObservableArrayList(children) /** * The [children] of this stack. * The first [SingleLayerVisual] gets displayed at the bottom of the stack. * * @see childrenProperty */ var children: List<SingleLayerVisual> get() = childrenProperty.toList() set(value) { childrenProperty.clear() childrenProperty.addAll(value) } init { childrenProperty.internalListener = { _, _ -> //TODO maybe performance? notifyGUIListener() } } /** * [CompoundVisual] constructor with vararg parameter for initial children. * * @param children Children [SingleLayerVisual]s in the order they should be displayed, where the first * [SingleLayerVisual] gets displayed at the bottom of the stack. */ constructor(vararg children: SingleLayerVisual) : this(children.toList()) /** * Copies this [CompoundVisual] to a new object recursively including children. */ override fun copy(): CompoundVisual = CompoundVisual(children.map { it.copy() as SingleLayerVisual }.toList()) }
0
Kotlin
0
0
13ff98b359c5058a028bfa46fa1253a440810c27
2,613
bgw
Apache License 2.0
kmath-histograms/src/jvmMain/kotlin/scientifik/kmath/histogram/Counters.kt
avrong
255,243,332
true
{"Kotlin": 213917}
package scientifik.kmath.histogram import java.util.concurrent.atomic.DoubleAdder import java.util.concurrent.atomic.LongAdder actual typealias LongCounter = LongAdder actual typealias DoubleCounter = DoubleAdder
0
Kotlin
0
0
a94440d5fbd411b28383bda5cd237c8600f62dee
214
kmath
Apache License 2.0
site/src/jsMain/kotlin/example/shadcn_kotlin/ui/components/sections/NavHeader.kt
dead8309
657,395,822
false
null
package example.shadcn_kotlin.ui.components.sections import example.shadcn_kotlin.ui.components.ThemeToggle import example.shadcn_kotlin.ui.config.SiteConfig import lucide_react.LucideProps import lucide_react.Twitter import react.FC import react.Props import react.dom.html.ReactHTML.a import react.dom.html.ReactHTML.div import react.dom.html.ReactHTML.header import react.dom.html.ReactHTML.nav import react.dom.html.ReactHTML.span import react.dom.svg.ReactSVG.path import react.dom.svg.ReactSVG.svg import web.cssom.ClassName import web.window.WindowTarget val NavHeader = FC<Props>{ header { className = ClassName("supports-backdrop-blur:bg-background/60 sticky top-0 z-40 w-full border-b bg-background/95 backdrop-blur") div { className = ClassName("container flex h-14 items-center") MainNav {} MobileNav {} div { className = ClassName("flex flex-1 items-center justify-between space-x-2 sm:space-x-4 md:justify-end") div { className = ClassName("w-full flex-1 md:w-auto md:flex-none") // CommandMenu {} } nav { className = ClassName("flex items-center space-x-1") a { href = SiteConfig.Links.github target = WindowTarget._blank rel = "noreferrer" div { className = ClassName("inline-flex items-center justify-center text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground h-9 rounded-md w-9 px-0") github { className = ClassName("h-5 w-5") } span { className = ClassName("sr-only") +"Github" } } } a { href = SiteConfig.Links.twitter target = WindowTarget._blank rel = "noreferrer" div { className = ClassName("inline-flex items-center justify-center text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground h-9 rounded-md w-9 px-0") Twitter { className = ClassName("h-5 w-5 fill-current") } span { className = ClassName("sr-only") +"Twitter" } } } ThemeToggle {} } } } } } val github = FC<LucideProps> { svg { viewBox = "0 0 438.549 438.549" className = it.className path { fill = "currentColor" d = "M409.132 114.573c-19.608-33.596-46.205-60.194-79.798-79.8-33.598-19.607-70.277-29.408-110.063-29.408-39.781 0-76.472 9.804-110.063 29.408-33.596 19.605-60.192 46.204-79.8 79.8C9.803 148.168 0 184.854 0 224.63c0 47.78 13.94 90.745 41.827 128.906 27.884 38.164 63.906 64.572 108.063 79.227 5.14.954 8.945.283 11.419-1.996 2.475-2.282 3.711-5.14 3.711-8.562 0-.571-.049-5.708-.144-15.417a2549.81 2549.81 0 01-.144-25.406l-6.567 1.136c-4.187.767-9.469 1.092-15.846 1-6.374-.089-12.991-.757-19.842-1.999-6.854-1.231-13.229-4.086-19.13-8.559-5.898-4.473-10.085-10.328-12.56-17.556l-2.855-6.57c-1.903-4.374-4.899-9.233-8.992-14.559-4.093-5.331-8.232-8.945-12.419-10.848l-1.999-1.431c-1.332-.951-2.568-2.098-3.711-3.429-1.142-1.331-1.997-2.663-2.568-3.997-.572-1.335-.098-2.43 1.427-3.289 1.525-.859 4.281-1.276 8.28-1.276l5.708.853c3.807.763 8.516 3.042 14.133 6.851 5.614 3.806 10.229 8.754 13.846 14.842 4.38 7.806 9.657 13.754 15.846 17.847 6.184 4.093 12.419 6.136 18.699 6.136 6.28 0 11.704-.476 16.274-1.423 4.565-.952 8.848-2.383 12.847-4.285 1.713-12.758 6.377-22.559 13.988-29.41-10.848-1.14-20.601-2.857-29.264-5.14-8.658-2.286-17.605-5.996-26.835-11.14-9.235-5.137-16.896-11.516-22.985-19.126-6.09-7.614-11.088-17.61-14.987-29.979-3.901-12.374-5.852-26.648-5.852-42.826 0-23.035 7.52-42.637 22.557-58.817-7.044-17.318-6.379-36.732 1.997-58.24 5.52-1.715 13.706-.428 24.554 3.853 10.85 4.283 18.794 7.952 23.84 10.994 5.046 3.041 9.089 5.618 12.135 7.708 17.705-4.947 35.976-7.421 54.818-7.421s37.117 2.474 54.823 7.421l10.849-6.849c7.419-4.57 16.18-8.758 26.262-12.565 10.088-3.805 17.802-4.853 23.134-3.138 8.562 21.509 9.325 40.922 2.279 58.24 15.036 16.18 22.559 35.787 22.559 58.817 0 16.178-1.958 30.497-5.853 42.966-3.9 12.471-8.941 22.457-15.125 29.979-6.191 7.521-13.901 13.85-23.131 18.986-9.232 5.14-18.182 8.85-26.84 11.136-8.662 2.286-18.415 4.004-29.263 5.146 9.894 8.562 14.842 22.077 14.842 40.539v60.237c0 3.422 1.19 6.279 3.572 8.562 2.379 2.279 6.136 2.95 11.276 1.995 44.163-14.653 80.185-41.062 108.068-79.226 27.88-38.161 41.825-81.126 41.825-128.906-.01-39.771-9.818-76.454-29.414-110.049z" } } }
0
null
1
4
8413055f558c4fccaee9f39fe372d21ff6d466c8
5,422
shadcn-kotlin
MIT License
src/main/kotlin/no/nav/bidrag/arbeidsflyt/dto/oppgave.kt
navikt
295,692,779
false
null
package no.nav.bidrag.arbeidsflyt.dto import com.fasterxml.jackson.annotation.JsonInclude import no.nav.bidrag.arbeidsflyt.model.JournalpostHendelse import no.nav.bidrag.arbeidsflyt.model.OppgaveDataForHendelse import no.nav.bidrag.arbeidsflyt.utils.DateUtils import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import java.time.LocalDate import java.time.format.DateTimeFormatter private const val PARAM_JOURNALPOST_ID = "journalpostId={id}" private const val PARAMS_100_APNE_OPPGAVER = "tema=BID&statuskategori=AAPEN&sorteringsrekkefolge=ASC&sorteringsfelt=FRIST&limit=100" private const val PARAMS_JOURNALPOST_ID_MED_OG_UTEN_PREFIKS = "$PARAM_JOURNALPOST_ID&journalpostId={prefix}-{id}" data class OppgaveSokRequest(val journalpostId: String) { fun hentParametre(): String { if (harJournalpostIdPrefiks()) { val prefix = hentPrefiks() val idWithoutPrefix = hentJournalpostIdUtenPrefiks() return "$PARAMS_100_APNE_OPPGAVER&${ PARAMS_JOURNALPOST_ID_MED_OG_UTEN_PREFIKS .replace("{prefix}", prefix) .replace("{id}", idWithoutPrefix) }" } return "$PARAMS_100_APNE_OPPGAVER&${ PARAMS_JOURNALPOST_ID_MED_OG_UTEN_PREFIKS .replace("{prefix}", "BID") .replace("{id}", journalpostId) }" } private fun harJournalpostIdPrefiks() = journalpostId.contains("-") private fun hentJournalpostIdUtenPrefiks() = if (harJournalpostIdPrefiks()) journalpostId.split('-')[1] else journalpostId private fun hentPrefiks() = journalpostId.split('-')[0] } data class OppgaveSokResponse(var antallTreffTotalt: Int = 0, var oppgaver: List<OppgaveData> = emptyList()) data class OppgaveData( var id: Long? = null, var tildeltEnhetsnr: String? = null, var endretAvEnhetsnr: String? = null, var opprettetAvEnhetsnr: String? = null, var journalpostId: String? = null, var journalpostkilde: String? = null, var behandlesAvApplikasjon: String? = null, var saksreferanse: String? = null, var bnr: String? = null, var samhandlernr: String? = null, var aktoerId: String? = null, var orgnr: String? = null, var tilordnetRessurs: String? = null, var beskrivelse: String? = null, var temagruppe: String? = null, var tema: String? = null, var behandlingstema: String? = null, var oppgavetype: String? = null, var behandlingstype: String? = null, var versjon: Int? = null, var mappeId: String? = null, var fristFerdigstillelse: String? = null, var aktivDato: String? = null, var opprettetTidspunkt: String? = null, var opprettetAv: String? = null, var endretAv: String? = null, var ferdigstiltTidspunkt: String? = null, val statuskategori: Oppgavestatuskategori? = null, var endretTidspunkt: String? = null, var prioritet: String? = null, var status: String? = null, var metadata: Map<String, String>? = null ) { fun somOppgaveForHendelse() = OppgaveDataForHendelse( id = id ?: -1, versjon = versjon ?: -1, aktorId = aktoerId, oppgavetype = oppgavetype, tema = tema, tildeltEnhetsnr = tildeltEnhetsnr ) override fun toString() = "{id=$id,journalpostId=$journalpostId,tema=$tema,oppgavetype=$oppgavetype,status=$status,tildeltEnhetsnr=$tildeltEnhetsnr,opprettetTidspunkt=$opprettetTidspunkt...}" } @Suppress("unused") // used by jackson... data class OpprettJournalforingsOppgaveRequest(var journalpostId: String) { // Default verdier var beskrivelse: String = "Innkommet brev som skal journalføres og eventuelt saksbehandles. (Denne oppgaven er opprettet automatisk)" var oppgavetype: String = "JFR" var opprettetAvEnhetsnr: String = "9999" var prioritet: String = Prioritet.HOY.name var tildeltEnhetsnr: String? = "4833" var tema: String? = "BID" var aktivDato: String = LocalDate.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd")) var fristFerdigstillelse: String = DateUtils.finnNesteArbeidsdag().format(DateTimeFormatter.ofPattern("YYYY-MM-dd")) var aktoerId: String? = null var bnr: String? = null constructor(oppgaveHendelse: OppgaveHendelse): this(oppgaveHendelse.journalpostId!!){ this.aktoerId = oppgaveHendelse.hentAktoerId this.bnr = oppgaveHendelse.hentBnr this.tema = oppgaveHendelse.tema ?: this.tema this.tildeltEnhetsnr = oppgaveHendelse.tildeltEnhetsnr } constructor(journalpostHendelse: JournalpostHendelse): this(journalpostHendelse.journalpostMedBareBIDprefix){ this.aktoerId = journalpostHendelse.aktorId this.tema = journalpostHendelse.fagomrade ?: this.tema this.tildeltEnhetsnr = journalpostHendelse.enhet } constructor(oppgaveData: OppgaveData): this(oppgaveData.journalpostId!!){ this.aktoerId = oppgaveData.aktoerId this.bnr = oppgaveData.bnr this.tema = oppgaveData.tema ?: this.tema this.tildeltEnhetsnr = oppgaveData.tildeltEnhetsnr } constructor(journalpostId: String, aktoerId: String? = null, tema: String? = "BID", tildeltEnhetsnr: String? = "4833"): this(journalpostId){ this.aktoerId = aktoerId this.tema = tema this.tildeltEnhetsnr = tildeltEnhetsnr } fun somHttpEntity(): HttpEntity<*> { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON return HttpEntity<OpprettJournalforingsOppgaveRequest>(this, headers) } } /** * Påkrevde data for en oppgave som skal patches i oppgave api */ @JsonInclude(JsonInclude.Include.NON_NULL) sealed class PatchOppgaveRequest { var id: Long = -1 var versjon: Int = -1 open var aktoerId: String? = null open var endretAvEnhetsnr: String? = null open var oppgavetype: String? = null open var prioritet: String? = null open var status: String? = null open var tema: String? = null open var tildeltEnhetsnr: String? = null open var tilordnetRessurs: String? = null fun leggOppgaveIdPa(contextUrl: String) = "$contextUrl/${id}".replace("//", "/") fun somHttpEntity(): HttpEntity<*> { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON return HttpEntity<PatchOppgaveRequest>(this, headers) } protected fun leggTilObligatoriskeVerdier(oppgaveDataForHendelse: OppgaveDataForHendelse) { id = oppgaveDataForHendelse.id versjon = oppgaveDataForHendelse.versjon } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PatchOppgaveRequest if (id != other.id) return false if (aktoerId != other.aktoerId) return false if (endretAvEnhetsnr != other.endretAvEnhetsnr) return false if (oppgavetype != other.oppgavetype) return false if (prioritet != other.prioritet) return false if (status != other.status) return false if (tema != other.tema) return false if (tildeltEnhetsnr != other.tildeltEnhetsnr) return false if (versjon != other.versjon) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + aktoerId.hashCode() result = 31 * result + endretAvEnhetsnr.hashCode() result = 31 * result + (oppgavetype?.hashCode() ?: 0) result = 31 * result + prioritet.hashCode() result = 31 * result + (status?.hashCode() ?: 0) result = 31 * result + tema.hashCode() result = 31 * result + (tildeltEnhetsnr?.hashCode() ?: 0) result = 31 * result + versjon return result } override fun toString() = "${javaClass.simpleName}: id=$id,version=$versjon${fieldsWithValues()}" private fun fieldsWithValues(): String { return StringBuilder("") .append(fieldToString("aktorId", aktoerId)) .append(fieldToString("endretAvEnhetsnr", endretAvEnhetsnr)) .append(fieldToString("oppgavetype", oppgavetype)) .append(fieldToString("prioritet", prioritet)) .append(fieldToString("status", status)) .append(fieldToString("tema", tema)) .append(fieldToString("tildeltEnhetsnr", tildeltEnhetsnr)) .toString() } private fun fieldToString(fieldName: String, value: String?) = if (value != null) ",$fieldName=$value" else "" } class UpdateOppgaveAfterOpprettRequest(var journalpostId: String) : PatchOppgaveRequest() { constructor(oppgaveDataForHendelse: OppgaveDataForHendelse, journalpostIdMedPrefix: String) : this(journalpostIdMedPrefix) { leggTilObligatoriskeVerdier(oppgaveDataForHendelse) } } class OverforOppgaveRequest(override var tildeltEnhetsnr: String?) : PatchOppgaveRequest() { override var tilordnetRessurs: String? = "" constructor(oppgaveDataForHendelse: OppgaveDataForHendelse, nyttEnhetsnummer: String) : this(nyttEnhetsnummer) { leggTilObligatoriskeVerdier(oppgaveDataForHendelse) } } class OppdaterOppgaveRequest(override var aktoerId: String?) : PatchOppgaveRequest() { constructor(oppgaveDataForHendelse: OppgaveDataForHendelse, aktoerId: String?) : this(aktoerId) { leggTilObligatoriskeVerdier(oppgaveDataForHendelse) } } class FerdigstillOppgaveRequest(override var status: String?) : PatchOppgaveRequest() { constructor(oppgaveDataForHendelse: OppgaveDataForHendelse) : this(status = "FERDIGSTILT") { leggTilObligatoriskeVerdier(oppgaveDataForHendelse) } } enum class Prioritet { HOY //, NORM, LAV } enum class OppgaveIdentType { AKTOERID, ORGNR, SAMHANDLERNR, BNR } enum class OppgaveStatus { FERDIGSTILT, AAPNET, OPPRETTET, FEILREGISTRERT, UNDER_BEHANDLING } enum class Oppgavestatuskategori { AAPEN, AVSLUTTET }
3
Kotlin
0
1
9c999650de179ec26ec7298b7922b97caf707dd5
10,067
bidrag-arbeidsflyt
MIT License
app/src/main/java/org/ballistic/dreamjournalai/dream_dictionary/presentation/DictionaryScreen.kt
ErickSorto
546,852,272
false
{"Kotlin": 442723, "TypeScript": 12320, "JavaScript": 826, "Python": 404}
package org.ballistic.dreamjournalai.dream_dictionary.presentation import android.app.Activity import android.content.Context import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.util.Log import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource 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 kotlinx.coroutines.launch import org.ballistic.dreamjournalai.R import org.ballistic.dreamjournalai.dream_dictionary.presentation.components.BuyDictionaryWordDrawer import org.ballistic.dreamjournalai.dream_dictionary.presentation.components.DictionaryWordDrawer import org.ballistic.dreamjournalai.dream_dictionary.presentation.components.DictionaryWordItem import org.ballistic.dreamjournalai.dream_dictionary.presentation.viewmodel.DictionaryScreenState @Composable fun DictionaryScreen( dictionaryScreenState: DictionaryScreenState, paddingValues: PaddingValues, onEvent: (DictionaryEvent) -> Unit = {}, ) { val alphabet = remember { ('A'..'Z').toList() } val listState = rememberLazyListState() var selectedHeader by remember { mutableStateOf('A') } val screenWidth = remember { mutableStateOf(0) } // to store screen width val context = LocalContext.current val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator val scope = rememberCoroutineScope() // create vibrator effect with the constant EFFECT_CLICK val vibrationEffect1: VibrationEffect = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE) } else { Log.e("TAG", "Cannot vibrate device..") TODO("VERSION.SDK_INT < O") } LaunchedEffect(Unit) { Log.d("DictionaryScreen", "LaunchedEffect triggered") onEvent(DictionaryEvent.LoadWords) onEvent(DictionaryEvent.GetUnlockedWords) onEvent(DictionaryEvent.FilterByLetter('A')) } Scaffold( snackbarHost = { dictionaryScreenState.snackBarHostState.value }, containerColor = Color.Transparent ) { it if (!dictionaryScreenState.isClickedWordUnlocked && dictionaryScreenState.bottomSheetState.value) { BuyDictionaryWordDrawer( title = dictionaryScreenState.clickedWord.word, onAdClick = { scope.launch { onEvent( DictionaryEvent.ClickBuyWord( dictionaryWord = dictionaryScreenState.clickedWord, isAd = true, activity = context as Activity, ) ) } }, onDreamTokenClick = { onEvent( DictionaryEvent.ClickBuyWord( dictionaryWord = dictionaryScreenState.clickedWord, isAd = false, activity = context as Activity, ) ) }, onClickOutside = { dictionaryScreenState.bottomSheetState.value = false }, dictionaryScreenState = dictionaryScreenState, amount = dictionaryScreenState.clickedWord.cost ) } else if (dictionaryScreenState.isClickedWordUnlocked && dictionaryScreenState.bottomSheetState.value) { DictionaryWordDrawer( title = dictionaryScreenState.clickedWord.word, definition = dictionaryScreenState.clickedWord.definition, onClickOutside = { dictionaryScreenState.bottomSheetState.value = false }, ) } Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .background(color = colorResource(id = R.color.dark_blue).copy(alpha = 0.5f)) .onGloballyPositioned { layoutCoordinates -> screenWidth.value = layoutCoordinates.size.width // Store the width } .pointerInput(Unit) { detectHorizontalDragGestures { change, _ -> val positionX = change.position.x val letterWidth = screenWidth.value / alphabet.size.toFloat() val index = (positionX / letterWidth).coerceIn( 0f, (alphabet.size - 1).toFloat() ) val letter = alphabet[index.toInt()] if (selectedHeader != letter) { selectedHeader = letter onEvent(DictionaryEvent.FilterByLetter(letter)) vibrator.cancel() vibrator.vibrate(vibrationEffect1) } } } .padding(horizontal = 2.dp) ) { alphabet.forEach { letter -> Text( text = letter.toString(), modifier = Modifier .animateContentSize { _, _ -> } .weight(1f) .clickable { vibrator.vibrate(vibrationEffect1) selectedHeader = letter onEvent(DictionaryEvent.FilterByLetter(letter)) } .scale(if (letter == selectedHeader) 1.5f else 1f) // Slightly scale up the selected letter .align(Alignment.CenterVertically), textAlign = TextAlign.Center, fontSize = 10.sp, fontWeight = if (letter == selectedHeader) FontWeight.SemiBold else FontWeight.Normal, color = if (letter == selectedHeader) Color.White else Color.White.copy( alpha = 0.5f ) ) } } val processedWords = dictionaryScreenState.filteredWords.map { wordItem -> wordItem.copy( isUnlocked = wordItem.isUnlocked || dictionaryScreenState.unlockedWords.contains(wordItem.word), cost = if (dictionaryScreenState.unlockedWords.contains(wordItem.word)) 0 else wordItem.cost ) } LazyColumn( state = listState, modifier = Modifier.weight(1f), contentPadding = PaddingValues(bottom = 32.dp) ) { items(processedWords) { wordItem -> Log.d("DictionaryScreen", "Displaying word: ${wordItem.word}") DictionaryWordItem( wordItem = wordItem, onWordClick = { onEvent(DictionaryEvent.ClickWord(wordItem)) } ) } } } } }
0
Kotlin
0
2
d6f1c124f83cce6a4ce5d73e97eebb1f91dbe240
9,068
Dream-Journal-AI
MIT License
app/src/main/java/com/example/myapplication/jetpack/data/Message.kt
szaszpeter
492,782,637
false
{"Kotlin": 78211}
package com.example.myapplication.jetpack.data data class Message( val title : String, val body : String )
0
Kotlin
0
1
4320317b2f664d29691d79f027c92cff6bf0bd75
115
BasicTools
Apache License 2.0
app/src/main/java/ch/admin/foitt/pilotwallet/platform/activity/domain/usecase/DeleteActivity.kt
e-id-admin
775,912,525
false
{"Kotlin": 1521284}
package ch.admin.foitt.pilotwallet.platform.activity.domain.usecase import ch.admin.foitt.pilotwallet.platform.activity.domain.model.DeleteActivityError import com.github.michaelbull.result.Result interface DeleteActivity { suspend operator fun invoke(activityId: Long): Result<Unit, DeleteActivityError> }
1
Kotlin
1
4
6572b418ec5abc5d94b18510ffa87a1e433a5c82
313
eidch-pilot-android-wallet
MIT License
shared/src/commonMain/kotlin/com/amsavarthan/note/domain/note/SearchNotes.kt
amsavarthan
574,365,043
false
{"Kotlin": 43830, "Swift": 10071}
package com.amsavarthan.note.domain.note import com.amsavarthan.note.domain.time.DateTimeUtil class SearchNotes { fun execute(notes: List<Note>, query: String): List<Note> { if (query.isBlank()) return notes return notes.filter { note -> note.title.trim().lowercase().contains(query.lowercase()) || note.content.trim().lowercase().contains(query.lowercase()) }.sortedByDescending { note -> DateTimeUtil.toEpochMillis(note.created) } } }
0
Kotlin
1
3
7cdcf6564c712e345a3f3d8f29324490bfb8dcb4
524
NotesKmm
MIT License
app/src/test/java/nerd/tuxmobil/fahrplan/congress/schedule/ConferenceTest.kt
grote
114,628,676
true
{"Java": 333159, "Kotlin": 125801, "Prolog": 647}
package nerd.tuxmobil.fahrplan.congress.schedule import nerd.tuxmobil.fahrplan.congress.models.Lecture as Event import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.threeten.bp.Instant import org.threeten.bp.ZoneOffset import org.threeten.bp.temporal.ChronoField class ConferenceTest { @Test fun calculateTimeFrameFromFrabData() { // 2018-09-07T17:00:00+02:00 -> UTC: 1536332400000 milliseconds val opening = Event("Opening").apply { dateUTC = 1536332400000L // milliseconds duration = 30 } // 2018-09-09T16:45:00+02:00 -> UTC: 1536504300000 milliseconds val closing = Event("Closing").apply { dateUTC = 1536504300000L duration = 30 } with(Conference()) { calculateTimeFrame(listOf(opening, closing), ::minutesOfDay) assertThat(firstEventStartsAt).isEqualTo(1020) // -> 17:00 assertThat(lastEventEndsAt).isEqualTo(1035) // -> 17:15 } } @Test fun calculateTimeFrameFromPentabarfData() { val opening = Event("Opening").apply { duration = 25 relStartTime = 570 // -> 09:30 } val closing = Event("Closing").apply { duration = 10 relStartTime = 1070 // = 17:50 } with(Conference()) { calculateTimeFrame(listOf(opening, closing), ::minutesOfDay) assertThat(firstEventStartsAt).isEqualTo(570) // -> 09:30 assertThat(lastEventEndsAt).isEqualTo(1080) // -> 18:00 } } private fun minutesOfDay(dateUtc: Long): Int { val offset = ZoneOffset.ofHours(2) // according to the test data! +02:00 val offsetDateTime = Instant.ofEpochMilli(dateUtc).atOffset(offset) return offsetDateTime.get(ChronoField.MINUTE_OF_DAY) } }
1
Java
1
3
761d339bf804698760db17ba00990e164f90cff2
1,875
EventFahrplan
Apache License 2.0
src/main/kotlin/org/codroid/textmate/rule/IncludeOnlyRule.kt
haodong404
515,856,562
false
{"Kotlin": 272268, "SCSS": 6030, "TypeScript": 4119, "Groovy": 3928, "CSS": 3257, "HTML": 2518, "Python": 2119, "JavaScript": 2017, "Perl": 1922, "Ruby": 1703, "PowerShell": 1432, "Objective-C": 1387, "Go": 1226, "Clojure": 1206, "Handlebars": 1064, "Less": 1014, "C++": 1000, "Visual Basic .NET": 893, "C": 818, "PHP": 802, "F#": 634, "Shell": 634, "CoffeeScript": 590, "Java": 576, "Makefile": 553, "Rust": 532, "Batchfile": 488, "Dockerfile": 425, "R": 362, "ShaderLab": 330, "Lua": 252, "Swift": 220, "Pug": 22}
package org.codroid.textmate.rule import org.codroid.textmate.RegexSource class IncludeOnlyRule( override val id: RuleId, override val name: String?, override val contentName: String?, patterns: CompilePatternsResult ) : Rule(), WithPatternRule { override val nameIsCapturing: Boolean = RegexSource.hasCaptures(name) override val contentNameIsCapturing: Boolean = RegexSource.hasCaptures(contentName) override val patterns: Array<RuleId> override val hasMissingPatterns: Boolean private var cachedCompiledPatterns: RegExpSourceList? init { this.patterns = patterns.patterns this.hasMissingPatterns = patterns.hasMissingPatterns this.cachedCompiledPatterns = null } override fun dispose() { if (this.cachedCompiledPatterns != null) { this.cachedCompiledPatterns!!.dispose() this.cachedCompiledPatterns = null } } override fun collectPatterns(grammar: RuleRegistry, out: RegExpSourceList) { for (pattern in this.patterns) { grammar.getRule(pattern)?.collectPatterns(grammar, out) } } override fun compile(grammar: RuleRegistryRegexLib, endRegexSource: String): CompiledRule = this.getCachedCompiledPatterns(grammar).compile(grammar) override fun compileAG( grammar: RuleRegistryRegexLib, endRegexSource: String, allowA: Boolean, allowG: Boolean ): CompiledRule = this.getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG) private fun getCachedCompiledPatterns(grammar: RuleRegistryRegexLib): RegExpSourceList { if (this.cachedCompiledPatterns == null) { this.cachedCompiledPatterns = RegExpSourceList() this.collectPatterns(grammar, this.cachedCompiledPatterns!!) } return this.cachedCompiledPatterns!! } }
0
Kotlin
0
6
db528d988f9e94f5fb91719e67a8300ef06a498e
1,891
codroid-textmate
MIT License
db/src/main/kotlin/org/jaram/jubaky/db/table/Jobs.kt
jubaky
195,964,455
false
null
package org.jaram.jubaky.db.table import org.jetbrains.exposed.dao.IntIdTable object Jobs : IntIdTable("Jobs") { val branch = varchar("branch", 128) val applicationId = reference("application_id", Applications) val lastBuildNumber = integer("last_build_number").default(0) val tag = varchar("tag", 128).default("lts") }
1
Kotlin
1
0
834790726cc2d9be82eded60fc2449cf7e22591a
337
api_server
Apache License 2.0
core/network/src/main/kotlin/com/example/visitedcountries/network/model/CountryResponse.kt
tecruz
858,709,650
false
{"Kotlin": 165426}
/* * Designed and developed by 2024 tecruz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.visitedcountries.network.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class CountryResponse( @SerialName("flag") val flag: String, @SerialName("iso2") val iso2: String, @SerialName("iso3") val iso3: String, @SerialName("name") val name: String, )
1
Kotlin
0
0
ee2f34939b17b387fcd67eab7a2308b7c7578bd4
950
VisitedCountries
Apache License 2.0
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/domain/recommendations/ValidatorRecommendator.kt
novasamatech
415,834,480
false
null
package io.novafoundation.nova.feature_staking_impl.domain.recommendations import io.novafoundation.nova.common.utils.applyFilters import io.novafoundation.nova.feature_staking_api.domain.model.Validator import io.novafoundation.nova.feature_staking_impl.domain.recommendations.settings.RecommendationSettings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ValidatorRecommendator(val availableValidators: List<Validator>) { suspend fun recommendations(settings: RecommendationSettings) = withContext(Dispatchers.Default) { val all = availableValidators.applyFilters(settings.allFilters) .sortedWith(settings.sorting) val postprocessed = settings.postProcessors.fold(all) { acc, postProcessor -> postProcessor.apply(acc) } settings.limit?.let(postprocessed::take) ?: postprocessed } }
9
Kotlin
3
5
67bd23703276cdc1b804919d0baa679ada28db7f
888
nova-wallet-android
Apache License 2.0
common/src/main/java/dev/hitools/common/modules/image/cutter/PhotoCutterActivity.kt
EHG613
389,940,695
true
{"Kotlin": 1096191, "Java": 274915, "Python": 4980, "Shell": 505}
/* * Copyright (C) 2016 The yuhaiyang Android 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 dev.hitools.common.modules.image.cutter import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.view.View import dev.hitools.common.app.activity.BaseActivity import dev.hitools.common.databinding.ActivityCropImageBinding import dev.hitools.common.extensions.binding import dev.hitools.common.extensions.loadUrl import dev.hitools.common.extensions.compress import dev.hitools.common.extensions.save import dev.hitools.common.utils.image.select.SelectImageUtils import dev.hitools.common.widget.loading.LoadingDialog /** * 图片剪切界面 * 需要使用的Theme android:theme="@Style/Theme.NoActionBar.Fullscreen" */ class PhotoCutterActivity : BaseActivity() { private lateinit var compressFormat: Bitmap.CompressFormat private val binding: ActivityCropImageBinding by binding() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent val path = intent.getStringExtra(KEY_PATH) val x = intent.getIntExtra(KEY_RATIO_X, 1) val y = intent.getIntExtra(KEY_RATIO_Y, 1) binding.cropView.setCustomRatio(x, y) binding.cropView.loadUrl(path) } override fun initNecessaryData() { super.initNecessaryData() val format = intent.getSerializableExtra(KEY_FORMAT) compressFormat = if (format == null) { Bitmap.CompressFormat.JPEG } else { format as Bitmap.CompressFormat } } override fun onRightClick(v: View) { super.onRightClick(v) val dialog = LoadingDialog.show(this, null) val cachePath = binding.cropView.croppedBitmap.compress(compressFormat).save(context, compressFormat) val intent = Intent() intent.putExtra(KEY_RESULT_PATH, cachePath) setResult(SelectImageUtils.Request.REQUEST_CROP_IMAGE, intent) LoadingDialog.dismiss(dialog) finish() } companion object { /** * 图片路径 */ const val KEY_PATH = "crop_image_path" /** * 生成图片的路径 */ const val KEY_RESULT_PATH = "result_cutting_image_path" /** * x 轴比例 */ const val KEY_RATIO_X = "result_cutting_image_ratio_x" /** * y 轴比例 */ const val KEY_RATIO_Y = "result_cutting_image_ratio_y" /** * format */ const val KEY_FORMAT = "result_cutting_image_format" } }
0
null
0
0
be12dc9266810f3e64d55025e926a01b946c7228
3,115
android-Common
Apache License 2.0
app/src/main/java/com/uptech/videolist/PlayersPool.kt
uptechteam
524,049,332
false
{"Kotlin": 13011}
package com.uptech.videolist import android.content.Context import androidx.media3.common.Player import androidx.media3.exoplayer.ExoPlayer import kotlinx.coroutines.channels.Channel import timber.log.Timber import java.util.LinkedList import java.util.Queue class PlayersPool( private val context: Context, private val maxPoolSize: Int ) { private val unlockedPlayers: MutableList<Player> = mutableListOf(ExoPlayer.Builder(context).build()) private val lockedPlayers: MutableList<Player> = mutableListOf() private val waitingQueue: Queue<Channel<Player>> = LinkedList() @Synchronized fun acquire(): Channel<Player> = if(unlockedPlayers.isEmpty()) { if(lockedPlayers.size >= maxPoolSize) { Channel<Player>(capacity = 1).also { channel -> waitingQueue.offer(channel) } } else { Channel<Player>(capacity = 1).apply { trySend(ExoPlayer.Builder(context).build().also(lockedPlayers::add)) } } } else { Channel<Player>(capacity = 1).apply { trySend(unlockedPlayers.removeLast().also(lockedPlayers::add)) } }.also { Timber.tag(VIDEO_LIST).d("pool size = %s", lockedPlayers.size + unlockedPlayers.size) } @Synchronized fun removeFromAwaitingQueue(channel: Channel<Player>) { waitingQueue.remove(channel) } @Synchronized fun release(player: Player) { lockedPlayers.remove(player) } @Synchronized fun stop(player: Player) { if(!reusePlayer(player)) { lockedPlayers.remove(player) unlockedPlayers.add(player) } } private fun reusePlayer(player: Player): Boolean = waitingQueue.poll()?.run { trySend(player) true } ?: false @Synchronized fun releaseAll() { waitingQueue.clear() unlockedPlayers.addAll(lockedPlayers) lockedPlayers.clear() } }
2
Kotlin
0
5
5c6c1b6e099ca07ebd437e591d1662d75500e4b0
1,832
VideoList
Apache License 2.0
voice/src/main/kotlin/gateway/DefaultVoiceGatewayBuilder.kt
mixtape-oss
417,789,903
false
{"Kotlin": 1722728, "Java": 87103}
package dev.kord.voice.gateway import dev.kord.common.annotation.KordVoice import dev.kord.common.entity.Snowflake import dev.kord.common.retry.LinearRetry import dev.kord.common.retry.Retry import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.features.json.* import io.ktor.client.features.websocket.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.util.* import kotlinx.coroutines.flow.MutableSharedFlow import kotlin.time.Duration @KordVoice class DefaultVoiceGatewayBuilder( val selfId: Snowflake, val guildId: Snowflake, val sessionId: String, ) { var client: HttpClient? = null var reconnectRetry: Retry? = null var eventFlow: MutableSharedFlow<VoiceEvent> = MutableSharedFlow(extraBufferCapacity = Int.MAX_VALUE) @OptIn(InternalAPI::class) fun build(): DefaultVoiceGateway { val client = client ?: HttpClient(CIO) { install(WebSockets) install(JsonFeature) } val retry = reconnectRetry ?: LinearRetry(Duration.seconds(2), Duration.seconds(20), 10) client.requestPipeline.intercept(HttpRequestPipeline.Render) { // CIO adds this header even if no extensions are used, which causes it to be empty // This immediately kills the gateway connection if (context.url.protocol.isWebsocket()) { val header = context.headers[HttpHeaders.SecWebSocketExtensions] // If it's blank Discord rage quits if (header?.isBlank() == true) { context.headers.remove(HttpHeaders.SecWebSocketExtensions) } } proceed() } val data = DefaultVoiceGatewayData( selfId, guildId, sessionId, client, retry, eventFlow ) return DefaultVoiceGateway(data) } }
0
Kotlin
0
4
a7f848268e9036e680b27028ac1f208bef4008ef
1,928
kord
MIT License
app/src/main/java/com/dtsedemo/mtwoauth/ui/email/MailLoginActivity.kt
swai-collins
299,668,639
true
{"Kotlin": 54797}
package com.dtsedemo.mtwoauth.ui.email import android.widget.Toast import com.dtsedemo.mtwoauth.R import com.dtsedemo.mtwoauth.common.click import com.dtsedemo.mtwoauth.model.ResultEvent import com.dtsedemo.mtwoauth.ui.base.BaseActivity import com.dtsedemo.mtwoauth.viewmodel.EmailViewModel import io.reactivex.rxjava3.functions.Consumer import kotlinx.android.synthetic.main.activity_mail_login.* import org.koin.android.ext.android.inject class MailLoginActivity : BaseActivity() { override val pageTitle: String = "Email ile Giriş Yap" override val res: Int = R.layout.activity_mail_login override val viewModel: EmailViewModel by inject() override fun viewCreated() { btn_email_login?.click(compositeDisposable) { edtxt_email?.text?.toString()?.let { email -> edtxt_email_password?.text?.toString()?.let { password -> viewModel.login(email, password) } } } } override fun observe() { viewModel.loginSubscription = Consumer { when (it) { is ResultEvent.Success -> { Toast.makeText(this, "Giriş Yapıldı", Toast.LENGTH_SHORT).show() onBackPressed() } is ResultEvent.Error -> { Toast.makeText( this, "Giriş yapılamadı hata: ${it.exception.message}", Toast.LENGTH_SHORT ).show() } } } } }
0
null
0
0
927c3b98e545e1b25239eae379950af81060d450
1,570
HuaweiAuth
Apache License 2.0
analysis/analysis-api/testData/components/expressionInfoProvider/isUsedAsExpression/computedClassExpression.kt
JetBrains
3,432,266
false
null
fun test(b: Boolean) { val x = <expr>(if (b) { 45 } else { "OK" })::class</expr> }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
86
kotlin
Apache License 2.0
dexfile/src/main/kotlin/com/github/netomi/bat/dexfile/MethodHandle.kt
netomi
265,488,804
false
{"Kotlin": 1925501, "Smali": 713862, "ANTLR": 25494, "Shell": 12074, "Java": 2326}
/* * Copyright (c) 2020-2022 <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 org.tinygears.bat.dexfile import org.tinygears.bat.dexfile.io.DexDataInput import org.tinygears.bat.dexfile.io.DexDataOutput import org.tinygears.bat.dexfile.util.DexType import org.tinygears.bat.dexfile.visitor.PropertyAccessor import org.tinygears.bat.dexfile.visitor.ReferencedIDVisitor import java.util.* /** * A class representing a method handle item inside a dex file. * * @see <a href="https://source.android.com/devices/tech/dalvik/dex-format#method-handle-item">method handle item @ dex format</a> */ @DataItemAnn( type = TYPE_METHOD_HANDLE_ITEM, dataAlignment = 4, dataSection = false) class MethodHandle private constructor(methodHandleTypeValue: Int = -1, fieldOrMethodId: Int = NO_INDEX) : DataItem() { var methodHandleTypeValue: Int = methodHandleTypeValue private set var fieldOrMethodId: Int = fieldOrMethodId private set val methodHandleType: MethodHandleType get() = MethodHandleType.of(methodHandleTypeValue) fun getFieldID(dexFile: DexFile): FieldID? { return if (methodHandleType.targetsField) dexFile.getFieldID(fieldOrMethodId) else null } fun getMethodID(dexFile: DexFile): MethodID? { return if (methodHandleType.targetsField) null else dexFile.getMethodID(fieldOrMethodId) } fun getTargetClassType(dexFile: DexFile): DexType { return if (methodHandleType.targetsField) { val fieldID = getFieldID(dexFile) fieldID!!.getClassType(dexFile) } else { val methodID = getMethodID(dexFile) methodID!!.getClassType(dexFile) } } fun getTargetMemberName(dexFile: DexFile): String { return if (methodHandleType.targetsField) { val fieldID = getFieldID(dexFile) fieldID!!.getName(dexFile) } else { val methodID = getMethodID(dexFile) methodID!!.getName(dexFile) } } fun getTargetMemberDescriptor(dexFile: DexFile): String { return if (methodHandleType.targetsField) { val fieldID = getFieldID(dexFile) fieldID!!.getType(dexFile).type } else { val methodID = getMethodID(dexFile) methodID!!.getProtoID(dexFile).getDescriptor(dexFile) } } fun getTargetDescriptor(dexFile: DexFile): String { return if (methodHandleType.targetsInstance) { "(%s%s".format(getTargetClassType(dexFile), getTargetMemberDescriptor(dexFile).substring(1)) } else { getTargetMemberDescriptor(dexFile) } } override val isEmpty: Boolean get() = methodHandleTypeValue == -1 internal fun referencedIDsAccept(dexFile: DexFile, visitor: ReferencedIDVisitor) { if (methodHandleType.targetsField) { visitor.visitFieldID(dexFile, PropertyAccessor(::fieldOrMethodId)) } else { visitor.visitMethodID(dexFile, PropertyAccessor(::fieldOrMethodId)) } } override fun read(input: DexDataInput) { methodHandleTypeValue = input.readUnsignedShort() input.readUnsignedShort() fieldOrMethodId = input.readUnsignedShort() input.readUnsignedShort() } override fun write(output: DexDataOutput) { output.writeUnsignedShort(methodHandleTypeValue) output.writeUnsignedShort(0x0) output.writeUnsignedShort(fieldOrMethodId) output.writeUnsignedShort(0x0) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MethodHandle return methodHandleTypeValue == other.methodHandleTypeValue && fieldOrMethodId == other.fieldOrMethodId } override fun hashCode(): Int { return Objects.hash(methodHandleTypeValue, fieldOrMethodId) } override fun toString(): String { return "MethodHandle[type=%02x,fieldOrMethodId=%d]".format(methodHandleType, fieldOrMethodId) } companion object { fun of(methodHandleType: MethodHandleType, fieldOrMethodId: Int): MethodHandle { return of(methodHandleType.value, fieldOrMethodId) } fun of(methodHandleType: Int, fieldOrMethodId: Int): MethodHandle { require(fieldOrMethodId >= 0) { "fieldOrMethodId must not be negative" } return MethodHandle(methodHandleType, fieldOrMethodId) } internal fun read(input: DexDataInput): MethodHandle { val methodHandle = MethodHandle() methodHandle.read(input) return methodHandle } } }
1
Kotlin
3
10
5f5ec931c47dd34f14bd97230a29413ef1cf219c
5,325
bat
Apache License 2.0
shared/src/commonMain/kotlin/domain/repository/IdpRepository.kt
tkhs-dev
654,871,518
false
{"Kotlin": 238026, "Swift": 580, "Shell": 228, "Ruby": 101}
package domain.repository import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok import com.github.michaelbull.result.Result import com.github.michaelbull.result.andThen import com.github.michaelbull.result.flatMap import com.github.michaelbull.result.map import com.github.michaelbull.result.mapError import com.github.michaelbull.result.onFailure import com.github.michaelbull.result.runCatching import data.cache.CacheManager import de.jensklingenberg.ktorfit.Ktorfit import io.ktor.client.HttpClient import io.ktor.client.plugins.cookies.AcceptAllCookiesStorage import io.ktor.client.plugins.cookies.HttpCookies import io.ktor.client.statement.bodyAsText import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.withContext import network.ApiError import network.AuthRequestData import network.AuthResponseData import network.IdpService import util.FileCookiesStorage import util.Logger class IdpRepository( private val cacheManager: CacheManager, private val fileCookiesStorage: FileCookiesStorage? = null, private val idpApi: IdpService = Ktorfit.Builder().httpClient(HttpClient { followRedirects = false install(HttpCookies){ storage = fileCookiesStorage ?: AcceptAllCookiesStorage() } }).baseUrl(IdpService.BASE_URL) .build() .create() ):ApiRepository(cacheManager) { suspend fun authenticate(authRequestData: AuthRequestData, userid: String, password: String, code: String): Result<AuthResponseData, ApiError> { return prepareForLogin(authRequestData) .andThen { if(it == IdpStatus.NEED_CREDENTIALS){ authPassword(userid, password) }else{ Ok(it) } } .andThen { if(it == IdpStatus.NEED_OTP){ authOtp(code) }else{ Ok(it) } } .flatMap { roleSelect() } } suspend fun prepareForLogin(authRequestData: AuthRequestData):Result<IdpStatus, ApiError>{ return withContext(Dispatchers.IO){ validateHttpResponse(ignoreAuthError = true) { idpApi.connectSsoSite(authRequestData.samlRequest, authRequestData.relayState, authRequestData.sigAlg, authRequestData.signature) } .flatMap{ if(it.status.value == 200) { if(it.bodyAsText().contains("利用者選択")){ Logger.debug(this::class.simpleName, "Pass idp auth with saved cookies") Ok(IdpStatus.SUCCESS) }else{ Ok(IdpStatus.NEED_CREDENTIALS) } }else{ Err(ApiError.InvalidResponse(it.status.value, it.bodyAsText())) } } } } suspend fun authPassword(userId:String,password:String):Result<IdpStatus, ApiError>{ return withContext(Dispatchers.IO){ runCatching { idpApi.authPassword(userId,password) }.onFailure { Logger.error(this::class.simpleName, it) }.mapError { ApiError.InternalException(it) }.andThen { if (it.contains("認証エラー")) { idpApi.refreshAuthPage() Err(ApiError.WrongCredentials) } else if (it.contains("MFA")) { Ok(IdpStatus.NEED_OTP) } else if (it.contains("利用者選択")) { Ok(IdpStatus.SUCCESS) } else { Err(ApiError.InvalidResponse(200, it)) } } } } suspend fun authOtp(code:String):Result<IdpStatus, ApiError>{ return withContext(Dispatchers.IO){ runCatching{ idpApi.authMfa(code) }.onFailure { Logger.error(this::class.simpleName, it) }.mapError { ApiError.InternalException(it) }.andThen { if(it.contains("認証エラー")){ Err(ApiError.WrongCredentials) }else if(it.contains("利用者選択")){ Ok(IdpStatus.SUCCESS) }else{ Err(ApiError.InvalidResponse(200, it)) } } } } suspend fun roleSelect():Result<AuthResponseData, ApiError>{ return withContext(Dispatchers.IO){ runCatching { idpApi.roleSelect() }.onFailure { Logger.error(this::class.simpleName, it) }.mapError { ApiError.InternalException(it) }.map { val map = mutableMapOf<String, String>() "name=\"([^\"]+)\"\\s*value=\"([^\"]+)\"".toRegex(RegexOption.IGNORE_CASE).findAll(it) .forEach { matchResult-> val (name, value) = matchResult.destructured map[name] = value } map }.flatMap { val samlResponse = it["SAMLResponse"] ?: return@flatMap Err(ApiError.InvalidResponse(200, "SAMLResponse not found")) val relayState = it["RelayState"] ?: "null" Logger.info(this::class.simpleName, "OU idp login successful") Ok(AuthResponseData(samlResponse,relayState)) } } } enum class IdpStatus{ NEED_CREDENTIALS, NEED_OTP, SUCCESS } }
4
Kotlin
0
0
eadefe3882c8dd21997afe4e1aad2829674f9fe1
5,744
HandaiManager
Apache License 2.0
core/ui/compose/designsystem/src/main/kotlin/app/k9mail/core/ui/compose/designsystem/molecule/input/PasswordInput.kt
thunderbird
1,326,671
false
{"Kotlin": 4572978, "Java": 2232770, "Shell": 6489, "AIDL": 1946}
package app.k9mail.core.ui.compose.designsystem.molecule.input import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import app.k9mail.core.ui.compose.designsystem.R import app.k9mail.core.ui.compose.designsystem.atom.textfield.TextFieldOutlinedPassword import app.k9mail.core.ui.compose.theme.PreviewWithThemes @Composable fun PasswordInput( onPasswordChange: (String) -> Unit, modifier: Modifier = Modifier, password: String = "", errorMessage: String? = null, contentPadding: PaddingValues = inputContentPadding(), ) { InputLayout( modifier = modifier, contentPadding = contentPadding, errorMessage = errorMessage, ) { TextFieldOutlinedPassword( value = password, onValueChange = onPasswordChange, label = stringResource(id = R.string.designsystem_molecule_password_input_label), hasError = errorMessage != null, modifier = Modifier.fillMaxWidth(), ) } } @Preview(showBackground = true) @Composable internal fun PasswordInputPreview() { PreviewWithThemes { PasswordInput( onPasswordChange = {}, ) } } @Preview(showBackground = true) @Composable internal fun PasswordInputWithErrorPreview() { PreviewWithThemes { PasswordInput( onPasswordChange = {}, errorMessage = "Password error", ) } }
789
Kotlin
2414
9,379
71f6713a2e7cc9d587e849329908fc2526f3923a
1,645
thunderbird-android
Apache License 2.0
android/app/src/main/kotlin/com/sofferjacob/lazy_loading_demo/MainActivity.kt
sofferjacob
295,876,891
false
{"Dart": 8332, "Ruby": 1354, "HTML": 1131, "Swift": 404, "Kotlin": 138, "Objective-C": 38}
package com.sofferjacob.lazy_loading_demo import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
2
4
202c02b80259bf8127d23a05319071e51149bb50
138
lazy-loading-demo
MIT License
app/src/main/java/io/github/nircek/hpcounter/MainActivity.kt
Nircek
163,596,900
false
null
package io.github.nircek.hpcounter import android.content.Intent import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.app_bar_main.* class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) val sfm = supportFragmentManager.beginTransaction() sfm.replace(R.id.frameLayout, CounterFragment()) sfm.commit() val toggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) drawer_layout.addDrawerListener(toggle) toggle.syncState() nav_view.setNavigationItemSelectedListener(this) } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. when (item.itemId) { R.id.action_settings -> { invokeSettings() return true } } return super.onOptionsItemSelected(item) } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_add_counter -> { // Handle the counter add action } R.id.nav_sett -> this.invokeSettings() } drawer_layout.closeDrawer(GravityCompat.START) return true } fun invokeSettings() { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) } }
0
Kotlin
0
0
802f55a4d9b8e37e993f0883174b634bab2915b3
2,612
HPcounter
MIT License
idea/idea-completion/testData/basic/common/autoPopup/NoAutopopupInGenericVarName.kt
nskvortsov
4,137,859
true
{"Kotlin": 54887563, "Java": 7682828, "JavaScript": 185344, "HTML": 79768, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "Swift": 9789, "CSS": 9270, "Shell": 7220, "Batchfile": 5727, "Ruby": 2655, "Objective-C": 444, "Scala": 80, "C": 59}
// FIR_COMPARISON var <T> <caret> // INVOCATION_COUNT: 0 // NUMBER: 0
0
Kotlin
0
3
39d15501abb06f18026bbcabfd78ae4fbcbbe2cb
71
kotlin
Apache License 2.0
kotlin-antd/antd-samples/src/main/kotlin/samples/pagination/Basic.kt
oxiadenine
206,398,615
false
{"Kotlin": 1619835, "HTML": 1515}
package samples.pagination import antd.pagination.pagination import react.RBuilder import styled.css import styled.styledDiv fun RBuilder.basic() { styledDiv { css { +PaginationStyles.basic } pagination { attrs { defaultCurrent = 1 total = 50 } } } }
1
Kotlin
8
50
e0017a108b36025630c354c7663256347e867251
341
kotlin-js-wrappers
Apache License 2.0
wallet/binance/src/main/java/com/gexabyte/android/wallet/binance/data/BinanceBalanceRepositoryImpl.kt
LinDevHard
467,245,166
false
null
package com.gexabyte.android.wallet.binance.data import com.binance.dex.api.client.BinanceDexApi import com.binance.dex.api.client.BinanceDexApiRestClient import com.gexabyte.android.wallet.binance.domain.BinanceBalanceRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class BinanceBalanceRepositoryImpl( private val client: BinanceDexApiRestClient, ): BinanceBalanceRepository { override fun getTokenBalance(symbol: String, address: String): Flow<String> = flow { val balanceAccount = client.getAccount(address).balances.find { it.symbol == symbol } if(balanceAccount != null) { emit(balanceAccount.free) } else { emit("0.0") } } }
0
Kotlin
1
0
19871d912c4548b6cf643a1405988d8030e9ab9d
736
FeliaWallet
Apache License 2.0
core/src/androidMain/kotlin/tech/skot/core/SKStringUtilsAndroid.kt
skot-framework
235,318,194
false
{"Kotlin": 773248, "Shell": 117}
package tech.skot.core actual fun String.skFormat(vararg values: Any): String = this.format(*values)
1
Kotlin
4
6
8fcff82c719c9775e63da9c3808817704068cbba
101
skot
Apache License 2.0
test/src/me/anno/tests/collider/SphereCollider2.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
package me.anno.tests.collider import me.anno.ecs.components.collider.SphereCollider import me.anno.engine.DefaultAssets fun main() { val mesh = DefaultAssets.icoSphere.ref val collider = SphereCollider() testCollider(collider, mesh) }
0
Kotlin
3
24
013af4d92e0f89a83958008fbe1d1fdd9a10e992
249
RemsEngine
Apache License 2.0
shared/src/commonMain/kotlin/model/CounterRepository.kt
jabouzi
696,048,736
false
{"Kotlin": 22241, "Ruby": 1788, "Swift": 708, "Shell": 228}
/* * Copyright 2021 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package model import io.realm.kotlin.Realm import io.realm.kotlin.RealmConfiguration import io.realm.kotlin.notifications.SingleQueryChange import io.realm.kotlin.ext.query import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import model.entity.Counter /** * Repository class. Responsible for storing the io.realm.kotlin.demo.model.entity.Counter and expose updates to it. */ class CounterRepository { private var realm: Realm private val counterObj: Counter init { val config = RealmConfiguration.Builder( schema = setOf(Counter::class) ).build() // Open Realm realm = Realm.open(config) // With no support for setting up initial values, we just do it manually. // WARNING: Writing directly on the UI thread is not encouraged. counterObj = realm.writeBlocking { val objects = query<Counter>().find() when (objects.size) { 0 -> copyToRealm(Counter()) 1 -> objects.first() else -> throw IllegalStateException("Too many counters: ${objects.size}") } } } /** * Adjust the counter up and down. */ fun adjust(change: Int) { CoroutineScope(Dispatchers.Default).launch { realm.write { findLatest(counterObj)?.run { operations.add(change) } ?: println("Could not update io.realm.kotlin.demo.model.entity.Counter") } } } /** * Listen to changes to the counter. */ fun observeCounter(): Flow<Long> { return realm.query<Counter>("id = 'primary'").first().asFlow() .map { it: SingleQueryChange<Counter> -> it.obj?.operations!!.fold(0L,) { sum, el -> sum + el } } } fun observeTest(start: Boolean): Flow<Int> { return flow { for (i in 0 .. 10) { delay(1000) } } } }
0
Kotlin
0
0
6f08c8f230a9c66dc1899320f78ba40946f33231
2,776
KMPTest
Apache License 2.0
app/src/main/java/exh/ui/lock/LockController.kt
NerdNumber9
65,055,291
false
null
package exh.ui.lock import android.annotation.SuppressLint import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.afollestad.materialdialogs.MaterialDialog import com.andrognito.pinlockview.PinLockListener import com.github.ajalt.reprint.core.AuthenticationResult import com.github.ajalt.reprint.rxjava.RxReprint import com.mattprecious.swirl.SwirlView import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.NucleusController import exh.util.dpToPx import kotlinx.android.synthetic.main.activity_lock.view.* import uy.kohesive.injekt.injectLazy class LockController : NucleusController<LockPresenter>() { val prefs: PreferencesHelper by injectLazy() override fun inflateView(inflater: LayoutInflater, container: ViewGroup) = inflater.inflate(R.layout.activity_lock, container, false)!! override fun createPresenter() = LockPresenter() override fun getTitle() = "Application locked" override fun onViewCreated(view: View) { super.onViewCreated(view) if(!lockEnabled(prefs)) { closeLock() return } with(view) { //Setup pin lock pin_lock_view.attachIndicatorDots(indicator_dots) pin_lock_view.pinLength = prefs.eh_lockLength().getOrDefault() pin_lock_view.setPinLockListener(object : PinLockListener { override fun onEmpty() {} override fun onComplete(pin: String) { if (sha512(pin, prefs.eh_lockSalt().get()!!) == prefs.eh_lockHash().get()) { //Yay! closeLock() } else { MaterialDialog.Builder(context) .title("PIN code incorrect") .content("The PIN code you entered is incorrect. Please try again.") .cancelable(true) .canceledOnTouchOutside(true) .positiveText("Ok") .autoDismiss(true) .show() pin_lock_view.resetPinLockView() } } override fun onPinChange(pinLength: Int, intermediatePin: String?) {} }) } } @SuppressLint("NewApi") override fun onAttach(view: View) { super.onAttach(view) with(view) { //Fingerprint if (presenter.useFingerprint) { swirl_container.visibility = View.VISIBLE swirl_container.removeAllViews() val icon = SwirlView(context).apply { val size = dpToPx(context, 60) layoutParams = (layoutParams ?: ViewGroup.LayoutParams( size, size )).apply { width = size height = size val pSize = dpToPx(context, 8) setPadding(pSize, pSize, pSize, pSize) } val lockColor = resolvColor(android.R.attr.windowBackground) setBackgroundColor(lockColor) val bgColor = resolvColor(android.R.attr.colorBackground) //Disable elevation if lock color is same as background color if (lockColor == bgColor) [email protected]_container.cardElevation = 0f setState(SwirlView.State.OFF, true) } swirl_container.addView(icon) icon.setState(SwirlView.State.ON) RxReprint.authenticate() .subscribeUntilDetach { when (it.status) { AuthenticationResult.Status.SUCCESS -> closeLock() AuthenticationResult.Status.NONFATAL_FAILURE -> icon.setState(SwirlView.State.ERROR) AuthenticationResult.Status.FATAL_FAILURE, null -> { MaterialDialog.Builder(context) .title("Fingerprint error!") .content(it.errorMessage) .cancelable(false) .canceledOnTouchOutside(false) .positiveText("Ok") .autoDismiss(true) .show() icon.setState(SwirlView.State.OFF) } } } } else { swirl_container.visibility = View.GONE } } } private fun resolvColor(color: Int): Int { val typedVal = TypedValue() activity!!.theme!!.resolveAttribute(color, typedVal, true) return typedVal.data } override fun onDetach(view: View) { super.onDetach(view) } fun closeLock() { router.popCurrentController() } override fun handleBack() = true }
54
null
28
332
db764b4d96c937df1345a3d372f10d00796ecdec
5,459
TachiyomiEH
Apache License 2.0
app/src/main/java/com/e444er/cleanmovie/core/domain/Language.kt
e444er
597,756,971
false
null
package com.e444er.cleanmovie.core.domain import androidx.annotation.StringRes import com.e444er.cleanmovie.R data class Language( @StringRes val textId: Int, val iso: String ) val supportedLanguages = mutableListOf<Language>( Language(R.string.language_english, "en"), Language(R.string.language_turkish, "tr"), Language(R.string.language_spanish, "es"), Language(R.string.language_german, "de"), Language(R.string.language_french, "fr"), Language(R.string.language_russian, "ru"), )
0
Kotlin
0
0
1c939de424b4eb254fd4258f4e56e4399bdfb3cd
521
KinoGoClean
Apache License 2.0
src/main/kotlin/it/anesin/DefaultCashRegister.kt
pieroanesin
540,757,888
false
{"Kotlin": 14170}
package it.anesin class DefaultCashRegister : CashRegister { override fun invoice(packages: List<Package>) = FlowerType.values() .map { flowerType -> packagesOf(flowerType, packages) } .filter { filteredPackages -> filteredPackages.isNotEmpty() } .map { filteredPackages -> sort(filteredPackages) } .map { sortedPackages -> invoiceByType(sortedPackages) } .joinToString("\n") private fun packagesOf(flowerType: FlowerType, packages: List<Package>) = packages.filter { it.bundle.type == flowerType } private fun sort(packagesSingleType: List<Package>) = packagesSingleType.sortedByDescending { pack -> pack.bundle.size } private fun invoiceByType(packages: List<Package>): String? { var totalFlowers = 0 var totalPrice = 0.0 packages.forEach { pack -> totalFlowers += pack.totalFlowers() totalPrice += pack.price() } var receipt = "$totalFlowers ${packages.first().bundle.type} $${String.format("%.2f", totalPrice)}" packages.forEach { pack -> receipt += "\n\t ${pack.bundleQuantity} x ${pack.bundle.size} $${pack.bundle.price}" } return receipt } }
0
Kotlin
0
0
643a95fcc84a0e33978da830f6895b23be5d4a64
1,137
flower-shop
MIT License
app/src/main/java/com/awsgroup3/combustifier/MainActivity.kt
AWS-Accelerator-Group-3-2021
437,801,542
false
{"Kotlin": 64667}
package com.awsgroup3.combustifier import android.app.Activity import android.app.ActivityManager import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.os.Environment import android.util.Log import android.view.animation.OvershootInterpolator import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AddCircle import androidx.compose.material.icons.filled.Home import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType.Companion.Uri import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.FileProvider import androidx.navigation.NavController import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import coil.annotation.ExperimentalCoilApi import com.awsgroup3.combustifier.ui.theme.CombustifierTheme import com.awsgroup3.combustifier.ui.theme.Typography import com.google.accompanist.permissions.ExperimentalPermissionsApi import kotlinx.coroutines.delay import java.io.File import java.net.URI import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.* class MainActivity : ComponentActivity() { @ExperimentalMaterial3Api override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CombustifierTheme { // A surface container using the 'background' color from the theme Surface(color = MaterialTheme.colorScheme.background) { ScreenInitializer() } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ScreenInitializer() { val navController = rememberNavController() NavHost( navController = navController, startDestination = "splash_screen" ) { composable("splash_screen") { SplashScreen(navController = navController) } // Main Screen composable("main_screen") { MainScreen() } } } @Composable fun SplashScreen(navController: NavController) { val scale = remember { androidx.compose.animation.core.Animatable(1f) } // AnimationEffect LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 1.7f, animationSpec = tween( durationMillis = 800, easing = { OvershootInterpolator(4f).getInterpolation(it) }) ) delay(3000L) navController.navigate("main_screen") } // Image Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Image( painter = painterResource(id = R.drawable.combustifierlogo), contentDescription = "Combustifier", modifier = Modifier.scale(scale.value) ) } } @ExperimentalMaterial3Api @Composable fun MainScreen() { val items = listOf( Screen.Home, Screen.Measurement, ) val navController = rememberNavController() Scaffold( bottomBar = { NavigationBar() { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination items.forEach { screen -> NavigationBarItem( icon = { if (stringResource(screen.resourceId) == "Home") { Icon(Icons.Filled.Home, contentDescription = null) } else { Icon( painterResource(id = R.drawable.baseline_straighten_24), contentDescription = null ) } }, label = { Text(stringResource(screen.resourceId)) }, selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true, onClick = { navController.navigate(screen.route) { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination when // reselecting the same item launchSingleTop = true // Restore state when reselecting a previously selected item restoreState = true } } ) } } } ) { innerPadding -> NavHost( navController, startDestination = Screen.Home.route, Modifier.padding(innerPadding) ) { composable(Screen.Home.route) { HomeScreen(navController) } composable(Screen.Measurement.route) { MeasurementScreen(navController) } } } } @Composable fun TopAppBar(pageName: String) { SmallTopAppBar( title = { Text( modifier = Modifier .padding(10.dp, 48.dp, 24.dp, 24.dp), text = pageName, fontFamily = Typography.titleLarge.fontFamily, fontSize = 32.sp, fontWeight = FontWeight.SemiBold, ) } ) } @Composable @OptIn( ExperimentalCoilApi::class, ExperimentalPermissionsApi::class, androidx.compose.material3.ExperimentalMaterial3Api::class ) fun NewCheckButton() { val context = LocalContext.current //get local datetime val date = LocalDateTime.now() val uuid = UUID.randomUUID() // cut short uuid val uuidString = uuid.toString().substring(0, 8) // log uuidstring Log.d("uuid", uuidString) val datetime = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd.HH:mm:ss")) val launcher = rememberLauncherForActivityResult( ActivityResultContracts.TakePicture() ) { it -> // get latest image in directory val dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val files = dir?.listFiles() val latestFile = files?.maxByOrNull{ it.lastModified() } val imageUri = android.net.Uri.fromFile(latestFile) if(it) { val intent = Intent(context, SendImageActivity::class.java) intent.putExtra("imageUri", imageUri) context.startActivity(intent) } } ExtendedFloatingActionButton( modifier = Modifier .padding(16.dp), text = { Text("New Check") }, icon = { Icon(Icons.Filled.AddCircle, contentDescription = null) }, onClick = { val photoFile = File.createTempFile( "combustifier_$uuidString", ".jpg", context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) ) val uri = FileProvider.getUriForFile( context, "${context.packageName}.fileprovider", photoFile ) launcher.launch(uri) } ) }
0
Kotlin
0
1
8d10c928cd5c15801590229ca104cd6aa358f67b
8,744
Combustifier-Android
FSF All Permissive License
app/src/androidTest/java/com/deonolarewaju/ulesson/repository/local/dao/RecentlyViewedDaoTest.kt
DeonWaju
331,329,050
false
null
package com.deonolarewaju.ulesson.repository.local.dao import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.deonolarewaju.ulesson.repository.local.ProjectDatabaseSetup import com.deonolarewaju.ulesson.repository.model.RecentlyViewed import com.deonolarewaju.ulesson.util.getOrAwaitValue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) @SmallTest class RecentlyViewedDaoTest : ProjectDatabaseSetup() { @Test fun insertAndRetrieve() = runBlocking { val singleRecentView = RecentlyViewed(15L, "Physics", "Gravity") recentDao.saveRecentView(singleRecentView) val recentViews = recentDao.getRecentViews(2).getOrAwaitValue() assertThat(recentViews.size, `is`(1)) assertThat(recentViews[0], `is`(singleRecentView)) } @Test fun insertManyAndRetrieve() = runBlocking { val recentView1 = RecentlyViewed(1L, "Physics", "Gravity") val recentView2 = RecentlyViewed(2L, "Biology", "Osmosis") val recentView3 = RecentlyViewed(3L, "Chemistry", "Gravity") val recentView4 = RecentlyViewed(4L, "Mathematics", "Trig") val recentView5 = RecentlyViewed(5L, "English", "Vocabulary") val allRecentViews = listOf(recentView1, recentView2, recentView3, recentView4, recentView5) recentDao.saveRecentView(recentView1) recentDao.saveRecentView(recentView2) recentDao.saveRecentView(recentView3) recentDao.saveRecentView(recentView4) recentDao.saveRecentView(recentView5) //view less val recentViewsViewLess = recentDao.getRecentViews(2).getOrAwaitValue() assertThat(recentViewsViewLess.size, `is`(2)) assertThat(recentViewsViewLess, `is`(allRecentViews.take(2))) //view more val recentViewsViewMore = recentDao.getRecentViews(10).getOrAwaitValue() assertThat(recentViewsViewMore.size, `is`(allRecentViews.size)) assertThat(recentViewsViewMore, `is`(allRecentViews.take(10))) } }
0
Kotlin
0
1
6daea1d4291d92a47a862ce37fb332f896b623dd
2,263
Ulesson-TakeHomeTest
Apache License 2.0
ui-main/src/main/java/pl/kamilszustak/read/ui/main/profile/ProfileAction.kt
swistak7171
289,985,013
false
null
package pl.kamilszustak.read.ui.main.profile import pl.kamilszustak.read.ui.base.view.ViewAction sealed class ProfileAction : ViewAction { object NavigateToProfileEditFragment : ProfileAction() object NavigateToStatisticsFragment : ProfileAction() }
2
Kotlin
0
1
70d7be58042410bdb969035413b726126426e3d3
259
read
Apache License 2.0
domain/src/main/kotlin/dev/notypie/domain/history/mapper/HistoryMapper.kt
TrulyNotMalware
810,739,918
false
{"Kotlin": 85865}
package dev.notypie.domain.history.mapper import dev.notypie.domain.command.dto.response.SlackApiResponse import dev.notypie.domain.history.entity.History class HistoryMapper private constructor(){ companion object{ fun map(requestType: String, slackApiResponse: SlackApiResponse) = History( apiAppId = slackApiResponse.apiAppId, channel = slackApiResponse.channel, commandType = slackApiResponse.commandType, status = slackApiResponse.status, token = slackApiResponse.token, states = slackApiResponse.actionStates, type = requestType, publisherId = slackApiResponse.publisherId, idempotencyKey = slackApiResponse.idempotencyKey ) } }
0
Kotlin
0
0
efb8c2aa68cec81e2d09fb6f2862cb59ebffce01
740
CodeCompanion
MIT License
android/src/main/kotlin/com/receivelink/shareintent/GetShareIntentPlugin.kt
miraculix92
272,429,631
false
{"Dart": 7436, "Kotlin": 2967, "Swift": 922, "Ruby": 889, "Objective-C": 704}
package com.receivelink.shareintent import android.content.Context import android.content.Intent import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.* import io.flutter.plugin.common.PluginRegistry.Registrar /** ShareintentPlugin */ class GetShareIntentPlugin: MethodChannel.MethodCallHandler, FlutterPlugin, EventChannel.StreamHandler, PluginRegistry.NewIntentListener, ActivityAware { private var currentShare: String? = null private var methodChannel: MethodChannel? = null private var eventChannel: EventChannel? = null private var eventSink: EventChannel.EventSink? = null fun registerWith(registrar: Registrar) { val plugin = GetShareIntentPlugin() plugin.setupChannels(registrar.messenger(), registrar.context()) } override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { setupChannels(binding.binaryMessenger, binding.applicationContext) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { teardownChannels() } override fun onAttachedToActivity(binding: ActivityPluginBinding) { binding.addOnNewIntentListener(this) } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { onAttachedToActivity(binding) } override fun onDetachedFromActivityForConfigChanges() { onDetachedFromActivity() } override fun onDetachedFromActivity() { teardownChannels() } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (call.method == "shareIntent" && currentShare != null) { result.success(currentShare) } else {result.error("No Intent received.", "", "");} } override fun onListen(arguments: Any?, events: EventChannel.EventSink?) { this.eventSink = events } override fun onCancel(arguments: Any?) { eventSink = null } override fun onNewIntent(intent: Intent?): Boolean { handleIntent(intent) return false } private fun handleIntent(intent: Intent?) { currentShare = intent!!.getStringExtra(Intent.EXTRA_TEXT) eventSink!!.success(currentShare) } private fun setupChannels(messenger : BinaryMessenger, context : Context) { methodChannel = MethodChannel(messenger, "plugins.flutter.io/shareintent") eventChannel = EventChannel(messenger, "plugins.flutter.io/shareintent_status") methodChannel!!.setMethodCallHandler(this) eventChannel!!.setStreamHandler(this) } private fun teardownChannels() { methodChannel!!.setMethodCallHandler(null) eventChannel!!.setStreamHandler(null) methodChannel = null eventChannel = null } }
0
Dart
0
0
0ab229df688571052e771073415b8713c1350825
2,827
shareintent
MIT License
src/main/kotlin/views/MainView.kt
mhsquire
100,083,417
false
{"Gherkin": 42648, "Kotlin": 11259, "Java": 7998}
package views import controllers.MainController import javafx.beans.value.ChangeListener import javafx.collections.ObservableList import javafx.event.ActionEvent import javafx.scene.Node import javafx.scene.layout.StackPane import javafx.scene.layout.VBox import javafx.stage.Stage import tornadofx.* import java.util.logging.Logger import javafx.scene.Parent import javafx.scene.control.* import javafx.scene.layout.AnchorPane import javafx.scene.paint.Paint import models.FileDir import java.util.ArrayList import javafx.event.Event import javafx.scene.text.Text import javafx.beans.value.ObservableValue import java.io.File /** * Created by Matthew Squire on 8/12/17. */ class MainView : View("External Brain") { companion object { val LOG = Logger.getLogger(MainView::class.java.name) } override val root: VBox by fxml("/layouts/main.fxml") var mainController: MainController val selectorsStack: StackPane by fxid("SelectorsStack") val listViewStack: AnchorPane by fxid("ListViewStack") val detailsStack: StackPane by fxid("DetailsStack") val viewMenuItem: MenuItem by fxid("viewer_menuitem_id") val taggingMenuItem: MenuItem by fxid("tagging_menuitem_id") val sortingMenuItem: MenuItem by fxid("sorting_menuitem_id") val includeRadioButton: RadioButton by fxid("include_radiobutton_id") val excludeRadioButton: RadioButton by fxid("exclude_radiobutton_id") init { setTopStackPaneTo("ViewSelectorsPane", selectorsStack) setTopStackPaneTo("ViewDetailsPane", detailsStack) mainController = MainController(currentStage as Stage) includeRadioButton.isSelected = true } fun handleMainListViewClick(e: Event) { val listView: ListView<File> = e.source as ListView<File> val file: File = listView.selectionModel.selectedItem } fun handleModeMenuAction(e: ActionEvent) { when(e.source) { viewMenuItem -> { setTopStackPaneTo("ViewSelectorsPane", selectorsStack) setTopStackPaneTo("ViewDetailsPane", detailsStack) } taggingMenuItem -> { setTopStackPaneTo("TaggingSelectorsPane", selectorsStack) setTopStackPaneTo("TaggingDetailsPane", detailsStack) } sortingMenuItem -> { setTopStackPaneTo("SortingSelectorsPane", selectorsStack) setTopStackPaneTo("SortingDetailsPane", detailsStack) } else -> { LOG.severe("MenuItem not found!") } } } private fun setTopStackPaneTo(paneId: String, stack: StackPane) { val panes: ObservableList<Node> = stack.children val topNode: Node = panes.get(panes.size - 1) var newTopNode: Node = topNode if(panes.size > 1) { for(pane in panes) { if(pane.id == paneId) { newTopNode = pane } } topNode.isVisible = false newTopNode.isVisible = true newTopNode.toFront() } } fun handleIncludeRadioButtonEvent(e: ActionEvent) { when(e.source) { includeRadioButton -> { excludeRadioButton.isSelected = !excludeRadioButton.isSelected excludeRadioButton.isSelected = !includeRadioButton.isSelected mainController.inclusiveDirItem = includeRadioButton.isSelected } excludeRadioButton -> { includeRadioButton.isSelected = !includeRadioButton.isSelected includeRadioButton.isSelected = !excludeRadioButton.isSelected mainController.inclusiveDirItem = includeRadioButton.isSelected } } LOG.finer("Inclusiveness is: " + mainController.inclusiveDirItem) } fun handleApplyButtonEvent(e: ActionEvent) { val fileCollection = getNodeById(listViewStack, "main_listview_id") as ListView<File> mainController.populateCollection() fileCollection.items = mainController.fileCollection } fun handleAddDirectoryEvent(e: ActionEvent) { val fileBox: TextField = getNodeById(selectorsStack, "filefield_textbox_id") as TextField mainController.addDirectory(fileBox) val fileList = getNodeById(selectorsStack, "directory_listview_id") as ListView<FileDir> fileList.items = mainController.fileList fileList.cellFormat { graphic = cache { form { fieldset { label(it.file.path) { style { borderColor += box(Paint.valueOf(it.color)) borderInsets += box(3.px) } } } } } } fileBox.deleteText(0, fileBox.text.length) } fun handleRemoveDirectoryEvent(e: ActionEvent) { val fileList = getNodeById(selectorsStack, "directory_listview_id") as ListView<*> mainController.fileList .filter { fileList.selectedItem == it } .forEach { mainController.fileList.remove(it) } } /** * About MenuItem Action that launches the about information screen. */ fun handleAboutMenuAction() { replaceWith(AboutView::class) } fun getNodeById(root: Parent, id: String): Node { val selectorsStackNodeList: ArrayList<Node> = getAllNodes(root) var node: Node = selectorsStackNodeList.get(0) for(child in selectorsStackNodeList) { if(child.id == id) { node = child break } } return node } fun getAllNodes(root: Parent): ArrayList<Node> { val nodes = ArrayList<Node>() addAllDescendents(root, nodes) return nodes } private fun addAllDescendents(parent: Parent, nodes: ArrayList<Node>) { for (node in parent.childrenUnmodifiable) { nodes.add(node) if (node is Parent) addAllDescendents(node, nodes) } } }
1
Gherkin
1
1
7ebac122e04d6eb9df21063dc3525968bb55f8c0
6,211
externalBrain
MIT License
solutions/src/test/kotlin/de/thermondo/solutions/basics/Basics02SolutionTest.kt
thermondo
552,876,124
false
null
package de.thermondo.solutions.basics import de.thermondo.test.utils.BasePrintlnTest import kotlin.test.Test class Basics02SolutionTest : BasePrintlnTest() { @Test fun `Validate helloWorld function`() { helloWorld() assertPrintln("Hello World!") } }
5
Kotlin
2
0
490fe3a0f079d3aef32ebd35dec8b33293b5a39f
280
lets-learn-kotlin
MIT License
kotlin-introspection/src/main/kotlin/DataClassRunMe.kt
mgrouch
488,594,994
false
{"Kotlin": 710720, "JavaScript": 84210, "HTML": 977}
fun main(args: Array<String>) { val obj = DataClass(1L, "name", "readOnly", -1) println("$obj") // it's kind of inefficient (if prop name is not a variable) println("${obj[DataClass::readOnly.name]} ${obj[DataClass::nonNull.name]}") // better just println("${DataClass::readOnly.get(obj)} ${DataClass::nonNull.get(obj)}") // it's kind of inefficient (if prop name is not a variable) obj[DataClass::data.name] = "name2" obj[DataClass::nonNull.name] = -3 println("$obj") // better just DataClass::data.set(obj, "name3") println("$obj") for ((key, value) in obj) { println("$key=$value") } }
0
Kotlin
0
0
270b88ef0fa5303ef3a4a273ef7267fac92b56da
663
kotlin-sandbox
Apache License 2.0
plugin/src/org/jetbrains/yesod/hamlet/completion/HamletCompletionContributor.kt
Atsky
12,811,746
false
null
package org.jetbrains.yesod.hamlet.completion /** * @author Leyla H */ import com.intellij.codeInsight.completion.CompletionContributor import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElementBuilder import java.util.Arrays class HamletCompletionContributor : CompletionContributor() { override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (parameters.completionType === CompletionType.BASIC) { for (tagName in TAGS) { result.addElement(LookupElementBuilder.create(tagName)) } for (tagName in ATTRIBUTES) { result.addElement(LookupElementBuilder.create(tagName)) } } } companion object { var ATTRIBUTES: List<String> = Arrays.asList( "accept", "accept-charset", "accesskey", "action", "align", "itemprop", "alt", "async", "autocomplete", "autofocus", "autoplay", "autosave", "bgcolor", "border", "buffered", "challenge", "charset", "checked", "cite", "class", "code", "codebase", "color", "cols", "colspan", "content", "contenteditable", "contextmenu", "controls", "coords", "data", "data-*", "datetime", "default", "defer", "dir", "dirname", "disabled", "download", "draggable", "dropzone", "enctype", "for", "form", "formaction", "headers", "height", "hidden", "high", "href", "hreflang", "http-equiv", "icon", "id", "ismap", "keytype", "kind", "label", "lang", "language", "list", "loop", "low", "manifest", "max", "maxlength", "media", "method", "min", "multiple", "name", "novalidate", "open", "optimum", "pattern", "ping", "placeholder", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "alternate", "archives", "author", "bookmark", "external", "first", "help", "icon", "index", "last", "license", "next", "nofollow", "noreferrer", "pingback", "prefetch", "prev", "search", "sidebar", "stylesheet", "tag", "up", "required", "reversed", "rows", "rowspan", "sandbox", "scope", "scoped", "seamless", "selected", "shape", "size", "sizes", "span", "spellcheck", "src", "srcdoc", "srclang", "srcset", "start", "step", "style", "summary", "tabindex", "target", "title", "type", "usemap", "value", "width", "wrap" ) var TAGS: List<String> = Arrays.asList( "a", "abbr", "address", "area", "b", "base", "bdo", "blockquote", "body", "br", "button", "caption", "cite", "code", "col", "colgroup", "dd", "del", "dfn", "div", "dl", "dt", "em", "fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "label", "legend", "li", "link", "map", "meta", "noscript", "object", "ol", "optgroup", "option", "p", "param", "pre", "q", "s", "samp", "script", "select", "small", "span", "strong", "style", "sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "title", "tr", "u", "ul", "var", "acronym", "applet", "basefont", "big", "blink", "center", "command", "dir", "font", "frame", "frameset", "hgroup", "isindex", "listing", "noframes", "plaintext", "spacer", "strike", "tt", "xmp", "article", "aside", "audio", "bdi", "canvas", "content", "data", "datalist", "details", "dialog", "element", "embed", "figcaption", "figure", "footer", "header", "keygen", "main", "mark", "menu", "menuitem", "meter", "nav", "output", "picture", "progress", "rp", "rt", "rtc", "ruby", "section", "source", "summary", "template", "time", "track", "video", "wbr" ) } }
47
Kotlin
22
205
a9be4e8c41202cba50f6f9aa72eb912f1fa92b8c
5,529
haskell-idea-plugin
Apache License 2.0
src/org/jetbrains/r/classes/s4/context/setClass/RS4SetClassContextProvider.kt
JetBrains
214,212,060
false
null
/* * Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.r.classes.s4.context.setClass import com.intellij.pom.PomTargetPsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.r.classes.s4.classInfo.RSkeletonS4ClassPomTarget import org.jetbrains.r.classes.s4.context.RS4ContextProvider import org.jetbrains.r.hints.parameterInfo.RArgumentInfo import org.jetbrains.r.psi.api.RCallExpression import org.jetbrains.r.psi.api.RNamedArgument import org.jetbrains.r.psi.api.RPsiElement import org.jetbrains.r.psi.api.RStringLiteralExpression import org.jetbrains.r.psi.isFunctionFromLibrarySoft sealed class RS4SetClassTypeContext : RS4SetClassContext() // setClass("<caret>") data class RS4SetClassClassNameContext(override val originalElement: RPsiElement, override val contextFunctionCall: RCallExpression) : RS4SetClassTypeContext() sealed class RS4SetClassTypeUsageContext : RS4SetClassTypeContext() // setClass("MyClass", "<caret>") data class RS4SetClassRepresentationContext(override val originalElement: RPsiElement, override val contextFunctionCall: RCallExpression) : RS4SetClassTypeUsageContext() // setClass("MyClass", , , "<caret>") data class RS4SetClassContainsContext(override val originalElement: RPsiElement, override val contextFunctionCall: RCallExpression) : RS4SetClassTypeUsageContext() // setClass("MyClass", contains = "<caret>") // setClass("MyClass", contains = c("<caret>")) // setClass("MyClass", contains = c(smt = "<caret>") // setClass("MyClass", representation = representation(smt = "<caret>") // setClass("MyClass", representation = representation("<caret>") // setClass("MyClass", slots = c(name = "<caret>")) data class RS4SetClassDependencyClassNameContext(override val originalElement: RPsiElement, override val contextFunctionCall: RCallExpression) : RS4SetClassTypeUsageContext() class RS4SetClassTypeContextProvider : RS4ContextProvider<RS4SetClassTypeContext>() { override fun getS4ContextWithoutCaching(element: RPsiElement): RS4SetClassTypeContext? { val parentCall = PsiTreeUtil.getParentOfType(element, RCallExpression::class.java) ?: return null return if (parentCall.isFunctionFromLibrarySoft("setClass", "methods")) { val parentArgumentInfo = RArgumentInfo.getArgumentInfo(parentCall) ?: return null when (element) { parentArgumentInfo.getArgumentPassedToParameter("Class") -> { // setClass("<caret>") if (element is RStringLiteralExpression) RS4SetClassClassNameContext(element, parentCall) else null } parentArgumentInfo.getArgumentPassedToParameter("representation") -> { // setClass("MyClass", "<caret>") RS4SetClassRepresentationContext(element, parentCall) } parentArgumentInfo.getArgumentPassedToParameter("contains") -> { // setClass("MyClass", , , "<caret>") RS4SetClassContainsContext(element, parentCall) } else -> null } } else { val grandParentCall = PsiTreeUtil.getParentOfType(parentCall, RCallExpression::class.java) ?: return null if (grandParentCall.isFunctionFromLibrarySoft("setClass", "methods")) { val grandParentArgumentInfo = RArgumentInfo.getArgumentInfo(grandParentCall) ?: return null return when { // setClass("MyClass", contains = "<caret>") // setClass("MyClass", contains = c("<caret>")) // setClass("MyClass", contains = c(smt = "<caret>") // setClass("MyClass", representation = representation(smt = "<caret>") // setClass("MyClass", representation = representation("<caret>") PsiTreeUtil.isAncestor(grandParentArgumentInfo.getArgumentPassedToParameter("contains"), element, false) || PsiTreeUtil.isAncestor(grandParentArgumentInfo.getArgumentPassedToParameter("representation"), element, false) -> { val parent = element.parent if (parent is RNamedArgument && parent.nameIdentifier == element) null else RS4SetClassDependencyClassNameContext(element, grandParentCall) } // setClass("MyClass", slots = c(name = "<caret>")) PsiTreeUtil.isAncestor(grandParentArgumentInfo.getArgumentPassedToParameter("slots"), element, false) -> { val parent = element.parent if (parent !is RNamedArgument || parent.assignedValue != element) null else RS4SetClassDependencyClassNameContext(element, grandParentCall) } else -> null } } else { val grandGrandParentCall = PsiTreeUtil.getParentOfType(grandParentCall, RCallExpression::class.java) ?: return null if (!grandGrandParentCall.isFunctionFromLibrarySoft("setClass", "methods")) return null val grandGrandParentArgumentInfo = RArgumentInfo.getArgumentInfo(grandGrandParentCall) ?: return null // setClass("MyClass", slots = c(name = c("<caret>"))) // setClass("MyClass", slots = c(name = c(ext = "<caret>"))) if (PsiTreeUtil.isAncestor(grandGrandParentArgumentInfo.getArgumentPassedToParameter("slots"), element, false)) { val parent = element.parent if (parent is RNamedArgument && parent.nameIdentifier == element) null else RS4SetClassDependencyClassNameContext(element, grandGrandParentCall) } else null } } } override fun getS4ContextForPomTarget(element: PomTargetPsiElement): RS4SetClassTypeContext? { return when (val target = element.target) { is RSkeletonS4ClassPomTarget -> RS4SetClassClassNameContext(element as RPsiElement, target.setClass) else -> null } } }
2
null
13
62
8b4f3aac10693cbfb5841f0afff46338bffbc50e
5,931
Rplugin
Apache License 2.0
app/src/main/java/com/example/freeweather/domain/WeatherForecast.kt
85-simo
432,492,481
false
{"Kotlin": 65315}
package com.example.freeweather.domain import java.util.* /** * Domain level classes used to provide a data representation that fits the business requirements/logic. * By not giving upper layers access to the data-level representation, we minimise the impact that any changes at the data level could * have on the rest of the application. */ data class WeatherForecast( val currentWeather: CurrentWeather, val dailyWeather: List<WeatherPrediction> ) data class CurrentWeather( val description: String, val iconSmall: String, val iconLarge: String, val temperature: Float, val perceivedTemp: Float, val minTemp: Float, val maxTemp: Float, val pressure: Int, val humidity: Int, val visibility: Int, val windSpeed: Float, val windAngle: Int, val timestamp: Date, val sunrise: Date, val sunset: Date ) data class WeatherPrediction( val description: String, val iconSmall: String, val iconLarge: String, val minTemp: Float, val maxTemp: Float, val timestamp: Date )
0
Kotlin
0
0
7f93e66882a64cec87e8825c876296a1a5e3291c
1,061
freeweather
Apache License 2.0
src/main/java/com/ecwid/maleorang/method/v3_0/reports/CampaignIndustryStatsReport.kt
lararojasmr
70,038,605
true
{"Kotlin": 134005, "Java": 18725}
package com.ecwid.maleorang.method.v3_0.reports import com.ecwid.maleorang.MailchimpObject import com.ecwid.maleorang.annotation.Field import java.util.* /** * Created by: Manuel Lara <[email protected]> */ class CampaignIndustryStatsReport : MailchimpObject() { @JvmField @Field var type: String? = null @JvmField @Field var open_rate: Double? = null @JvmField @Field var click_rate: Double? = null @JvmField @Field var bounce_rate: Double? = null @JvmField @Field var unopen_rate: Double? = null @JvmField @Field var unsub_rate: Double? = null @JvmField @Field var abuse_rate: Double? = null }
0
Kotlin
0
0
5b22bdc5fb1efa9ead2c45f9824577da1fb71aeb
712
maleorang
Apache License 2.0
integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/android/app/src/main/java/com/workflowgenexample/WorkflowGenExamplePackage.kt
advantys
72,514,996
false
{"Text": 9, "Ignore List": 11, "Markdown": 31, "XML": 76, "Microsoft Visual Studio Solution": 3, "ASP.NET": 7, "HTML": 4, "C#": 61, "Smalltalk": 6, "JSON": 44, "HTML+Razor": 18, "CSS": 23, "JavaScript": 140, "Git Attributes": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Starlark": 3, "Proguard": 1, "Java": 1, "Kotlin": 6, "INI": 1, "Objective-C": 10, "Swift": 3, "OpenStep Property List": 4}
package com.workflowgenexample import android.view.View import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ReactShadowNode import com.facebook.react.uimanager.ViewManager import com.workflowgenexample.modules.CodeGenerator import com.workflowgenexample.modules.JWT import com.workflowgenexample.modules.WebBrowser class WorkflowGenExamplePackage : ReactPackage { override fun createViewManagers(reactContext: ReactApplicationContext): MutableList<ViewManager<View, ReactShadowNode<*>>> = mutableListOf() override fun createNativeModules(reactContext: ReactApplicationContext): MutableList<NativeModule> = mutableListOf( WebBrowser(reactContext), CodeGenerator(reactContext), JWT(reactContext) ) }
27
JavaScript
0
2
6235148a525a7fe513d34a4928bba21407c40119
895
workflowgen-templates
MIT License
app/src/main/java/com/melonhead/mangadexfollower/navigation/MainActivityResolver.kt
julieminer
542,405,576
false
{"Kotlin": 200334}
package com.melonhead.mangadexfollower.navigation import android.content.Context import android.content.Intent import com.melonhead.lib_navigation.keys.ActivityKey import com.melonhead.lib_navigation.resolvers.ActivityResolver import com.melonhead.mangadexfollower.ui.scenes.MainActivity class MainActivityResolver: ActivityResolver<ActivityKey.MainActivity> { override fun intentForKey(context: Context, key: ActivityKey.MainActivity): Intent { return Intent(context, MainActivity::class.java) } }
7
Kotlin
0
0
2fdb5aee10ee750a22c6d6827472f7fe2362192e
517
mangadexdroid
Do What The F*ck You Want To Public License
core/src/main/kotlin/ch/ergon/dope/resolvable/expression/unaliased/type/stringfunction/RpadExpression.kt
ergon
745,483,606
false
{"Kotlin": 173739}
package ch.ergon.dope.resolvable.expression.unaliased.type.stringfunction import ch.ergon.dope.resolvable.expression.TypeExpression import ch.ergon.dope.resolvable.expression.unaliased.type.toNumberType import ch.ergon.dope.resolvable.expression.unaliased.type.toStringType import ch.ergon.dope.resolvable.operator.FunctionOperator import ch.ergon.dope.validtype.StringType class RpadExpression( private val inStr: TypeExpression<StringType>, private val size: Int, private val extra: TypeExpression<StringType> = " ".toStringType(), ) : TypeExpression<StringType>, FunctionOperator { override fun toQueryString(): String = toFunctionQueryString(symbol = "RPAD", inStr, size.toNumberType(), extra) } fun rpad(inStr: TypeExpression<StringType>, size: Int, extra: TypeExpression<StringType> = "".toStringType()) = RpadExpression(inStr, size, extra) fun rpad(inStr: String, size: Int, extra: String = ""): RpadExpression = rpad(inStr.toStringType(), size, extra.toStringType()) fun rpad(inStr: String, size: Int): RpadExpression = rpad(inStr.toStringType(), size) fun rpad(inStr: TypeExpression<StringType>, size: Int): RpadExpression = RpadExpression(inStr, size) fun rpad(inStr: TypeExpression<StringType>, size: Int, extra: String = ""): RpadExpression = rpad(inStr, size, extra.toStringType()) fun rpad(inStr: String, size: Int, extra: TypeExpression<StringType> = "".toStringType()): RpadExpression = rpad( inStr.toStringType(), size, extra, )
0
Kotlin
0
3
0d97fb4a52b6f0face58f3ae4529d59e2cb9b4ec
1,486
dope-query-builder
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/networkfirewall/RuleOptionPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.networkfirewall import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.networkfirewall.CfnRuleGroup @Generated public fun buildDimensionProperty(initializer: @AwsCdkDsl CfnRuleGroup.DimensionProperty.Builder.() -> Unit): CfnRuleGroup.DimensionProperty = CfnRuleGroup.DimensionProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
457
aws-cdk-kt
Apache License 2.0
plugins/kotlin/j2k/new/tests/testData/newJ2k/newJavaFeatures/textBlocks/tripleQuote.kt
ingokegel
72,937,917
false
null
object J { @JvmStatic fun main(args: Array<String>) { val code = """ String source = ${'"'}"" String message = "Hello, World!"; System.out.println(message); ""${'"'}; """.trimIndent() } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
241
intellij-community
Apache License 2.0
bitgouel-domain/src/main/kotlin/team/msg/domain/student/repository/StudentActivityHistoryRepository.kt
GSM-MSG
700,741,727
false
{"Kotlin": 210262, "Shell": 788, "Dockerfile": 206}
package team.msg.domain.student.repository import org.springframework.data.repository.CrudRepository import team.msg.domain.student.model.StudentActivityHistory import java.util.UUID interface StudentActivityHistoryRepository : CrudRepository<StudentActivityHistory, UUID> { }
4
Kotlin
0
11
d06ca08da1f751f55e2b6a2fdaf4be2bf179ff44
278
Bitgouel-Server
MIT License
domain/client/src/test/kotlin/io/github/siyual_park/client/domain/auth/RefreshTokenAuthorizationStrategyTest.kt
siyul-park
403,557,925
false
null
package io.github.siyual_park.client.domain.auth import io.github.siyual_park.auth.domain.authentication.RefreshTokenPayload import io.github.siyual_park.auth.domain.token.ClaimEmbedder import io.github.siyual_park.auth.domain.token.TokenMapper import io.github.siyual_park.auth.domain.token.TokenStorage import io.github.siyual_park.auth.domain.token.TokenTemplate import io.github.siyual_park.auth.domain.token.TypeMatchClaimFilter import io.github.siyual_park.auth.repository.TokenEntityRepository import io.github.siyual_park.client.domain.ClientTestHelper import io.github.siyual_park.client.domain.MockCreateClientPayloadFactory import io.github.siyual_park.client.entity.ClientAssociable import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.Duration class RefreshTokenAuthorizationStrategyTest : ClientTestHelper() { private val tokenEntityRepository = TokenEntityRepository(mongoTemplate) private val tokenMapper = TokenMapper(tokenEntityRepository, scopeTokenStorage) private val claimEmbedder = ClaimEmbedder() private val tokenStorage = TokenStorage(claimEmbedder, tokenEntityRepository, tokenMapper) private val refreshTokenAuthorizationStrategy = RefreshTokenAuthorizationStrategy(tokenStorage) init { claimEmbedder.register(TypeMatchClaimFilter(ClientAssociable::class), ClientAssociableClaimEmbeddingStrategy()) } @Test fun authenticate() = blocking { val template = TokenTemplate(type = "test", age = Duration.ofMinutes(30)) val tokenFactory = tokenStorage.createFactory(template) val client = MockCreateClientPayloadFactory.create() .let { clientStorage.save(it) } val principal = client.toPrincipal() val token = tokenFactory.create(principal) assertEquals( principal.copy(id = token.id), refreshTokenAuthorizationStrategy.authenticate(RefreshTokenPayload(token.signature)) ) } }
9
Kotlin
0
18
4030accdd8b8e9a2d5f3bdbfbf782bfce4e6c5f3
1,999
spring-webflux-multi-module-boilerplate
MIT License
core/src/main/java/io/github/keep2iron/pejoy/internal/entity/IncapableCause.kt
ieewbbwe
194,812,354
true
{"Kotlin": 181793, "Java": 3397}
/* * Copyright 2017 Zhihu 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 &quot;AS IS&quot; BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.keep2iron.pejoy.internal.entity import android.content.Context import android.support.annotation.IntDef import android.widget.Toast class IncapableCause @JvmOverloads constructor( @Form val form: Int? = TOAST, val title: String? = null, val message: String ) { @Retention(AnnotationRetention.SOURCE) @IntDef(TOAST, DIALOG, NONE) annotation class Form companion object { const val TOAST = 0x00 const val DIALOG = 0x01 const val NONE = 0x02 fun handleCause(context: Context, cause: IncapableCause?) { if (cause == null) { return } when (cause.form) { NONE -> { } DIALOG -> { } TOAST -> Toast.makeText(context, cause.message, Toast.LENGTH_SHORT).show() else -> Toast.makeText(context, cause.message, Toast.LENGTH_SHORT).show() }// do nothing. // IncapableDialog incapableDialog = IncapableDialog.newInstance(cause.title, cause.message); // incapableDialog.show(((FragmentActivity) context).getSupportFragmentManager(), // IncapableDialog.class.getName()); } } }
0
Kotlin
0
0
9bbee331bd8a17a620be49538acc7737a135e45d
1,905
pejoy
Apache License 2.0
client/src/main/java/app/kula/onlaunch/client/data/models/Message.kt
kula-app
574,968,481
false
{"Kotlin": 13012}
package app.kula.onlaunch.client.data.models import android.os.Parcelable import androidx.annotation.Keep import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize internal data class Message( val id: Int, val title: String, val body: String, val isBlocking: Boolean, val actions: List<Action>, ) : Parcelable @Parcelize internal data class Action( val title: String, val actionType: Type, ) : Parcelable { @Keep enum class Type { @SerializedName("DISMISS") DISMISS } }
4
Kotlin
0
1
8335d75c0009cb5d78a75fae946bf23fdd1d6c8a
567
OnLaunch-Android-Client
MIT License
graphql-dgs-codegen-core/src/integTest/kotlin/com/netflix/graphql/dgs/codegen/cases/inputWithDefaultStringValueForArray/expected/DgsConstants.kt
Netflix
317,379,776
false
{"Kotlin": 1255293, "Python": 7680, "Java": 5969, "Makefile": 982, "Dockerfile": 246}
package com.netflix.graphql.dgs.codegen.cases.inputWithDefaultStringValueForArray.expected import kotlin.String public object DgsConstants { public object SOMETYPE { public const val TYPE_NAME: String = "SomeType" public const val Names: String = "names" } }
91
Kotlin
96
181
57b2e1e6db8da146cfa590a0c331ac15ef156085
274
dgs-codegen
Apache License 2.0
mobile_app1/module224/src/main/java/module224packageKt0/Foo206.kt
uber-common
294,831,672
false
null
package module224packageKt0; annotation class Foo206Fancy @Foo206Fancy class Foo206 { fun foo0(){ module224packageKt0.Foo205().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
237
android-build-eval
Apache License 2.0
app/src/main/java/com/example/gekata_mobile/ui/Screens/PathIndoorScreen/IndoorMainScreen.kt
Onixx-dev
754,679,819
false
{"Kotlin": 103826}
package com.example.gekata_mobile.ui.Screens.PathIndoorScreen import android.util.Log import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowLeft import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.wear.compose.material.LocalContentAlpha import com.example.gekata_mobile.ModelView.Realisation.PathFinding.LevelPathFinder import com.example.gekata_mobile.ModelView.Realisation.PathFinding.PathContainer import com.example.gekata_mobile.ModelView.Realisation.PathFinding.TreeNode import com.example.gekata_mobile.ModelView.Realisation.ProjectsViewModel import com.example.gekata_mobile.Models.Basic.Level import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import java.util.ArrayDeque import kotlin.math.pow import kotlin.math.sqrt @Composable fun IndoorMainScreen( modifier: Modifier = Modifier, projectsViewModel: ProjectsViewModel, pathContainer: PathContainer ) { Column( modifier = modifier.fillMaxSize() ) { LevelCanvas( modifier = modifier, projectsViewModel = projectsViewModel, pathContainer = pathContainer ) LevelSelector( modifier = modifier, projectsViewModel = projectsViewModel, pathContainer = pathContainer ) } } @Composable fun LevelCanvas( modifier: Modifier, projectsViewModel: ProjectsViewModel, pathContainer: PathContainer ) { val paint = Paint().asFrameworkPaint().apply { this.textSize = 50f } val offset = remember { mutableStateOf(projectsViewModel.levelCanvasOffset) } val scale = remember { mutableFloatStateOf(projectsViewModel.levelCanvasScale) } val rotate = remember { mutableFloatStateOf(projectsViewModel.levelCanvasRotate) } val rotateMagnitude = 0.2f val zoomMagnitude = 0.4f Canvas( modifier = modifier .fillMaxHeight(0.9f) .fillMaxWidth() .background(Color.White) .border(2.dp, color = Color.Cyan) .pointerInput(Unit) { detectTransformGestures { var1, localOffset, zoom, rotation -> run { scale.floatValue *= zoom rotate.floatValue += rotation offset.value = Offset( x = offset.value.x + localOffset.x, y = offset.value.y + localOffset.y ) } } } ) { drawIntoCanvas { it.nativeCanvas.drawText( projectsViewModel.levelCanvasOffset.toString(), 20f, 60f, paint ) } withTransform({ translate(offset.value.x, offset.value.y) rotate(rotate.floatValue * rotateMagnitude) scale(scale.floatValue * zoomMagnitude, scale.floatValue * zoomMagnitude) }) { pathContainer.getItem(projectsViewModel.levelIndex).walls.forEach { drawLine( start = Offset(x = it.startX!!.toFloat(), y = it.startY!!.toFloat()), end = Offset(x = it.endX!!.toFloat(), y = it.endY!!.toFloat()), strokeWidth = 4f, color = Color.Black ) } /////// TREE DRAW val stack = ArrayDeque<TreeNode>() var treeItem: TreeNode if (!pathContainer.getItem(projectsViewModel.levelIndex).isTreeNodeInitialised()) pathContainer.getItem(projectsViewModel.levelIndex).pathTreeRoot = TreeNode(100, 100) stack.push(pathContainer.getItem(projectsViewModel.levelIndex).pathTreeRoot) do { treeItem = stack.pop() for (way in treeItem.childs) drawLine( start = Offset(x = treeItem.x.toFloat(), y = treeItem.y.toFloat()), end = Offset(x = way.x.toFloat(), y = way.y.toFloat()), strokeWidth = 3f, color = Color.Red ) for (child in treeItem.childs) stack.push(child) } while (!stack.isEmpty()) ////////////////////////// FINAL PATH DRAW if (pathContainer.getItem(projectsViewModel.levelIndex).isFinalPathInitialised()) { stack.clear() stack.push(pathContainer.getItem(projectsViewModel.levelIndex).finalPath) do { treeItem = stack.pop() for (way in treeItem.childs) drawLine( start = Offset(x = treeItem.x.toFloat(), y = treeItem.y.toFloat()), end = Offset(x = way.x.toFloat(), y = way.y.toFloat()), strokeWidth = 9f, color = Color.Green ) for (child in treeItem.childs) stack.push(child) } while (!stack.isEmpty()) } ////////////////////////// FINAL PATH DRAW if (pathContainer.getItem(projectsViewModel.levelIndex).isFinalPathInitialised()) { stack.clear() stack.push(pathContainer.getItem(projectsViewModel.levelIndex).test) do { treeItem = stack.pop() for (way in treeItem.childs) drawLine( start = Offset(x = treeItem.x.toFloat(), y = treeItem.y.toFloat()), end = Offset(x = way.x.toFloat(), y = way.y.toFloat()), strokeWidth = 4f, color = Color.Red ) for (child in treeItem.childs) stack.push(child) } while (!stack.isEmpty()) } pathContainer.getItem(projectsViewModel.levelIndex).wayPoints.forEach { drawCircle( center = Offset(x = it.x!!.toFloat(), y = it.y!!.toFloat()), radius = 25f, color = Color.Black ) drawCircle( center = Offset(x = it.x!!.toFloat(), y = it.y!!.toFloat()), radius = 23f, color = Color.Cyan ) } pathContainer.getItem(projectsViewModel.levelIndex).interestPoints.forEach { drawCircle( center = Offset(x = it.x!!.toFloat(), y = it.y!!.toFloat()), radius = 25f, color = Color.Black ) drawCircle( center = Offset(x = it.x!!.toFloat(), y = it.y!!.toFloat()), radius = 23f, color = Color.Green ) } drawCircle( center = Offset( x = pathContainer.getItem(projectsViewModel.levelIndex).startPoint.getX().toFloat(), y = pathContainer.getItem(projectsViewModel.levelIndex).startPoint.getY().toFloat()), radius = 14f, color = Color.Magenta ) drawCircle( center = Offset( x = pathContainer.getItem(projectsViewModel.levelIndex).endpoint.getX().toFloat(), y = pathContainer.getItem(projectsViewModel.levelIndex).endpoint.getY().toFloat()), radius = 14f, color = Color.Blue ) } } } @Composable fun LevelSelector( modifier: Modifier, projectsViewModel: ProjectsViewModel, pathContainer: PathContainer ) { Row( modifier = modifier .fillMaxHeight(1.0f) .fillMaxWidth() ) { OutlinedTextField( value = pathContainer.getItem(projectsViewModel.levelIndex).name!!, onValueChange = {}, enabled = false, readOnly = true, colors = OutlinedTextFieldDefaults.colors( disabledTextColor = LocalContentColor.current.copy( LocalContentAlpha.current ) ), modifier = modifier .weight(14f) .fillMaxHeight() ) Button( onClick = { if (projectsViewModel.levelIndex > 0) { projectsViewModel.levelIndex = projectsViewModel.levelIndex - 1 } }, modifier = modifier .weight(3f) .fillMaxHeight(), shape = RectangleShape ) { Icon(imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft, contentDescription = "") } Button( onClick = { if (projectsViewModel.levelIndex < pathContainer.getSize() - 1) { projectsViewModel.levelIndex = projectsViewModel.levelIndex + 1 } }, modifier = modifier .weight(3f) .fillMaxHeight(), shape = RectangleShape ) { Icon( imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = "", modifier = modifier.fillMaxSize() ) } } }
0
Kotlin
0
0
398ab133654b1a71db30afb669251d2eea1cade0
12,123
Gekata_mobile
MIT License
src/test/kotlin/jenkins/plugins/accurevclient/CacheUnitTest.kt
moegwsa
140,700,194
false
{"Gradle": 1, "Markdown": 3, "Gradle Kotlin DSL": 1, "Java Properties": 1, "YAML": 4, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Groovy": 1, "INI": 1, "Java": 2, "XML": 11, "Kotlin": 38}
package jenkins.plugins.accurevclient import hudson.util.ArgumentListBuilder import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Test import java.util.concurrent.Callable import java.util.concurrent.TimeUnit class CacheUnitTest { @Test fun testEmptyCache() { val cacheUnit: Cache<String, CacheUnitTest> = Cache(1, TimeUnit.MINUTES) assertEquals(cacheUnit.size(), 0) } @Test fun testInitialCache() { val cache: Cache<String, TestObject> = Cache(1, TimeUnit.MINUTES) assertEquals(cache.size(), 0) val items = cache["testKey", Callable { with(argumentBuilder("CacheEntry1")) { return@Callable launch() } } ] ?: TestObject() assertEquals(items.name, "CacheEntry1") assertEquals(cache.size(), 1) } @Test fun testNoDuplicateEntries() { val cache: Cache<String, TestObject> = Cache(1, TimeUnit.MINUTES) assertEquals(cache.size(), 0) val item1 = cache["testKey", Callable { with(argumentBuilder("CacheEntry1")) { return@Callable launch() } } ] ?: TestObject() assertEquals(item1.name, "CacheEntry1") assertEquals(cache.size(), 1) val item2 = cache["testKey", Callable { with(argumentBuilder("CacheEntry1")) { return@Callable launch() } } ] ?: TestObject() assertEquals(item1.name, item2.name) assertEquals(cache.size(), 1) } @Test fun testItemNotInCache() { val cache: Cache<String, TestObject> = Cache(1, TimeUnit.MINUTES) assertEquals(cache.size(), 0) val item1 = cache["testKey", Callable { with(argumentBuilder("CacheEntry1")) { return@Callable launch() } } ] ?: TestObject() assertEquals(cache.size(), 1) assertNotEquals(item1.name, "CacheEntry2") val item2 = cache["testKey2", Callable { with(argumentBuilder("CacheEntry2")) { return@Callable launch() } } ] ?: TestObject() assertEquals(item2.name, "CacheEntry2") assertEquals(cache.size(), 2) } @Test fun testReplaceKeyWhenFullCache() { val cache: Cache<String, TestObject> = Cache(1, TimeUnit.MINUTES, 1) assertEquals(0, cache.size()) val item1 = cache["testKey", Callable { with(argumentBuilder("CacheEntry1")) { return@Callable launch() } } ] ?: TestObject() assertEquals(cache.size(), 1) assertEquals(item1.name, "CacheEntry1") val item2 = cache["testKey1", Callable { with(argumentBuilder("CacheEntry2")) { return@Callable launch() } } ] ?: TestObject() assertEquals(cache.size(), 1) assertEquals(item2.name, "CacheEntry2") } @Test fun testClearCache() { val cache: Cache<String, TestObject> = Cache(1, TimeUnit.MINUTES, 1) assertEquals(0, cache.size()) val item1 = cache["testKey", Callable { with(argumentBuilder("CacheEntry1")) { return@Callable launch() } } ] ?: TestObject() assertEquals(1, cache.size()) assertEquals("CacheEntry1", item1.name) cache.evictAll() assertEquals(0, cache.size()) } private fun argumentBuilder(cmd: String) = ArgumentListBuilder().apply { add(cmd) } private fun ArgumentListBuilder.launch(): TestObject = [email protected](this) private fun emulateLaunchCommand(args: ArgumentListBuilder): TestObject { val list = args.toList() val requestedKeys: MutableList<TestObject> = arrayListOf() list.forEach { word -> requestedKeys.add(TestObject(word)) } return requestedKeys[0] } data class TestObject( val name: String = "" ) }
0
Kotlin
0
0
73647acc7c94d39a0a95df1d75064189e4142b6a
4,048
accurev-client-plugin
MIT License
src/main/kotlin/io/newm/kogmios/protocols/model/ParamsUtxo.kt
projectNEWM
469,781,993
false
{"Kotlin": 332376, "Shell": 26}
package io.newm.kogmios.protocols.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed class ParamsUtxo : Params() @Serializable data class ParamsUtxoByOutputReferences( @SerialName("outputReferences") val outputReferences: List<UtxoOutputReference>, ) : ParamsUtxo() @Serializable data class ParamsUtxoByAddresses( @SerialName("addresses") val addresses: List<String>, ) : ParamsUtxo()
0
Kotlin
0
4
b611cda42cae450b6b4398e029cf69d3059032f1
463
kogmios
Apache License 2.0
app/src/main/java/com/lagradost/cloudstream3/mvvm/ArchComponentExt.kt
LagradOst
363,210,353
false
null
package com.lagradost.cloudstream3.mvvm import android.util.Log import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import com.bumptech.glide.load.HttpException import com.lagradost.cloudstream3.ErrorLoadingException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.net.SocketTimeoutException import java.net.UnknownHostException import javax.net.ssl.SSLHandshakeException fun <T> LifecycleOwner.observe(liveData: LiveData<T>, action: (t: T) -> Unit) { liveData.observe(this) { it?.let { t -> action(t) } } } fun <T> LifecycleOwner.observeDirectly(liveData: LiveData<T>, action: (t: T) -> Unit) { liveData.observe(this) { it?.let { t -> action(t) } } val currentValue = liveData.value if (currentValue != null) action(currentValue) } sealed class Resource<out T> { data class Success<out T>(val value: T) : Resource<T>() data class Failure( val isNetworkError: Boolean, val errorCode: Int?, val errorResponse: Any?, //ResponseBody val errorString: String, ) : Resource<Nothing>() data class Loading(val url: String? = null) : Resource<Nothing>() } fun logError(throwable: Throwable) { Log.d("ApiError", "-------------------------------------------------------------------") Log.d("ApiError", "safeApiCall: " + throwable.localizedMessage) Log.d("ApiError", "safeApiCall: " + throwable.message) throwable.printStackTrace() Log.d("ApiError", "-------------------------------------------------------------------") } fun <T> normalSafeApiCall(apiCall: () -> T): T? { return try { apiCall.invoke() } catch (throwable: Throwable) { logError(throwable) return null } } fun <T> safeFail(throwable: Throwable): Resource<T> { val stackTraceMsg = (throwable.localizedMessage ?: "") + "\n\n" + throwable.stackTrace.joinToString( separator = "\n" ) { "${it.fileName} ${it.lineNumber}" } return Resource.Failure(false, null, null, stackTraceMsg) } suspend fun <T> safeApiCall( apiCall: suspend () -> T, ): Resource<T> { return withContext(Dispatchers.IO) { try { Resource.Success(apiCall.invoke()) } catch (throwable: Throwable) { logError(throwable) when (throwable) { is NullPointerException -> { for (line in throwable.stackTrace) { if (line.fileName.endsWith("provider.kt", ignoreCase = true)) { return@withContext Resource.Failure( false, null, null, "NullPointerException at ${line.fileName} ${line.lineNumber}\nSite might have updated or added Cloudflare/DDOS protection" ) } } safeFail(throwable) } is SocketTimeoutException -> { Resource.Failure(true, null, null, "Connection Timeout\nPlease try again later.") } is HttpException -> { Resource.Failure(false, throwable.statusCode, null, throwable.message ?: "HttpException") } is UnknownHostException -> { Resource.Failure(true, null, null, "Cannot connect to server, try again later.") } is ErrorLoadingException -> { Resource.Failure(true, null, null, throwable.message ?: "Error loading, try again later.") } is NotImplementedError -> { Resource.Failure(false, null, null, "This operation is not implemented.") } is SSLHandshakeException -> { Resource.Failure( true, null, null, (throwable.message ?: "SSLHandshakeException") + "\nTry again later." ) } else -> safeFail(throwable) } } } }
98
Kotlin
75
489
317d6c2f83a6b0d10464c468a055ce2f08413a17
4,219
CloudStream-3
MIT License
app/src/main/java/com/lagradost/cloudstream3/mvvm/ArchComponentExt.kt
LagradOst
363,210,353
false
null
package com.lagradost.cloudstream3.mvvm import android.util.Log import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import com.bumptech.glide.load.HttpException import com.lagradost.cloudstream3.ErrorLoadingException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.net.SocketTimeoutException import java.net.UnknownHostException import javax.net.ssl.SSLHandshakeException fun <T> LifecycleOwner.observe(liveData: LiveData<T>, action: (t: T) -> Unit) { liveData.observe(this) { it?.let { t -> action(t) } } } fun <T> LifecycleOwner.observeDirectly(liveData: LiveData<T>, action: (t: T) -> Unit) { liveData.observe(this) { it?.let { t -> action(t) } } val currentValue = liveData.value if (currentValue != null) action(currentValue) } sealed class Resource<out T> { data class Success<out T>(val value: T) : Resource<T>() data class Failure( val isNetworkError: Boolean, val errorCode: Int?, val errorResponse: Any?, //ResponseBody val errorString: String, ) : Resource<Nothing>() data class Loading(val url: String? = null) : Resource<Nothing>() } fun logError(throwable: Throwable) { Log.d("ApiError", "-------------------------------------------------------------------") Log.d("ApiError", "safeApiCall: " + throwable.localizedMessage) Log.d("ApiError", "safeApiCall: " + throwable.message) throwable.printStackTrace() Log.d("ApiError", "-------------------------------------------------------------------") } fun <T> normalSafeApiCall(apiCall: () -> T): T? { return try { apiCall.invoke() } catch (throwable: Throwable) { logError(throwable) return null } } fun <T> safeFail(throwable: Throwable): Resource<T> { val stackTraceMsg = (throwable.localizedMessage ?: "") + "\n\n" + throwable.stackTrace.joinToString( separator = "\n" ) { "${it.fileName} ${it.lineNumber}" } return Resource.Failure(false, null, null, stackTraceMsg) } suspend fun <T> safeApiCall( apiCall: suspend () -> T, ): Resource<T> { return withContext(Dispatchers.IO) { try { Resource.Success(apiCall.invoke()) } catch (throwable: Throwable) { logError(throwable) when (throwable) { is NullPointerException -> { for (line in throwable.stackTrace) { if (line.fileName.endsWith("provider.kt", ignoreCase = true)) { return@withContext Resource.Failure( false, null, null, "NullPointerException at ${line.fileName} ${line.lineNumber}\nSite might have updated or added Cloudflare/DDOS protection" ) } } safeFail(throwable) } is SocketTimeoutException -> { Resource.Failure(true, null, null, "Connection Timeout\nPlease try again later.") } is HttpException -> { Resource.Failure(false, throwable.statusCode, null, throwable.message ?: "HttpException") } is UnknownHostException -> { Resource.Failure(true, null, null, "Cannot connect to server, try again later.") } is ErrorLoadingException -> { Resource.Failure(true, null, null, throwable.message ?: "Error loading, try again later.") } is NotImplementedError -> { Resource.Failure(false, null, null, "This operation is not implemented.") } is SSLHandshakeException -> { Resource.Failure( true, null, null, (throwable.message ?: "SSLHandshakeException") + "\nTry again later." ) } else -> safeFail(throwable) } } } }
98
Kotlin
75
489
317d6c2f83a6b0d10464c468a055ce2f08413a17
4,219
CloudStream-3
MIT License
app/src/main/java/com/sky/echo/Intent/LoginIntent.kt
Charlottenpl
725,392,352
false
{"Kotlin": 62317, "Java": 20752}
package com.sky.echo.Intent /** * 用户操作意图 */ sealed class LoginIntent { data class UpdateUsername(val username: String) : LoginIntent() data class UpdatePassword(val password: String) : LoginIntent() object Login : LoginIntent() object Logout : LoginIntent() data class CheckLoginStatus(val isLogin: (name: String)-> Unit, val isNotLogin: ()->Unit) : LoginIntent() }
0
Kotlin
0
0
458e94225ffe84c19b8af7481ec5a92405425721
389
echo
MIT License
kotlin-electron/src/jsMain/generated/electron/TouchBarSegmentedControlConstructorOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron typealias TouchBarSegmentedControlConstructorOptions = electron.core.TouchBarSegmentedControlConstructorOptions
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
184
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/geovnn/meteoapuane/presentation/incendi/IncendiViewModel.kt
geovnn
806,232,559
false
{"Kotlin": 407000}
package com.geovnn.meteoapuane.presentation.incendi import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.geovnn.meteoapuane.domain.models.HomePage import com.geovnn.meteoapuane.domain.models.IncendiPage import com.geovnn.meteoapuane.domain.use_cases.GetHomePage import com.geovnn.meteoapuane.domain.use_cases.GetIncendiPage import com.geovnn.meteoapuane.domain.utils.Resource import com.geovnn.meteoapuane.presentation.home.HomeState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class IncendiViewModel @Inject constructor( private val getIncendiPage: GetIncendiPage ) : ViewModel() { private val _state = MutableStateFlow(IncendiState()) val state: StateFlow<IncendiState> = _state.asStateFlow() private var updateJob: Job? = null init { // updateData() } fun updateData() { updateJob = viewModelScope.launch(Dispatchers.IO) { getIncendiPage().onEach {result -> when (result) { is Resource.Success -> { _state.value = state.value.copy( isLoading = false, error = "", incendiPage = result.data ?: IncendiPage(), ) } is Resource.Error -> { Log.d("Debug",result.message?: "e' null") _state.value = state.value.copy( isLoading = false, error = result.message ?: "Errore caricamento", incendiPage = IncendiPage(), ) } is Resource.Loading -> { _state.value = state.value.copy( isLoading = true, error = "" ) } } }.launchIn(this) } } }
0
Kotlin
0
0
4e9ef3838083395bd8acdbe7af6633a1c882622b
2,375
MeteoApuane-App
MIT License
core/src/main/java/com/lumiwallet/android/core/eos/ec/EcDsa.kt
lumiwallet
255,998,575
false
null
package com.lumiwallet.android.core.eos.ec import com.google.common.base.Preconditions import com.lumiwallet.android.core.crypto.ECKey import com.lumiwallet.android.core.utils.Sha256Hash import org.bouncycastle.asn1.x9.X9ECParameters import org.bouncycastle.crypto.digests.SHA256Digest import org.bouncycastle.crypto.signers.HMacDSAKCalculator import org.bouncycastle.math.ec.ECAlgorithms import java.math.BigInteger import java.util.* object EcDsa { class SigChecker internal constructor( hash: ByteArray, private var privKey: BigInteger ) { internal var e: BigInteger = BigInteger(1, hash) internal var r: BigInteger = BigInteger.ONE internal var s: BigInteger = BigInteger.ONE internal fun checkSignature( curveParam: X9ECParameters, k: BigInteger ): Boolean { val ecPoint = ECAlgorithms.referenceMultiply(curveParam.g, k).normalize() if (ecPoint.isInfinity) return false r = ecPoint.xCoord.toBigInteger().mod(curveParam.n) if (r.signum() == 0) return false s = k.modInverse(curveParam.n) .multiply(e.add(privKey.multiply(r))) .mod(curveParam.n) return s.signum() != 0 } fun isRSEachLength(length: Int): Boolean = r.toByteArray().size == length && s.toByteArray().size == length } fun sign(hash: ByteArray, key: EosPrivateKey): EcSignature { val privAsBI = key.asBigInteger val checker = SigChecker(hash, privAsBI) val curveParam = key.curveParam var nonce = 0 val calculator = HMacDSAKCalculator(SHA256Digest()) while (true) { val noncedHash = if (nonce > 0){ Sha256Hash.hash(hash, BigInteger.valueOf(nonce.toLong()).toByteArray()) } else hash calculator.init(ECKey.SECP256_K1_CURVE_PARAMS.n, privAsBI, noncedHash) checker.checkSignature(curveParam, calculator.nextK()) if (checker.s > (curveParam.n.shiftRight(1))) { checker.s = curveParam.n.subtract(checker.s) } if (checker.isRSEachLength(32)) { break } nonce++ } val signature = EcSignature(checker.r, checker.s, curveParam) val pubKey = key.publicKey for (i in 0..3) { val recovered = recoverPubKey(curveParam, hash, signature, i) if (pubKey == recovered) { signature.setRecid(i) break } } check(signature.recId >= 0) { "could not find recid. Was this data signed with this key?" } return signature } fun recoverPubKey(messageSigned: ByteArray, signature: EcSignature): EosPublicKey? { return recoverPubKey(signature.curveParam, messageSigned, signature, signature.recId) } private fun recoverPubKey( curveParam: X9ECParameters, messageSigned: ByteArray, signature: EcSignature, recId: Int ): EosPublicKey? { Preconditions.checkArgument(recId >= 0, "recId must be positive") Preconditions.checkArgument(signature.r >= BigInteger.ZERO, "r must be positive") Preconditions.checkArgument(signature.s >= BigInteger.ZERO, "s must be positive") Preconditions.checkNotNull(messageSigned) val n = curveParam.n val i = BigInteger.valueOf(recId.toLong() / 2) val x = signature.r.add(i.multiply(n)) if (x >= curveParam.getQ()) return null val r = EcTools.decompressKey(curveParam, x, recId and 1 == 1) if (!r.multiply(n).isInfinity) return null val e = BigInteger(1, messageSigned) val eInv = BigInteger.ZERO.subtract(e).mod(n) val rInv = signature.r.modInverse(n) val srInv = rInv.multiply(signature.s).mod(n) val eInvrInv = rInv.multiply(eInv).mod(n) val q = ECAlgorithms.sumOfTwoMultiplies(curveParam.g, eInvrInv, r, srInv) return EosPublicKey(q.getEncoded(true)) } private fun isSignerOf( curveParam: X9ECParameters, messageSigned: ByteArray, recId: Int, sig: EcSignature, pubKeyBytes: ByteArray ): Boolean { Preconditions.checkArgument(recId >= 0, "recId must be positive") Preconditions.checkArgument(sig.r >= BigInteger.ZERO, "r must be positive") Preconditions.checkArgument(sig.s >= BigInteger.ZERO, "s must be positive") Preconditions.checkNotNull(messageSigned) val n = curveParam.n val i = BigInteger.valueOf(recId.toLong() / 2) val x = sig.r.add(i.multiply(n)) if (x >= curveParam.getQ()) return false val r = EcTools.decompressKey(curveParam, x, recId and 1 == 1) if (!r.multiply(n).isInfinity) return false val e = BigInteger(1, messageSigned) val eInv = BigInteger.ZERO.subtract(e).mod(n) val rInv = sig.r.modInverse(n) val srInv = rInv.multiply(sig.s).mod(n) val eInvrInv = rInv.multiply(eInv).mod(n) val q = ECAlgorithms.sumOfTwoMultiplies(curveParam.g, eInvrInv, r, srInv) val recoveredPub = q.getEncoded(true) return Arrays.equals(recoveredPub, pubKeyBytes) } }
0
Kotlin
1
4
f4ba3bf7b4cd934f25b5b0271e1170aae496b4e5
5,391
lumi-android-core
Apache License 2.0