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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spesialist-selve/src/main/kotlin/no/nav/helse/modell/automatisering/AutomatiskAvvisningCommand.kt | navikt | 244,907,980 | false | null | package no.nav.helse.modell.automatisering
import java.util.UUID
import no.nav.helse.mediator.GodkjenningMediator
import no.nav.helse.mediator.meldinger.løsninger.HentEnhetløsning
import no.nav.helse.modell.UtbetalingsgodkjenningMessage
import no.nav.helse.modell.egenansatt.EgenAnsattDao
import no.nav.helse.modell.kommando.Command
import no.nav.helse.modell.kommando.CommandContext
import no.nav.helse.modell.kommando.CommandContext.Companion.ferdigstill
import no.nav.helse.modell.person.PersonDao
import no.nav.helse.modell.utbetaling.Utbetaling
import no.nav.helse.modell.vergemal.VergemålDao
import org.slf4j.LoggerFactory
internal class AutomatiskAvvisningCommand(
private val fødselsnummer: String,
private val vedtaksperiodeId: UUID,
private val egenAnsattDao: EgenAnsattDao,
private val personDao: PersonDao,
private val vergemålDao: VergemålDao,
private val godkjenningsbehovJson: String,
private val godkjenningMediator: GodkjenningMediator,
private val hendelseId: UUID,
private val utbetaling: Utbetaling?
) : Command {
override fun execute(context: CommandContext): Boolean {
val erEgenAnsatt = egenAnsattDao.erEgenAnsatt(fødselsnummer) ?: false
val tilhørerEnhetUtland = HentEnhetløsning.erEnhetUtland(personDao.finnEnhetId(fødselsnummer))
val underVergemål = vergemålDao.harVergemål(fødselsnummer) ?: false
if (!erEgenAnsatt && !tilhørerEnhetUtland && !underVergemål) return true
val årsaker = mutableListOf<String>()
if (erEgenAnsatt) årsaker.add("Egen ansatt")
if (tilhørerEnhetUtland) årsaker.add("Utland")
if (underVergemål) årsaker.add("Vergemål")
val behov = UtbetalingsgodkjenningMessage(godkjenningsbehovJson, utbetaling)
godkjenningMediator.automatiskAvvisning(context, behov, vedtaksperiodeId, fødselsnummer, årsaker.toList(), hendelseId)
logg.info("Automatisk avvisning av vedtaksperiode $vedtaksperiodeId pga:$årsaker")
return ferdigstill(context)
}
private companion object {
private val logg = LoggerFactory.getLogger(AutomatiskAvvisningCommand::class.java)
}
}
| 9 | Kotlin | 1 | 0 | 41cd81ebe57e453ba09d1ac5b0add2713850e4a6 | 2,156 | helse-spesialist | MIT License |
sample/src/main/java/com/jaber/stackcarousel/MainActivity.kt | JaberAhamed | 850,446,704 | false | {"Kotlin": 18365} | /*
* Copyright 2024 <NAME>. All rights reserved.
*
* ------------------------------------------------------------------------
*
* Project: StackCarousel
* Developed by: <NAME>
*
* Source:
*/
package com.jaber.stackcarousel
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import com.jaber.jbastackcarousel.StackCarousel
import com.jaber.jbastackcarousel.StackType
import com.jaber.jbastackcarousel.rememberCarouselState
import com.jaber.stackcarousel.ui.theme.StackCarouselTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
StackCarouselTheme {
Scaffold(
modifier = Modifier.fillMaxSize()
) { innerPadding ->
StackCarouselSample(
modifier = Modifier.padding(innerPadding)
)
}
}
}
}
}
@Suppress("ktlint:standard:function-naming")
@Composable
fun StackCarouselSample(modifier: Modifier = Modifier) {
val images =
listOf(
R.drawable.stack_sample_one,
R.drawable.stack_sample_two,
R.drawable.stack_sample_three
)
val carouselState = rememberCarouselState(totalPageCount = images.size)
Column(modifier = modifier) {
Spacer(modifier = Modifier.height(40.dp))
StackCarousel(
modifier =
Modifier.padding(
start = 30.dp,
end = 30.dp
),
state = carouselState,
isEnableAnimation = true,
stackType = StackType.Top,
items = images
) { page: Int ->
Image(
painter = painterResource(id = page),
modifier =
Modifier
.height(400.dp)
.fillMaxWidth(),
contentDescription = "",
contentScale = ContentScale.Crop
)
}
}
}
@Suppress("ktlint:standard:function-naming")
@PreviewLightDark
@Composable
private fun StackCarouselSamplePreview() {
StackCarouselTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Column(modifier = Modifier.padding(innerPadding)) {
StackCarouselSample()
}
}
}
}
| 0 | Kotlin | 0 | 0 | ca5f6fd8202deead9f224bb8cecf244155de6c8a | 3,200 | StackCarouselCompose | Apache License 2.0 |
web/src/jsMain/kotlin/app/softwork/composetodo/login/Login.kt | cybernetics | 377,738,587 | true | {"Kotlin": 65983, "Swift": 8093, "HTML": 655, "Dockerfile": 93} | package app.softwork.composetodo.login
import androidx.compose.runtime.*
import app.softwork.bootstrapcompose.*
import app.softwork.composetodo.*
import kotlinx.coroutines.*
import org.jetbrains.compose.web.attributes.*
import org.jetbrains.compose.web.dom.*
@Composable
fun Login(api: API.LoggedOut, onLogin: (API.LoggedIn) -> Unit) {
var username by mutableStateOf("")
var password by mutableStateOf("")
Row {
Column {
H1 {
Text("Login")
}
Input(value = username, placeholder = "user.name", label = "Username") {
username = it.value
}
Input(type = InputType.Password, placeholder = "password", label = "Passwort", value = password) {
password = it.value
}
Button("Login", attrs = {
if (username.isEmpty() || password.isEmpty()) {
disabled()
}
}) {
scope.launch {
api.login(username = username, password = password)?.let {
onLogin(it)
}
}
}
}
}
}
| 0 | null | 0 | 0 | 0d2f2f1d8a07b371ac5e79eeb150cb979926e70f | 1,186 | ComposeTodo | Apache License 2.0 |
src/main/kotlin/io/kanro/idea/plugin/protobuf/buf/BufConfigurationModificationTracker.kt | devkanro | 351,091,577 | false | {"Kotlin": 720561, "Lex": 6597, "Java": 730} | package io.kanro.idea.plugin.protobuf.buf
import com.intellij.openapi.util.SimpleModificationTracker
object BufConfigurationModificationTracker : SimpleModificationTracker()
| 7 | Kotlin | 10 | 76 | ce15e02dec1f65ddbe1a23414e2450491e133fe9 | 176 | intellij-protobuf-plugin | Apache License 2.0 |
src/fr/voircartoon/src/eu/kanade/tachiyomi/animeextension/fr/voircartoon/extractors/ComedyShowExtractor.kt | almightyhak | 817,607,446 | false | {"Kotlin": 4066862} | package eu.kanade.tachiyomi.animeextension.fr.voircartoon.extractors
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.lib.playlistutils.PlaylistUtils
import eu.kanade.tachiyomi.network.POST
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.OkHttpClient
// Based on EPlayerExtractor (pt/Pobreflix)
class ComedyShowExtractor(private val client: OkHttpClient) {
private val headers by lazy {
Headers.headersOf(
"X-Requested-With",
"XMLHttpRequest",
"Referer",
COMEDY_SHOW_HOST,
"Origin",
COMEDY_SHOW_HOST,
)
}
private val playlistUtils by lazy { PlaylistUtils(client, headers) }
fun videosFromUrl(url: String): List<Video> {
val id = url.substringAfterLast("/")
val postUrl = "$COMEDY_SHOW_HOST/player/index.php?data=$id&do=getVideo"
val body = FormBody.Builder()
.add("hash", id)
.add("r", "")
.build()
val masterUrl = client.newCall(POST(postUrl, headers, body = body)).execute()
.body.string()
.substringAfter("videoSource\":\"")
.substringBefore('"')
.replace("\\", "")
return playlistUtils.extractFromHls(masterUrl, videoNameGen = { "ComedyShow - $it" })
}
companion object {
private const val COMEDY_SHOW_HOST = "https://comedyshow.to"
}
}
| 55 | Kotlin | 28 | 93 | 507dddff536702999357b17577edc48353eab5ad | 1,440 | aniyomi-extensions | Apache License 2.0 |
app/src/main/java/com/example/marsphotos/data/LocatorAlumnos.kt | Pedro-Calderon | 766,204,441 | false | {"Kotlin": 111984} |
import com.example.marsphotos.data.ServiceLocator
import com.example.marsphotos.network.PerfilSice
import retrofit2.Retrofit
import retrofit2.converter.simplexml.SimpleXmlConverterFactory
object LocatorAlumnos {
private const val BASE_URL = "https://sicenet.surguanajuato.tecnm.mx"
private val client = ServiceLocator.client
val retrofitAL = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(SimpleXmlConverterFactory.create())
.build()
val serviceAL: PerfilSice = retrofitAL.create(PerfilSice::class.java)
}
| 0 | Kotlin | 0 | 0 | b72959fa78e456a214a57e3939f3a52ce0883779 | 590 | SICENET-SOAP-V2.0 | Apache License 2.0 |
app/src/main/java/com/example/makanapa/adapter/MenuListAdapter.kt | obedkristiaji | 316,225,456 | false | null | package com.example.makanapa.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.example.makanapa.databinding.MenuListBinding
import com.example.makanapa.model.Menu
import com.example.makanapa.viewmodel.MainActivityViewModel
class MenuListAdapter(context: Context, viewModel: MainActivityViewModel): BaseAdapter() {
private var MenuList: List<Menu> = ArrayList()
private var view: Context = context
private var viewModel = viewModel
fun update(menu: List<Menu>) {
this.MenuList = menu
this.notifyDataSetChanged()
}
override fun getCount(): Int {
return MenuList.size
}
override fun getItem(position: Int): Menu {
return MenuList[position]
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getView(position : Int, view : View?, parent : ViewGroup) : View {
val itemView: View
val viewHolder: ViewHolder
if (view == null) {
itemView = MenuListBinding.inflate(LayoutInflater.from(this.view)).root
viewHolder = ViewHolder(itemView, viewModel)
itemView.tag = viewHolder
} else {
itemView = view
viewHolder = view.tag as ViewHolder
}
viewHolder.updateView(this.getItem(position), position, this.MenuList)
return itemView
}
private class ViewHolder(view: View, viewModel: MainActivityViewModel) {
private val binding: MenuListBinding = MenuListBinding.bind(view)
private val viewModel: MainActivityViewModel = viewModel
fun updateView(menu: Menu, position: Int, menuList: List<Menu>) {
this.binding.tvMenu.text = menu.getTitle()
this.viewModel.darkText(this.viewModel.dark.value!!, this.binding.tvMenu)
this.binding.tvMenu.setOnClickListener {
this.viewModel.updateSearch(menuList, position)
this.viewModel.changePage("Search")
}
this.binding.ibEdit.setOnClickListener {
this.viewModel.updateSearch(menuList, position)
this.viewModel.returnPostion(position)
this.viewModel.changePage("Edit")
}
this.binding.ibDelete.setOnClickListener {
this.viewModel.deleteMenu(menuList, position)
this.viewModel.changePage("Menu")
}
}
}
} | 0 | Kotlin | 0 | 0 | 9b01330d51fe78bdb5e5f75c8a6f5414167490af | 2,531 | Makan-Apa | MIT License |
dataforge-data/src/jvmTest/kotlin/space/kscience/dataforge/data/ActionsTest.kt | SciProgCentre | 148,831,678 | false | {"Kotlin": 411226} | package space.kscience.dataforge.data
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import space.kscience.dataforge.actions.Action
import space.kscience.dataforge.actions.invoke
import space.kscience.dataforge.actions.mapping
import space.kscience.dataforge.misc.DFExperimental
import kotlin.test.assertEquals
@OptIn(DFExperimental::class, ExperimentalCoroutinesApi::class)
internal class ActionsTest {
@Test
fun testStaticMapAction() = runTest {
val data: DataTree<Int> = DataTree {
repeat(10) {
static(it.toString(), it)
}
}
val plusOne = Action.mapping<Int, Int> {
result { it + 1 }
}
val result = plusOne(data)
assertEquals(2, result["1"]?.await())
}
@Test
fun testDynamicMapAction() = runTest {
val data: DataSourceBuilder<Int> = DataSource()
val plusOne = Action.mapping<Int, Int> {
result { it + 1 }
}
val result = plusOne(data)
repeat(10) {
data.static(it.toString(), it)
}
delay(20)
assertEquals(2, result["1"]?.await())
data.close()
}
} | 15 | Kotlin | 3 | 24 | ce0d3bb584e9e54d43de8119bd070982c0e0946d | 1,287 | dataforge-core | Apache License 2.0 |
dataforge-data/src/jvmTest/kotlin/space/kscience/dataforge/data/ActionsTest.kt | SciProgCentre | 148,831,678 | false | {"Kotlin": 411226} | package space.kscience.dataforge.data
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import space.kscience.dataforge.actions.Action
import space.kscience.dataforge.actions.invoke
import space.kscience.dataforge.actions.mapping
import space.kscience.dataforge.misc.DFExperimental
import kotlin.test.assertEquals
@OptIn(DFExperimental::class, ExperimentalCoroutinesApi::class)
internal class ActionsTest {
@Test
fun testStaticMapAction() = runTest {
val data: DataTree<Int> = DataTree {
repeat(10) {
static(it.toString(), it)
}
}
val plusOne = Action.mapping<Int, Int> {
result { it + 1 }
}
val result = plusOne(data)
assertEquals(2, result["1"]?.await())
}
@Test
fun testDynamicMapAction() = runTest {
val data: DataSourceBuilder<Int> = DataSource()
val plusOne = Action.mapping<Int, Int> {
result { it + 1 }
}
val result = plusOne(data)
repeat(10) {
data.static(it.toString(), it)
}
delay(20)
assertEquals(2, result["1"]?.await())
data.close()
}
} | 15 | Kotlin | 3 | 24 | ce0d3bb584e9e54d43de8119bd070982c0e0946d | 1,287 | dataforge-core | Apache License 2.0 |
library/src/main/kotlin/is/hth/opengrapher/Url.kt | hrafnthor | 598,508,368 | false | null | package `is`.hth.opengrapher
@JvmInline
public value class HttpUrl(public val url: String) {
init {
require(url.startsWith(HTTP, ignoreCase = true) || url.startsWith(HTTPS, ignoreCase = true)) {
"HttpUrl requires the url to start with '$HTTP' or '$HTTPS'"
}
}
}
private const val HTTP = "http://"
private const val HTTPS = "https://"
| 0 | Kotlin | 0 | 1 | a3211ea814f0a5d2393c80d84786c133e9f43884 | 372 | opengrapher | Apache License 2.0 |
funcify-feature-eng-json/src/main/kotlin/funcify/feature/json/design/KJsonDesign.kt | anticipasean | 458,910,592 | false | {"Kotlin": 2751524, "HTML": 1817} | package funcify.feature.json.design
import com.fasterxml.jackson.databind.JsonNode
import funcify.feature.json.KJson
import funcify.feature.json.KJsonContainer
import funcify.feature.json.KJsonScalar
import funcify.feature.json.data.KJsonData
import funcify.feature.json.behavior.KJsonBehavior
internal interface KJsonDesign<SWT, I> : KJson {
val behavior: KJsonBehavior<SWT>
val data: KJsonData<SWT, I>
override fun filterScalar(condition: (KJsonScalar) -> Boolean): KJson {
TODO("Not yet implemented")
}
override fun filterContainer(condition: (KJsonContainer) -> Boolean): KJson {
TODO("Not yet implemented")
}
override fun mapScalar(mapper: (KJsonScalar) -> KJsonScalar): KJson {
TODO("Not yet implemented")
}
override fun mapScalarToContainer(mapper: (KJsonScalar) -> KJsonContainer): KJsonContainer {
TODO("Not yet implemented")
}
override fun mapScalarToArray(): KJsonContainer {
TODO("Not yet implemented")
}
override fun mapScalarToObject(
mapper: (KJsonScalar) -> Pair<String, KJsonScalar>
): KJsonContainer {
TODO("Not yet implemented")
}
override fun mapContainer(mapper: (KJsonContainer) -> KJsonContainer): KJson {
TODO("Not yet implemented")
}
override fun mapContainerToScalar(mapper: (KJsonContainer) -> KJsonScalar): KJsonScalar {
TODO("Not yet implemented")
}
override fun map(mapper: (KJson) -> KJson): KJson {
TODO("Not yet implemented")
}
override fun flatMapScalar(mapper: (KJsonScalar) -> KJson): KJson {
TODO("Not yet implemented")
}
override fun flatMapContainer(mapper: (KJsonContainer) -> KJson): KJson {
TODO("Not yet implemented")
}
override fun flatMap(mapper: (KJson) -> KJsonContainer): KJson {
TODO("Not yet implemented")
}
override fun getScalar(): KJsonScalar? {
TODO("Not yet implemented")
}
override fun getScalarOrElse(alternative: KJsonScalar): KJsonScalar {
TODO("Not yet implemented")
}
override fun getScalarOrElseGet(supplier: () -> KJsonScalar): KJsonScalar {
TODO("Not yet implemented")
}
override fun getContainer(): KJsonContainer? {
TODO("Not yet implemented")
}
override fun getContainerOrElse(alternative: KJsonContainer): KJsonContainer {
TODO("Not yet implemented")
}
override fun getContainerOrElseGet(supplier: () -> KJsonContainer): KJsonContainer {
TODO("Not yet implemented")
}
override fun toJacksonJsonNode(): JsonNode {
TODO("Not yet implemented")
}
override fun <O> foldKJson(
scalarHandler: (KJsonScalar) -> O,
containerHandler: (KJsonContainer) -> O
): O {
TODO("Not yet implemented")
}
fun <WT> fold(template: KJsonBehavior<WT>): KJsonData<WT, I>
}
| 0 | Kotlin | 0 | 0 | 284b941de10a5b85b9ba1b5236a1d57289e10492 | 2,903 | funcify-feature-eng | Apache License 2.0 |
src/main/kotlin/tech/relaycorp/relaynet/nodes/NodeCryptoOptions.kt | relaycorp | 171,718,724 | false | {"Kotlin": 543225} | package tech.relaycorp.relaynet.nodes
import tech.relaycorp.relaynet.ECDHCurve
import tech.relaycorp.relaynet.HashingAlgorithm
import tech.relaycorp.relaynet.SymmetricCipher
data class NodeCryptoOptions(
val ecdhCurve: ECDHCurve = ECDHCurve.P256,
val symmetricCipher: SymmetricCipher = SymmetricCipher.AES_128,
val hashingAlgorithm: HashingAlgorithm = HashingAlgorithm.SHA256,
)
| 10 | Kotlin | 0 | 2 | 0999cf6d732449351866846fea4066183307d533 | 393 | awala-jvm | Apache License 2.0 |
exposedx-dao/src/test/kotlin/io/creavity/exposedx/dao/EntityCircularTest.kt | creavity-io | 254,755,628 | false | null | package io.creavity.exposedx.dao
import io.creavity.exposedx.dao.entities.*
import io.creavity.exposedx.dao.entities.generics.IntEntity
import io.creavity.exposedx.dao.entities.generics.IntEntityTable
import io.creavity.exposedx.dao.entities.asList
import io.creavity.exposedx.dao.tables.new
import io.creavity.exposedx.dao.entities.oneToMany
import io.mockk.clearMocks
import io.mockk.spyk
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.not
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.jupiter.api.*
import java.sql.Connection
import java.sql.DriverManager
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class EntityCircularTest {
open class UserTable: IntEntityTable<User, UserTable>() {
val name by varchar("name", 255)
val parent by manyToOptional("parent_id")
}
class User: IntEntity() {
companion object Table: UserTable()
var name by Table.name
var parent by Table.parent.nullable()
}
val UserTable.childs by oneToManyRef(User.parent, User)
val User.childs by User.childs.asList()
lateinit var connection: Connection
@BeforeAll
fun beforeAll() {
Class.forName("org.h2.Driver").newInstance()
Database.connect({
connection = spyk(DriverManager.getConnection("jdbc:h2:mem:regular;DB_CLOSE_DELAY=-1;", "", ""))
connection
})
}
@BeforeEach
fun before() {
transaction {
SchemaUtils.create(User)
}
clearMocks(connection)
}
@AfterEach
fun after() {
transaction {
SchemaUtils.drop(User)
}
}
@Test
fun `Create circular referencee`() {
val parent = User.new { name="Juan"; this.parent = null }
val child1 = User.new { name = "Jorgito"; this.parent = parent }
val child2 = User.new { name = "Anita"; this.parent = parent }
clearMocks(connection)
transaction {
assertThat(User.objects.count()).isEqualTo(3)
}
}
@Test
fun `Filter circular referencee`() {
val parent = User.new { name="Juan"; this.parent = null }
val child1 = User.new { name = "Jorgito"; this.parent = parent }
val child2 = User.new { name = "Anita"; this.parent = parent }
clearMocks(connection)
transaction {
assertThat(User.objects.filter { this.parent.isNull() }.count()).isEqualTo(1)
assertThat(User.objects.filter { not(this.parent.isNull()) }.count()).isEqualTo(2)
assertThat(User.objects.filter { this.parent eq parent }.count()).isEqualTo(2)
}
}
@Test
fun `Test OneToMany reference`() {
val parent = User.new { name="Juan"; this.parent = null }
val child1 = User.new { name = "Jorgito"; this.parent = parent }
val child2 = User.new { name = "Anita"; this.parent = parent }
clearMocks(connection)
transaction {
assertThat(parent.childs.count()).isEqualTo(2)
}
}
/*
@Test
fun `Test OneToMany filter`() {
val parent = User.new { name="Juan"; this.parent = null }
val child1 = User.new { name = "Jorgito"; this.parent = parent }
val child2 = User.new { name = "Anita"; this.parent = parent }
clearMocks(connection)
transaction {
assertThat(User.objects.filter { this.childs eq child1 }.first().id).isEqualTo(parent.id)
assertThat(User.objects.filter { this.childs.isNull() }.count()).isEqualTo(2)
}
}
*/
}
| 0 | Kotlin | 0 | 0 | 97075942fab9719e1f8bcac450f34ce6316e77c5 | 3,700 | exposedx | Apache License 2.0 |
app/src/main/java/com/abhrp/foodnearme/di/module/detail/DetailScope.kt | abhrp | 221,381,337 | false | null | package com.abhrp.foodnearme.di.module.detail
import javax.inject.Scope
@Scope
annotation class DetailScope | 0 | Kotlin | 0 | 0 | 4baa807a5c0fe56eae7706554ff772814f1cd553 | 109 | foodnearme | MIT License |
domain/src/main/java/com/egpayawal/module/domain/models/Paging.kt | egpayawal | 721,324,889 | false | {"Kotlin": 247106, "Java": 2332, "Shell": 1285} | package com.egpayawal.module.domain.models
data class Paging<T>(
val list: List<T>,
val nextPage: Int? = null
)
| 0 | Kotlin | 0 | 0 | 71034af5fc9d278247318368c753e8b858728383 | 121 | openweather-android | Apache License 2.0 |
app/src/main/java/com/pziska/androiddevchallenge/ui/navigation/NavGraph.kt | xziska02 | 343,461,476 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pziska.androiddevchallenge.ui.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.navigation.NavController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.navigate
import androidx.navigation.compose.rememberNavController
import com.pziska.androiddevchallenge.data.model.Puppy
import com.pziska.androiddevchallenge.ui.detail.PuppyDetailScreen
import com.pziska.androiddevchallenge.ui.navigation.MainDestinations.KEY_PUPPY
import com.pziska.androiddevchallenge.ui.navigation.MainDestinations.PUPPY_DETAIL
import com.pziska.androiddevchallenge.ui.navigation.MainDestinations.PUPPY_LIST
import com.pziska.androiddevchallenge.ui.puppies.PuppyListScreen
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
object MainDestinations {
const val PUPPY_DETAIL = "puppy"
const val PUPPY_LIST = "puppy_list"
const val KEY_PUPPY = "key_puppy"
}
@Composable
fun NavGraph(startDestination: String = PUPPY_LIST) {
val navController = rememberNavController()
val actions = remember(navController) { MainActions(navController) }
NavHost(navController, startDestination) {
composable(
"$PUPPY_DETAIL/{$KEY_PUPPY}",
arguments = listOf(
navArgument(KEY_PUPPY) {
type = NavType.StringType
}
)
) { backStackEntry ->
val arguments = requireNotNull(backStackEntry.arguments)
val puppyString = requireNotNull(arguments.getString(KEY_PUPPY))
val puppy = Json.decodeFromString<Puppy>(puppyString)
PuppyDetailScreen(puppy = puppy, actions.upPress)
}
composable(PUPPY_LIST) {
PuppyListScreen(actions.selectPuppy)
}
}
}
class MainActions(navController: NavController) {
val selectPuppy: (Puppy) -> Unit = {
val puppyString = Json.encodeToString(it)
navController.navigate("$PUPPY_DETAIL/$puppyString")
}
val upPress: () -> Unit = {
navController.navigateUp()
}
}
| 0 | Kotlin | 0 | 0 | bfffffd9499c3c61d57fd7a0fd547d0b3a9813e5 | 2,915 | android-dev-challenge-1 | Apache License 2.0 |
app/src/main/java/com/neuralbit/letsnote/ui/deletedNotes/DeletedNotesFragment.kt | NormanGadenya | 421,601,972 | false | {"Kotlin": 373046, "Java": 20226} | package com.neuralbit.letsnote.ui.deletedNotes
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.android.gms.ads.AdRequest
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import com.neuralbit.letsnote.R
import com.neuralbit.letsnote.databinding.DeletedNotesFragmentBinding
import com.neuralbit.letsnote.firebase.entities.NoteFire
import com.neuralbit.letsnote.receivers.DeleteReceiver
import com.neuralbit.letsnote.ui.adapters.NoteFireClick
import com.neuralbit.letsnote.ui.adapters.NoteRVAdapter
import com.neuralbit.letsnote.ui.addEditNote.AddEditNoteActivity
import com.neuralbit.letsnote.ui.addEditNote.Fingerprint
import com.neuralbit.letsnote.ui.allNotes.AllNotesViewModel
import com.neuralbit.letsnote.ui.settings.SettingsViewModel
import kotlinx.coroutines.*
import kotlin.math.floor
class DeletedNotesFragment : Fragment() , NoteFireClick {
private var noteRVAdapter: NoteRVAdapter? = null
private val allNotesViewModel: AllNotesViewModel by activityViewModels()
private val deletedNotesViewModel: DeletedNotesViewModel by activityViewModels()
private val settingsViewModel: SettingsViewModel by activityViewModels()
private lateinit var deletedRV : RecyclerView
private var _binding : DeletedNotesFragmentBinding? = null
private val binding get() = _binding!!
val TAG = "DELETEDNOTESFRAG"
private lateinit var trashIcon : ImageView
private lateinit var trashText : TextView
private lateinit var parentLayout : CoordinatorLayout
private val tempNotesToDelete = ArrayList<NoteFire>()
@Volatile
var restoreDeleted = false
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = DeletedNotesFragmentBinding.inflate(inflater, container, false)
deletedRV = binding.deletedRV
val root: View = binding.root
trashIcon = binding.trashIcon
trashText = binding.trashText
parentLayout = binding.coordinatorlayout
val adView = binding.adView
val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)
settingsViewModel.settingsFrag.value = false
noteRVAdapter = context?.let { NoteRVAdapter(it,this) }
deletedRV.layoutManager = LinearLayoutManager(context)
noteRVAdapter?.viewModel = allNotesViewModel
noteRVAdapter?.lifecycleScope = lifecycleScope
noteRVAdapter?.lifecycleOwner = this
deletedRV.adapter= noteRVAdapter
allNotesViewModel.archiveFrag = false
allNotesViewModel.deleteFrag.value = true
noteRVAdapter?.deleteFrag = true
val settingsSharedPref = context?.getSharedPreferences("Settings", AppCompatActivity.MODE_PRIVATE)
val fontStyle = settingsSharedPref?.getString("font",null)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
noteRVAdapter?.fontStyle = fontStyle
}
val useLocalStorage = settingsSharedPref?.getBoolean("useLocalStorage",false)
if (useLocalStorage != null) {
allNotesViewModel.useLocalStorage = useLocalStorage
deletedNotesViewModel.useLocalStorage = useLocalStorage
}
val staggeredLayoutManagerAll = StaggeredGridLayoutManager( 2,LinearLayoutManager.VERTICAL)
allNotesViewModel.staggeredView.observe(viewLifecycleOwner){
if (it){
deletedRV.layoutManager = staggeredLayoutManagerAll
}else{
deletedRV.layoutManager = LinearLayoutManager(context)
}
}
setHasOptionsMenu(true)
lifecycleScope.launch {
allNotesViewModel.getAllFireNotes().observe(viewLifecycleOwner){
allNotesViewModel.allFireNotes.value = it
}
}
allNotesViewModel.allFireNotes.observe(viewLifecycleOwner){
val filteredNotes = HashSet<NoteFire>()
for (n in it){
val timeLeftMS = n.deletedDate + 6.048e+8 - System.currentTimeMillis()
val daysLeft = floor(timeLeftMS * 1.1574E-8)
if (n.deletedDate > 0 && daysLeft > 0){
if (daysLeft > 0){
filteredNotes.add(n)
Log.d(TAG, "onCreateView: $filteredNotes")
}else{
n.noteUid?.let { uid ->
deletedNotesViewModel.deleteNote(
uid,
n.label,
n.tags
)
cancelDelete(n.timeStamp.toInt())
}
}
}
}
if (filteredNotes.isEmpty()){
trashText.visibility = View.VISIBLE
trashIcon.visibility = View.VISIBLE
}else{
trashText.visibility = View.GONE
trashIcon.visibility = View.GONE
}
deletedNotesViewModel.deletedNotes = filteredNotes
noteRVAdapter?.updateListFire(ArrayList(filteredNotes))
}
deletedNotesViewModel.clearTrash.observe(viewLifecycleOwner){
if (it ){
val snackbar :Snackbar
val selectedNotesCount = deletedNotesViewModel.deletedNotes.size
snackbar = if (selectedNotesCount > 1){
Snackbar.make(parentLayout,resources.getString(R.string.notes_deleted_successfully,"s"), Snackbar.LENGTH_LONG)
}else{
Snackbar.make(parentLayout,resources.getString(R.string.notes_deleted_successfully,""), Snackbar.LENGTH_LONG)
}
snackbar.setAction("UNDO"
) { restoreTempNotes()}
snackbar.show()
GlobalScope.launch {
permanentlyDeleteNotes()
}
val notes = ArrayList(deletedNotesViewModel.deletedNotes)
for (deletedNote in deletedNotesViewModel.deletedNotes) {
tempNotesToDelete.add(deletedNote)
notes.remove(deletedNote)
}
noteRVAdapter?.updateListFire(notes)
trashText.visibility = View.VISIBLE
trashIcon.visibility = View.VISIBLE
allNotesViewModel.itemSelectEnabled.value = false
deletedNotesViewModel.clearTrash.value = false
}
}
deletedNotesViewModel.itemDeleteClicked.observe(viewLifecycleOwner){
if (it && allNotesViewModel.selectedNotes.isNotEmpty()){
val snackbar :Snackbar
val selectedNotesCount = allNotesViewModel.selectedNotes.size
snackbar = if (selectedNotesCount > 1){
Snackbar.make(parentLayout,resources.getString(R.string.notes_deleted_successfully,"s"), Snackbar.LENGTH_LONG)
}else{
Snackbar.make(parentLayout,resources.getString(R.string.notes_deleted_successfully,""), Snackbar.LENGTH_LONG)
}
snackbar.setAction("UNDO"
) { restoreTempNotes()}
snackbar.show()
GlobalScope.launch {
permanentlyDeleteNotes()
}
val notes = ArrayList(deletedNotesViewModel.deletedNotes)
for (deletedNote in allNotesViewModel.selectedNotes) {
if (deletedNote.selected){
tempNotesToDelete.add(deletedNote)
notes.remove(deletedNote)
}
}
noteRVAdapter?.updateListFire(notes)
allNotesViewModel.itemSelectEnabled.value = false
deletedNotesViewModel.itemDeleteClicked.value = false
}
}
deletedNotesViewModel.itemRestoreClicked.observe(viewLifecycleOwner){
if (it && allNotesViewModel.selectedNotes.isNotEmpty()){
val selectedNotesCount = allNotesViewModel.selectedNotes.size
val notes = ArrayList(deletedNotesViewModel.deletedNotes)
for ( note in allNotesViewModel.selectedNotes){
if (note.selected){
val noteUpdate = HashMap<String,Any>()
noteUpdate["title"] = note.title
noteUpdate["description"] = note.description
noteUpdate["label"] = note.label
noteUpdate["pinned"] = note.pinned
noteUpdate["reminderDate"] = note.reminderDate
noteUpdate["protected"] = note.protected
noteUpdate["deletedDate"] = 0
note.noteUid?.let { it1 -> allNotesViewModel.updateFireNote(noteUpdate, it1) }
cancelDelete(note.timeStamp.toInt())
deletedNotesViewModel.deletedNotes.remove(note)
notes.remove(note)
}
}
noteRVAdapter?.updateListFire(notes)
allNotesViewModel.selectedNotes.clear()
allNotesViewModel.itemSelectEnabled.value = false
if (selectedNotesCount == 1){
Toast.makeText(context,resources.getString(R.string.notes_restored_successfully,""),Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(context,resources.getString(R.string.notes_restored_successfully, "s"),Toast.LENGTH_SHORT).show()
}
if (deletedNotesViewModel.deletedNotes.isEmpty()){
trashText.visibility = View.VISIBLE
trashIcon.visibility = View.VISIBLE
}else{
trashText.visibility = View.GONE
trashIcon.visibility = View.GONE
}
}
}
return root
}
private fun restoreTempNotes() {
trashText.visibility = View.GONE
trashIcon.visibility = View.GONE
restoreDeleted = true
tempNotesToDelete.clear()
noteRVAdapter?.updateListFire(ArrayList(deletedNotesViewModel.deletedNotes))
}
private suspend fun permanentlyDeleteNotes() {
withContext(Dispatchers.Main){
delay(2000L)
if (!restoreDeleted){
for (deletedNote in tempNotesToDelete) {
deletedNotesViewModel.deletedNotes.remove(deletedNote)
deletedNote.noteUid?.let { uid ->
deletedNotesViewModel.deleteNote(
uid,
deletedNote.label,
deletedNote.tags
)
cancelDelete(deletedNote.timeStamp.toInt())
}
}
}
}
}
private fun cancelDelete(timestamp : Int){
val alarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, DeleteReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, timestamp, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager.cancel(pendingIntent)
}
override fun onNoteFireClick(note: NoteFire, activated : Boolean) {
if (!note.selected && !activated){
val intent : Intent = if(note.protected){
Intent( context, Fingerprint::class.java)
}else{
Intent( context, AddEditNoteActivity::class.java)
}
intent.putExtra("noteType","Edit")
intent.putExtra("noteTitle",note.title)
intent.putExtra("noteDescription",note.description)
intent.putExtra("noteUid",note.noteUid)
intent.putExtra("timeStamp",note.timeStamp)
intent.putExtra("labelColor",note.label)
intent.putExtra("pinned",note.pinned)
intent.putExtra("archieved",note.archived)
intent.putExtra("protected",note.protected)
intent.putExtra("deleted",true)
val toDoItemString: String = Gson().toJson(note.todoItems)
intent.putExtra("todoItems", toDoItemString)
intent.putStringArrayListExtra("tagList", ArrayList(note.tags))
startActivity(intent)
}else{
if (note.selected){
allNotesViewModel.selectedNotes.add(note)
}else{
allNotesViewModel.selectedNotes.remove(note)
}
}
}
override fun onNoteFireLongClick(note: NoteFire) {
if (note.selected){
allNotesViewModel.selectedNotes.add(note)
}else{
allNotesViewModel.selectedNotes.remove(note)
}
allNotesViewModel.itemSelectEnabled.value = true
}
} | 0 | Kotlin | 0 | 4 | 7e7295e5a35d5413ee660c2af8022ee991706af1 | 13,751 | Lets-Note-App | Apache License 2.0 |
app/src/main/java/com/acxdev/poolguardapps/model/gpu/GPUDatabase.kt | dodyac | 606,656,789 | false | null | package com.acxdev.poolguardapps.model.gpu
class GPUDatabase {
var model: String = ""
var count: Int = 1
var isChecked: Int = 0
var _id: Long? = null
constructor()
constructor(
model: String,
count: Int,
isChecked: Int,
_id: Long? = null
) {
this.model = model
this.count = count
this.isChecked = isChecked
this._id = _id
}
} | 0 | Kotlin | 0 | 1 | effd2aa0ac41e81f8b4684c97d5e9c1f2b30542a | 424 | Poolguard | MIT License |
android/buildSrc/src/main/kotlin/com/github/pgreze/kotlinci/Config.kt | pgreze | 535,231,537 | false | {"Kotlin": 23102} | package com.github.pgreze.kotlinci
object Config {
const val compileSdk = 32
const val minSdk = 23
const val targetSdk = 32
const val testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
| 0 | Kotlin | 2 | 4 | 32a03204fc65c3a2dc5cc5781383225314afa253 | 224 | kotlin-ci | Apache License 2.0 |
core/src/main/kotlin/com/exactpro/th2/read/db/core/impl/BaseDataSourceProvider.kt | th2-net | 522,950,261 | false | {"Kotlin": 211275, "Python": 4581, "Dockerfile": 115} | /*
* Copyright 2022-2023 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.th2.read.db.core.impl
import com.exactpro.th2.read.db.core.DataSourceConfiguration
import com.exactpro.th2.read.db.core.DataSourceHolder
import com.exactpro.th2.read.db.core.DataSourceId
import com.exactpro.th2.read.db.core.DataSourceProvider
import mu.KotlinLogging
import org.apache.commons.dbcp2.BasicDataSource
class BaseDataSourceProvider(
configurations: Map<DataSourceId, DataSourceConfiguration>,
) : DataSourceProvider {
private val sourcesById: Map<DataSourceId, DataSourceHolder> = configurations.mapValues { (id, cfg) ->
LOGGER.trace { "Creating data source for $id" }
DataSourceHolder(
BasicDataSource().apply {
url = cfg.url
cfg.username?.also { username = it }
cfg.password?.also { password = it }
cfg.properties.forEach { (key, value) -> addConnectionProperty(key, value) }
LOGGER.trace { "Data source for $id created" }
},
cfg
)
}
override fun dataSource(dataSourceId: DataSourceId) =
sourcesById[dataSourceId]
?: error("cannot find data source $dataSourceId. Known: ${sourcesById.keys}")
companion object {
private val LOGGER = KotlinLogging.logger { }
}
} | 1 | Kotlin | 0 | 1 | c21fc32b2c750cfedeef6869c2e06b9af02df201 | 1,916 | th2-read-db | Apache License 2.0 |
src/main/kotlin/br/com/alura/dto/ContaAssociada.kt | PedroAugustoZup | 408,182,065 | true | {"Kotlin": 54924} | package br.com.alura.dto
import br.com.alura.TipoConta
import br.com.alura.model.Instituicao
data class ContaAssociada(
val tipo: TipoConta,
val instituicao: Instituicao,
val agencia: String,
val numero: String,
val titular: String,
val cpfTitular: String
) | 0 | Kotlin | 0 | 0 | 4862fb2d8dbff0260a0db23db6c41e23ac157684 | 283 | orange-talents-07-template-pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/com/adityakamble49/wordlist/ui/main/MainActivityViewModel.kt | adityakamble49 | 131,319,368 | false | null | package com.adityakamble49.wordlist.ui.main
import android.arch.lifecycle.ViewModel
import javax.inject.Inject
/**
* Main Activity View Model
*
* @author <NAME>
* @since 4/4/2018
*/
class MainActivityViewModel @Inject constructor() : ViewModel() | 2 | Kotlin | 1 | 2 | ea1f7cf58574b4a87dbe689cbf9ce69610b1718d | 252 | word-list | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/service/FriskmeldingTilArbeidsformidlingVedtakService.kt | navikt | 303,972,532 | false | {"Kotlin": 392358, "Dockerfile": 148} | package no.nav.syfo.service
import no.nav.syfo.consumer.distribuerjournalpost.DistibusjonsType
import no.nav.syfo.kafka.consumers.varselbus.domain.ArbeidstakerHendelse
import no.nav.syfo.utils.dataToVarselData
import org.slf4j.LoggerFactory
class FriskmeldingTilArbeidsformidlingVedtakService(
private val senderFacade: SenderFacade,
) {
suspend fun sendVarselTilArbeidstaker(varselHendelse: ArbeidstakerHendelse) {
log.info("[VEDTAK_FRISKMELDING_TIL_ARBEIDSFORMIDLING] sending enabled")
val data = dataToVarselData(varselHendelse.data)
requireNotNull(data.journalpost)
requireNotNull(data.journalpost.id)
log.info("Sending [VEDTAK_FRISKMELDING_TIL_ARBEIDSFORMIDLING] with uuid ${data.journalpost.uuid} to print")
senderFacade.sendBrevTilFysiskPrint(
uuid = data.journalpost.uuid,
varselHendelse = varselHendelse,
journalpostId = data.journalpost.id,
distribusjonsType = DistibusjonsType.VIKTIG,
)
}
companion object {
private val log = LoggerFactory.getLogger(FriskmeldingTilArbeidsformidlingVedtakService::class.qualifiedName)
}
}
| 0 | Kotlin | 2 | 0 | 0c055e20a396bc4d1745baf3b48703c5b8e59f93 | 1,174 | esyfovarsel | MIT License |
serenity-common/src/main/java/us/nineworlds/serenity/common/rest/SerenityClient.kt | NineWorlds | 7,139,471 | false | {"Java": 701863, "Kotlin": 293495, "Shell": 2466} | package us.nineworlds.serenity.common.rest
import us.nineworlds.serenity.common.media.model.IMediaContainer
import java.io.IOException
import java.lang.Exception
interface SerenityClient {
@Throws(Exception::class)
fun fetchSimilarItemById(itemId: String, types: Types): IMediaContainer
@Throws(Exception::class)
fun fetchItemById(itemId: String): IMediaContainer
@Throws(Exception::class)
fun retrieveRootData(): IMediaContainer
@Throws(Exception::class)
fun retrieveLibrary(): IMediaContainer
@Throws(Exception::class)
fun retrieveItemByCategories(): IMediaContainer
@Throws(Exception::class)
fun retrieveCategoriesById(key: String): IMediaContainer
@Throws(Exception::class)
fun retrieveItemByIdCategory(key: String, category: String, types: Types): IMediaContainer
@Throws(Exception::class)
fun retrieveItemByIdCategory(key: String, category: String, types: Types, startIndex: Int = 0, limit: Int? = null): IMediaContainer
@Throws(Exception::class)
fun retrieveItemByCategories(key: String, category: String, secondaryCategory: String): IMediaContainer
@Throws(Exception::class)
fun retrieveSeasons(key: String): IMediaContainer
@Throws(Exception::class)
fun retrieveMusicMetaData(key: String): IMediaContainer
@Throws(Exception::class)
fun retrieveEpisodes(key: String): IMediaContainer
@Throws(Exception::class)
fun retrieveMovieMetaData(key: String): IMediaContainer
@Throws(Exception::class)
fun searchMovies(key: String, query: String): IMediaContainer?
@Throws(Exception::class)
fun searchEpisodes(key: String, query: String): IMediaContainer?
fun updateBaseUrl(baseUrl: String)
fun baseURL(): String?
@Throws(IOException::class)
fun watched(key: String): Boolean
@Throws(IOException::class)
fun unwatched(key: String): Boolean
@Throws(IOException::class)
fun progress(key: String, offset: String): Boolean
fun createMediaTagURL(resourceType: String, resourceName: String, identifier: String): String?
fun createSectionsURL(key: String, category: String): String
fun createSectionsURL(): String
fun createSectionsUrl(key: String): String
fun createMovieMetadataURL(key: String): String
fun createEpisodesURL(key: String): String
fun createSeasonsURL(key: String): String
fun createImageURL(url: String, width: Int, height: Int): String
fun createTranscodeUrl(id: String, offset: Int): String
fun reinitialize()
fun userInfo(userId: String): SerenityUser?
fun allAvailableUsers(): List<SerenityUser>
fun authenticateUser(user: SerenityUser): SerenityUser
fun createUserImageUrl(user: SerenityUser, width: Int, height: Int): String
fun startPlaying(key: String)
fun stopPlaying(key: String, offset: Long)
fun retrieveSeriesById(key: String, categoryId: String): IMediaContainer
fun retrieveSeriesCategoryById(key: String): IMediaContainer
/**
* Whether the client supports multiple users or not. Plex is false, Emby is true.
* @return true or false if the client supports multiple users
*/
fun supportsMultipleUsers(): Boolean
} | 25 | Java | 65 | 177 | 155cfb76bb58f2f06ccac8e3e45151221c59560d | 3,207 | serenity-android | MIT License |
feature/selectingModules/impl/src/main/kotlin/odoo/miem/android/feature/selectingModules/impl/searchScreen/components/SearchRecommendationsContent.kt | 19111OdooApp | 546,191,502 | false | null | package odoo.miem.android.feature.selectingModules.impl.searchScreen.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import odoo.miem.android.common.network.selectingModules.api.entities.OdooModule
import odoo.miem.android.core.uiKitTheme.mainVerticalPadding
import odoo.miem.android.feature.selectingModules.impl.R
import odoo.miem.android.feature.selectingModules.impl.searchScreen.SearchModulesScreen
/**
* [SearchRecommendationsContent] is located in [SearchModulesScreen]
* Looks like two lazy rows with favourite and all modules
* Disappears when the search began
*
* @author Egor Danilov
*/
@Composable
fun SearchRecommendationsContent(
allModules: List<OdooModule>,
favouriteModules: List<OdooModule>,
onModuleCardClick: (OdooModule) -> Unit,
onLikeModuleClick: (OdooModule) -> Unit = {},
) {
Column(
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.Start,
modifier = Modifier.fillMaxWidth()
) {
if (favouriteModules.isNotEmpty()) {
ModulesLazyRow(
headerRes = R.string.favourite_modules_header,
modules = favouriteModules,
onModuleCardClick = onModuleCardClick,
onLikeModuleClick = onLikeModuleClick
)
}
if (allModules.isNotEmpty()) {
Spacer(modifier = Modifier.height(mainVerticalPadding))
ModulesLazyRow(
headerRes = R.string.all_modules_header,
modules = allModules,
onModuleCardClick = onModuleCardClick,
onLikeModuleClick = onLikeModuleClick
)
}
}
}
| 0 | null | 1 | 5 | e107fcbb8db2d179d40b5c1747051d2cb75e58c6 | 2,003 | OdooApp-Android | Apache License 2.0 |
Rectangle.kt | bunakovs | 262,303,662 | false | null | import java.util.Random
class Rectangle(val height: Int, val width: Int){
val isSquare: Boolean
get() = height==width
val area: Int
get(){
return height*width
}
fun createRandom() = createRandomRectangle()
fun print(){
println("Rectangle:\n Heigth = $height,\n Width = $width,\n Square = $isSquare,\n Area = $area")
}
}
fun createRandomRectangle(): Rectangle {
val random = Random()
return Rectangle(random.nextInt(100), random.nextInt(100))
}
fun main(args: Array<String>){
val rectangles = listOf(Rectangle(10, 10), Rectangle(2, 5), createRandomRectangle())
for(rectangle in rectangles){
rectangle.print()
}
} | 0 | Kotlin | 0 | 0 | 790e2c82b9a33152ab86d0dc761b431a6d90fe35 | 715 | kotlin-learning | MIT License |
component-acgcomic/src/main/java/com/rabtman/acgcomic/base/constant/Constant.kt | Rabtman | 129,618,096 | false | null | package com.rabtman.acgcomic.base.constant
/**
* @author Rabtman
*/
class SystemConstant {
companion object {
const val DB_NAME = "lib.acgcomic.realm"
const val DB_VERSION = 1L
/**
* 漫画来源
*/
const val COMIC_SOURCE_OACG = "oacg"
const val COMIC_SOURCE_QIMIAO = "qimiao"
}
}
class HtmlConstant {
companion object {
const val DMZJ_URL = "https://m.dmzj.com/"
const val DMZJ_IMG_URL = "https://images.dmzj.com/"
const val qimiao_URL = "http://comic.oacg.cn/"
const val qimiao_IMG_URL = "http://gx.cdn.comic.oacg.cn"
const val QIMIAO_URL = "https://m.qimiaomh.com"
}
}
class IntentConstant {
companion object {
const val QIMIAO_COMIC_ITEM = "qimiao_comic_item"
const val QIMIAO_COMIC_ID = "qimiao_comic_id"
const val QIMIAO_COMIC_TITLE = "qimiao_comic_title"
const val QIMIAO_COMIC_CHAPTER_URL = "qimiao_comic_chapter_url"
const val QIMIAO_COMIC_CHAPTER_ID = "qimiao_comic_chapter_id"
}
}
class SPConstant {
companion object {
const val VER_3_CLEAR_DB = "ver_3_clear_db"
}
}
| 2 | null | 120 | 840 | 9150f3abe50e046afd83cc97cb4415a39b1f1bd1 | 1,158 | AcgClub | Apache License 2.0 |
extension/core/src/main/kotlin/io/holunda/camunda/bpm/correlate/correlation/CorrelationMetrics.kt | holunda-io | 450,565,449 | false | {"Kotlin": 243470, "TypeScript": 20331, "Shell": 2838, "Dockerfile": 2012, "JavaScript": 1481, "CSS": 308} | package io.holunda.camunda.bpm.correlate.correlation
import io.holunda.camunda.bpm.correlate.persist.CountByStatus
import io.holunda.camunda.bpm.correlate.util.ComponentLike
import io.micrometer.core.instrument.Gauge
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Tag
import mu.KLogging
import java.util.concurrent.atomic.AtomicLong
/**
* Captures correlation metrics.
*/
@ComponentLike
class CorrelationMetrics(
private val registry: MeterRegistry
) {
companion object : KLogging() {
const val PREFIX = "camunda.bpm.correlate"
const val COUNTER_CORRELATED = "$PREFIX.correlation.success"
const val COUNTER_ERROR = "$PREFIX.correlation.error"
const val GAUGE_MESSAGES = "$PREFIX.inbox.messages"
const val TAG_STATUS = "status"
}
private val total = AtomicLong(0L)
private val retrying = AtomicLong(0L)
private val error = AtomicLong(0L)
private val maxRetriesReached = AtomicLong(0L)
private val inProgress = AtomicLong(0L)
private val paused = AtomicLong(0L)
init {
Gauge.builder(GAUGE_MESSAGES, total::get).tag(TAG_STATUS, "total").register(registry)
Gauge.builder(GAUGE_MESSAGES, retrying::get).tag(TAG_STATUS, "retrying").register(registry)
Gauge.builder(GAUGE_MESSAGES, error::get).tag(TAG_STATUS, "error").register(registry)
Gauge.builder(GAUGE_MESSAGES, maxRetriesReached::get).tag(TAG_STATUS, "maxRetriesReached").register(registry)
Gauge.builder(GAUGE_MESSAGES, inProgress::get).tag(TAG_STATUS, "inProgress").register(registry)
Gauge.builder(GAUGE_MESSAGES, paused::get).tag(TAG_STATUS, "paused").register(registry)
}
/**
* Reports message count.
*/
fun reportMessageCounts(countByStatus: CountByStatus) {
if (countByStatus.total == 0L) {
logger.debug { "No messages found, the inbox message table is clean." }
} else {
logger.debug { "Message counts: total: ${countByStatus.total}, retrying: ${countByStatus.retrying}, error: ${countByStatus.error}, retries exhausted: ${countByStatus.maxRetriesReached}, in progress: ${countByStatus.inProgress}, paused: ${countByStatus.paused}" }
}
total.set(countByStatus.total)
retrying.set(countByStatus.retrying)
error.set(countByStatus.error)
maxRetriesReached.set(countByStatus.maxRetriesReached)
inProgress.set(countByStatus.inProgress)
paused.set(countByStatus.paused)
}
/**
* Increment correlation success counter.
*/
fun incrementSuccess(size: Int) {
registry.counter(COUNTER_CORRELATED).increment(size.toDouble())
}
/**
* Increment correlation error counter by number of messages.
*/
fun incrementError(size: Int) {
registry.counter(COUNTER_ERROR).increment(size.toDouble())
}
/**
* Increment correlation success counter by one.
*/
fun incrementError() {
incrementError(1)
}
}
| 6 | Kotlin | 2 | 9 | fad54870ef76440ff61412f390ba53d0cf970f88 | 2,862 | camunda-bpm-correlate | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/real-literals/p-1/pos/1.2.fir.kt | JetBrains | 3,432,266 | false | null | // TESTCASE NUMBER: 1
val value_1 = 0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
// TESTCASE NUMBER: 2
val value_2 = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
// TESTCASE NUMBER: 3
val value_3 = -0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456789012345678901234567890123456789012345678901234567890
// TESTCASE NUMBER: 4
val value_4 = -0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456789012345678901234567890123456789012345678901234567890
// TESTCASE NUMBER: 5
val value_5 = -99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.0
// TESTCASE NUMBER: 6
val value_6 = 222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222.0
// TESTCASE NUMBER: 7
val value_7 = -555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555123456785012345678501234567850123456785012345678501234567850.0
// TESTCASE NUMBER: 8
val value_8 = 33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
// TESTCASE NUMBER: 9
val value_9 = -44444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
// TESTCASE NUMBER: 10
val value_10 = 777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
// TESTCASE NUMBER: 11
val value_11 = 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
// TESTCASE NUMBER: 12
val value_12 = -555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555123456785012345678501234567850123456785012345678501234567850.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456789012345678901234567890123456789012345678901234567890
| 154 | null | 5563 | 44,965 | e6633d3d9214402fcf3585ae8c24213a4761cc8b | 6,163 | kotlin | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/FileAudio.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.FileAudio: ImageVector
get() {
if (_fileAudio != null) {
return _fileAudio!!
}
_fileAudio = Builder(name = "FileAudio", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(19.95f, 5.536f)
lineToRelative(-3.485f, -3.485f)
curveToRelative(-1.322f, -1.322f, -3.08f, -2.05f, -4.95f, -2.05f)
horizontalLineToRelative(-4.515f)
curveTo(4.243f, 0.0f, 2.0f, 2.243f, 2.0f, 5.0f)
verticalLineToRelative(14.0f)
curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f)
horizontalLineToRelative(10.0f)
curveToRelative(2.757f, 0.0f, 5.0f, -2.243f, 5.0f, -5.0f)
verticalLineToRelative(-8.515f)
curveToRelative(0.0f, -1.87f, -0.728f, -3.628f, -2.05f, -4.95f)
close()
moveTo(18.536f, 6.95f)
curveToRelative(0.318f, 0.318f, 0.587f, 0.671f, 0.805f, 1.05f)
horizontalLineToRelative(-4.341f)
curveToRelative(-0.552f, 0.0f, -1.0f, -0.449f, -1.0f, -1.0f)
lineTo(14.0f, 2.659f)
curveToRelative(0.38f, 0.218f, 0.733f, 0.488f, 1.051f, 0.805f)
lineToRelative(3.485f, 3.485f)
close()
moveTo(20.0f, 19.0f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
lineTo(7.0f, 22.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
lineTo(4.0f, 5.0f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
horizontalLineToRelative(4.515f)
curveToRelative(0.163f, 0.0f, 0.325f, 0.008f, 0.485f, 0.023f)
verticalLineToRelative(4.977f)
curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f)
horizontalLineToRelative(4.977f)
curveToRelative(0.015f, 0.16f, 0.023f, 0.322f, 0.023f, 0.485f)
verticalLineToRelative(8.515f)
close()
moveTo(17.0f, 16.02f)
curveToRelative(0.0f, 1.105f, -0.895f, 2.0f, -2.0f, 2.0f)
verticalLineToRelative(-4.0f)
curveToRelative(1.105f, 0.0f, 2.0f, 0.895f, 2.0f, 2.0f)
close()
moveTo(13.0f, 13.02f)
verticalLineToRelative(5.936f)
curveToRelative(0.0f, 0.5f, -0.071f, 1.231f, -1.0f, 1.0f)
reflectiveCurveToRelative(-2.886f, -2.0f, -2.886f, -2.0f)
horizontalLineToRelative(-0.614f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
verticalLineToRelative(-0.936f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(0.614f)
reflectiveCurveToRelative(1.956f, -1.769f, 2.886f, -2.0f)
reflectiveCurveToRelative(1.0f, 0.5f, 1.0f, 1.0f)
close()
}
}
.build()
return _fileAudio!!
}
private var _fileAudio: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,063 | icons | MIT License |
app/src/main/java/com/desnyki/moviedb/di/AppModule.kt | desnyki | 271,080,985 | false | null | package com.desnyki.moviedb.di
import android.app.Application
import com.desnyki.moviedb.BuildConfig
import com.desnyki.moviedb.api.AuthInterceptor
import com.desnyki.moviedb.api.MovieService
import com.desnyki.moviedb.data.AppDatabase
import com.desnyki.moviedb.movie.data.MovieRemoteSource
import dagger.Module
import dagger.Provides
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module(includes = [ViewModelModule::class, NetworkModule::class])
class AppModule {
@Singleton
@Provides
fun provideMovieService(okHttpClient: OkHttpClient,
converterFactory: GsonConverterFactory
) = provideService(okHttpClient, converterFactory, MovieService::class.java)
@Singleton
@Provides
fun provideMovieRemoteSource(movieService: MovieService)
= MovieRemoteSource(movieService)
// @MovieAPI
// @Provides
// fun providePrivateOkHttpClient(
// upstreamClient: OkHttpClient
// ): OkHttpClient {
// return upstreamClient.newBuilder()
// .addInterceptor(AuthInterceptor(BuildConfig.API_DEVELOPER_TOKEN)).build()
// }
@Singleton
@Provides
fun provideDb(app: Application) = AppDatabase.getInstance(app)
@Singleton
@Provides
fun provideMovieDao(db: AppDatabase) = db.movieDao()
@CoroutineScopeIO
@Provides
fun provideCoroutineScopeIO() = CoroutineScope(Dispatchers.IO)
private fun createRetrofit(
okHttpClient: OkHttpClient,
converterFactory: GsonConverterFactory
): Retrofit {
return Retrofit.Builder()
.baseUrl(MovieService.ENDPOINT)
.client(okHttpClient)
.addConverterFactory(converterFactory)
.build()
}
private fun <T> provideService(okHttpClient: OkHttpClient,
converterFactory: GsonConverterFactory, clazz: Class<T>): T {
return createRetrofit(okHttpClient, converterFactory).create(clazz)
}
} | 0 | Kotlin | 0 | 1 | f6bc7246e9bb53df78218e769adf0bccdc4fa5de | 2,143 | MovieDB | Apache License 2.0 |
src/commonMain/kotlin/org/intellij/markdown/parser/sequentialparsers/SequentialParserManager.kt | JetBrains | 27,873,341 | false | {"Kotlin": 1305157, "Lex": 29252, "Ruby": 691, "Shell": 104} | package org.intellij.markdown.parser.sequentialparsers
import org.intellij.markdown.ExperimentalApi
import org.intellij.markdown.parser.CancellationToken
abstract class SequentialParserManager {
abstract fun getParserSequence(): List<SequentialParser>
@OptIn(ExperimentalApi::class)
fun runParsingSequence(
tokensCache: TokensCache,
rangesToParse: List<IntRange>,
): Collection<SequentialParser.Node> {
return runParsingSequence(tokensCache, rangesToParse, CancellationToken.NonCancellable)
}
@ExperimentalApi
fun runParsingSequence(
tokensCache: TokensCache,
rangesToParse: List<IntRange>,
cancellationToken: CancellationToken
): Collection<SequentialParser.Node> {
val result = ArrayList<SequentialParser.Node>()
var parsingSpaces = ArrayList<List<IntRange>>()
parsingSpaces.add(rangesToParse)
for (sequentialParser in getParserSequence()) {
cancellationToken.checkCancelled()
val nextLevelSpaces = ArrayList<List<IntRange>>()
for (parsingSpace in parsingSpaces) {
val currentResult = sequentialParser.parse(tokensCache, parsingSpace)
result.addAll(currentResult.parsedNodes)
nextLevelSpaces.addAll(currentResult.rangesToProcessFurther)
}
parsingSpaces = nextLevelSpaces
}
return result
}
}
| 56 | Kotlin | 75 | 661 | 43c06cb6a9d66caab8b431f738aba3c57aee559f | 1,442 | markdown | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/CopyrightSolid.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.CopyrightSolid: ImageVector
get() {
if (_copyrightSolid != null) {
return _copyrightSolid!!
}
_copyrightSolid = Builder(name = "CopyrightSolid", defaultWidth = 32.0.dp, defaultHeight =
32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.0f, 3.0f)
curveTo(8.832f, 3.0f, 3.0f, 8.832f, 3.0f, 16.0f)
curveTo(3.0f, 23.168f, 8.832f, 29.0f, 16.0f, 29.0f)
curveTo(23.168f, 29.0f, 29.0f, 23.168f, 29.0f, 16.0f)
curveTo(29.0f, 8.832f, 23.168f, 3.0f, 16.0f, 3.0f)
close()
moveTo(16.0f, 5.0f)
curveTo(22.086f, 5.0f, 27.0f, 9.914f, 27.0f, 16.0f)
curveTo(27.0f, 22.086f, 22.086f, 27.0f, 16.0f, 27.0f)
curveTo(9.914f, 27.0f, 5.0f, 22.086f, 5.0f, 16.0f)
curveTo(5.0f, 9.914f, 9.914f, 5.0f, 16.0f, 5.0f)
close()
moveTo(15.906f, 10.0f)
curveTo(12.582f, 10.0f, 9.906f, 12.676f, 9.906f, 16.0f)
curveTo(9.906f, 19.324f, 12.582f, 22.0f, 15.906f, 22.0f)
curveTo(18.305f, 22.0f, 20.355f, 20.563f, 21.313f, 18.531f)
lineTo(19.5f, 17.688f)
curveTo(18.855f, 19.059f, 17.508f, 20.0f, 15.906f, 20.0f)
curveTo(13.629f, 20.0f, 11.906f, 18.277f, 11.906f, 16.0f)
curveTo(11.906f, 13.723f, 13.629f, 12.0f, 15.906f, 12.0f)
curveTo(17.508f, 12.0f, 18.855f, 12.941f, 19.5f, 14.313f)
lineTo(21.313f, 13.469f)
curveTo(20.355f, 11.438f, 18.305f, 10.0f, 15.906f, 10.0f)
close()
}
}
.build()
return _copyrightSolid!!
}
private var _copyrightSolid: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,647 | compose-icons | MIT License |
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/AllView.kt | cliffano | 90,140,540 | false | null | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
/**
*
* @param propertyClass
* @param name
* @param url
*/
data class AllView(
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@field:JsonProperty("name") val name: kotlin.String? = null,
@field:JsonProperty("url") val url: kotlin.String? = null
) {
}
| 21 | Java | 11 | 18 | 1c4f48053076afe835a65c342932ba6d7dff690f | 746 | swaggy-jenkins | MIT License |
src/main/kotlin/org/gmd/repository/jdbc/ParametrizedDataSource.kt | akustik | 184,784,065 | false | null | package org.gmd.repository.jdbc
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Component
import java.sql.SQLException
import javax.sql.DataSource
@Component
open class ParametrizedDataSource {
@Value("\${spring.datasource.url}")
private var dbUrl: String? = null
@Bean
@Throws(SQLException::class)
fun dataSource(): DataSource {
if (dbUrl?.isEmpty() ?: true) {
return HikariDataSource()
} else {
val config = HikariConfig()
config.jdbcUrl = dbUrl
return HikariDataSource(config)
}
}
} | 8 | Kotlin | 3 | 4 | 07184b0ea0889b22c78b46f710818187d36b1af7 | 764 | topscores | MIT License |
library/kotlin/io/envoyproxy/envoymobile/stats/GaugeImpl.kt | envoyproxy | 173,839,917 | false | {"Java": 1303400, "C++": 879901, "NASL": 327095, "Kotlin": 304881, "Swift": 296564, "Starlark": 181018, "Objective-C": 87555, "Python": 53476, "C": 45954, "Shell": 10905, "HTML": 513, "Ruby": 47} | package io.envoyproxy.envoymobile
import io.envoyproxy.envoymobile.engine.EnvoyEngine
import java.lang.ref.WeakReference
/**
* Envoy implementation of a `Gauge`.
*/
internal class GaugeImpl : Gauge {
var envoyEngine: WeakReference<EnvoyEngine>
var series: String
var tags: Tags
internal constructor(engine: EnvoyEngine, elements: List<Element>, tags: Tags = TagsBuilder().build()) {
this.envoyEngine = WeakReference<EnvoyEngine>(engine)
this.series = elements.joinToString(separator = ".") { it.value }
this.tags = tags
}
override fun set(value: Int) {
envoyEngine.get()?.recordGaugeSet(series, this.tags.allTags(), value)
}
override fun set(tags: Tags, value: Int) {
envoyEngine.get()?.recordGaugeSet(series, tags.allTags(), value)
}
override fun add(amount: Int) {
envoyEngine.get()?.recordGaugeAdd(series, this.tags.allTags(), amount)
}
override fun add(tags: Tags, amount: Int) {
envoyEngine.get()?.recordGaugeAdd(series, tags.allTags(), amount)
}
override fun sub(amount: Int) {
envoyEngine.get()?.recordGaugeSub(series, this.tags.allTags(), amount)
}
override fun sub(tags: Tags, amount: Int) {
envoyEngine.get()?.recordGaugeSub(series, tags.allTags(), amount)
}
}
| 214 | Java | 88 | 555 | a9ce5f854d789a9d95d53f8ed3a0f3e4013b7671 | 1,252 | envoy-mobile | Apache License 2.0 |
app/src/test/java/pl/elpassion/eltc/recap/RecapControllerTest.kt | elpassion | 95,693,966 | false | null | @file:Suppress("IllegalIdentifier")
package pl.elpassion.eltc.recap
import com.nhaarman.mockito_kotlin.*
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers.trampoline
import io.reactivex.schedulers.TestScheduler
import io.reactivex.subjects.SingleSubject
import org.junit.Before
import org.junit.Test
import pl.elpassion.eltc.Build
import pl.elpassion.eltc.Status
import pl.elpassion.eltc.api.TeamCityApi
import pl.elpassion.eltc.createBuild
import pl.elpassion.eltc.login.AuthData
import pl.elpassion.eltc.login.LoginRepository
import pl.elpassion.eltc.util.SchedulersSupplier
import pl.elpassion.eltc.util.logger
import pl.elpassion.eltc.util.testLogger
import java.util.*
class RecapControllerTest {
private val ADDRESS = "http://teamcity"
private val CREDENTIALS = "credentials"
private val loginRepository = mock<LoginRepository>()
private val recapRepository = mock<RecapRepository>()
private val api = mock<TeamCityApi>()
private val notifier = mock<RecapNotifier>()
private val onFinish = mock<() -> Unit>()
private val apiSubject = SingleSubject.create<List<Build>>()
@Before
fun setup() {
logger = testLogger
whenever(loginRepository.authData).thenReturn(AuthData(ADDRESS, CREDENTIALS))
whenever(api.getFinishedBuilds(any())).thenReturn(apiSubject)
whenever(api.getFinishedBuildsForProjects(any(), any())).thenReturn(apiSubject)
}
@Test
fun `Set last finish date to initial date on first start`() {
whenever(recapRepository.lastFinishDate).thenReturn(null)
createController().onStart()
verify(recapRepository).lastFinishDate = any()
}
@Test
fun `Do not set last finish date to new date on subsequent start`() {
whenever(recapRepository.lastFinishDate).thenReturn(Date())
createController().onStart()
verify(recapRepository, never()).lastFinishDate = anyOrNull()
}
@Test
fun `Call api to get finished builds after last finish date`() {
val calendar = Calendar.getInstance().apply {
set(Calendar.YEAR, 2017)
set(Calendar.MONTH, Calendar.AUGUST)
set(Calendar.DAY_OF_MONTH, 1)
}
whenever(recapRepository.lastFinishDate).thenReturn(calendar.time)
createController().onStart()
verify(api).getFinishedBuilds(calendar.time)
}
@Test
fun `Do not call api to get finished builds on first start`() {
whenever(recapRepository.lastFinishDate).thenReturn(null)
createController().onStart()
verify(api, never()).getFinishedBuilds(any())
}
@Test
fun `Call api to get finished builds only for selected projects when preferred`() {
val projectsIds = listOf("Project1", "Project1")
val calendar = Calendar.getInstance().apply {
set(Calendar.YEAR, 2017)
set(Calendar.MONTH, Calendar.AUGUST)
set(Calendar.DAY_OF_MONTH, 1)
}
whenever(recapRepository.lastFinishDate).thenReturn(calendar.time)
createController(projectsIds = projectsIds).onStart()
verify(api).getFinishedBuildsForProjects(calendar.time, projectsIds)
}
@Test
fun `Update last finish date with new value from finished builds on api result`() {
val lastFinishDate = Date(1502103373000)
val newFinishDate = Date(1502103410000)
whenever(recapRepository.lastFinishDate).thenReturn(lastFinishDate)
createController().onStart()
apiSubject.onSuccess(listOf(createBuild(finishDate = newFinishDate)))
verify(recapRepository).lastFinishDate = newFinishDate
}
@Test
fun `Update last finish date with max value from finished builds on api result`() {
val lastFinishDate = Date(1502103373000)
val newFinishDates = listOf(Date(1502103410000), Date(1502103410002), Date(1502103410001))
whenever(recapRepository.lastFinishDate).thenReturn(lastFinishDate)
createController().onStart()
apiSubject.onSuccess(listOf(
createBuild(finishDate = newFinishDates[0]),
createBuild(finishDate = newFinishDates[1]),
createBuild(finishDate = newFinishDates[2])))
verify(recapRepository).lastFinishDate = newFinishDates[1]
}
@Test
fun `Do not update last finish date on api error`() {
val lastFinishDate = Date(1502103373000)
whenever(recapRepository.lastFinishDate).thenReturn(lastFinishDate)
createController().onStart()
apiSubject.onError(RuntimeException())
verify(recapRepository, never()).lastFinishDate = anyOrNull()
}
@Test
fun `Do not update last finish date on empty result`() {
val lastFinishDate = Date(1502103373000)
whenever(recapRepository.lastFinishDate).thenReturn(lastFinishDate)
createController().onStart()
apiSubject.onSuccess(listOf(createBuild(finishDate = null)))
verify(recapRepository, never()).lastFinishDate = anyOrNull()
}
@Test
fun `Show notifications with failed builds on api result`() {
val successfulBuild = createBuild(finishDate = Date(1502103410000), status = Status.SUCCESS)
val failedBuild = createBuild(finishDate = Date(1502103410001), status = Status.FAILURE)
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
createController().onStart()
apiSubject.onSuccess(listOf(successfulBuild, failedBuild))
verify(notifier).showFailureNotifications(listOf(failedBuild))
}
@Test
fun `Do not show notifications when no failures on api result`() {
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
createController().onStart()
apiSubject.onSuccess(listOf(
createBuild(finishDate = Date(1502103410000), status = Status.SUCCESS)))
verify(notifier, never()).showFailureNotifications(any())
}
@Test
fun `Invoke finish on first start`() {
whenever(recapRepository.lastFinishDate).thenReturn(null)
createController().onStart()
verify(onFinish).invoke()
}
@Test
fun `Invoke finish when auth data not available`() {
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
whenever(loginRepository.authData).thenReturn(null)
createController().onStart()
verify(onFinish).invoke()
}
@Test
fun `Do not invoke finish on subsequent start before result from api`() {
val lastFinishDate = Date(1502103373000)
whenever(recapRepository.lastFinishDate).thenReturn(lastFinishDate)
createController().onStart()
verify(onFinish, never()).invoke()
}
@Test
fun `Invoke finish on api error`() {
val lastFinishDate = Date(1502103373000)
whenever(recapRepository.lastFinishDate).thenReturn(lastFinishDate)
createController().onStart()
apiSubject.onError(RuntimeException())
verify(onFinish).invoke()
}
@Test
fun `Invoke finish on successful api result`() {
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
createController().onStart()
apiSubject.onSuccess(listOf(createBuild(finishDate = Date(1502103410000))))
verify(onFinish).invoke()
}
@Test
fun `Subscribe on given scheduler`() {
val subscribeOn = TestScheduler()
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
createController(subscribeOnScheduler = subscribeOn).onStart()
apiSubject.onSuccess(emptyList())
verify(onFinish, never()).invoke()
subscribeOn.triggerActions()
verify(onFinish).invoke()
}
@Test
fun `Observe on given scheduler`() {
val observeOn = TestScheduler()
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
createController(observeOnScheduler = observeOn).onStart()
apiSubject.onSuccess(emptyList())
verify(onFinish, never()).invoke()
observeOn.triggerActions()
verify(onFinish).invoke()
}
@Test
fun `Clear disposable on stop`() {
whenever(recapRepository.lastFinishDate).thenReturn(Date(1502103373000))
createController().run {
onStart()
onStop()
}
apiSubject.onError(RuntimeException())
verify(onFinish, never()).invoke()
}
private fun createController(projectsIds: List<String>? = null,
subscribeOnScheduler: Scheduler = trampoline(),
observeOnScheduler: Scheduler = trampoline()) =
RecapController(loginRepository, recapRepository, projectsIds, api, notifier, onFinish,
SchedulersSupplier(subscribeOnScheduler, observeOnScheduler))
} | 5 | Kotlin | 3 | 8 | 903bfdeaf04726a87b2b6a316f531aad1a0443b9 | 8,908 | el-teamcity | Apache License 2.0 |
libraries/base-ui/src/main/kotlin/catchup/base/ui/RootContent.kt | ZacSweers | 57,029,623 | false | null | package catchup.base.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import catchup.di.AppScope
import catchup.di.SingleIn
import com.slack.circuit.runtime.Navigator
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
@Stable
interface RootContent {
@Composable fun Content(navigator: Navigator, content: @Composable () -> Unit)
}
@SingleIn(AppScope::class)
@ContributesBinding(AppScope::class)
class DefaultRootContent @Inject constructor() : RootContent {
@Composable
override fun Content(navigator: Navigator, content: @Composable () -> Unit) {
content()
}
}
| 37 | null | 201 | 1,980 | 3ac348452590f8d9ba02c3e6163fb210df9e37f4 | 646 | CatchUp | Apache License 2.0 |
src/main/kotlin/com/thermondo/usecase/note/NoteModule.kt | TheBunksTie | 602,194,368 | false | null | package com.thermondo.usecase.note
import com.thermondo.domain.note.Note
import com.thermondo.usecase.note.viewmodel.INoteDomainViewModelConverter
import com.thermondo.usecase.note.viewmodel.NoteViewModelConverter
import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module
/**
* DI registrations for all auto-injected classes/interfaces related to use cases of [Note]
*/
val noteUseCaseModule = module {
singleOf(::NoteViewModelConverter) { bind<INoteDomainViewModelConverter>() }
singleOf(::CreateNote)
singleOf(::DeleteNote)
singleOf(::UpdateNote)
singleOf(::GetNotesByAuthor)
singleOf(::GetNotesByTags)
singleOf(::GetNotesByKeywords)
singleOf(::GetNotesByPublicState)
}
| 4 | Kotlin | 0 | 0 | 6b6b2c19c62ebe39360b65762fc9de04c882073a | 755 | note-taking-app-backend | MIT License |
core/src/main/java/org/aakotlin/core/client/CreateClient.kt | Syn-McJ | 755,053,065 | false | {"Kotlin": 102294} | /*
* Copyright (c) 2024 aa-kotlin
*
* This file is part of the aa-kotlin project: https://github.com/syn-mcj/aa-kotlin,
* and is released under the MIT License: https://opensource.org/licenses/MIT
*/
package org.aakotlin.core.client
import org.aakotlin.core.Chain
import org.web3j.protocol.http.HttpService
fun createPublicErc4337Client(
rpcUrl: String,
headers: Map<String, String> = emptyMap(),
): Erc4337Client {
val version = Chain::class.java.`package`.implementationVersion
val service =
HttpService(rpcUrl).apply {
addHeader("AA-Kotlin-Sdk-Version", version)
addHeaders(headers)
}
return JsonRpc2_Erc4337(service)
}
| 0 | Kotlin | 0 | 0 | 1d71c32a210a3da51355759ec9c688af0b9b82e3 | 691 | aa-kotlin | MIT License |
android/src/main/java/io/mosip/tuvali/verifier/transfer/message/InitTransferMessage.kt | mosip | 572,876,523 | false | {"Kotlin": 156258, "Swift": 66396, "Java": 11120, "TypeScript": 5017, "Ruby": 1353, "Objective-C": 550, "JavaScript": 77} | package io.mosip.tuvali.verifier.transfer.message
class InitTransferMessage(val data: ByteArray): IMessage(TransferMessageTypes.INIT_REQUEST_TRANSFER) {}
| 26 | Kotlin | 10 | 9 | 987b2d2512e57010c8a115b63b3b9093767c19ac | 155 | tuvali | MIT License |
module-telemetry/src/main/java/com/mapbox/maps/module/telemetry/PhoneState.kt | mapbox | 330,365,289 | false | null | package com.mapbox.maps.module.telemetry
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import com.google.gson.annotations.SerializedName
import com.mapbox.common.TelemetrySystemUtils
/**
* Class that holds kinds of states of the current phone.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal class PhoneState {
@SerializedName("created")
var created: String
@SerializedName("cellularNetworkType")
var cellularNetworkType: String? = null
@SerializedName("orientation")
var orientation: Orientation
@SerializedName("carrier")
var carrier: String? = null
@SerializedName("batteryLevel")
var batteryLevel = 0
@SerializedName("pluggedIn")
var isPluggedIn = false
@SerializedName("wifi")
var isWifi = false
@SerializedName("accessibilityFontScale")
var accessibilityFontScale = 0f
@SerializedName("resolution")
var resolution = 0f
@VisibleForTesting
constructor() {
created = "2020-07-12"
orientation = Orientation.ORIENTATION_PORTRAIT
}
constructor(context: Context) {
created = TelemetrySystemUtils.obtainCurrentDate()
batteryLevel = TelemetrySystemUtils.obtainBatteryLevel(context)
isPluggedIn = TelemetrySystemUtils.isPluggedIn(context)
cellularNetworkType = TelemetrySystemUtils.obtainCellularNetworkType(context)
orientation =
Orientation.getOrientation(
context.resources.configuration.orientation
)
accessibilityFontScale = context.resources.configuration.fontScale
carrier = obtainCellularCarrier(context)
resolution = obtainDisplayDensity(context)
isWifi = isConnectedToWifi(context)
}
private fun obtainCellularCarrier(context: Context): String {
val manager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val carrierName = manager.networkOperatorName
return if (TextUtils.isEmpty(carrierName)) {
NO_CARRIER
} else carrierName
}
private fun obtainDisplayDensity(context: Context): Float {
val displayMetrics = DisplayMetrics()
@Suppress("DEPRECATION")
(context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
.getMetrics(displayMetrics)
return displayMetrics.density
}
@SuppressLint("MissingPermission")
private fun isConnectedToWifi(context: Context): Boolean {
try {
val connectivityManager =
context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val activeNetwork = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
@Suppress("DEPRECATION")
val activeNetworkInfo = connectivityManager.activeNetworkInfo ?: return false
@Suppress("DEPRECATION")
return activeNetworkInfo.isConnected && activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}
} catch (exception: Exception) {
return false
}
}
internal enum class Orientation(val orientation: String) {
ORIENTATION_PORTRAIT("Portrait"), ORIENTATION_LANDSCAPE("Landscape");
companion object {
fun getOrientation(index: Int): Orientation {
return if (Configuration.ORIENTATION_PORTRAIT == index) {
ORIENTATION_PORTRAIT
} else ORIENTATION_LANDSCAPE
}
}
}
companion object {
private const val NO_CARRIER = "EMPTY_CARRIER"
private const val NO_NETWORK = -1
}
} | 216 | null | 131 | 472 | 2700dcaf18e70d23a19fc35b479bff6a2d490475 | 3,999 | mapbox-maps-android | Apache License 2.0 |
test/base/src/androidTest/kotlin/io/realm/test/RealmConfigurationTests.kt | seanadams540 | 430,690,173 | true | {"Kotlin": 1049705, "C++": 74855, "SWIG": 9542, "JavaScript": 8846, "Shell": 8312, "CMake": 5486, "Dockerfile": 2460, "C": 1762} | /*
* 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 io.realm.test
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.entities.Sample
import io.realm.internal.platform.singleThreadDispatcher
import org.junit.Test
class RealmConfigurationTests {
@Test
@Suppress("invisible_member")
fun testDispatcherAsWriteDispatcher() {
val configuration = RealmConfiguration.Builder(schema = setOf(Sample::class))
.writeDispatcher(singleThreadDispatcher("foo")).build()
val realm = Realm.open(configuration)
realm.writeBlocking {
copyToRealm(Sample())
}
realm.close()
}
}
| 0 | null | 0 | 0 | 392f212cf72342381211d633d291d4c0cf5c890a | 1,207 | realm-kotlin | DOC License |
openai-client/client/src/commonMain/kotlin/com/xebia/functional/openai/models/ext/transcription/create/CreateTranscriptionRequestModel.kt | xebia-functional | 629,411,216 | false | {"Kotlin": 4214569, "TypeScript": 67083, "Scala": 16969, "Mustache": 7004, "CSS": 6570, "JavaScript": 1935, "Java": 974, "HTML": 395, "Shell": 131} | package com.xebia.functional.openai.models.ext.transcription.create
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class CreateTranscriptionRequestModel(val value: String) {
@SerialName(value = "whisper-1") `whisper_1`("whisper-1");
fun asByteArray(): ByteArray = this.value.toByteArray(Charsets.UTF_8)
}
| 48 | Kotlin | 11 | 116 | bd5d7da61881fea5ec8d635236e182a7da979ad2 | 432 | xef | Apache License 2.0 |
app/src/test/java/com/kostyrev/giphytrend/details/middleware/LoadDetailsMiddlewareTest.kt | dkostyrev | 118,791,479 | false | null | @file:Suppress("IllegalIdentifier")
package com.kostyrev.giphytrend.details.middleware
import com.jakewharton.rxrelay2.BehaviorRelay
import com.jakewharton.rxrelay2.PublishRelay
import com.kostyrev.giphytrend.api.model.Gif
import com.kostyrev.giphytrend.api.model.Response
import com.kostyrev.giphytrend.details.DetailsInteractor
import com.kostyrev.giphytrend.details.DetailsState
import com.kostyrev.giphytrend.details.action.DetailsAction
import com.kostyrev.giphytrend.details.action.DetailsViewAction
import com.kostyrev.giphytrend.details.action.LoadAction
import com.kostyrev.giphytrend.details.action.StartAction
import com.kostyrev.giphytrend.util.instanceOf
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.Observable
import io.reactivex.observers.TestObserver
import junitparams.JUnitParamsRunner
import junitparams.Parameters
import org.hamcrest.Matcher
import org.hamcrest.Matchers
import org.hamcrest.Matchers.instanceOf
import org.hamcrest.core.Is
import org.junit.Assert
import org.junit.Assert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.internal.matchers.InstanceOf
@RunWith(JUnitParamsRunner::class)
internal class LoadDetailsMiddlewareTest {
private val interactor: DetailsInteractor = mockInteractor()
private val actions = PublishRelay.create<DetailsAction>()
private val state = BehaviorRelay.createDefault(DetailsState())
@Suppress("unused")
private fun positiveCases() = arrayOf(
Case(StartAction(), DetailsState(loading = false)),
Case(DetailsViewAction.Retry(), DetailsState(loading = false))
)
@Suppress("unused")
private fun negativeCases() = arrayOf(
Case(StartAction(), DetailsState(loading = true)),
Case(StartAction(), DetailsState(image = mock(), user = mock())),
Case(StartAction(), DetailsState(image = mock(), user = null)),
Case(DetailsViewAction.Retry(), DetailsState(loading = true))
)
@Test
@Parameters(method = "positiveCases")
fun `action received - starts with loading action`(case: Case) {
val observer = create()
state.accept(case.state)
actions.accept(case.action)
observer.assertValueAt(0) { it is LoadAction.Loading }
}
@Test
@Parameters(method = "positiveCases")
fun `action received - emits loaded action with gif`(case: Case) {
val gif = mock<Gif>()
interactor.setResult(Observable.just(Response(gif)))
val observer = create()
state.accept(case.state)
actions.accept(case.action)
observer.assertValueAt(1) {
it is LoadAction.Loaded && it.result === gif
}
}
@Test
@Parameters(method = "positiveCases")
fun `action received - emits error action with gif`(case: Case) {
interactor.setResult(Observable.error(Throwable("message")))
val observer = create()
state.accept(case.state)
actions.accept(case.action)
observer.assertValueAt(1) {
it is LoadAction.Error && it.error == "message"
}
}
@Test
@Parameters(method = "negativeCases")
fun `action received - does not start with loading action`(case: Case) {
val observer = create()
state.accept(case.state)
actions.accept(case.action)
observer.assertNoValues()
}
private fun create(): TestObserver<DetailsAction> {
return LoadDetailsMiddleware(interactor).create(actions, state).test()
}
private fun DetailsInteractor.setResult(observable: Observable<Response<Gif>> = Observable.empty()) {
whenever(loadGif()).thenReturn(observable)
}
private fun mockInteractor() = mock<DetailsInteractor>().also {
it.setResult(Observable.empty())
}
internal class Case(val action: DetailsAction, val state: DetailsState)
} | 0 | Kotlin | 0 | 1 | bdcc7a4cf2cd651c1e804c4ad8388a5d9af6f09f | 3,980 | giphytrend | MIT License |
libraries/kotlinlibrary/src/main/java/demo/Closed.kt | uber | 43,598,554 | false | null | package demo
@Anno
class Closed | 24 | null | 166 | 1,535 | 6f6a72b23d84bb70e49028cf7177377631d2bbe4 | 32 | okbuck | Apache License 2.0 |
android/src/main/java/vn/luongvo/kmm/survey/android/ui/screens/home/views/HomeHeader.kt | luongvo | 566,890,934 | false | null | package vn.luongvo.kmm.survey.android.ui.screens.home.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import vn.luongvo.kmm.survey.android.R
import vn.luongvo.kmm.survey.android.extension.placeholder
import vn.luongvo.kmm.survey.android.ui.preview.HomeParameterProvider
import vn.luongvo.kmm.survey.android.ui.screens.home.HomeUserAvatar
import vn.luongvo.kmm.survey.android.ui.screens.home.UserUiModel
import vn.luongvo.kmm.survey.android.ui.theme.AppTheme.dimensions
import vn.luongvo.kmm.survey.android.ui.theme.AppTheme.typography
import vn.luongvo.kmm.survey.android.ui.theme.ComposeTheme
@Composable
fun HomeHeader(
isLoading: Boolean,
dateTime: String,
user: UserUiModel?,
onUserAvatarClick: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier.padding(horizontal = dimensions.paddingMedium)
) {
Text(
text = dateTime.uppercase(),
color = White,
style = typography.subtitle1,
modifier = Modifier.placeholder(isLoading = isLoading)
)
Spacer(modifier = Modifier.height(4.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = stringResource(id = R.string.home_today),
color = White,
style = typography.h4,
modifier = Modifier.placeholder(isLoading = isLoading)
)
AsyncImage(
model = user?.avatarUrl.orEmpty(),
contentDescription = HomeUserAvatar,
modifier = Modifier
.size(dimensions.avatarSize)
.clip(CircleShape)
.placeholder(isLoading = isLoading)
.clickable { onUserAvatarClick() }
)
}
}
}
@Preview
@Composable
fun HomeHeaderPreview(
@PreviewParameter(HomeParameterProvider::class, limit = 2) params: HomeParameterProvider.Params
) {
with(params) {
ComposeTheme {
HomeHeader(
isLoading = isLoading,
dateTime = currentDate,
user = user,
onUserAvatarClick = {}
)
}
}
}
| 1 | Kotlin | 0 | 1 | df14cb68f68ed93c4fa52e7d3da2245665291e95 | 2,808 | kmm-survey | MIT License |
app/src/main/java/com/hannesdorfmann/mosby3/conductor/sample/create/CreateTaskPresenter.kt | sockeqwe | 56,765,949 | false | null | package com.hannesdorfmann.mosby.conductor.sample.create
import android.net.Uri
import com.hannesdorfmann.mosby.conductor.sample.model.tasks.TaskBuilder
import com.hannesdorfmann.mosby.conductor.sample.model.tasks.TaskDao
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter
import rx.Subscription
import javax.inject.Inject
/**
* Presenter to create a new Task
*
* @author <NAME>
*/
class CreateTaskPresenter @Inject constructor(private val dao: TaskDao, private val taskBuilder: TaskBuilder) : MvpBasePresenter<CreateTaskView>() {
private lateinit var taskBuilderSubscription: Subscription
override fun attachView(view: CreateTaskView) {
super.attachView(view)
taskBuilderSubscription = taskBuilder.observable.subscribe({ getView()?.setTaskSnapshot(it) })
}
override fun detachView(retainInstance: Boolean) {
super.detachView(retainInstance)
taskBuilderSubscription.unsubscribe()
}
fun setTaskTitle(title: String) {
taskBuilder.setTitle(title)
}
fun setTaskDescription(description: String) {
taskBuilder.setDescription(description)
}
fun addImage(uri: Uri) {
taskBuilder.addImage(uri)
}
fun saveTask() {
}
} | 16 | null | 21 | 135 | 2a70b20eb8262ca3bcddd30efdc080a3cdabb96c | 1,177 | mosby-conductor | Apache License 2.0 |
base/src/test/resources/__snapshots__/QuarkusProjectServiceTest/testGradleKotlin/src_main_kotlin_com_test_TestResource.kt | quarkusio | 192,503,868 | false | null | package com.test
import jakarta.ws.rs.GET
import jakarta.ws.rs.Path
import jakarta.ws.rs.Produces
import jakarta.ws.rs.core.MediaType
@Path("/hello")
class TestResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
fun hello() = "Hello from Quarkus REST"
} | 36 | null | 64 | 115 | 61aa32a5884b4a8c867e6169654ec91b7de14abb | 264 | code.quarkus.io | Apache License 2.0 |
app/src/main/java/com/inspirati/nutriapp/utils/Constants.kt | michaeloki | 296,335,976 | false | null | package com.inspirati.nutriapp.utils
object Constants {
val BASE_URL = "https://api.spoonacular.com/"
val NETWORK_TIMEOUT = 3000
val API_KEY = "<KEY>"
} | 1 | Kotlin | 1 | 1 | 7570beab1fbe16a3155aa062252b69fc2ca02734 | 166 | nutri-app | MIT License |
app/src/main/kotlin/me/thanel/quickimage/uploader/imgur/model/UploadedImage.kt | Tunous | 88,639,812 | false | null | package me.thanel.quickimage.uploader.imgur.model
/**
* The base model for an image.
*
* [See documentation](http://api.imgur.com/models/image)
*
* @property id The ID for the image.
* @property link The direct link to the the image.
*/
data class UploadedImage(val id: String, val link: String) : ImgurResponseData | 1 | null | 1 | 1 | 69a349a2726d56e1a881e62d43a0e7cf5e36f104 | 323 | QuickImage | Apache License 2.0 |
eco-api/src/main/kotlin/com/willfp/eco/util/VectorUtils.kt | Auxilor | 325,856,799 | false | null | @file:JvmName("VectorUtilsExtensions")
package com.willfp.eco.util
import org.bukkit.util.Vector
/** @see VectorUtils.isFinite */
val Vector.isFinite: Boolean
get() = VectorUtils.isFinite(this)
/** @see VectorUtils.simplifyVector */
fun Vector.simplify(): Vector =
VectorUtils.simplifyVector(this)
/** @see VectorUtils.isSafeVelocity */
val Vector.isSafeVelocity: Boolean
get() = VectorUtils.isSafeVelocity(this)
| 82 | null | 53 | 156 | 81de46a1c122a3cd6be06696b5b02d55fd9a73e5 | 430 | eco | MIT License |
app/src/main/kotlin/com/github/sdt/cypher/ui/adapters/keysadapter/InterfaceKeysAdapter.kt | shahadat-sdt | 433,701,557 | false | {"Java": 1896999, "Kotlin": 484679, "Assembly": 134} | package com.github.sdt.cypher.ui.adapters.keysadapter
import com.github.sdt.cypher.ui.adapters.basedapter.InterfaceAdapter
/**
* Created by <NAME> on 20/03/18.
*/
interface InterfaceKeysAdapter : InterfaceAdapter | 1 | Java | 1 | 1 | 87af8d63352b4ee3a03729a28ffeda44967904be | 216 | Cypher | Apache License 2.0 |
gradle-plugin/src/main/java/me/chen/resourcefix/ResourceFixProcessor.kt | chenqizheng | 187,644,347 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 10, "XML": 21, "Java": 8, "INI": 1} | package me.chen.resourcefix
import org.apache.commons.io.IOUtils
import org.objectweb.asm.*
import java.io.File
import java.io.FileOutputStream
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry
class ResourceFixProcessor {
companion object {
fun performClassFile(file: File) {
var byteArray = IOUtils.toByteArray(file.inputStream())
if (ActivityScanner.shouldProcessClass(byteArray)) {
modifyClass(byteArray).rewrite(file)
}
}
fun exlude(name: String): Boolean {
if (ResourceFixPlugin.getResourceFixConfig() == null) {
return false
}
ResourceFixPlugin.getResourceFixConfig().exludePattern.forEach {
var isExclude = it.matcher(
name.replace("/", ".").replace(
"\\",
"."
)
).matches()
if (isExclude) {
return true
}
}
return false
}
fun performJarFile(file: File) {
var jarFile = JarFile(file)
var optJar = File(file.parent, file.name + ".opt")
if (optJar.exists()) {
optJar.delete()
}
var enumeration = jarFile.entries()
var jarOutputStream = JarOutputStream(FileOutputStream(optJar))
while (enumeration.hasMoreElements()) {
var jarEntry = enumeration.nextElement() as JarEntry
var entryName = jarEntry.name
jarOutputStream.putNextEntry(ZipEntry(entryName))
var inputStream = jarFile.getInputStream(jarEntry)
var byteArray = IOUtils.toByteArray(inputStream);
if (entryName.endsWith(".class") && !exlude(
entryName
) && ActivityScanner.shouldProcessClass(byteArray)
) {
byteArray = modifyClass(byteArray)
}
jarOutputStream.write(byteArray)
inputStream.close()
jarOutputStream.closeEntry()
}
jarOutputStream.close()
jarFile.close()
if (file.exists()) {
file.delete()
}
optJar.renameTo(file)
}
private fun modifyClass(byteArray: ByteArray): ByteArray {
if (ResourceFixPlugin.getResourceFixConfig() == null
|| ResourceFixPlugin.getResourceFixConfig().insertClass == null
|| ResourceFixPlugin.getResourceFixConfig().insertStaticMethod == null
) {
return byteArray
}
var result: ByteArray;
var reader = ClassReader(byteArray)
var cw = ClassWriter(reader, 0)
var classVisitor = ModifyGetResourceVisitor(cw)
reader.accept(classVisitor, Opcodes.ASM5)
result = cw.toByteArray()
if (!classVisitor.hasGetResource) {
result = addGetResourceMethod(byteArray)
}
return result;
}
private fun addGetResourceMethod(byteArray: ByteArray): ByteArray {
var reader = ClassReader(byteArray)
var cw = ClassWriter(reader, 0)
var classVisitor = AddGetResourceMethodVisitor(cw)
reader.accept(classVisitor, Opcodes.ASM5)
var mv =
cw.visitMethod(Opcodes.ACC_PUBLIC, "getResources", "()Landroid/content/res/Resources;", null, null)
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
"android/support/v7/app/AppCompatActivity",
"getResources",
"()Landroid/content/res/Resources;",
false
);
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
ResourceFixPlugin.getResourceFixConfig().getInsertClass(),
ResourceFixPlugin.getResourceFixConfig().insertStaticMethod,
"(Landroid/content/res/Resources;)Landroid/content/res/Resources;",
false
);
mv.visitInsn(Opcodes.ARETURN);
mv.visitVarInsn(Opcodes.ALOAD, 0)
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
"android/support/v7/app/AppCompatActivity",
"getResources",
"()Landroid/content/res/Resources;",
false
)
mv.visitInsn(Opcodes.ARETURN)
mv.visitMaxs(1, 1)
mv.visitEnd()
return cw.toByteArray()!!
}
}
class ModifyGetResourceVisitor(
classVisitor: ClassWriter
) : ClassVisitor(Opcodes.ASM5, classVisitor) {
var hasGetResource = false
override fun visitMethod(
access: Int,
name: String?,
desc: String?,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor {
if (name == "getResources") {
//先得到原始的方法
val mv = cv.visitMethod(access, name, desc, signature, exceptions)
var newMethod: MethodVisitor? =
ModifyGetResourceMethodVisit(mv)
hasGetResource = true
return newMethod!!
}
return super.visitMethod(access, name, desc, signature, exceptions)
}
}
class ModifyGetResourceMethodVisit(mv: MethodVisitor) : MethodVisitor(Opcodes.ASM5, mv) {
override fun visitInsn(opcode: Int) {
if (opcode == Opcodes.ARETURN) {
mv.visitVarInsn(Opcodes.ALOAD, 0)
mv.visitMethodInsn(
Opcodes.INVOKESPECIAL,
"android/support/v7/app/AppCompatActivity",
"getResources",
"()Landroid/content/res/Resources;",
false
);
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
ResourceFixPlugin.getResourceFixConfig().getInsertClass(),
ResourceFixPlugin.getResourceFixConfig().insertStaticMethod,
"(Landroid/content/res/Resources;)Landroid/content/res/Resources;",
false
);
mv.visitInsn(Opcodes.ARETURN);
}
}
}
class AddGetResourceMethodVisitor(classWriter: ClassWriter) : ClassVisitor(Opcodes.ASM5, classWriter)
} | 1 | null | 1 | 1 | 6f15b0dd9d5e4d9a8eab474de8a5b9b798868207 | 6,692 | ResourceFix | Apache License 2.0 |
jaxrs/kotlin/src/main/kotlin/org/wildfly/swarm/examples/kotlin/KotlinApplication.kt | wildfly-swarm | 36,889,530 | false | null | package org.wildfly.swarm.examples.kotlin
import javax.ws.rs.ApplicationPath
import javax.ws.rs.core.Application
@ApplicationPath("/")
class MyApplication: Application() {
}
| 2 | JavaScript | 281 | 314 | 0f5d3e0d01af0d77eec357e0a2cdff6dd3bd8807 | 176 | wildfly-swarm-examples | Apache License 2.0 |
jaxrs/kotlin/src/main/kotlin/org/wildfly/swarm/examples/kotlin/KotlinApplication.kt | wildfly-swarm | 36,889,530 | false | null | package org.wildfly.swarm.examples.kotlin
import javax.ws.rs.ApplicationPath
import javax.ws.rs.core.Application
@ApplicationPath("/")
class MyApplication: Application() {
}
| 2 | JavaScript | 281 | 314 | 0f5d3e0d01af0d77eec357e0a2cdff6dd3bd8807 | 176 | wildfly-swarm-examples | Apache License 2.0 |
src/r3/atomic-swap/corda/evm-bridge-contracts/src/main/kotlin/com/r3/corda/evmbridge/states/LockState.kt | hyperledger-labs | 648,500,313 | false | null | package com.r3.corda.evmbridge.states
import net.corda.core.crypto.SignableData
import net.corda.core.crypto.SignatureMetadata
import net.corda.core.identity.Party
import net.corda.core.serialization.CordaSerializable
import net.corda.core.transactions.WireTransaction
@CordaSerializable
data class ValidatedDraftTransferOfOwnership(
val tx: WireTransaction,
val controllingNotary: Party,
val notarySignatureMetadata: SignatureMetadata
) {
val txHash get() = SignableData(tx.id, notarySignatureMetadata)
val timeWindow get() = tx.timeWindow!!
} | 1 | Kotlin | 6 | 9 | 42f1f3523bb8cc8a887bdc8fd5506e7595bf40d4 | 566 | harmonia | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ui/dsl/validation/impl/CompoundCellValidation.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.validation.impl
import com.intellij.openapi.observable.properties.ObservableProperty
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.dsl.validation.CellValidation
import com.intellij.ui.dsl.validation.Level
import com.intellij.ui.layout.ComponentPredicate
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
internal class CompoundCellValidation<out T>(private vararg val cellValidations: CellValidation<T>) : CellValidation<T> {
override var enabled: Boolean
get() = cellValidations.all { it.enabled }
set(value) {
for (validation in cellValidations) {
validation.enabled = value
}
}
override fun enabledIf(predicate: ComponentPredicate) {
for (cellValidation in cellValidations) {
cellValidation.enabledIf(predicate)
}
}
override fun enabledIf(property: ObservableProperty<Boolean>) {
for (cellValidation in cellValidations) {
cellValidation.enabledIf(property)
}
}
override fun addApplyRule(message: String, level: Level, condition: (T) -> Boolean) {
for (cellValidation in cellValidations) {
cellValidation.addApplyRule(message, level, condition)
}
}
override fun addApplyRule(validation: () -> ValidationInfo?) {
for (cellValidation in cellValidations) {
cellValidation.addApplyRule(validation)
}
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,500 | intellij-community | Apache License 2.0 |
feature_explore/src/main/java/com/igorwojda/showcase/feature/explore/presentation/explorelist/recyclerview/ExploreAdapter.kt | RohidanTiger | 353,037,677 | false | {"Gradle Kotlin DSL": 10, "YAML": 1, "Markdown": 3, "Java Properties": 1, "Proguard": 8, "Kotlin": 101, "XML": 60, "JSON": 2, "Java": 1} | package com.igorwojda.showcase.feature.explore.presentation.explorelist.recyclerview
import android.content.res.Resources
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import coil.transform.RoundedCornersTransformation
import com.igorwojda.showcase.feature.explore.R
import com.igorwojda.showcase.feature.explore.domain.model.ExploreDomainModel
import com.igorwojda.showcase.library.base.delegate.observer
import kotlinx.android.synthetic.main.fragment_explore_list_item.view.*
internal class ExploreAdapter : RecyclerView.Adapter<ExploreAdapter.MyViewHolder>() {
var albums: List<ExploreDomainModel> by observer(listOf()) {
notifyDataSetChanged()
}
private val startItemCount: Int = 0
private val endItemCount: Int = 8
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.fragment_explore_list_item, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(albums[position])
var names = albums[position].name.split("")
var exploreName = ""
for (item: Int in startItemCount..endItemCount) {
exploreName += names[item]
}
exploreName += "..."
holder.itemView.tv_name.text = exploreName
}
override fun getItemCount(): Int = albums.size
internal inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var url by observer<String?>(null) {
itemView.iv_explore_item.load(it) {
crossfade(true)
error(R.drawable.ic_image)
transformations(RoundedCornersTransformation(10F))
}
}
fun bind(albumDomainModel: ExploreDomainModel) {
url = albumDomainModel.getDefaultImageUrl()
}
}
}
| 0 | Kotlin | 0 | 0 | 6b90f17f66b0bd9ee414a7d9591c9b33030a33cd | 2,059 | novel | MIT License |
mvvmbase/src/main/java/de/trbnb/mvvmbase/ViewModel.kt | apm-thorben-buchta | 260,314,817 | true | {"Kotlin": 104187, "Java": 3650} | package de.trbnb.mvvmbase
import androidx.databinding.Observable
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import de.trbnb.mvvmbase.events.EventChannel
import kotlin.reflect.KProperty
/**
* Base interface that defines basic functionality for all view models.
*
* View models are bound to either an [MvvmBindingActivity] or an [MvvmBindingFragment] and saved
* throughout the lifecycle of these by the Architecture Components.
*
* It extends the [Observable] interface provided by the Android data binding library. This means
* that implementations have to handle [androidx.databinding.Observable.OnPropertyChangedCallback]s.
* This is done the easiest way by extending [androidx.databinding.BaseObservable].
*/
interface ViewModel : Observable, LifecycleOwner {
/**
* Object that can be used to send one-time or not-state information to the UI.
*/
val eventChannel: EventChannel
/**
* Notifies listeners that all properties of this instance have changed.
*/
fun notifyChange()
/**
* Notifies listeners that a specific property has changed. The getter for the property
* that changes should be marked with [Bindable] to generate a field in
* `BR` to be used as `fieldId`.
*
* @param fieldId The generated BR id for the Bindable field.
*/
fun notifyPropertyChanged(fieldId: Int)
/**
* Notifies listeners that a specific property has changed. The getter for the property
* that changes should be marked with [Bindable] to generate a field in
* `BR` to be used as `fieldId`.
*
* @see notifyPropertyChanged
*
* @param property The property whose BR field ID will be detected via reflection.
*/
fun notifyPropertyChanged(property: KProperty<*>)
/**
* Registers a property changed callback.
*/
override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback)
/**
* Unregisters a property changed callback.
*/
override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback)
/**
* Is called when this ViewModel is bound to a View.
*/
fun onBind()
/**
* Is called this ViewModel is not bound to a View anymore.
*/
fun onUnbind()
/**
* Is called when this instance is about to be removed from memory.
* This means that this object is no longer bound to a view and will never be. It is about to
* be garbage collected.
* Implementations should use this method to deregister from callbacks, etc.
*/
fun onDestroy()
/**
* Destroys all ViewModels in that list when the containing ViewModel is destroyed.
*/
fun <VM : ViewModel> List<VM>.autoDestroy() {
lifecycle.addObserver(object : LifecycleObserver {
@Suppress("unused")
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
forEach { it.onDestroy() }
}
})
}
}
| 0 | null | 0 | 1 | 648141649221b5d11ec71da4f410580eddbe7ec4 | 3,135 | MvvmBase | Apache License 2.0 |
plugins/markdown/test/src/org/intellij/plugins/markdown/model/HeaderAnchorCompletionPopupTypedHandlerTest.kt | ingokegel | 72,937,917 | true | null | package org.intellij.plugins.markdown.model
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.CompletionAutoPopupTestCase
import com.intellij.util.application
import junit.framework.TestCase
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class HeaderAnchorCompletionPopupTypedHandlerTest: CompletionAutoPopupTestCase() {
override fun setUp() {
super.setUp()
application.invokeAndWait {
myFixture.copyDirectoryToProject("", "")
}
}
@Test
fun `test reference to own header`() {
doTest(
"header-in-main",
"other-header-in-main"
)
}
@Test
fun `test reference to header in other file`() {
doTest(
"header-near-main",
"other-header-near-main"
)
}
@Test
fun `test reference to header in subdirectory`() {
doTest(
"header-in-subdirectory",
"other-header-in-subdirectory"
)
}
private fun doTest(vararg expectedLookupString: String) {
val testName = getTestName(true)
myFixture.configureByFile("$testName.md")
type("#")
TestCase.assertNotNull(lookup)
val elements = myFixture.lookupElementStrings ?: emptyList()
UsefulTestCase.assertSameElements(elements, *expectedLookupString)
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val name = super.getTestName(lowercaseFirstLetter)
return name.trimStart().replace(' ', '_')
}
override fun getTestDataPath(): String {
return "${MarkdownTestingUtil.TEST_DATA_PATH}/model/headers/completion"
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,667 | intellij-community | Apache License 2.0 |
platform/feedback/src/com/intellij/feedback/kafka/TestShowKafkaProducerFeedbackAction.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.feedback.kafka
import com.intellij.feedback.common.IdleFeedbackTypes
import com.intellij.feedback.kafka.bundle.KafkaFeedbackBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
class TestShowKafkaProducerFeedbackAction : AnAction(KafkaFeedbackBundle.message("kafka.producer.test.action.name")) {
override fun actionPerformed(e: AnActionEvent) {
IdleFeedbackTypes.KAFKA_PRODUCER_FEEDBACK.showNotification(e.project, true)
}
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
} | 229 | null | 4931 | 15,571 | 92c8aad1c748d6741e2c8e326e76e68f3832f649 | 780 | intellij-community | Apache License 2.0 |
common/src/main/java/jp/co/soramitsu/common/compose/component/MnemonicWords.kt | soramitsu | 278,060,397 | false | {"Kotlin": 5738459, "Java": 18796} | package jp.co.soramitsu.common.compose.component
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.SubcomposeLayout
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import jp.co.soramitsu.common.compose.theme.customColors
data class MnemonicWordModel(
val numberToShow: String,
val word: String
)
fun mapMnemonicToMnemonicWords(mnemonic: List<String>): List<MnemonicWordModel> {
return mnemonic.mapIndexed { index: Int, word: String ->
MnemonicWordModel(
(index + 1).toString(),
word
)
}
}
fun List<MnemonicWordModel>.toMnemonicString(): String {
return joinToString(separator = "")
}
@Composable
fun MnemonicWords(
mnemonicWords: List<MnemonicWordModel>,
modifier: Modifier = Modifier
) {
val mnemonicWordsCount by remember(mnemonicWords) {
derivedStateOf { mnemonicWords.size }
}
Row(modifier = modifier) {
Spacer(modifier = Modifier.weight(1f))
val firstPart by remember(mnemonicWords, mnemonicWordsCount) {
derivedStateOf {
mnemonicWords.subList(0, (mnemonicWordsCount + 1) / 2)
}
}
MnemonicWordsColumn(mnemonicWords = firstPart)
Spacer(modifier = Modifier.weight(1f))
val secondPart by remember(mnemonicWords, mnemonicWordsCount) {
derivedStateOf {
mnemonicWords.subList((mnemonicWordsCount + 1) / 2, mnemonicWordsCount)
}
}
MnemonicWordsColumn(mnemonicWords = secondPart)
Spacer(modifier = Modifier.weight(1f))
}
}
@Composable
private fun MnemonicWordsColumn(
modifier: Modifier = Modifier,
mnemonicWords: List<MnemonicWordModel>
) {
val maxSymbolsInColumn by remember(mnemonicWords) {
derivedStateOf {
mnemonicWords
.maxByOrNull { it.numberToShow.length }
?.numberToShow.orEmpty()
.length
}
}
MeasureUnconstrainedViewWidth(
modifier = modifier,
viewToMeasure = {
MnemonicWordNumber(
number = "0".repeat(maxSymbolsInColumn)
)
}
) { numberTextWidth ->
Column {
mnemonicWords.forEach { mnemonicWord ->
MnemonicWord(
mnemonicWord = mnemonicWord,
numberTextWidth = numberTextWidth
)
}
}
}
}
@Composable
private fun MnemonicWord(
mnemonicWord: MnemonicWordModel,
numberTextWidth: Dp,
modifier: Modifier = Modifier
) {
Row(modifier = modifier) {
MnemonicWordNumber(
modifier = Modifier.width(numberTextWidth),
number = mnemonicWord.numberToShow
)
MarginHorizontal(margin = 12.dp)
B0(text = mnemonicWord.word)
}
}
@Composable
private fun MnemonicWordNumber(
number: String,
modifier: Modifier = Modifier
) {
B0(
modifier = modifier,
text = number,
color = MaterialTheme.customColors.colorGreyText
)
}
@Composable
private fun MeasureUnconstrainedViewWidth(
modifier: Modifier = Modifier,
viewToMeasure: @Composable () -> Unit,
content: @Composable (measuredWidth: Dp) -> Unit
) {
SubcomposeLayout(modifier = modifier) { constraints ->
val measuredWidth = subcompose("viewToMeasure", viewToMeasure)[0]
.measure(Constraints()).width.toDp()
val contentPlaceable = subcompose("content") {
content(measuredWidth)
}[0].measure(constraints)
layout(contentPlaceable.width, contentPlaceable.height) {
contentPlaceable.place(0, 0)
}
}
}
@Preview
@Composable
fun MnemonicWordsPreview(
modifier: Modifier = Modifier
) {
val mnemonicWords = listOf(
MnemonicWordModel(numberToShow = "1", word = "song"),
MnemonicWordModel(numberToShow = "2", word = "toss"),
MnemonicWordModel(numberToShow = "3", word = "odor"),
MnemonicWordModel(numberToShow = "4", word = "click"),
MnemonicWordModel(numberToShow = "5", word = "blouse"),
MnemonicWordModel(numberToShow = "6", word = "lesson"),
MnemonicWordModel(numberToShow = "7", word = "runway"),
MnemonicWordModel(numberToShow = "8", word = "popular"),
MnemonicWordModel(numberToShow = "9", word = "owner"),
MnemonicWordModel(numberToShow = "10", word = "caught"),
MnemonicWordModel(numberToShow = "11", word = "wrist"),
MnemonicWordModel(numberToShow = "12", word = "poverty")
)
MnemonicWords(mnemonicWords = mnemonicWords)
}
| 15 | Kotlin | 30 | 89 | 1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2 | 5,157 | fearless-Android | Apache License 2.0 |
core-utils/src/main/java/io/appmetrica/analytics/coreutils/internal/services/SafePackageManagerHelperForR.kt | appmetrica | 650,662,094 | false | null | package io.appmetrica.analytics.coreutils.internal.services
import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.os.Build
import io.appmetrica.analytics.coreapi.internal.annotations.DoNotInline
@DoNotInline
@TargetApi(Build.VERSION_CODES.R)
object SafePackageManagerHelperForR {
@JvmStatic
fun extractPackageInstaller(packageManager: PackageManager, packageName: String): String? {
return packageManager.getInstallSourceInfo(packageName).installingPackageName
}
}
| 1 | null | 5 | 54 | 472d3dfb1e09f4e7f35497e5049f53287ccce7d1 | 525 | appmetrica-sdk-android | MIT License |
alerting/src/test/kotlin/com/amazon/opendistroforelasticsearch/alerting/action/GetEmailAccountResponseTests.kt | marshell0 | 400,442,979 | true | {"Kotlin": 1021367, "Java": 94668, "Batchfile": 76} | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.alerting.action
import com.amazon.opendistroforelasticsearch.alerting.randomEmailAccount
import org.elasticsearch.common.io.stream.BytesStreamOutput
import org.elasticsearch.common.io.stream.StreamInput
import org.elasticsearch.rest.RestStatus
import org.elasticsearch.test.ESTestCase
class GetEmailAccountResponseTests : ESTestCase() {
fun `test get email account response`() {
val res = GetEmailAccountResponse("1234", 1L, 2L, 0L, RestStatus.OK, null)
assertNotNull(res)
val out = BytesStreamOutput()
res.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newRes = GetEmailAccountResponse(sin)
assertEquals("1234", newRes.id)
assertEquals(1L, newRes.version)
assertEquals(RestStatus.OK, newRes.status)
assertEquals(null, newRes.emailAccount)
}
fun `test get email account with email account`() {
val emailAccount = randomEmailAccount(name = "test_email_account")
val res = GetEmailAccountResponse("1234", 1L, 2L, 0L, RestStatus.OK, emailAccount)
assertNotNull(res)
val out = BytesStreamOutput()
res.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newRes = GetEmailAccountResponse(sin)
assertEquals("1234", newRes.id)
assertEquals(1L, newRes.version)
assertEquals(RestStatus.OK, newRes.status)
assertNotNull(newRes.emailAccount)
assertEquals("test_email_account", newRes.emailAccount?.name)
}
}
| 0 | Kotlin | 0 | 3 | e571571c7abd4ade9fc230c0d449423f947ae0ea | 2,208 | alerting | Apache License 2.0 |
src/test/java/no/nav/sbl/redis/RedisVeilederContextDatabaseTest.kt | navikt | 149,753,566 | false | {"Kotlin": 147533, "Dockerfile": 352, "Shell": 313} | package no.nav.sbl.redis
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.lettuce.core.RedisClient
import io.lettuce.core.RedisURI
import kotlinx.coroutines.runBlocking
import no.nav.sbl.domain.VeilederContext
import no.nav.sbl.domain.VeilederContextType
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
@Testcontainers
class RedisVeilederContextDatabaseTest {
companion object {
@Container
private val redisContainer = TestUtils.RedisContainer()
}
@AfterEach
fun afterEach(): Unit =
runBlocking {
redis.flushall()
}
private val redis by lazy {
val redisConnection =
RedisClient
.create(
RedisURI
.builder()
.withHost(redisContainer.host)
.withPort(redisContainer.getMappedPort(6379))
.withAuthentication("default", "password")
.build(),
).connect()
redisConnection.sync()
}
private val redisVeilederContextDatabase by lazy {
RedisVeilederContextDatabase(
redis,
jacksonObjectMapper().registerModule(JavaTimeModule()),
)
}
private val enhetEvent: VeilederContext =
VeilederContext(
contextType = VeilederContextType.NY_AKTIV_ENHET,
verdi = "enhet",
veilederIdent = "veileder",
)
private val brukerEvent =
VeilederContext(
contextType = VeilederContextType.NY_AKTIV_BRUKER,
verdi = "bruker",
veilederIdent = "veileder",
)
@Test
fun `brukereventer kan lagres og hentes`() {
redisVeilederContextDatabase.save(brukerEvent)
val aktivBrukerEvent = redisVeilederContextDatabase.sistAktiveBrukerEvent("veileder")
assertThat(aktivBrukerEvent?.verdi).isNotNull
assertThat(aktivBrukerEvent?.verdi).isEqualTo(brukerEvent.verdi)
}
@Test
fun `enheteventer kan lagres og hentes`() {
redisVeilederContextDatabase.save(enhetEvent)
val aktivEnhetEvent = redisVeilederContextDatabase.sistAktiveEnhetEvent("veileder")
assertThat(aktivEnhetEvent?.verdi).isNotNull
assertThat(aktivEnhetEvent?.verdi).isEqualTo(enhetEvent.verdi)
}
@Test
fun `sletter alle enheteventer for en veileder`() {
redisVeilederContextDatabase.save(enhetEvent)
redisVeilederContextDatabase.save(brukerEvent)
redisVeilederContextDatabase.slettAlleAvEventTypeForVeileder(VeilederContextType.NY_AKTIV_ENHET, "veileder")
val aktivEnhetEvent = redisVeilederContextDatabase.sistAktiveEnhetEvent("veileder")
val aktivBrukerEvent = redisVeilederContextDatabase.sistAktiveBrukerEvent("veileder")
assertThat(aktivEnhetEvent).isNull()
assertThat(aktivBrukerEvent?.verdi).isNotNull
assertThat(aktivBrukerEvent?.verdi).isEqualTo(brukerEvent.verdi)
}
@Test
fun `sletter alle brukereventer for en veileder`() {
redisVeilederContextDatabase.save(brukerEvent)
redisVeilederContextDatabase.save(enhetEvent)
redisVeilederContextDatabase.slettAlleAvEventTypeForVeileder(VeilederContextType.NY_AKTIV_BRUKER, "veileder")
val aktivBrukerEvent = redisVeilederContextDatabase.sistAktiveBrukerEvent("veileder")
val aktivEnhetEvent = redisVeilederContextDatabase.sistAktiveEnhetEvent("veileder")
assertThat(aktivBrukerEvent).isNull()
assertThat(aktivEnhetEvent?.verdi).isNotNull
assertThat(aktivEnhetEvent?.verdi).isEqualTo(enhetEvent.verdi)
}
@Test
fun `alle eventer for en veileder kan slettes`() {
redisVeilederContextDatabase.save(brukerEvent)
redisVeilederContextDatabase.save(enhetEvent)
redisVeilederContextDatabase.slettAlleEventer("veileder")
val aktivBrukerEvent = redisVeilederContextDatabase.sistAktiveBrukerEvent("veileder")
val aktivEnhetEvent = redisVeilederContextDatabase.sistAktiveEnhetEvent("veileder")
assertThat(aktivBrukerEvent).isNull()
assertThat(aktivEnhetEvent).isNull()
}
}
| 1 | Kotlin | 0 | 0 | 8fa7a00fb9ad05826e899eb4f658bf15334b9d46 | 4,448 | modiacontextholder | MIT License |
app/src/main/java/com/jiangyy/wanandroid/ui/MainActivity.kt | jyygithub | 563,629,875 | false | null | package com.jiangyy.wanandroid.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.addCallback
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.jiangyy.wanandroid.R
import com.jiangyy.wanandroid.databinding.ActivityMainBinding
import com.jiangyy.wanandroid.ui.home.HomeFragment
import com.jiangyy.wanandroid.ui.home.HomeMyFragment
import com.jiangyy.wanandroid.ui.home.HomeSubFragment
import com.jiangyy.wanandroid.ui.home.HomeSearchFragment
import com.koonny.appcompat.BaseActivity
import com.koonny.appcompat.core.toast
import kotlin.system.exitProcess
class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var pressedTime: Long = 0
onBackPressedDispatcher.addCallback(this) {
val nowTime = System.currentTimeMillis()
if (nowTime - pressedTime > 2000) {
toast("再按一次退出程序")
pressedTime = nowTime
} else {
finish()
exitProcess(0)
}
}
}
override fun onPrepareWidget() {
super.onPrepareWidget()
binding.containerView.isUserInputEnabled = false
binding.containerView.adapter = object : FragmentStateAdapter(this) {
override fun getItemCount(): Int = 4
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
recyclerView.setItemViewCacheSize(4)
}
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> HomeFragment.newInstance()
1 -> HomeSearchFragment.newInstance()
2 -> HomeSubFragment.newInstance()
3 -> HomeMyFragment.newInstance()
else -> HomeFragment.newInstance()
}
}
}
binding.bottomNavigationView.itemIconTintList = null
binding.bottomNavigationView.setOnItemSelectedListener {
val recyclerView = binding.containerView.getChildAt(0) as RecyclerView
when (it.itemId) {
R.id.nav_home -> recyclerView.scrollToPosition(0)
R.id.nav_explore -> recyclerView.scrollToPosition(1)
R.id.nav_sub -> recyclerView.scrollToPosition(2)
R.id.nav_smile -> recyclerView.scrollToPosition(3)
}
true
}
}
companion object {
fun actionStart(context: Context) {
context.startActivity(Intent(context, MainActivity::class.java))
}
}
} | 0 | Kotlin | 0 | 0 | fb2c92fc3649a82cd393a464d2d5655af90e5925 | 2,883 | wanandroid | Apache License 2.0 |
react-table-kotlin/src/main/kotlin/tanstack/table/core/AggregationFn.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
package tanstack.table.core
import kotlinx.js.ReadonlyArray
typealias AggregationFn<TData /* : RowData */> = (columnId: String, leafRows: ReadonlyArray<Row<TData>>, childRows: ReadonlyArray<Row<TData>>) -> Any | 0 | Kotlin | 5 | 13 | 0f67fb7955dc2c00a7fd18d369ea546d93fa7a92 | 256 | react-types-kotlin | Apache License 2.0 |
intellij-plugin-verifier/verifier-intellij/src/main/java/com/jetbrains/pluginverifier/usages/properties/EnumPropertyUsageProcessor.kt | JetBrains | 3,686,654 | false | {"Kotlin": 2521867, "Java": 253600, "CSS": 1454, "JavaScript": 692} | package com.jetbrains.pluginverifier.usages.properties
import com.jetbrains.pluginverifier.results.reference.MethodReference
import com.jetbrains.pluginverifier.verifiers.VerificationContext
import com.jetbrains.pluginverifier.verifiers.bytecode.InterpreterAdapter
import com.jetbrains.pluginverifier.verifiers.bytecode.InvokeSpecialInterpreterListener
import com.jetbrains.pluginverifier.verifiers.bytecode.StringValue
import com.jetbrains.pluginverifier.verifiers.resolution.Method
import com.jetbrains.pluginverifier.verifiers.resolution.MethodAsm
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.analysis.Analyzer
import org.objectweb.asm.tree.analysis.BasicValue
class EnumPropertyUsageProcessor : AbstractPropertyUsageProcessor() {
private val enumClassPropertyUsage = EnumClassPropertyUsageAdapter()
override fun processMethodInvocation(
methodReference: MethodReference,
resolvedMethod: Method,
instructionNode: AbstractInsnNode,
callerMethod: Method,
context: VerificationContext
) {
if (callerMethod !is MethodAsm) return
val invokeSpecialDetector = InvokeSpecialInterpreterListener()
Analyzer(InterpreterAdapter(invokeSpecialDetector)).analyze(
callerMethod.containingClassFile.name,
callerMethod.asmNode
)
enumClassPropertyUsage.resolve(resolvedMethod)?.let { resourceBundledProperty ->
invokeSpecialDetector.invocations.filter {
it.methodName == "<init>" && it.desc == ENUM_PRIVATE_CONSTRUCTOR_DESC
}.forEach { constructorInvocation ->
// Drop the following parameters
// 1) invocation target 2) enum member name 3) enum ordinal value
// Such parameters are passed to the pseudo-synthetic private enum constructor
val invocationParameteres = constructorInvocation.values.drop(3)
// TODO support more parameters
invocationParameteres.firstStringOrNull()?.let { propertyKey ->
checkProperty(resourceBundledProperty.bundleName, propertyKey, context, callerMethod.location)
}
}
}
return
}
fun supports(method: Method): Boolean {
return enumClassPropertyUsage.supports(method)
}
private fun List<BasicValue>.firstStringOrNull(): String? =
filterIsInstance<StringValue>().firstOrNull()?.value
} | 4 | Kotlin | 38 | 178 | 8be19a2c67854545d719fe56f3677122481b372f | 2,312 | intellij-plugin-verifier | Apache License 2.0 |
app/src/main/java/de/drtobiasprinz/summitbook/ui/GarminPythonExecutor.kt | prinztob | 370,702,913 | false | null | package de.drtobiasprinz.summitbook.ui
import android.os.AsyncTask
import android.util.Log
import android.view.View
import com.chaquo.python.PyObject
import com.chaquo.python.Python
import com.chaquo.python.android.AndroidPlatform
import com.google.gson.JsonArray
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import de.drtobiasprinz.summitbook.MainActivity
import de.drtobiasprinz.summitbook.fragments.SummitViewFragment
import de.drtobiasprinz.summitbook.models.*
import de.drtobiasprinz.summitbook.ui.dialog.BaseDialog
import de.drtobiasprinz.summitbook.ui.utils.GarminTrackAndDataDownloader
import de.drtobiasprinz.summitbook.ui.utils.GarminTrackAndDataDownloader.Companion.getTempGpsFilePath
import de.drtobiasprinz.summitbook.ui.utils.SortFilterHelper
import java.io.File
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.pow
import kotlin.math.roundToLong
class GarminPythonExecutor(val username: String, val password: String) {
lateinit var pythonInstance: Python
lateinit var pythonModule: PyObject
var client: PyObject? = null
private fun login() {
if (client == null) {
if (!Python.isStarted()) {
MainActivity.mainActivity?.let { AndroidPlatform(it) }?.let { Python.start(it) }
}
pythonInstance = Python.getInstance()
pythonModule = pythonInstance.getModule("start")
Log.i("GarminPythonExecutor", "do login")
val result = pythonModule.callAttr("get_authenticated_client", username, password)
checkOutput(result)
client = result
}
}
fun getActivityJsonAtDate(dateAsString: String): List<Summit> {
if (client == null) {
login()
}
val result = pythonModule.callAttr("get_activity_json_for_date", client, dateAsString)
checkOutput(result)
val jsonResponse = JsonParser().parse(result.toString()) as JsonArray
return getSummitsAtDate(jsonResponse)
}
fun downloadGpxFile(garminActivityId: String, downloadPath: String) {
if (client == null) {
login()
}
val result = pythonModule.callAttr("download_gpx", client, garminActivityId, downloadPath)
checkOutput(result)
}
fun downloadTcxFile(garminActivityId: String, downloadPath: String) {
if (client == null) {
login()
}
val result = pythonModule.callAttr("download_tcx", client, garminActivityId, downloadPath)
checkOutput(result)
}
fun downloadActivitiesByDate(activitiesDir: File, startDate: String, endDate: String) {
if (client == null) {
login()
}
if (!activitiesDir.exists()) {
activitiesDir.mkdirs()
}
val result = pythonModule.callAttr("download_activities_by_date", client, activitiesDir.absolutePath, startDate, endDate)
checkOutput(result)
}
fun downloadSpeedDataForActivity(activitiesDir: File, activityId: String): JsonObject {
if (client == null) {
login()
}
val result = pythonModule.callAttr("get_split_data", client, activityId, activitiesDir.absolutePath)
checkOutput(result)
return JsonParser().parse(result.toString()) as JsonObject
}
fun getMultiSportData(activityId: String): JsonObject {
if (client == null) {
login()
}
val result = pythonModule.callAttr("get_multi_sport_data", client, activityId)
checkOutput(result)
return JsonParser().parse(result.toString()) as JsonObject
}
fun getMultiSportPowerData(dateAsString: String): JsonObject {
if (client == null) {
login()
}
val result = pythonModule.callAttr("get_power_data", client, dateAsString)
checkOutput(result)
return JsonParser().parse(result.toString()) as JsonObject
}
private fun checkOutput(result: PyObject?) {
if (result == null || result.toString() == "") {
throw RuntimeException("Execution failed")
}
if (result.toString().startsWith("return code: 1")) {
throw RuntimeException(result.toString().replace("return code: 1", ""))
}
}
companion object {
class AsyncDownloadGpxViaPython(garminPythonExecutor: GarminPythonExecutor, entries: List<Summit>, private val sortFilterHelper: SortFilterHelper, useTcx: Boolean = false, private val dialog: BaseDialog, private val index: Int = -1) : AsyncTask<Void?, Void?, Void?>() {
private val downloader = GarminTrackAndDataDownloader(entries, garminPythonExecutor, useTcx)
override fun doInBackground(vararg params: Void?): Void? {
try {
downloader.downloadTracks()
} catch (e: RuntimeException) {
Log.e("AsyncDownloadGpxViaPython.doInBackground", e.message ?: "")
}
return null
}
override fun onPostExecute(param: Void?) {
try {
downloader.extractFinalSummit()
if (dialog.isStepByStepDownload()) {
val activityId = downloader.finalEntry?.garminData?.activityId
if (activityId != null) {
downloader.composeFinalTrack(getTempGpsFilePath(activityId).toFile())
}
} else {
downloader.composeFinalTrack()
downloader.updateFinalEntry(sortFilterHelper)
}
if (index != -1) {
dialog.doInPostExecute(index, downloader.downloadedTracks.none { !it.exists() })
}
} catch (e: RuntimeException) {
Log.e("AsyncDownloadGpxViaPython", e.message ?: "")
} finally {
SummitViewFragment.updateNewSummits(SummitViewFragment.activitiesDir, sortFilterHelper.entries, dialog.getDialogContext())
val progressBar = dialog.getProgressBarForAsyncTask()
if (progressBar != null) {
progressBar.visibility = View.GONE
progressBar.tooltipText = ""
}
}
}
}
fun getSummitsAtDate(activities: JsonArray): List<Summit> {
val entries = ArrayList<Summit>()
for (i in 0 until activities.size()) {
val row = activities[i] as JsonObject
try {
entries.add(parseJsonObject(row))
} catch (e: ParseException) {
e.printStackTrace()
}
}
return entries
}
fun getAllDownloadedSummitsFromGarmin(directory: File): MutableList<Summit> {
val entries = mutableListOf<Summit>()
if (directory.exists() && directory.isDirectory) {
val files = directory.listFiles()
if (files?.isNotEmpty() == true) {
files.forEach {
if (it.name.startsWith("activity_") && !it.name.endsWith("_splits.json")) {
val gson = JsonParser().parse(it.readText()) as JsonObject
entries.add(parseJsonObject(gson))
}
}
}
}
return entries
}
@Throws(ParseException::class)
fun parseJsonObject(jsonObject: JsonObject): Summit {
val date = SimpleDateFormat(Summit.DATETIME_FORMAT, Locale.ENGLISH)
.parse(jsonObject.getAsJsonPrimitive("startTimeLocal").asString) ?: Date()
val duration: Double = if (jsonObject["movingDuration"] != JsonNull.INSTANCE) jsonObject["movingDuration"].asDouble else jsonObject["duration"].asDouble
val averageSpeed = convertMphToKmh(jsonObject["distance"].asDouble / duration)
val activityIds: MutableList<String> = mutableListOf(jsonObject["activityId"].asString)
if (jsonObject.has("childIds")) {
activityIds.addAll(jsonObject["childIds"].asJsonArray.map { it.asString })
}
val garminData = GarminData(
activityIds,
getJsonObjectEntryNotNull(jsonObject, "calories"),
getJsonObjectEntryNotNull(jsonObject, "averageHR"),
getJsonObjectEntryNotNull(jsonObject, "maxHR"),
getPower(jsonObject),
getJsonObjectEntryNotNull(jsonObject, "maxFtp").toInt(),
getJsonObjectEntryNotNull(jsonObject, "vO2MaxValue").toInt(),
getJsonObjectEntryNotNull(jsonObject, "aerobicTrainingEffect"),
getJsonObjectEntryNotNull(jsonObject, "anaerobicTrainingEffect"),
getJsonObjectEntryNotNull(jsonObject, "grit"),
getJsonObjectEntryNotNull(jsonObject, "avgFlow"),
getJsonObjectEntryNotNull(jsonObject, "activityTrainingLoad")
)
return Summit(date,
jsonObject["activityName"].asString,
parseSportType(jsonObject["activityType"].asJsonObject),
emptyList(), emptyList(), "",
ElevationData.parse(if (jsonObject["maxElevation"] != JsonNull.INSTANCE) round(jsonObject["maxElevation"].asDouble, 2).toInt() else 0,
getJsonObjectEntryNotNull(jsonObject, "elevationGain").toInt()),
round(convertMeterToKm(getJsonObjectEntryNotNull(jsonObject, "distance").toDouble()), 2),
VelocityData.parse(round(averageSpeed, 2),
if (jsonObject["maxSpeed"] != JsonNull.INSTANCE) round(convertMphToKmh(jsonObject["maxSpeed"].asDouble), 2) else 0.0),
null, null,
emptyList(),
false,
mutableListOf(),
garminData,
null
)
}
private fun getPower(jsonObject: JsonObject) =
PowerData(
getJsonObjectEntryNotNull(jsonObject, "avgPower"),
getJsonObjectEntryNotNull(jsonObject, "maxPower"),
getJsonObjectEntryNotNull(jsonObject, "normPower"),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_1").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_2").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_5").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_10").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_20").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_30").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_60").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_120").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_300").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_600").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_1200").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_1800").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_3600").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_7200").toInt(),
getJsonObjectEntryNotNull(jsonObject, "maxAvgPower_18000").toInt()
)
private fun getJsonObjectEntryNotNull(jsonObject: JsonObject, key: String): Float {
return if (jsonObject[key].isJsonNull) 0.0f else jsonObject[key].asFloat
}
private fun convertMphToKmh(mph: Double): Double {
return mph * 3.6
}
private fun convertMeterToKm(meter: Double): Double {
return meter / 1000.0
}
private fun parseSportType(jsonObject: JsonObject): SportType {
return when (jsonObject["typeId"].asInt) {
1 -> SportType.Running
2 -> SportType.Bicycle
5 -> SportType.Mountainbike
89 -> SportType.BikeAndHike
169 -> SportType.Skitour
else -> SportType.Hike
}
}
private fun round(value: Double, precision: Int): Double {
val scale = 10.0.pow(precision.toDouble()).toInt()
return (value * scale).roundToLong().toDouble() / scale
}
}
} | 0 | Kotlin | 0 | 0 | dae46b5b9781c06cc2c7a47a107c05a8fe0e05d3 | 12,961 | summitbook | MIT License |
runtime/commonMain/src/kotlinx/benchmark/CommonSuiteExecutor.kt | Kotlin | 162,275,279 | false | null | package kotlinx.benchmark
import kotlinx.benchmark.internal.KotlinxBenchmarkRuntimeInternalApi
@KotlinxBenchmarkRuntimeInternalApi
abstract class CommonSuiteExecutor(
executionName: String,
configPath: String,
xmlReporter: (() -> BenchmarkProgress)? = null
) : SuiteExecutor(executionName, configPath, xmlReporter) {
private fun runBenchmark(
benchmark: BenchmarkDescriptor<Any?>,
configuration: BenchmarkConfiguration,
parameters: Map<String, String>,
id: String,
): DoubleArray? {
val instance = benchmark.suite.factory()
benchmark.suite.parametrize(instance, parameters)
benchmark.suite.setup(instance)
var exception: Throwable? = null
val samples = try {
val cycles = estimateCycles(instance, benchmark, configuration)
val measurer = createIterationMeasurer(instance, benchmark, configuration, cycles)
warmup(id, configuration, cycles, measurer)
measure(id, configuration, cycles, measurer)
} catch (e: Throwable) {
exception = e
doubleArrayOf()
} finally {
benchmark.suite.teardown(instance)
benchmark.blackhole.flush()
}
if (exception != null) {
val error = exception.toString()
val stacktrace = exception.stackTraceToString()
reporter.endBenchmarkException(executionName, id, error, stacktrace)
return null
}
return samples
}
private fun saveBenchmarkResults(benchmark: BenchmarkDescriptor<Any?>, configuration: BenchmarkConfiguration, parameters: Map<String, String>, id: String, samples: DoubleArray) {
val convertedSamples = samples
.map { it.nanosToSample(configuration.mode, configuration.outputTimeUnit) }
.toDoubleArray()
val result = ReportBenchmarksStatistics.createResult(benchmark, parameters, configuration, convertedSamples)
val message = with(result) {
" ~ ${score.sampleToText(
config.mode,
config.outputTimeUnit
)} ±${(error / score * 100).formatSignificant(2)}%"
}
reporter.endBenchmark(executionName, id, BenchmarkProgress.FinishStatus.Success, message)
result(result)
}
override fun run(runnerConfiguration: RunnerConfiguration, benchmarks: List<BenchmarkDescriptor<Any?>>, start: () -> Unit, complete: () -> Unit) {
start()
for (benchmark in benchmarks) {
val suite = benchmark.suite
val benchmarkConfiguration = BenchmarkConfiguration(runnerConfiguration, suite)
runWithParameters(suite.parameters, runnerConfiguration.params, suite.defaultParameters) { parameters ->
val id = id(benchmark.name, parameters)
reporter.startBenchmark(executionName, id)
val samples = runBenchmark(benchmark, benchmarkConfiguration, parameters, id)
if (samples != null) {
saveBenchmarkResults(benchmark, benchmarkConfiguration, parameters, id, samples)
}
}
}
complete()
}
private fun <T> estimateCycles(
instance: T,
benchmark: BenchmarkDescriptor<T>,
configuration: BenchmarkConfiguration
): Int {
val estimator = wrapBenchmarkFunction(instance, benchmark) { body ->
var iterations = 0
var elapsedTime = 0L
val benchmarkIterationTime = configuration.iterationTime * configuration.iterationTimeUnit.toMultiplier()
do {
val subIterationDuration = measureNanoseconds(body)
elapsedTime += subIterationDuration
iterations++
} while (elapsedTime < benchmarkIterationTime)
iterations
}
return estimator()
}
private fun warmup(
id: String,
configuration: BenchmarkConfiguration,
cycles: Int,
measurer: () -> Long
) {
var currentIteration = 0
while(currentIteration < configuration.warmups) {
val elapsedTime = measurer()
val metricInNanos = elapsedTime.toDouble() / cycles
val sample = metricInNanos.nanosToText(configuration.mode, configuration.outputTimeUnit)
reporter.output(executionName, id, "Warm-up #$currentIteration: $sample")
currentIteration++
}
}
private fun measure(
id: String,
configuration: BenchmarkConfiguration,
cycles: Int,
measurer: () -> Long
) : DoubleArray = DoubleArray(configuration.iterations) { iteration ->
val nanosecondsPerOperation = measurer().toDouble() / cycles
val text = nanosecondsPerOperation.nanosToText(configuration.mode, configuration.outputTimeUnit)
reporter.output(executionName, id, "Iteration #$iteration: $text")
nanosecondsPerOperation
}
private inline fun <T, R> wrapBenchmarkFunction(
instance: T,
benchmark: BenchmarkDescriptor<T>,
crossinline wrapper: (() -> Unit) -> R): () -> R = when(benchmark) {
is BenchmarkDescriptorWithBlackholeParameter -> {
{
val localBlackhole = benchmark.blackhole
val localDelegate = benchmark.function
val localInstance = instance
wrapper {
localBlackhole.consume(localInstance.localDelegate(localBlackhole))
}
}
}
is BenchmarkDescriptorWithNoBlackholeParameter -> {
{
val localBlackhole = benchmark.blackhole
val localDelegate = benchmark.function
val localInstance = instance
wrapper {
localBlackhole.consume(localInstance.localDelegate())
}
}
}
else -> error("Unexpected ${benchmark::class.simpleName}")
}
protected open fun <T> createIterationMeasurer(
instance: T,
benchmark: BenchmarkDescriptor<T>,
configuration: BenchmarkConfiguration,
cycles: Int
): () -> Long = wrapBenchmarkFunction(instance, benchmark) { payload ->
var cycle = cycles
measureNanoseconds {
while(cycle-- > 0) {
payload()
}
}
}
}
| 61 | null | 36 | 469 | 7950a879c92b765d8df43feb9c667efc2d5fd75d | 6,428 | kotlinx-benchmark | Apache License 2.0 |
src/main/kotlin/behavioral/observer/usage/NewsObserver.kt | gvoltr | 151,469,613 | false | null | package behavioral.observer.usage
import behavioral.observer.pattern.Observer
class NewsObserver: Observer<String> {
override fun update(data: String) {
print("News observer received $data")
}
} | 0 | Kotlin | 0 | 0 | 8a6ef2b336fea0848b2c220672b2a020abecd005 | 213 | patterns | Apache License 2.0 |
src/main/kotlin/com/github/blarc/ai/commits/intellij/plugin/settings/clients/LLMClientTable.kt | Blarc | 618,925,533 | false | {"Kotlin": 85721} | package com.github.blarc.ai.commits.intellij.plugin.settings.clients
import com.github.blarc.ai.commits.intellij.plugin.AICommitsBundle.message
import com.github.blarc.ai.commits.intellij.plugin.createColumn
import com.github.blarc.ai.commits.intellij.plugin.settings.AppSettings2
import com.github.blarc.ai.commits.intellij.plugin.settings.clients.ollama.OllamaClientConfiguration
import com.github.blarc.ai.commits.intellij.plugin.settings.clients.openAi.OpenAiClientConfiguration
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter
import com.intellij.ui.JBCardLayout
import com.intellij.ui.components.JBList
import com.intellij.ui.popup.list.GroupedItemsListRenderer
import com.intellij.ui.table.TableView
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.ListTableModel
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListSelectionModel.SINGLE_SELECTION
class LLMClientTable {
private var llmClients = AppSettings2.instance.llmClientConfigurations
private val tableModel = createTableModel()
val table = TableView(tableModel).apply {
setShowColumns(true)
setSelectionMode(SINGLE_SELECTION)
columnModel.getColumn(0).preferredWidth = 150
columnModel.getColumn(0).maxWidth = 250
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) {
if (e?.clickCount == 2) {
editLlmClient()
}
}
})
}
private fun createTableModel(): ListTableModel<LLMClientConfiguration> = ListTableModel(
arrayOf(
createColumn<LLMClientConfiguration>(message("settings.llmClient.name")) { llmClient -> llmClient.name },
createColumn(message("settings.llmClient.host")) { llmClient -> llmClient.host },
createColumn(message("settings.llmClient.modelId")) { llmClient -> llmClient.modelId }
),
llmClients.toList()
)
fun addLlmClient(): LLMClientConfiguration? {
val dialog = LLMClientDialog()
if (dialog.showAndGet()) {
llmClients = llmClients.plus(dialog.llmClient)
refreshTableModel()
return dialog.llmClient
}
return null
}
fun removeLlmClient(): LLMClientConfiguration? {
val selectedLlmClient = table.selectedObject ?: return null
llmClients = llmClients.minus(selectedLlmClient)
refreshTableModel()
return selectedLlmClient
}
fun editLlmClient(): Pair<LLMClientConfiguration, LLMClientConfiguration>? {
val selectedLlmClient = table.selectedObject ?: return null
val dialog = LLMClientDialog(selectedLlmClient.clone())
if (dialog.showAndGet()) {
llmClients = llmClients.minus(selectedLlmClient)
llmClients = llmClients.plus(dialog.llmClient)
refreshTableModel()
return selectedLlmClient to dialog.llmClient
}
return null
}
private fun refreshTableModel() {
tableModel.items = llmClients.toList()
}
fun reset() {
llmClients = AppSettings2.instance.llmClientConfigurations
refreshTableModel()
}
fun isModified() = llmClients != AppSettings2.instance.llmClientConfigurations
fun apply() {
AppSettings2.instance.llmClientConfigurations = llmClients
}
private class LLMClientDialog(val newLlmClientConfiguration: LLMClientConfiguration? = null) : DialogWrapper(true) {
private val llmClientConfigurations: List<LLMClientConfiguration> = getLlmClients(newLlmClientConfiguration)
var llmClient = newLlmClientConfiguration ?: llmClientConfigurations[0]
private val cardLayout = JBCardLayout()
init {
title = newLlmClientConfiguration?.let { "Edit LLM Client" } ?: "Add LLM Client"
setOKButtonText(newLlmClientConfiguration?.let { message("actions.update") } ?: message("actions.add"))
init()
}
override fun doOKAction() {
if (newLlmClientConfiguration == null) {
(cardLayout.findComponentById(llmClient.getClientName()) as DialogPanel).apply()
}
// TODO: Figure out how to call apply of the currently active panel
super.doOKAction()
}
override fun createCenterPanel() = if (newLlmClientConfiguration == null) {
createCardSplitter()
} else {
llmClient.panel().create()
}.apply {
isResizable = false
}
private fun getLlmClients(newLLMClientConfiguration: LLMClientConfiguration?): List<LLMClientConfiguration> {
return if (newLLMClientConfiguration == null) {
// TODO(@Blarc): Is there a better way to create the list of all possible LLM Clients that implement LLMClient abstract class
listOf(
OpenAiClientConfiguration(),
OllamaClientConfiguration()
)
} else {
listOf(newLLMClientConfiguration)
}
}
private fun createCardSplitter(): JComponent {
return Splitter(false, 0.25f).apply {
val cardPanel = JPanel(cardLayout).apply {
preferredSize = JBUI.size(640, 480)
llmClientConfigurations.forEach {
add(it.getClientName(), it.panel().create())
}
}
// Register validators of the currently active cards
val dialogPanel = cardLayout.findComponentById(llmClient.getClientName()) as DialogPanel
dialogPanel.registerValidators(myDisposable) {
isOKActionEnabled = ContainerUtil.and(it.values) { info: ValidationInfo -> info.okEnabled }
}
val cardsList = JBList(llmClientConfigurations).apply {
val descriptor = object : ListItemDescriptorAdapter<LLMClientConfiguration>() {
override fun getTextFor(value: LLMClientConfiguration) = value.getClientName()
override fun getIconFor(value: LLMClientConfiguration) = value.getClientIcon()
}
cellRenderer = object : GroupedItemsListRenderer<LLMClientConfiguration>(descriptor) {
override fun customizeComponent(list: JList<out LLMClientConfiguration>?, value: LLMClientConfiguration?, isSelected: Boolean) {
myTextLabel.border = JBUI.Borders.empty(4)
}
}
addListSelectionListener {
llmClient = selectedValue
cardLayout.show(cardPanel, llmClient.getClientName())
}
setSelectedValue(llmClient, true)
}
firstComponent = cardsList
secondComponent = cardPanel
}
}
}
}
| 12 | Kotlin | 20 | 145 | 73d4187ad9bcc316767ffc7186c53cbc197275a8 | 7,373 | ai-commits-intellij-plugin | MIT License |
app/src/main/java/com/android/ao/blogapp/data/model/User.kt | kairos34 | 533,413,248 | false | {"Kotlin": 31551} | package com.android.ao.blogapp.data.model
import androidx.annotation.Keep
@Keep
data class User(
val name: String,
val thumbnailUrl: String,
val url: String,
val userId: Int
) | 0 | Kotlin | 0 | 0 | d2e1a2f21e6dc017bbaa1dd7829c7a32b0706469 | 193 | BlogApp | MIT License |
libs/pandautils/src/main/java/com/instructure/pandautils/room/appdatabase/daos/AttachmentDao.kt | instructure | 179,290,947 | false | {"Kotlin": 16085132, "Dart": 4413539, "HTML": 185120, "Ruby": 32390, "Shell": 19157, "Java": 13488, "Groovy": 11717, "JavaScript": 9505, "CSS": 1356, "Swift": 404, "Dockerfile": 112, "Objective-C": 37} | package com.instructure.pandautils.room.appdatabase.daos
import androidx.room.*
import com.instructure.pandautils.room.appdatabase.entities.AttachmentEntity
@Dao
interface AttachmentDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(attachment: AttachmentEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(attachments: List<AttachmentEntity>)
@Delete
suspend fun delete(attachment: AttachmentEntity)
@Delete
suspend fun deleteAll(attachments: List<AttachmentEntity>)
@Update
suspend fun update(attachment: AttachmentEntity)
@Query("SELECT * FROM AttachmentEntity WHERE workerId=:parentId")
suspend fun findByParentId(parentId: String): List<AttachmentEntity>?
} | 7 | Kotlin | 102 | 127 | f82ec380673be5812c88bbc6b15c3d960515c6d8 | 768 | canvas-android | Apache License 2.0 |
test/com/shopping/queries/OrdersQueriesTest.kt | alialbaali | 285,645,104 | false | {"Kotlin": 224319} | package com.shopping.queries
import com.shopping.DefaultSpec
import com.shopping.dataSourceModule
import com.shopping.db.OrdersQueries
import com.shopping.dbModule
import com.shopping.domain.model.valueObject.ID
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.matchers.collections.shouldHaveAtLeastSize
import io.kotest.matchers.collections.shouldHaveAtMostSize
import io.kotest.matchers.string.shouldContainIgnoringCase
import org.koin.core.inject
import java.time.LocalDate
class OrdersQueriesTest : DefaultSpec(dbModule, dataSourceModule) {
private val ordersQueries by inject<OrdersQueries>()
init {
Given("a list of orders") {
And("a unique customer id") {
When("inserting the order into the db") {
Then("we should be able to query it using the same customer id") {
val customerId = ID.random()
shouldNotThrowAny {
repeat(10) {
ordersQueries.createOrder(
ID.random(),
customerId,
4242,
"Home",
LocalDate.now(),
)
}
}
ordersQueries.getOrdersByCustomerId(customerId)
.executeAsList() shouldHaveAtLeastSize 10
}
}
}
}
Given("a list of orders with same order id") {
And("a unique customer id") {
When("inserting the order into the db") {
Then("it should fail due to unique constraint") {
val customerId = ID.random()
val orderId = ID.random()
shouldThrowAny {
repeat(10) {
ordersQueries.createOrder(
orderId,
customerId,
4242,
"Home",
LocalDate.now(),
)
}
}.message shouldContainIgnoringCase "UNIQUE CONSTRAINT FAILED"
ordersQueries.getOrdersByCustomerId(customerId)
.executeAsList() shouldHaveAtMostSize 1
}
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | e8d003386bfff065c9a775b4a808c2d7dd9acd87 | 2,724 | Shopally | Apache License 2.0 |
kondor-examples/src/jmh/kotlin/com/ubertob/kondor/json/jmh/BenchmarkKondorNdJson.kt | uberto | 343,412,601 | false | {"Kotlin": 342010, "Java": 46239, "Shell": 922} | package com.ubertob.kondor.json.jmh
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.infra.Blackhole
open class BenchmarkKondorNdJson {
@Benchmark
fun kondorSerializationOfDemoClass(blackHole: Blackhole, testFix: DemoClassFixtures) {
with(testFix) {
val json = demoClassNdProducer(objList).toList()
blackHole.consume(json)
}
}
@Benchmark
fun kondorDeserializationOfDemoClass(blackHole: Blackhole, testFix: DemoClassFixtures) =
with(testFix) {
val list = demoClassNdConsumer(ndJsonStrings)
blackHole.consume(list)
}
}
fun main() {
benchLoopNd(::toNdJson, ::fromNdJson)
}
private fun fromNdJson(lines: Sequence<String>): List<DemoClass> = demoClassNdConsumer(lines).orThrow()
private fun toNdJson(objs: List<DemoClass>): Sequence<String> =
demoClassNdProducer(objs)
| 0 | Kotlin | 14 | 81 | b186b1693d422c9ac9a4c70beb30403d7ede80c3 | 900 | kondor-json | Apache License 2.0 |
app/src/main/java/cz/cuni/mff/ufal/translator/interactors/analytics/events/SpeechToTextEvent.kt | ufal | 479,050,528 | false | null | package cz.cuni.mff.ufal.translator.interactors.analytics.events
import cz.cuni.mff.ufal.translator.ui.translations.models.Language
/**
* @author Tomas Krabac
*/
data class SpeechToTextEvent(
val language: Language,
val text: String,
) | 7 | Kotlin | 0 | 2 | 3412f958a4b506bbe535688c3341831564bb009f | 248 | charles-translator-android | MIT License |
app/src/main/java/com/edwin/github_app/model/repo/RepoModel.kt | LiangLliu | 445,907,238 | false | {"Kotlin": 247539, "Java": 117126} | package com.edwin.github_app.model.repo
import com.edwin.github_app.model.page.ListPage
import com.edwin.github_app.network.services.RepositoryService
import com.edwin.github_app.network.entities.Repository
import com.edwin.github_app.network.entities.User
import com.edwin.github_app.utils.format
import retrofit2.adapter.rxjava.GitHubPaging
import rx.Observable
import java.util.*
class RepoListPage(val owner: User?) : ListPage<Repository>() {
override fun getData(page: Int): Observable<GitHubPaging<Repository>> {
return if (owner == null) {
RepositoryService.allRepositories(page, "pushed:<" + Date().format("yyyy-MM-dd"))
.map { it.paging }
} else {
RepositoryService.listRepositoriesOfUser(owner.login, page)
}
}
} | 0 | Kotlin | 0 | 0 | 7f828dedc343d3a5a19d052951692987bc714c5d | 797 | github-app | MIT License |
src/systemtest/kotlin/de/unisaarland/cs/se/selab/systemtest/scenarioTests/LooooonggggTickkkkkkk.kt | Atharvakore | 872,001,311 | false | {"Kotlin": 614544} | package de.unisaarland.cs.se.selab.systemtest.scenarioTests
import de.unisaarland.cs.se.selab.systemtest.api.SystemTestAssertionError
import de.unisaarland.cs.se.selab.systemtest.utils.ExampleSystemTestExtension
import de.unisaarland.cs.se.selab.systemtest.utils.Logs
/**
* Basic 6 Tile Test. deep ocean on right with a current pushing left
*/
class LooooonggggTickkkkkkk : ExampleSystemTestExtension() {
override val description = "Do 50 tick simulation and Pray.."
override val corporations = "corporationJsons/toManyShipsAnsCorpo.json"
override val scenario = "scenarioJsons/dontBreakPlease.json"
override val map = "mapFiles/bigMap1.json"
override val name = "LONGLONGLONGLONG"
override val maxTicks = 50
override suspend fun run() {
val expectedString = "Simulation Statistics: Corporation 1 collected 19000 of garbage."
if (skipUntilLogType(Logs.SIMULATION_STATISTICS) != expectedString) {
throw SystemTestAssertionError("Collected plastic should be 0!")
}
assertNextLine("Simulation Statistics: Corporation 2 collected 23000 of garbage.")
assertNextLine("Simulation Statistics: Corporation 3 collected 23000 of garbage.")
assertNextLine("Simulation Statistics: Total amount of plastic collected: 0.")
assertNextLine("Simulation Statistics: Total amount of oil collected: 65000.")
assertNextLine("Simulation Statistics: Total amount of chemicals collected: 0.")
assertNextLine("Simulation Statistics: Total amount of garbage still in the ocean: 0.")
}
}
| 0 | Kotlin | 0 | 0 | 00f5a18e7d4c695f9d5e93451da2f864ebe77151 | 1,581 | Save-The-Saardines | MIT License |
Code/CurrencyConversionApp/app-core/ui/src/main/kotlin/com/istudio/core_ui/composables/FloatingActionButton.kt | devrath | 708,793,882 | false | {"Kotlin": 421506} | package com.istudio.core_ui.composables
import androidx.compose.foundation.background
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayCircleFilled
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.istudio.core_ui.theme.fontFamily
import com.istudio.currency_converter.R
@Composable
fun FloatingActionButton(
onAction: () -> Unit
) {
val cxt = LocalContext.current
ExtendedFloatingActionButton(
onClick = { onAction.invoke() },
icon = {
Icon(
imageVector = Icons.Filled.PlayCircleFilled,
contentDescription = cxt.getString(R.string.str_currency_calculate)
)
},
text = {
Text(
text = cxt.getString(R.string.str_currency_calculate),
fontFamily = fontFamily,
)
},
expanded = true,
containerColor = MaterialTheme.colorScheme.tertiary
)
} | 0 | Kotlin | 0 | 0 | 43e1b2d0f4b275f1aa3f74f2be536d9bc2575b3e | 1,243 | DroidCurrencyConverter | Apache License 2.0 |
app/src/main/kotlin/me/rei_m/hbfavmaterial/App.kt | rei-m | 45,727,691 | false | null | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial
import android.content.Context
import android.support.multidex.MultiDex
import android.util.Log
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.core.CrashlyticsCore
import com.google.firebase.analytics.FirebaseAnalytics
import com.squareup.leakcanary.LeakCanary
import com.twitter.sdk.android.core.*
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import dagger.android.support.DaggerApplication
import io.fabric.sdk.android.Fabric
import me.rei_m.hbfavmaterial.di.ApplicationModule
import me.rei_m.hbfavmaterial.infra.di.InfraLayerModule
import me.rei_m.hbfavmaterial.model.di.ModelModule
import me.rei_m.hbfavmaterial.presentation.activity.*
import javax.inject.Singleton
open class App : DaggerApplication() {
private lateinit var analytics: FirebaseAnalytics
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this);
}
override fun onCreate() {
super.onCreate()
// Application起動時に実行される。アプリの初期処理など
// LeakCanaryの設定
if (BuildConfig.DEBUG) {
LeakCanary.install(this)
}
// Set up Fabric
val authConfig = TwitterAuthConfig(getString(R.string.api_key_twitter_consumer_key),
getString(R.string.api_key_twitter_consumer_secret))
val config = TwitterConfig.Builder(this)
.logger(DefaultLogger(Log.DEBUG))
.twitterAuthConfig(authConfig)
.debug(true)
.build()
Twitter.initialize(config)
val crashlyticsCore = CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()
Fabric.with(this, Crashlytics.Builder().core(crashlyticsCore).build())
// Set up FireBase Analytics
analytics = FirebaseAnalytics.getInstance(this)
}
override fun applicationInjector(): AndroidInjector<App> {
return DaggerApp_Component.builder()
.applicationModule(ApplicationModule(this))
.build()
}
@Singleton
@dagger.Component(modules = arrayOf(
AndroidSupportInjectionModule::class,
ApplicationModule::class,
InfraLayerModule::class,
ModelModule::class,
BookmarkActivity.Module::class,
BookmarkedUsersActivity.Module::class,
ExplainAppActivity.Module::class,
MainActivity.Module::class,
OAuthActivity.Module::class,
OthersBookmarkActivity.Module::class,
SettingActivity.Module::class,
SplashActivity.Module::class))
internal interface Component : AndroidInjector<App>
}
| 0 | Kotlin | 7 | 21 | 79ebe1d902212c681df05182bc4e0958b5767be7 | 3,331 | HBFav_material | Apache License 2.0 |
domain/src/main/java/ng/devtamuno/bolt/domain/usecase/user/SaveUserUseCase.kt | dalafiarisamuel | 495,213,486 | false | null | package ng.devtamuno.bolt.domain.usecase.user
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.withContext
import ng.devtamuno.bolt.domain.executor.CoroutinePostDispatchers
import ng.devtamuno.bolt.domain.model.UserDomainModel
import ng.devtamuno.bolt.domain.repository.UserRepository
import javax.inject.Inject
class SaveUserUseCase @Inject constructor(
private val userRepository: UserRepository,
private val dispatchers: CoroutinePostDispatchers
) {
@ExperimentalCoroutinesApi
suspend operator fun invoke(param: Param) {
withContext(dispatchers.io) {
userRepository.saveUserCache(param.user)
}
}
data class Param(val user: UserDomainModel)
} | 0 | Kotlin | 0 | 0 | 3af3f325ba8b427cd9a0292d99f7d2dc05868c0c | 730 | bolt-clone-jetpack-compose | MIT License |
kotlin/src/test/kotlin/year2023/Day13Test.kt | adrisalas | 725,641,735 | false | {"Kotlin": 134149, "Python": 1548} | package year2023
import org.junit.jupiter.api.Assertions.assertEquals
import kotlin.test.Test
class Day13Test {
private val input = """
#.##..##.
..#.##.#.
##......#
##......#
..#.##.#.
..##..##.
#.#.##.#.
#...##..#
#....#..#
..##..###
#####.##.
#####.##.
..##..###
#....#..#
""".trimIndent()
@Test
fun part1() {
val output = Day13.part1(input)
assertEquals(405, output)
}
@Test
fun part2() {
val output = Day13.part2(input)
assertEquals(400, output)
}
} | 0 | Kotlin | 0 | 2 | e8b1731ea49355d279d6d6bdc55386786e5dc1c1 | 639 | advent-of-code | MIT License |
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/entities/requests/KickChatMember.kt | gagarski | 314,041,476 | false | null | package ski.gagar.vxutil.vertigram.entities.requests
import java.time.Instant
data class KickChatMember(
val chatId: Long,
val userId: Long,
val untilDate: Instant? = null
) : JsonTgCallable<Boolean>()
| 0 | Kotlin | 0 | 0 | 929197c18c45673baeeea8cc81dc8290afa82cb0 | 216 | vertigram | Apache License 2.0 |
nugu-agent/src/main/java/com/skt/nugu/sdk/agent/DefaultSoundAgent.kt | yooncheongrok | 310,163,864 | true | {"Kotlin": 2106267, "Java": 2807} | /**
* Copyright (c) 2020 SK Telecom Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skt.nugu.sdk.agent
import com.google.gson.JsonObject
import com.skt.nugu.sdk.agent.mediaplayer.UriSourcePlayablePlayer
import com.skt.nugu.sdk.agent.sound.BeepDirective
import com.skt.nugu.sdk.agent.sound.BeepDirectiveDelegate
import com.skt.nugu.sdk.agent.sound.SoundProvider
import com.skt.nugu.sdk.agent.util.IgnoreErrorContextRequestor
import com.skt.nugu.sdk.agent.version.Version
import com.skt.nugu.sdk.core.interfaces.common.NamespaceAndName
import com.skt.nugu.sdk.core.interfaces.context.*
import com.skt.nugu.sdk.core.interfaces.directive.BlockingPolicy
import com.skt.nugu.sdk.core.interfaces.focus.ChannelObserver
import com.skt.nugu.sdk.core.interfaces.focus.FocusManagerInterface
import com.skt.nugu.sdk.core.interfaces.focus.FocusState
import com.skt.nugu.sdk.core.interfaces.message.MessageRequest
import com.skt.nugu.sdk.core.interfaces.message.MessageSender
import com.skt.nugu.sdk.core.interfaces.message.Status
import com.skt.nugu.sdk.core.interfaces.message.request.EventMessageRequest
import com.skt.nugu.sdk.core.utils.Logger
import java.util.concurrent.Executors
class DefaultSoundAgent(
private val mediaPlayer: UriSourcePlayablePlayer,
private val messageSender: MessageSender,
private val contextManager: ContextManagerInterface,
private val soundProvider: SoundProvider,
private val focusChannelName: String,
private val focusManager: FocusManagerInterface,
private val beepDirectiveDelegate: BeepDirectiveDelegate?
) : AbstractCapabilityAgent(NAMESPACE) {
companion object {
private const val TAG = "DefaultSoundAgent"
const val NAMESPACE = "Sound"
private val VERSION = Version(1, 0)
/** directives */
private const val NAME_BEEP = "Beep"
/** events */
private const val NAME_BEEP_SUCCEEDED = "BeepSucceeded"
private const val NAME_BEEP_FAILED = "BeepFailed"
private val BEEP = NamespaceAndName(NAMESPACE, NAME_BEEP)
private const val PAYLOAD_PLAY_SERVICE_ID = "playServiceId"
private fun buildCompactContext(): JsonObject = JsonObject().apply {
addProperty("version", VERSION.toString())
}
private val COMPACT_STATE: String = buildCompactContext().toString()
}
private val contextState = object : BaseContextState {
override fun value(): String = COMPACT_STATE
}
private val executor = Executors.newSingleThreadExecutor()
init {
contextManager.setStateProvider(namespaceAndName, this)
provideState(contextManager, namespaceAndName, ContextType.FULL, 0)
provideState(contextManager, namespaceAndName, ContextType.COMPACT, 0)
}
override fun provideState(
contextSetter: ContextSetterInterface,
namespaceAndName: NamespaceAndName,
contextType: ContextType,
stateRequestToken: Int
) {
Logger.d(TAG, "[provideState] namespaceAndName: $namespaceAndName, contextType: $contextType, stateRequestToken: $stateRequestToken")
contextSetter.setState(
namespaceAndName,
contextState,
StateRefreshPolicy.NEVER,
contextType,
stateRequestToken
)
}
override fun preHandleDirective(info: DirectiveInfo) {
// no-op
}
override fun handleDirective(info: DirectiveInfo) {
when (info.directive.getName()) {
NAME_BEEP -> handleBeep(info)
else -> {
// nothing to do
Logger.d(TAG, "[handleDirective] unexpected directive: ${info.directive}")
}
}
}
private fun handleBeep(info: DirectiveInfo) {
val payload = BeepDirective.Payload.fromJson(info.directive.payload)
if (payload == null) {
Logger.d(TAG, "[handleBeep] unexpected payload: ${info.directive.payload}")
setHandlingFailed(
info,
"[handleBeep] unexpected payload: ${info.directive.payload}"
)
return
}
setHandlingCompleted(info)
executor.submit {
val playServiceId = payload.playServiceId
val referrerDialogRequestId = info.directive.header.dialogRequestId
val focusInterfaceName = "$NAMESPACE${info.directive.getMessageId()}"
focusManager.acquireChannel(focusChannelName, object: ChannelObserver {
var isHandled = false
override fun onFocusChanged(newFocus: FocusState) {
executor.submit {
Logger.d(TAG, "[onFocusChanged] focus: $newFocus, name: $focusInterfaceName")
when (newFocus) {
FocusState.FOREGROUND -> {
if(isHandled) {
return@submit
}
isHandled = true
val success = if (beepDirectiveDelegate != null) {
beepDirectiveDelegate.beep(
mediaPlayer,
soundProvider,
BeepDirective(info.directive.header, payload)
)
} else {
val sourceId =
mediaPlayer.setSource(soundProvider.getContentUri(payload.beepName))
!sourceId.isError() && mediaPlayer.play(sourceId)
}
if (success) {
sendBeepSucceededEvent(playServiceId, referrerDialogRequestId)
} else {
sendBeepFailedEvent(playServiceId, referrerDialogRequestId)
}
focusManager.releaseChannel(focusChannelName, this)
}
FocusState.NONE -> {
if (!isHandled) {
sendBeepFailedEvent(playServiceId, referrerDialogRequestId)
}
}
}
}
}
}, focusInterfaceName)
}
}
private fun setHandlingCompleted(info: DirectiveInfo) {
info.result.setCompleted()
}
private fun setHandlingFailed(info: DirectiveInfo, description: String) {
info.result.setFailed(description)
}
override fun cancelDirective(info: DirectiveInfo) {
}
override fun getConfiguration(): Map<NamespaceAndName, BlockingPolicy> {
val configuration = HashMap<NamespaceAndName, BlockingPolicy>()
configuration[BEEP] = BlockingPolicy(
BlockingPolicy.MEDIUM_AUDIO,
true
)
return configuration
}
private fun sendBeepSucceededEvent(playServiceId: String, referrerDialogRequestId: String) {
sendEvent(NAME_BEEP_SUCCEEDED, playServiceId, referrerDialogRequestId)
}
private fun sendBeepFailedEvent(playServiceId: String, referrerDialogRequestId: String) {
sendEvent(NAME_BEEP_FAILED, playServiceId, referrerDialogRequestId)
}
private fun sendEvent(name: String, playServiceId: String, referrerDialogRequestId: String) {
contextManager.getContext(object : IgnoreErrorContextRequestor() {
override fun onContext(jsonContext: String) {
val request =
EventMessageRequest.Builder(jsonContext, NAMESPACE, name, VERSION.toString())
.payload(JsonObject().apply {
addProperty(PAYLOAD_PLAY_SERVICE_ID, playServiceId)
}.toString())
.referrerDialogRequestId(referrerDialogRequestId)
.build()
messageSender.newCall(
request
).enqueue(object : MessageSender.Callback {
override fun onFailure(request: MessageRequest, status: Status) {
}
override fun onSuccess(request: MessageRequest) {
}
override fun onResponseStart(request: MessageRequest) {
}
})
}
}, namespaceAndName)
}
}
| 0 | null | 0 | 0 | 15d47b616e50fa2c93fdb04a46fa6c579e9bf3da | 9,157 | nugu-android | Apache License 2.0 |
adaptive-ui/src/commonMain/kotlin/fun/adaptive/ui/instruction/layout/AlignItems.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 2231374, "Java": 23999, "HTML": 7707, "JavaScript": 3880, "Shell": 687} | /*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package `fun`.adaptive.ui.instruction.layout
import `fun`.adaptive.adat.Adat
import `fun`.adaptive.foundation.instruction.AdaptiveInstruction
import `fun`.adaptive.ui.render.container
import `fun`.adaptive.ui.render.model.ContainerRenderData
@Adat
class AlignItems(
val vertical: Alignment?,
val horizontal: Alignment?,
) : AdaptiveInstruction {
override fun apply(subject: Any) {
container(subject) {
if (vertical != null) it.verticalAlignment = vertical
if (horizontal != null) it.horizontalAlignment = horizontal
}
}
companion object {
val center = AlignItems(vertical = Alignment.Center, horizontal = Alignment.Center)
val top = AlignItems(vertical = Alignment.Start, horizontal = null)
val topStart = AlignItems(vertical = Alignment.Start, horizontal = Alignment.Start)
val topCenter = AlignItems(vertical = Alignment.Start, horizontal = Alignment.Center)
val topEnd = AlignItems(vertical = Alignment.Start, horizontal = Alignment.End)
val start = AlignItems(vertical = null, horizontal = Alignment.Start)
val startTop = AlignItems(vertical = Alignment.Start, horizontal = Alignment.Start)
val startCenter = AlignItems(vertical = Alignment.Center, horizontal = Alignment.Start)
val startBottom = AlignItems(vertical = Alignment.End, horizontal = Alignment.Start)
val end = AlignItems(vertical = null, horizontal = Alignment.End)
val endTop = AlignItems(vertical = Alignment.Start, horizontal = Alignment.End)
val endCenter = AlignItems(vertical = Alignment.Center, horizontal = Alignment.End)
val endBottom = AlignItems(vertical = Alignment.End, horizontal = Alignment.End)
val bottom = AlignItems(vertical = Alignment.End, horizontal = null)
val bottomStart = AlignItems(vertical = Alignment.End, horizontal = Alignment.Start)
val bottomCenter = AlignItems(vertical = Alignment.End, horizontal = Alignment.Center)
val bottomEnd = AlignItems(vertical = Alignment.End, horizontal = Alignment.End)
}
} | 28 | Kotlin | 0 | 3 | c0fd95c9654bee332c20f8f9373f1dae9132cf6b | 2,251 | adaptive | Apache License 2.0 |
numerical-codec/src/main/kotlin/jp/justincase/jackson/kotlin/numerical/codec/NumericalDeserializerModifier.kt | justincase-jp | 198,945,609 | false | null | package jp.justincase.jackson.kotlin.numerical.codec
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.BeanDescription
import com.fasterxml.jackson.databind.DeserializationConfig
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier
import com.google.common.reflect.TypeToken
import jp.justincase.jackson.kotlin.internal.allNonInterfaceSuperclassesAndInterfaces
import jp.justincase.jackson.kotlin.internal.effectiveCompanion
import jp.justincase.jackson.kotlin.internal.primitive.codec.PrimitiveDeserializer
import jp.justincase.jackson.kotlin.internal.primitive.codec.PrimitiveSuperDeserializer
import jp.justincase.jackson.kotlin.internal.toTypeToken
import jp.justincase.jackson.kotlin.numerical.NumericalDecoder
import kotlin.reflect.KClass
internal
object NumericalDeserializerModifier : BeanDeserializerModifier() {
override
fun modifyDeserializer(
config: DeserializationConfig,
beanDesc: BeanDescription,
deserializer: JsonDeserializer<*>
): JsonDeserializer<*> =
modifyCovariantDeserializer(beanDesc, deserializer)
private
fun <T : Any> modifyCovariantDeserializer(
beanDesc: BeanDescription,
deserializer: JsonDeserializer<out T>
): JsonDeserializer<out T> =
(sequenceOf(beanDesc.beanClass.kotlin) + beanDesc.beanClass.kotlin.allNonInterfaceSuperclassesAndInterfaces)
.mapNotNull { it.effectiveCompanion as? NumericalDecoder<Any> }
.map {
@Suppress("UnstableApiUsage")
val typeToken = TypeToken
.of(it.javaClass)
.getSupertype(NumericalDecoder::class.java)
.resolveType(NumericalDecoder::class.java.typeParameters.first())
val baseTypeToken = beanDesc.type.toTypeToken()
when {
typeToken.isSubtypeOf(baseTypeToken) -> {
// The first parameter is a subtype of `T`
@Suppress("UNCHECKED_CAST")
it as NumericalDecoder<T>
PrimitiveDeserializer(
it::fromDecimal,
it::fromNull,
JsonParser::getDecimalValue
)
}
// We should reject unrelated types,
// but by now we will assume that only related type is used in the type parameter
// util we found a better way to confirm sub-typing
else -> {
// The requested raw type
@Suppress("UNCHECKED_CAST")
val requestedRawType = (baseTypeToken.rawType as Class<*>).kotlin as KClass<T>
PrimitiveSuperDeserializer(
requestedRawType,
it::fromDecimal,
it::fromNull,
JsonParser::getDecimalValue,
deserializer::deserialize,
deserializer::getNullValue
)
}
}
}
.firstOrNull()
.let { it ?: deserializer }
}
| 0 | Kotlin | 0 | 3 | 06942c06aaee36bbc6098794790bb8210347f8a5 | 3,100 | Jackson-Kotlin-Commons | Apache License 2.0 |
auth/requester/src/main/kotlin/com/walletconnect/requester/ui/events/RequesterEvents.kt | WalletConnect | 435,951,419 | false | null | package com.walletconnect.requester.ui.events
import com.walletconnect.auth.client.Auth
sealed class RequesterEvents {
object NoAction : RequesterEvents()
data class OnError(val code: Int, val message: String) : RequesterEvents()
data class OnAuthenticated(val cacao: Auth.Model.Cacao) : RequesterEvents()
data class ConnectionStateChange(val isAvailable: Boolean) : RequesterEvents()
} | 129 | Kotlin | 50 | 148 | a55e8516e8763b485655e091a091797f75cb461f | 404 | WalletConnectKotlinV2 | Apache License 2.0 |
src/iv_properties/n34DelegatesExamples.kt | AnkBurov | 101,580,084 | true | {"Kotlin": 73794, "Java": 4952} | package iv_properties
import util.TODO
import util.doc34
class LazyPropertyUsingDelegates(val initializer: () -> Int) {
val lazyValue: Int by lazy(initializer)
}
/*class MyDelegate(val initializer: () -> Int) {
private var value: Int? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
if (value == null) {
value = initializer.invoke()
}
return value!!
}
}*/
fun todoTask34(): Lazy<Int> = TODO(
"""
Task 34.
Read about delegated properties and make the property lazy by using delegates.
""",
documentation = doc34()
)
| 0 | Kotlin | 0 | 0 | cb8605641accfe72f873d2de83fb11d9f175da97 | 628 | kotlin-koans | MIT License |
src/main/kotlin/dev/mahabal/runetech/Gamepack.kt | runetech | 221,468,553 | false | null | package dev.mahabal.runetech
import org.jsoup.Jsoup
import org.objectweb.asm.ClassReader
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.IntInsnNode
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.BasicFileAttributeView
import java.util.*
import java.util.jar.JarFile
typealias ClassMap = HashMap<String, ClassNode>
/**
* Represents a Gamepack (a JAR file containing all of the client classes)
*/
abstract class Gamepack(private val bytes: ByteArray, private val initialClass: String = "client.class") {
// convert the gamepack ByteArray to a ClassMap
private val classMap = bytes.asClassMap()
// gets the current revision of the gamepack by analyzing the bytecode
val revision: Int by lazy {
var revision = -1
// get the initial_class of the jar (should be "client.class")
val client = classMap[initialClass.replace(".class", "")]
if (client != null) {
// in order to determine the revision of the client we are looking for an instanced method
// call similar to: method(765, 503, $revision, ...);, which means that we will look for
// two sipush instructions with the operands 765 and 503 respectively. the next IntInsnNode
// would be the revision.
for (method in client.methods.filter { mn -> mn.access.and(Opcodes.ACC_STATIC) == 0 }) {
// iterate over every instruction in the method
for (ain in method.instructions.toArray()) {
// continue if the instruction isn't
if (ain.opcode != Opcodes.SIPUSH) continue
// convert the instruction to an IntInsnNode
var sipush = ain as IntInsnNode
// continue if the operand isn't 765 or next insn isn't a SIPUSH
if (sipush.operand != 765 || sipush.next.opcode != Opcodes.SIPUSH) continue
sipush = sipush.next as IntInsnNode
// continue if the operand isn't 503 or next insn isn't a SIPUSH
if (sipush.operand != 503 || sipush.next.opcode != Opcodes.SIPUSH) continue
val rev = sipush.next as IntInsnNode
// this instruction should be the revision, so return the operand
revision = rev.operand
}
}
}
revision
}
/**
* Writes the ByteArray of the Gamepack to the provided path with the given fileName.
*
* It will also look at the creation time of the classes within the JAR and update the
* creation, modification, and access time to the time that the gamepack was compiled
* on Jagex's build server
*/
fun dump(directory: Path, fileNameFormat: String) {
val fileName = fileNameFormat.replace("\${revision}", revision.toString())
if (!Files.exists(directory))
Files.createDirectories(directory)
val outputPath = directory.resolve(fileName)
Files.write(outputPath, bytes, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
val jar = JarFile(outputPath.toFile())
val time = jar.getJarEntry(initialClass).lastModifiedTime
val attributes = Files.getFileAttributeView(outputPath, BasicFileAttributeView::class.java)
attributes.setTimes(time, time, time)
jar.close()
}
fun getClassMap(): ClassMap = classMap
}
/** Downloads and loads a gamepack using the [JavConfig] provided. */
class RemoteGamepack(javConfig: Properties) : Gamepack(
Jsoup.connect(javConfig.getProperty("codebase") + javConfig.getProperty("initial_jar"))
.maxBodySize(0)
.ignoreContentType(true)
.execute()
.bodyAsBytes(),
javConfig.getProperty("initial_class")
)
/** Loads a gamepack from the specified [Path]. */
class LocalGamepack(path: Path) : Gamepack(Files.readAllBytes(path))
/**
* Adds an extension to convert a byte array of a gamepack to a ClassMap
*/
private fun ByteArray.asClassMap(): ClassMap {
val temp = Paths.get("gamepack.jar")
val jar = JarFile(Files.write(temp, this, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING).toFile())
val map = ClassMap()
jar.stream()
.filter { entry -> entry.name.endsWith(".class") }
.map { entry -> jar.getInputStream(entry).asClassNode() }
.forEach { node -> map[node.name] = node }
jar.close()
Files.deleteIfExists(temp)
return map
}
/**
* Adds an extension to convert an InputStream to an ASM class node
*/
private fun InputStream.asClassNode(): ClassNode {
val clazz = ClassReader(this.readBytes())
val node = ClassNode()
clazz.accept(node, ClassReader.EXPAND_FRAMES)
return node
} | 0 | Kotlin | 6 | 7 | 9d2f9e4e6424889ce47683aef76378546d4240cd | 4,987 | osrs-gamepack-downloader | Do What The F*ck You Want To Public License |
vire-api/src/main/kotlin/net/voxelpi/vire/api/circuit/event/network/NetworkCreateEvent.kt | VoxelPi | 700,036,011 | false | {"Kotlin": 229548} | package net.voxelpi.vire.api.circuit.event.network
import net.voxelpi.vire.api.circuit.network.Network
/**
* An event that is called when a network is created.
*/
data class NetworkCreateEvent(
override val network: Network,
) : NetworkEvent
| 0 | Kotlin | 0 | 0 | 65c2a6b0d2df9a32f84b614bf0eb1b4ca742c24f | 250 | Vire | MIT License |
common/src/main/kotlin/com/vnapnic/common/service/RedisService.kt | alphaNumericEntity | 763,513,563 | false | {"Kotlin": 397164, "Java": 8775, "HTML": 6673, "Dockerfile": 224} | package com.vnapnic.common.service
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
/**
* redis operation Service
* Created by nankai on 2020/3/3.
*/
interface RedisService {
/**
* Save properties
*/
operator fun set(key: String, value: Any, time: Long)
/**
*
* Save properties
*/
operator fun set(key: String, value: Any)
/**
* Get attributes
*/
fun gets(key: String): Set<Any>?
/**
* Get attributes
*/
operator fun get(key: String): Any?
/**
* Delete attribute
*/
fun del(key: String): Boolean?
/**
* Delete attributes in bulk
*/
fun del(keys: List<String>): Long?
/**
* Set expiration time
*/
fun expire(key: String, time: Long): Boolean?
/**
* Get expiration time
*/
fun getExpire(key: String): Long?
/**
* Determine whether there is this attribute
*/
fun hasKey(key: String): Boolean?
/**
* Increment by delta
*/
fun incr(key: String, delta: Long): Long?
/**
* Decrease by delta
*/
fun decr(key: String, delta: Long): Long?
/**
* Get the attributes in the Hash structure
*/
fun hGet(key: String, hashKey: String): Any?
/**
* Put an attribute into the Hash structure
*/
fun hSet(key: String, hashKey: String, value: Any, time: Long): Boolean?
/**
* Put an attribute into the Hash structure
*/
fun hSet(key: String, hashKey: String, value: Any)
/**
* Get the entire Hash structure directly
*/
fun hGetAll(key: String): Map<Any, Any?>?
/**
* Set the entire Hash structure directly
*/
fun hSetAll(key: String, map: Map<String, Any>, time: Long): Boolean?
/**
* Set the entire Hash structure directly
*/
fun hSetAll(key: String, map: Map<String, *>)
/**
* Delete the attributes in the Hash structure
*/
fun hDel(key: String, vararg hashKey: Any)
/**
* Determine whether there is this attribute in the Hash structure
*/
fun hHasKey(key: String, hashKey: String): Boolean?
/**
* Incremental attributes in the Hash structure
*/
fun hIncr(key: String, hashKey: String, delta: Long): Long?
/**
* Hash结构中属性递减
*/
fun hDecr(key: String, hashKey: String, delta: Long): Long?
/**
* Get the Set structure
*/
fun sMembers(key: String): Set<Any?>?
/**
* Add attributes to the Set structure
*/
fun sAdd(key: String, vararg values: Any): Long?
/**
* Add attributes to the Set structure结构中添加属性
*/
fun sAdd(key: String, time: Long, vararg values: Any): Long?
/**
* Is it an attribute in Set
*/
fun sIsMember(key: String, value: Any): Boolean?
/**
* Get the length of the Set structure
*/
fun sSize(key: String): Long?
/**
* Delete the attributes in the Set structure
*/
fun sRemove(key: String, vararg values: Any): Long?
/**
* Get the attributes in the List structure
*/
fun lRange(key: String, start: Long, end: Long): List<Any?>?
/**
* Get the length of the List structure
*/
fun lSize(key: String): Long?
/**
* Get the attributes in the List according to the index
*/
fun lIndex(key: String, index: Long): Any?
/**
* Add attributes to the List structure
*/
fun lPush(key: String, value: Any): Long?
/**
* Add attributes to the List structure
*/
fun lPush(key: String, value: Any, time: Long): Long?
/**
* Add attributes to the List structure in bulk
*/
fun lPushAll(key: String, vararg values: Any): Long?
/**
* Add attributes to the List structure in bulk
*/
fun lPushAll(key: String, time: Long, vararg values: Any): Long?
/**
* Remove attributes from the List structure
*/
fun lRemove(key: String, count: Long, value: Any): Long?
}
@Service
open class RedisServiceImpl(private val redisTemplate: RedisTemplate<String, Any>) : RedisService {
override fun set(key: String, value: Any, time: Long) {
redisTemplate.opsForValue()[key, value, time] = TimeUnit.SECONDS
}
override fun set(key: String, value: Any) {
redisTemplate.opsForValue()[key] = value
}
override fun gets(key: String): Set<Any>? {
return redisTemplate.keys(key)
}
override fun get(key: String): Any? {
return redisTemplate.opsForValue()[key]
}
override fun del(key: String): Boolean? {
return redisTemplate.delete(key)
}
override fun del(keys: List<String>): Long? {
return redisTemplate.delete(keys)
}
override fun expire(key: String, time: Long): Boolean? {
return redisTemplate.expire(key, time, TimeUnit.SECONDS)
}
override fun getExpire(key: String): Long? {
return redisTemplate.getExpire(key, TimeUnit.SECONDS)
}
override fun hasKey(key: String): Boolean? {
return redisTemplate.hasKey(key)
}
override fun incr(key: String, delta: Long): Long? {
return redisTemplate.opsForValue().increment(key, delta)
}
override fun decr(key: String, delta: Long): Long? {
return redisTemplate.opsForValue().increment(key, -delta)
}
override fun hGet(key: String, hashKey: String): Any? {
return redisTemplate.opsForHash<Any, Any>()[key, hashKey]
}
override fun hSet(key: String, hashKey: String, value: Any, time: Long): Boolean? {
redisTemplate.opsForHash<Any, Any>().put(key, hashKey, value)
return expire(key, time)
}
override fun hSet(key: String, hashKey: String, value: Any) {
redisTemplate.opsForHash<Any, Any>().put(key, hashKey, value)
}
override fun hGetAll(key: String): Map<Any, Any> {
return redisTemplate.opsForHash<Any, Any>().entries(key)
}
override fun hSetAll(key: String, map: Map<String, Any>, time: Long): Boolean? {
redisTemplate.opsForHash<Any, Any>().putAll(key, map)
return expire(key, time)
}
override fun hSetAll(key: String, map: Map<String, *>) {
redisTemplate.opsForHash<Any, Any>().putAll(key, map)
}
override fun hDel(key: String, vararg hashKey: Any) {
redisTemplate.opsForHash<Any, Any>().delete(key, *hashKey)
}
override fun hHasKey(key: String, hashKey: String): Boolean? {
return redisTemplate.opsForHash<Any, Any>().hasKey(key, hashKey)
}
override fun hIncr(key: String, hashKey: String, delta: Long): Long? {
return redisTemplate.opsForHash<Any, Any>().increment(key, hashKey, delta)
}
override fun hDecr(key: String, hashKey: String, delta: Long): Long? {
return redisTemplate.opsForHash<Any, Any>().increment(key, hashKey, -delta)
}
override fun sMembers(key: String): Set<Any>? {
return redisTemplate.opsForSet().members(key)
}
override fun sAdd(key: String, vararg values: Any): Long? {
return redisTemplate.opsForSet().add(key, *values)
}
override fun sAdd(key: String, time: Long, vararg values: Any): Long? {
val count = redisTemplate.opsForSet().add(key, *values)
expire(key, time)
return count
}
override fun sIsMember(key: String, value: Any): Boolean? {
return redisTemplate.opsForSet().isMember(key, value)
}
override fun sSize(key: String): Long? {
return redisTemplate.opsForSet().size(key)
}
override fun sRemove(key: String, vararg values: Any): Long? {
return redisTemplate.opsForSet().remove(key, *values)
}
override fun lRange(key: String, start: Long, end: Long): List<Any>? {
return redisTemplate.opsForList().range(key, start, end)
}
override fun lSize(key: String): Long? {
return redisTemplate.opsForList().size(key)
}
override fun lIndex(key: String, index: Long): Any? {
return redisTemplate.opsForList().index(key, index)
}
override fun lPush(key: String, value: Any): Long? {
return redisTemplate.opsForList().rightPush(key, value)
}
override fun lPush(key: String, value: Any, time: Long): Long? {
val index = redisTemplate.opsForList().rightPush(key, value)
expire(key, time)
return index
}
override fun lPushAll(key: String, vararg values: Any): Long? {
return redisTemplate.opsForList().rightPushAll(key, *values)
}
override fun lPushAll(key: String, time: Long, vararg values: Any): Long? {
val count = redisTemplate.opsForList().rightPushAll(key, *values)
expire(key, time)
return count
}
override fun lRemove(key: String, count: Long, value: Any): Long? {
return redisTemplate.opsForList().remove(key, count, value)
}
} | 0 | Kotlin | 0 | 0 | 495581ca09d1c4a03e2643ce8601886009b39665 | 8,965 | kotlin-spring-boot-microservices | Apache License 2.0 |
lib/line/src/main/java/de/luckyworks/compose/charts/line/renderer/point/FilledCircularPointDrawer.kt | lacky1991 | 462,792,840 | false | null | package de.luckyworks.compose.charts.line.renderer.point
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.PaintingStyle
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
class FilledCircularPointDrawer(
private val diameter: Dp = 8.dp,
private val color: Color = Color.Blue
) : PointDrawer {
private val paint = Paint().apply {
color = [email protected]
style = PaintingStyle.Fill
isAntiAlias = true
}
override fun drawPoint(
drawScope: DrawScope,
center: Offset,
isDragging: Boolean,
isSelected: Boolean
) {
with(drawScope as Density) {
drawScope.drawContext.canvas.drawCircle(center, diameter.toPx() / 2f, paint)
}
}
}
| 6 | Kotlin | 0 | 1 | ce0e120896e97c20dfef542165940f63537ea44e | 986 | compose-charts | Apache License 2.0 |
app/src/main/java/com/example/ascol_admin/data/pdfrepository/PdfRepositoryImpl.kt | ishhhizzbeast | 829,026,595 | false | {"Kotlin": 119829} | package com.example.ascol_admin.data.pdfrepository
import android.net.Uri
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import kotlinx.coroutines.tasks.await
import java.util.UUID
import javax.inject.Inject
class PdfRepositoryImpl @Inject constructor(
private val firebaseDatabase: FirebaseDatabase,
private val firebaseStorage: FirebaseStorage
) :PdfRepository{
override suspend fun uploadPdf(pdftitle: String, pdfurl: Uri):String {
//generate filename by random key generator
val filename = "${UUID.randomUUID()}.pdf"
// Upload the PDF to Firebase Storage
val storageref = firebaseStorage.reference.child("pdfs/$filename")
val uploadTask = storageref.putFile(pdfurl).await()
val downloadUrl = uploadTask.storage.downloadUrl.await().toString()
// Create a unique key for the PDF entry in the database
val pdfRef = firebaseDatabase.getReference("pdfs").push()
val key = pdfRef.key
val pdfData = mapOf(
"pdftitle" to pdftitle,
"pdfurl" to downloadUrl
)
pdfRef.setValue(pdfData).await()
return key ?: throw Exception("Failed to get database key")
}
} | 0 | Kotlin | 0 | 0 | e0cafab40a99fd0d1646fc326b1407a85e8d738b | 1,258 | CodeAlpha_Ascol_Admin | MIT License |
app/src/main/java/com/example/ascol_admin/data/pdfrepository/PdfRepositoryImpl.kt | ishhhizzbeast | 829,026,595 | false | {"Kotlin": 119829} | package com.example.ascol_admin.data.pdfrepository
import android.net.Uri
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import kotlinx.coroutines.tasks.await
import java.util.UUID
import javax.inject.Inject
class PdfRepositoryImpl @Inject constructor(
private val firebaseDatabase: FirebaseDatabase,
private val firebaseStorage: FirebaseStorage
) :PdfRepository{
override suspend fun uploadPdf(pdftitle: String, pdfurl: Uri):String {
//generate filename by random key generator
val filename = "${UUID.randomUUID()}.pdf"
// Upload the PDF to Firebase Storage
val storageref = firebaseStorage.reference.child("pdfs/$filename")
val uploadTask = storageref.putFile(pdfurl).await()
val downloadUrl = uploadTask.storage.downloadUrl.await().toString()
// Create a unique key for the PDF entry in the database
val pdfRef = firebaseDatabase.getReference("pdfs").push()
val key = pdfRef.key
val pdfData = mapOf(
"pdftitle" to pdftitle,
"pdfurl" to downloadUrl
)
pdfRef.setValue(pdfData).await()
return key ?: throw Exception("Failed to get database key")
}
} | 0 | Kotlin | 0 | 0 | e0cafab40a99fd0d1646fc326b1407a85e8d738b | 1,258 | CodeAlpha_Ascol_Admin | MIT License |
ui-lib/src/main/java/co/electriccoin/zcash/ui/preference/StandardPreferenceKeys.kt | Electric-Coin-Company | 390,808,594 | false | {"Kotlin": 1834553} | package co.electriccoin.zcash.ui.preference
import co.electriccoin.zcash.preference.model.entry.BooleanPreferenceDefault
import co.electriccoin.zcash.preference.model.entry.IntegerPreferenceDefault
import co.electriccoin.zcash.preference.model.entry.LongPreferenceDefault
import co.electriccoin.zcash.preference.model.entry.NullableBooleanPreferenceDefault
import co.electriccoin.zcash.preference.model.entry.PreferenceKey
import co.electriccoin.zcash.ui.common.model.OnboardingState
import co.electriccoin.zcash.ui.common.model.WalletRestoringState
object StandardPreferenceKeys {
/**
* State defining whether the user has completed any of the onboarding wallet states.
*/
val ONBOARDING_STATE =
IntegerPreferenceDefault(
PreferenceKey("onboarding_state"),
OnboardingState.NONE.toNumber()
)
/**
* State defining whether the current block synchronization run is in the restoring state or a subsequent
* synchronization state.
*/
val WALLET_RESTORING_STATE =
IntegerPreferenceDefault(
PreferenceKey("wallet_restoring_state"),
WalletRestoringState.RESTORING.toNumber()
)
val IS_ANALYTICS_ENABLED = BooleanPreferenceDefault(PreferenceKey("is_analytics_enabled"), true)
val IS_BACKGROUND_SYNC_ENABLED = BooleanPreferenceDefault(PreferenceKey("is_background_sync_enabled"), true)
val IS_KEEP_SCREEN_ON_DURING_SYNC = BooleanPreferenceDefault(PreferenceKey("is_keep_screen_on_during_sync"), true)
val IS_RESTORING_INITIAL_WARNING_SEEN =
BooleanPreferenceDefault(PreferenceKey("IS_RESTORING_INITIAL_WARNING_SEEN"), false)
/**
* Screens or flows protected by required authentication
*/
val IS_APP_ACCESS_AUTHENTICATION =
BooleanPreferenceDefault(
PreferenceKey("IS_APP_ACCESS_AUTHENTICATION"),
true
)
val IS_DELETE_WALLET_AUTHENTICATION =
BooleanPreferenceDefault(
PreferenceKey("IS_DELETE_WALLET_AUTHENTICATION"),
true
)
val IS_EXPORT_PRIVATE_DATA_AUTHENTICATION =
BooleanPreferenceDefault(
PreferenceKey("IS_EXPORT_PRIVATE_DATA_AUTHENTICATION"),
true
)
val IS_SEED_AUTHENTICATION =
BooleanPreferenceDefault(
PreferenceKey("IS_SEED_AUTHENTICATION"),
true
)
val IS_SEND_FUNDS_AUTHENTICATION =
BooleanPreferenceDefault(
PreferenceKey("IS_SEND_FUNDS_AUTHENTICATION"),
true
)
val IS_HIDE_BALANCES =
BooleanPreferenceDefault(
PreferenceKey("IS_HIDE_BALANCES"),
false
)
val EXCHANGE_RATE_OPTED_IN =
NullableBooleanPreferenceDefault(
PreferenceKey("EXCHANGE_RATE_OPTED_IN"),
null
)
val LATEST_APP_BACKGROUND_TIME_MILLIS =
LongPreferenceDefault(PreferenceKey("LATEST_APP_BACKGROUND_TIME_MILLIS"), 0)
}
| 172 | Kotlin | 15 | 25 | 359d4a5eea03dfb3c1ffbc5df1baca1c6f7917a7 | 2,973 | zashi-android | MIT License |
libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/java/helpers/TypeRef.kt | apollographql | 69,469,299 | false | {"Kotlin": 3463807, "Java": 198208, "CSS": 34435, "HTML": 5844, "JavaScript": 1191} | package com.apollographql.apollo.compiler.codegen.java.helpers
import com.apollographql.apollo.compiler.codegen.java.JavaClassNames
import com.apollographql.apollo.compiler.codegen.java.JavaContext
import com.apollographql.apollo.compiler.codegen.java.L
import com.apollographql.apollo.compiler.codegen.java.T
import com.apollographql.apollo.compiler.ir.IrListTypeRef
import com.apollographql.apollo.compiler.ir.IrNamedTypeRef
import com.apollographql.apollo.compiler.ir.IrNonNullTypeRef
import com.apollographql.apollo.compiler.ir.IrTypeRef
import com.squareup.javapoet.CodeBlock
internal fun IrTypeRef.codeBlock(context: JavaContext): CodeBlock {
return when (this) {
is IrNonNullTypeRef -> {
CodeBlock.of("new $T($L)", JavaClassNames.CompiledNotNullType, ofType.codeBlock(context))
}
is IrListTypeRef -> {
CodeBlock.of("new $T($L)", JavaClassNames.CompiledListType, ofType.codeBlock(context))
}
is IrNamedTypeRef -> {
context.resolver.resolveCompiledType(name)
}
}
} | 135 | Kotlin | 651 | 3,750 | 174cb227efe76672cf2beac1affc7054f6bb2892 | 1,017 | apollo-kotlin | MIT License |
src/main/kotlin/model/graph/DirectedGraph.kt | spbu-coding-2023 | 791,480,179 | false | {"Kotlin": 102030} | package model.graph
class DirectedGraph<V> : Graph<V>() {
override fun addEdge(from: V, to: V, weight: Int) {
if (weight != 1) isWeighted = true
if (weight < 0) negativeWeights = true
val edge = Edge(from, to, weight)
graph[from]?.add(edge) ?: { graph[from] = mutableListOf(edge) }
}
}
| 2 | Kotlin | 0 | 4 | af2956ded1ed04428c4f299e121df746c7319f9d | 327 | graphs-graphs-8 | The Unlicense |
app/src/main/java/dev/shorthouse/coinwatch/navigation/Screen.kt | shorthouse | 655,260,745 | false | {"Kotlin": 359954} | package dev.shorthouse.coinwatch.navigation
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.BarChart
import androidx.compose.material.icons.rounded.Favorite
import androidx.compose.material.icons.rounded.Search
import androidx.compose.ui.graphics.vector.ImageVector
import dev.shorthouse.coinwatch.R
sealed class NavigationBarScreen(
val route: String,
@StringRes val nameResourceId: Int,
val icon: ImageVector
) {
object Market : NavigationBarScreen(
route = "market_screen",
nameResourceId = R.string.market_screen,
icon = Icons.Rounded.BarChart
)
object Favourites : NavigationBarScreen(
route = "favourites_screen",
nameResourceId = R.string.favourites_screen,
icon = Icons.Rounded.Favorite
)
object Search : NavigationBarScreen(
route = "search_screen",
nameResourceId = R.string.search_screen,
icon = Icons.Rounded.Search
)
}
sealed class Screen(val route: String) {
object Details : Screen("details_screen")
object NavigationBar : Screen("navigation_bar_screen")
}
| 0 | Kotlin | 0 | 9 | ec946062b37a8c675798db0af440394a3c253d1d | 1,174 | CoinWatch | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.