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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/martinchamarro/filmgoer/data/entity/RatingEntity.kt
|
xaman
| 185,247,465
| false
| null |
package com.martinchamarro.filmgoer.data.entity
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
@Keep
data class RatingEntity(
@SerializedName("Source") val source: String?,
@SerializedName("Value") val value: String?)
| 0
|
Kotlin
|
0
| 0
|
1c4e69faa06d8dc2f46d5759df94996b5c506b56
| 270
|
Filmgoer
|
Apache License 2.0
|
access-checkout/src/test/java/com/worldpay/access/checkout/validation/listeners/focus/PanFocusChangeListenerTest.kt
|
Worldpay
| 186,591,910
| false
| null |
package com.worldpay.access.checkout.validation.listeners.focus
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import com.worldpay.access.checkout.validation.result.handler.PanValidationResultHandler
import org.junit.Before
import org.junit.Test
class PanFocusChangeListenerTest {
private val panValidationResultHandler = mock<PanValidationResultHandler>()
private lateinit var panFocusChangeListener: PanFocusChangeListener
@Before
fun setup() {
panFocusChangeListener = PanFocusChangeListener(panValidationResultHandler)
}
@Test
fun `should handle result when focus is lost`() {
panFocusChangeListener.onFocusChange(null, false)
verify(panValidationResultHandler).handleFocusChange()
}
@Test
fun `should do nothing when focus is gained`() {
panFocusChangeListener.onFocusChange(null, true)
verifyZeroInteractions(panValidationResultHandler)
}
}
| 0
|
Kotlin
|
0
| 8
|
5d465cdc1803be9cc08e7fad3d55c6c9d95b920f
| 1,033
|
access-checkout-android
|
MIT License
|
app/src/main/java/de/schwerin/stoppCoronaDE/screens/questionnaire/epoxy/QuestionnaireAnswerModel.kt
|
Mandarin-Medien
| 269,321,452
| false
| null |
package de.schwerin.stoppCoronaDE.screens.questionnaire.epoxy
import android.widget.RadioButton
import de.schwerin.stoppCoronaDE.R
import de.schwerin.stoppCoronaDE.model.entities.configuration.Decision
import de.schwerin.stoppCoronaDE.skeleton.core.screens.base.view.BaseEpoxyHolder
import de.schwerin.stoppCoronaDE.skeleton.core.screens.base.view.BaseEpoxyModel
import de.schwerin.stoppCoronaDE.utils.view.safeMap
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
/**
* Model for a single answer in the questionnaire flow
* Has to be placed inside of [QuestionnaireRadioGroupModel]
*/
@EpoxyModelClass(layout = R.layout.questionnaire_answer_epoxy_model)
abstract class QuestionnaireAnswerModel(
private val onAnswerSelected: (decision: Decision) -> Unit
) : BaseEpoxyModel<QuestionnaireAnswerModel.Holder>() {
/**
* Since [radioAnswer]-RadioButton in the layout has a fixed id, we need to set a unique id
* so that the behaviour of the parent RadioGroup is working properly
*/
@EpoxyAttribute
var hash: Int = 0
@EpoxyAttribute
var answer: String? = null
@EpoxyAttribute
var decision: Decision? = null
@EpoxyAttribute
var textSize: Float = 20f // in sp
override fun Holder.onBind() {
radioAnswer.id = hash
radioAnswer.text = answer
radioAnswer.textSize = textSize
radioAnswer.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
onAnswerSelected(decision.safeMap("No decision available!", Decision.NEXT))
}
}
}
class Holder : BaseEpoxyHolder() {
val radioAnswer by bind<RadioButton>(R.id.radioAnswer)
}
}
| 0
|
Kotlin
|
0
| 1
|
a8a489c25b55cce8b14d60b9afa3fb44cfecab43
| 1,714
|
stopp-corona-de-android
|
Apache License 2.0
|
app/src/main/java/com/example/matchmentor/repository/MentorProfileService.kt
|
RodrigoJrDev
| 795,927,508
| false
|
{"Kotlin": 44434}
|
package com.example.matchmentor.repository
import com.example.matchmentor.model.MentorProfile
import retrofit2.Call
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Multipart
import retrofit2.http.DELETE
import retrofit2.http.Part
import com.example.matchmentor.model.UserProfile
import okhttp3.ResponseBody
interface MentorProfileService {
@POST("mentores.php")
fun createMentor(@Body mentorProfile: MentorProfile): Call<ResponseBody>
@GET("mentores.php")
fun getMentores(): Call<List<MentorProfile>>
@PUT("mentores.php")
fun updateMentor(@Body profile: MentorProfile): Call<Void>
@DELETE("mentores.php")
fun deleteMentor(@Body profile: MentorProfile): Call<Void>
@Multipart
@POST("upload_image.php")
fun uploadImage(@Part file: MultipartBody.Part): Call<ResponseBody>
}
| 0
|
Kotlin
|
0
| 0
|
0e59a878805c88e9ea1c22846e4775c2f7a8cac7
| 958
|
MatchMentor
|
MIT License
|
io/retrofit2/src/test/kotlin/io/bluetape4k/retrofit2/client/vertx/VertxHttpClientTest.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.retrofit2.client.vertx
import io.bluetape4k.logging.KLogging
import io.bluetape4k.retrofit2.client.AbstractClientTest
import io.bluetape4k.retrofit2.clients.vertx.vertxCallFactoryOf
import okhttp3.Call
class VertxHttpClientTest: AbstractClientTest() {
companion object: KLogging()
override val callFactory: Call.Factory = vertxCallFactoryOf()
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 380
|
bluetape4k
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsbookavideolinkapi/service/BookingFacadeTest.kt
|
ministryofjustice
| 789,053,149
| false
|
{"Kotlin": 224702, "Dockerfile": 1486, "Shell": 1007}
|
package uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service
import org.junit.jupiter.api.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.config.EmailService
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.BIRMINGHAM
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.MOORLAND
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.courtBooking
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.courtBookingRequest
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.prisoner
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.probationBooking
import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.helper.probationBookingRequest
class BookingFacadeTest {
private val bookingService: CreateVideoBookingService = mock()
private val emailService: EmailService = mock()
private val facade = BookingFacade(bookingService, emailService)
@Test
fun `should delegate court booking creation to booking creation service`() {
val booking = courtBookingRequest(prisonCode = MOORLAND, prisonerNumber = "123456")
whenever(bookingService.create(booking, "facade court user")) doReturn Pair(courtBooking(), prisoner("123456", MOORLAND))
facade.create(booking, "facade court user")
verify(bookingService).create(booking, "facade court user")
}
@Test
fun `should delegate probation team booking creation to booking creation service`() {
val booking = probationBookingRequest(prisonCode = BIRMINGHAM, prisonerNumber = "123456")
whenever(bookingService.create(booking, "facade probation team user")) doReturn Pair(probationBooking(), prisoner("123456", BIRMINGHAM))
facade.create(booking, "facade probation team user")
verify(bookingService).create(booking, "facade probation team user")
}
}
| 2
|
Kotlin
|
0
| 0
|
23225353e4706ceb3366109227a872db718996c4
| 1,983
|
hmpps-book-a-video-link-api
|
MIT License
|
talos/android/src/main/kotlin/network/chainmetric/talos/controllers/EventSocket.kt
|
nulltea
| 332,248,270
| false
|
{"Dart": 335017, "Go": 10588, "Kotlin": 10305, "Makefile": 2718, "Ruby": 990, "Swift": 904, "Objective-C": 650}
|
package network.chainmetric.talos.controllers
import io.flutter.plugin.common.EventChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import plugins.Plugins
class EventSocketHandler(private val sdk: fabric.SDK) : EventChannel.StreamHandler {
private val channels = mutableMapOf<Int, events.EventChannel>()
override fun onListen(event: Any?, events: EventChannel.EventSink?) {
CoroutineScope(Dispatchers.IO).launch {
val args = (event as List<*>)
when (val method = args[0]) {
"bind" -> try {
val chaincode = args[1] as String
val argsJson = args[2] as String
val channel = Plugins.newEventSocket(sdk, chaincode).bind(argsJson)
channels[event.hashCode()] = channel
channel.setHandler {
artifact -> CoroutineScope(Dispatchers.Main).launch {
events?.success(artifact)
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
events?.error("EventSocket::bind", e.message, null)
}
}
"subscribe" -> try {
val chaincode = args[1] as String
val eventName = args[1] as String
val channel = Plugins.newEventSocket(sdk, chaincode).subscribe(eventName)
channels[event.hashCode()] = channel
channel.setHandler {
artifact -> CoroutineScope(Dispatchers.Main).launch {
events?.success(artifact)
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
events?.error("EventSocket::subscribe", e.message, null)
}
}
else -> throw IllegalStateException("Event '$method' unsupported")
}
}
}
override fun onCancel(event: Any?) {
CoroutineScope(Dispatchers.IO).launch {
channels[event.hashCode()]?.cancel()
}
}
}
| 0
|
Dart
|
4
| 11
|
8fcaae5030219b920d6578f9fd1703c05c52f63b
| 2,340
|
chainmetric-app
|
Apache License 2.0
|
app/src/main/java/com/apps/fullandroidcourseclassd/firebasefirestoreapp/model/ProfileDetails.kt
|
madahetooo
| 559,866,425
| false
|
{"Kotlin": 78600}
|
package com.apps.fullandroidcourseclassd.firebasefirestoreapp.model
data class ProfileDetails(
var firstName: String = "",
var lastName: String = "",
var age: Int = 0,
) {
}
| 0
|
Kotlin
|
0
| 1
|
effdf4a3df84c0db50f4a844a3f7c84fab0f5e6d
| 185
|
AndroidClassD
|
Apache License 2.0
|
backend/common-web/src/main/kotlin/io/featurehub/health/MetricsHealthRegistration.kt
|
nashjain
| 427,612,281
| true
|
{"Dart": 807678, "Java": 590572, "TypeScript": 405372, "Groovy": 245705, "Kotlin": 134946, "Gherkin": 76789, "Shell": 10214, "JavaScript": 4738, "TSQL": 4373, "Dockerfile": 3036, "C#": 1519, "HTML": 616}
|
package io.featurehub.health
import cd.connect.jersey.common.JerseyPrometheusResource
import io.featurehub.jersey.FeatureHubJerseyHost
import io.featurehub.utils.FallbackPropertyConfig
import io.prometheus.client.hotspot.DefaultExports
import org.glassfish.hk2.api.ServiceLocator
import org.glassfish.jersey.internal.inject.AbstractBinder
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.server.spi.Container
import org.glassfish.jersey.server.spi.ContainerLifecycleListener
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* This automatically detects if there is a monitor.port setting and if so, pulls the
* health and prometheus endpoint (/metrics) out of the main Jersey endpoint and waits
* until that one has fired up and then pulls out the health sources and creates a new
* resource
*/
class MetricsHealthRegistration {
companion object {
private val log: Logger = LoggerFactory.getLogger(MetricsHealthRegistration::class.java)
const val monitorPortName = "monitor.port"
fun registerMetrics(config: ResourceConfig) {
// turn on all jvm prometheus metrics
DefaultExports.initialize()
if (FallbackPropertyConfig.getConfig(monitorPortName) == null) {
config.register(JerseyPrometheusResource::class.java)
config.register(HealthFeature::class.java)
} else {
config.register(object : ContainerLifecycleListener {
override fun onStartup(container: Container) {
// access the ServiceLocator here
val injector = container.applicationHandler
.injectionManager.getInstance(ServiceLocator::class.java)
// pull all of the health sources out of the main context and replicate them
// into our health repository
val healthSources = injector.getAllServices(HealthSource::class.java);
val resourceConfig = ResourceConfig(JerseyPrometheusResource::class.java, HealthFeature::class.java)
resourceConfig.register(object: AbstractBinder() {
override fun configure() {
healthSources.forEach { hs ->
if (!(hs is ApplicationHealthSource)) {
bind(hs).to(HealthSource::class.java)
}
}
}
})
val port = FallbackPropertyConfig.getConfig(monitorPortName)!!.toInt()
FeatureHubJerseyHost(resourceConfig).start(port)
log.info("metric/health endpoint now active on port {}", port)
}
override fun onReload(container: Container) {
}
override fun onShutdown(container: Container) {/*...*/}
});
}
}
}
}
| 5
| null |
0
| 0
|
d0dd173a814bf1184a7aa671f49b669701e91314
| 2,727
|
featurehub
|
Apache License 2.0
|
tests/fixtures/kotlin_project/example.kt
|
helixbass
| 644,891,933
| false
|
{"Rust": 197298}
|
interface InterfaceB {
val barA: Int
}
| 15
|
Rust
|
0
| 1
|
851554e0c4d844d193c5099608d1d6e0258c77fe
| 43
|
tree-sitter-grep
|
The Unlicense
|
domain/src/main/java/com/semicolon/domain/usecase/friend/FetchFriendsUseCase.kt
|
shake-it-shake
| 473,043,498
| false
|
{"Kotlin": 158886}
|
package com.semicolon.domain.usecase.friend
import com.semicolon.domain.repository.FriendRepository
import javax.inject.Inject
class FetchFriendsUseCase @Inject constructor(
private val friendRepository: FriendRepository
) {
suspend fun execute() =
friendRepository.fetchFriends()
}
| 0
|
Kotlin
|
0
| 4
|
6c8c7278bc7839514f414086eef7509c4fca8b8c
| 300
|
shake-it-android
|
MIT License
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/stepfunctions/InputType.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 142794926}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.stepfunctions
public enum class InputType(
private val cdkObject: software.amazon.awscdk.services.stepfunctions.InputType,
) {
TEXT(software.amazon.awscdk.services.stepfunctions.InputType.TEXT),
OBJECT(software.amazon.awscdk.services.stepfunctions.InputType.OBJECT),
;
public companion object {
internal fun wrap(cdkObject: software.amazon.awscdk.services.stepfunctions.InputType): InputType
= when (cdkObject) {
software.amazon.awscdk.services.stepfunctions.InputType.TEXT -> InputType.TEXT
software.amazon.awscdk.services.stepfunctions.InputType.OBJECT -> InputType.OBJECT
}
internal fun unwrap(wrapped: InputType): software.amazon.awscdk.services.stepfunctions.InputType
= wrapped.cdkObject
}
}
| 0
|
Kotlin
|
0
| 4
|
03c839612cc64a7e205ffe2cf8c03927d0bafcdd
| 971
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ru/akella/cryptocoin/ktor/DogApi.kt
|
booblemax
| 626,108,800
| false
| null |
package ru.akella.cryptocoin.ktor
import ru.akella.cryptocoin.response.BreedResult
interface DogApi {
suspend fun getJsonFromApi(): BreedResult
}
| 0
|
Kotlin
|
0
| 0
|
44bbe5994c486ed7694e5879541f20dbe99109a3
| 152
|
CryptoCoin
|
Apache License 2.0
|
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/spec/interceptor/interceptors.kt
|
comahe-de
| 423,253,927
| true
|
{"Kotlin": 3297666, "CSS": 352, "Java": 145}
|
package io.kotest.engine.spec.interceptor
import io.kotest.core.spec.Spec
import io.kotest.core.spec.SpecRef
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
/**
* Interceptors that are executed before a spec is instantiated.
*/
internal interface SpecRefInterceptor {
suspend fun intercept(fn: suspend (SpecRef) -> Map<TestCase, TestResult>): suspend (SpecRef) -> Map<TestCase, TestResult>
}
/**
* Interceptors that are executed after a spec is instantiated.
*/
internal interface SpecInterceptor {
suspend fun intercept(fn: suspend (Spec) -> Map<TestCase, TestResult>): suspend (Spec) -> Map<TestCase, TestResult>
}
| 0
| null |
0
| 0
|
3a03d74521d406ff8e3ebc82285e34511812f973
| 656
|
kotest
|
Apache License 2.0
|
feature-weighbridge-create/src/test/java/android/template/feature/weighbridge/create/ui/UpdateWeighbridgeViewModelTest.kt
|
yoviekaputra
| 814,553,696
| false
|
{"Kotlin": 128604, "Shell": 3210}
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.template.feature.weighbridge.create.ui
import android.template.core.data.WeighbridgeRepository
import android.template.core.data.models.WeighbridgeData
import android.template.core.ut.UnconfinedTestRule
import androidx.lifecycle.SavedStateHandle
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.util.Calendar
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@OptIn(ExperimentalCoroutinesApi::class)
class UpdateWeighbridgeViewModelTest {
@RelaxedMockK
lateinit var weighbridgeRepository: WeighbridgeRepository
@get:Rule
val coroutineScopeRule = UnconfinedTestRule()
private lateinit var viewModel: NewWeighbridgeViewModel
private val data = WeighbridgeData(
id = 1,
datetime = Calendar.getInstance().timeInMillis,
driverName = "driverName",
licenceNumber = "licenceNumber",
inboundWeight = 100.0,
outboundWeight = 150.0
)
@Before
fun beforeTest() {
MockKAnnotations.init(this)
}
@Test
fun uiEvent_OnLoadData_Success() = runTest {
// [GIVEN]
every { weighbridgeRepository.get(id = any()) } returns flowOf(data)
val savedState = SavedStateHandle(mapOf("id" to data.id))
viewModel = NewWeighbridgeViewModel(weighbridgeRepository, savedState)
// [THEN]
val uiState = viewModel.uiState.value
assertFalse(uiState.isLoading)
assertTrue(uiState.shouldEdit)
assertEquals(data.driverName, uiState.driverName)
assertEquals(data.licenceNumber, uiState.licenceNumber)
assertEquals(data.inboundWeight.toString(), uiState.inboundWeight)
assertEquals(data.outboundWeight.toString(), uiState.outboundWeight)
assertEquals("50", uiState.netWeight)
assertTrue(uiState.errorMessage.isBlank())
verify { weighbridgeRepository.get(id = any()) }
}
@Test
fun uiEvent_OnLoadData_Error() = runTest {
// [GIVEN]
val error = "Data not found"
every { weighbridgeRepository.get(id = any()) } throws Throwable(error)
val savedState = SavedStateHandle(mapOf("id" to data.id))
viewModel = NewWeighbridgeViewModel(weighbridgeRepository, savedState)
// [THEN]
val uiState = viewModel.uiState.value
assertTrue(uiState.isLoading)
assertEquals(error, uiState.errorMessage)
verify { weighbridgeRepository.get(id = any()) }
}
@Test
fun uiEvent_OnSaveData_Success() = runTest {
// [GIVEN]
every { weighbridgeRepository.get(id = any()) } returns flowOf(data)
coEvery { weighbridgeRepository.update(any()) } returns Unit
val savedState = SavedStateHandle(mapOf("id" to data.id))
viewModel = NewWeighbridgeViewModel(weighbridgeRepository, savedState)
val uiEffects = mutableListOf<NewWeighbridgeUiEffect>()
backgroundScope.launch(UnconfinedTestDispatcher()) {
viewModel.uiEffect.toList(uiEffects)
}
// [WHEN]
viewModel.onEvent(NewWeighbridgeUiEvent.OnOutboundWeightChanged("1000"))
viewModel.onEvent(NewWeighbridgeUiEvent.OnInboundWeightChanged("100"))
viewModel.onEvent(NewWeighbridgeUiEvent.OnSaveClicked)
// [THEN]
val uiState = viewModel.uiState.value
assertTrue(uiState.shouldEdit)
assertEquals("1000", uiState.outboundWeight)
assertEquals("100", uiState.inboundWeight)
assertEquals("900", uiState.netWeight)
assertTrue(uiState.errorMessage.isBlank())
assertTrue(uiEffects.first() is NewWeighbridgeUiEffect.OnSavedSuccess)
verify { weighbridgeRepository.get(id = any()) }
coVerify { weighbridgeRepository.update(any()) }
}
@Test
fun uiEvent_OnSaveData_Failed() = runTest {
// [GIVEN]
val error = "Error occurred"
every { weighbridgeRepository.get(id = any()) } returns flowOf(data)
coEvery { weighbridgeRepository.update(any()) } throws Throwable(error)
val savedState = SavedStateHandle(mapOf("id" to data.id))
viewModel = NewWeighbridgeViewModel(weighbridgeRepository, savedState)
// [WHEN]
viewModel.onEvent(NewWeighbridgeUiEvent.OnSaveClicked)
// [THEN]
val uiState = viewModel.uiState.value
assertTrue(uiState.shouldEdit)
assertEquals(error, uiState.errorMessage)
verify { weighbridgeRepository.get(id = any()) }
coVerify { weighbridgeRepository.update(any()) }
}
}
| 0
|
Kotlin
|
0
| 0
|
32e109b73a25a7a611ed9c2fac528f8e027eeded
| 5,817
|
truck_weighbridge_app
|
Apache License 2.0
|
selectable-dynamic-table/src/main/java/dev/fazelx/selectable_dynamic_table/listeners/TableSelectStatusChangeListener.kt
|
FazelX
| 595,753,316
| false
| null |
/*
*Copyright 2023 <NAME>
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package dev.fazelx.selectable_dynamic_table.listeners
import dev.fazelx.selectable_dynamic_table.model.Cell
/**
* Created on : January 29, 2023
* Author : FazelX
* Name : Selectable dynamic table
* GitHub : https://github.com/fazelX
*/
/** Interface definition for a callback to be invoked when the table row or cell select state changes. */
interface TableSelectStatusChangeListener {
/**
* Register a callback to table rows select status changes.
*
* @param cellSelectChangeListener The callback that will run.
*/
fun setOnCellSelectChangeListener(cellSelectChangeListener: (isSelected: Boolean, cell: Cell) -> Unit)
/**
* Register a callback to table cells select status changes.
*
* @param rowSelectChangeListener The callback that will run.
*/
fun setOnRowSelectChangeListener(rowSelectChangeListener: (isSelected: Boolean, rowData: List<Cell>, pos: Int) -> Unit)
}
| 0
|
Kotlin
|
0
| 2
|
e0110447a5d36c9dfd92be0fe27996f4abfbe365
| 1,513
|
selectable-dynamic-table
|
Apache License 2.0
|
app/src/main/java/com/iammert/readablebottombar/MainActivity.kt
|
qijaz221
| 204,246,315
| true
|
{"Kotlin": 18204}
|
package com.iammert.readablebottombar
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.iammert.library.readablebottombar.BottomBarItem
import com.iammert.library.readablebottombar.ReadableBottomBar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottomBar : ReadableBottomBar = findViewById<ReadableBottomBar>(R.id.dynamic_bottom_bar)
//bottomBar.setTabItems(R.xml.tabs_disabled)
var items = ArrayList<BottomBarItem>()
items.add(BottomBarItem(0, 0, "Test", 15f,
Color.BLACK, Color.BLACK, getDrawable(R.drawable.ic_home_black_24dp),
ReadableBottomBar.ItemType.Icon))
bottomBar.setTabItems(items)
}
}
| 0
|
Kotlin
|
0
| 0
|
278083f2b4f7f43485772dde0ae38c6a73763ea5
| 892
|
ReadableBottomBar
|
Apache License 2.0
|
app/src/main/kotlin/template/core/data/repository/NbaRepository.kt
|
spekus
| 862,202,989
| false
|
{"Kotlin": 84881}
|
package template.core.data.repository
import kotlinx.coroutines.flow.Flow
import template.core.common.result.Result
import template.core.model.Game
import template.core.model.Player
import template.core.model.Team
interface NbaRepository {
fun getTeams(): Flow<Result<List<Team>>>
fun getGames(teamId: Int): Flow<Result<List<Game>>>
fun getPlayers(search: String): Flow<Result<List<Player>>>
}
| 0
|
Kotlin
|
0
| 0
|
d2fd5e83441f54192dc059215486e38372f40506
| 408
|
NBA
|
Apache License 2.0
|
src/com/ncorti/aoc2023/Day04.kt
|
cortinico
| 723,409,155
| false
|
{"Kotlin": 76642}
|
package com.ncorti.aoc2023
data class ScratchCard(val winningNumbers: List<Int>, val playerNumbers: List<Int>, var count: Int = 1) {
companion object {
fun from(input: String) = ScratchCard(
winningNumbers = input.substringAfter(":").substringBefore("|").split(" ").filter(String::isNotBlank)
.map(String::toInt),
playerNumbers = input.substringAfter("|").split(" ").filter(String::isNotBlank).map(String::toInt),
)
}
fun scoreV1(): Int {
var score = 0
playerNumbers.forEach { number ->
if (number in winningNumbers && score == 0) {
score = 1
} else if (number in winningNumbers) {
score *= 2
}
}
return score
}
fun countMatching(): Int = playerNumbers.count { it in winningNumbers }
}
fun main() {
fun part1(): Int {
return getInputAsText("04") {
split("\n").filter(String::isNotBlank).map { ScratchCard.from(it) }
}.sumOf { it.scoreV1() }
}
fun part2(): Int {
val cards = getInputAsText("04") {
split("\n").filter(String::isNotBlank).map { ScratchCard.from(it) }
}
for (i in cards.indices) {
val winnings = cards[i].countMatching()
val originalCount = cards[i].count
for (j in 1..winnings) {
cards[i + j].count += originalCount
}
}
return cards.sumOf { it.count }
}
println(part1())
println(part2())
}
| 3
|
Kotlin
|
0
| 2
|
c187eec664e0cedd66c87c9af7f8df87fe97aa74
| 1,555
|
adventofcode-2023
|
MIT License
|
src/test/kotlin/hu/advent/of/code/year2015/day6/Puzzle6ATest.kt
|
sztojkatamas
| 568,512,275
| false
|
{"Kotlin": 143687}
|
package hu.advent.of.code.year2015.day6
import hu.advent.of.code.year2015.day6.Puzzle6A
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class Puzzle6ATest {
@Test
fun `Some basic test`() {
val puzzle6A = Puzzle6A()
puzzle6A.initLamps(5, 5)
assertFalse { puzzle6A.getLamp("2-2").working }
assertFalse { puzzle6A.getLamp("3-2").working }
puzzle6A.toggleLamp("2-2")
puzzle6A.switchOnLamp("3-2")
assertTrue { puzzle6A.getLamp("2-2").working }
assertEquals(2, puzzle6A.countBrightLamps())
puzzle6A.switchOffLamp("3-2")
assertEquals(1, puzzle6A.countBrightLamps())
}
@Test
fun `Range tests`() {
val puzzle6A = Puzzle6A()
puzzle6A.initLamps(15, 15)
puzzle6A.toggleLamps("0-0", "2-2")
assertEquals(9, puzzle6A.countBrightLamps())
puzzle6A.switchOnLamps("2-2", "4-0")
assertEquals(15, puzzle6A.countBrightLamps())
puzzle6A.switchOffLamps("3-1", "1-1")
assertEquals(12, puzzle6A.countBrightLamps())
puzzle6A.toggleLamps("0-0", "4-2")
assertEquals(3, puzzle6A.countBrightLamps())
}
}
| 0
|
Kotlin
|
0
| 0
|
d9a3993378c8dcf5f5ae797fbd88fa6a5cdf4125
| 1,247
|
advent-of-code-universe
|
MIT License
|
math-helpers/src/test/kotlin/io/ducommun/collections/mathHelpers/IntMathTest.kt
|
MarkDucommun
| 96,490,546
| false
| null |
package io.ducommun.collections.mathHelpers
import org.assertj.core.api.KotlinAssertions.assertThat
import org.junit.Test
class IntMathTest {
@Test
fun `can transform numbers - byte to byte`() {
val start: Byte = 1
val end: Byte = start.asType()
assertThat(end).isEqualTo(1.toByte())
}
@Test
fun `can transform numbers - byte to short`() {
val start: Byte = 1
val end: Short = start.asType()
assertThat(end).isEqualTo(1.toShort())
}
@Test
fun `can transform numbers - byte to int`() {
val start: Byte = 1
val end: Int = start.asType()
assertThat(end).isEqualTo(1)
}
@Test
fun `can transform numbers - byte to long`() {
val start: Byte = 1
val end: Long = start.asType()
assertThat(end).isEqualTo(1.toLong())
}
@Test
fun `can transform numbers - byte to float`() {
val start: Byte = 1
val end: Float = start.asType()
assertThat(end).isEqualTo(1.toFloat())
}
@Test
fun `can transform numbers - byte to double`() {
val start: Byte = 1
val end: Double = start.asType()
assertThat(end).isEqualTo(1.toDouble())
}
// =================================================================================================================
@Test
fun `can transform numbers - short to byte`() {
val start: Short = 1
val end: Byte = start.asType()
assertThat(end).isEqualTo(1.toByte())
}
@Test
fun `can transform numbers - short to short`() {
val start: Short = 1
val end: Short = start.asType()
assertThat(end).isEqualTo(1.toShort())
}
@Test
fun `can transform numbers - short to int`() {
val start: Short = 1
val end: Int = start.asType()
assertThat(end).isEqualTo(1)
}
@Test
fun `can transform numbers - short to long`() {
val start: Short = 1
val end: Long = start.asType()
assertThat(end).isEqualTo(1.toLong())
}
@Test
fun `can transform numbers - short to float`() {
val start: Short = 1
val end: Float = start.asType()
assertThat(end).isEqualTo(1.toFloat())
}
@Test
fun `can transform numbers - short to double`() {
val start: Short = 1
val end: Double = start.asType()
assertThat(end).isEqualTo(1.toDouble())
}
// =================================================================================================================
@Test
fun `can transform numbers - int to byte`() {
val start: Int = 1
val end: Byte = start.asType()
assertThat(end).isEqualTo(1.toByte())
}
@Test
fun `can transform numbers - int to short`() {
val start: Int = 1
val end: Short = start.asType()
assertThat(end).isEqualTo(1.toShort())
}
@Test
fun `can transform numbers - int to int`() {
val start: Int = 1
val end: Int = start.asType()
assertThat(end).isEqualTo(1.toInt())
}
@Test
fun `can transform numbers - int to long`() {
val start: Int = 1
val end: Long = start.asType()
assertThat(end).isEqualTo(1.toLong())
}
@Test
fun `can transform numbers - int to float`() {
val start: Int = 1
val end: Float = start.asType()
assertThat(end).isEqualTo(1.toFloat())
}
@Test
fun `can transform numbers - int to double`() {
val start: Int = 1
val end: Double = start.asType()
assertThat(end).isEqualTo(1.toDouble())
}
// =================================================================================================================
@Test
fun `can transform numbers - long to byte`() {
val start: Long = 1
val end: Byte = start.asType()
assertThat(end).isEqualTo(1.toByte())
}
@Test
fun `can transform numbers - long to short`() {
val start: Long = 1
val end: Short = start.asType()
assertThat(end).isEqualTo(1.toShort())
}
@Test
fun `can transform numbers - long to int`() {
val start: Long = 1
val end: Int = start.asType()
assertThat(end).isEqualTo(1.toInt())
}
@Test
fun `can transform numbers - long to long`() {
val start: Long = 1
val end: Long = start.asType()
assertThat(end).isEqualTo(1.toLong())
}
@Test
fun `can transform numbers - long to float`() {
val start: Long = 1
val end: Float = start.asType()
assertThat(end).isEqualTo(1.toFloat())
}
@Test
fun `can transform numbers - long to double`() {
val start: Long = 1
val end: Double = start.asType()
assertThat(end).isEqualTo(1.toDouble())
}
// =================================================================================================================
@Test
fun `can transform numbers - float to byte`() {
val start: Float = 1.0F
val end: Byte = start.asType()
assertThat(end).isEqualTo(1.toByte())
}
@Test
fun `can transform numbers - float to short`() {
val start: Float = 1.0F
val end: Short = start.asType()
assertThat(end).isEqualTo(1.toShort())
}
@Test
fun `can transform numbers - float to int`() {
val start: Float = 1.0F
val end: Int = start.asType()
assertThat(end).isEqualTo(1.toInt())
}
@Test
fun `can transform numbers - float to long`() {
val start: Float = 1.0F
val end: Long = start.asType()
assertThat(end).isEqualTo(1.toLong())
}
@Test
fun `can transform numbers - float to float`() {
val start: Float = 1.0F
val end: Float = start.asType()
assertThat(end).isEqualTo(1.toFloat())
}
@Test
fun `can transform numbers - float to double`() {
val start: Float = 1.0F
val end: Double = start.asType()
assertThat(end).isEqualTo(1.toDouble())
}
// =================================================================================================================
@Test
fun `can transform numbers - double to byte`() {
val start: Double = 1.0
val end: Byte = start.asType()
assertThat(end).isEqualTo(1.toByte())
}
@Test
fun `can transform numbers - double to short`() {
val start: Double = 1.0
val end: Short = start.asType()
assertThat(end).isEqualTo(1.toShort())
}
@Test
fun `can transform numbers - double to int`() {
val start: Double = 1.0
val end: Int = start.asType()
assertThat(end).isEqualTo(1.toInt())
}
@Test
fun `can transform numbers - double to long`() {
val start: Double = 1.0
val end: Long = start.asType()
assertThat(end).isEqualTo(1.toLong())
}
@Test
fun `can transform numbers - double to float`() {
val start: Double = 1.0
val end: Float = start.asType()
assertThat(end).isEqualTo(1.toFloat())
}
@Test
fun `can transform numbers - double to double`() {
val start: Double = 1.0
val end: Double = start.asType()
assertThat(end).isEqualTo(1.toDouble())
}
}
| 0
|
Kotlin
|
0
| 0
|
44315c214f7301e1a3e994059d1c708eb9d829c5
| 7,377
|
collections
|
MIT License
|
commons-ktx/src/main/java/com/paulrybitskyi/commons/ktx/WindowExtensions.kt
|
mars885
| 285,931,745
| false
| null |
/*
* Copyright 2020 <NAME>, <EMAIL>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("WindowUtils")
package com.paulrybitskyi.commons.ktx
import android.view.Window
import android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND
import android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
var Window.isBackgroundDimmingEnabled: Boolean
set(value) {
if (value) {
addFlags(FLAG_DIM_BEHIND)
} else {
clearFlags(FLAG_DIM_BEHIND)
}
}
get() = ((attributes.flags and FLAG_DIM_BEHIND) == FLAG_DIM_BEHIND)
fun Window.makeScreenAlwaysAwake() {
addFlags(FLAG_KEEP_SCREEN_ON)
}
fun Window.makeScreenSleepable() {
clearFlags(FLAG_KEEP_SCREEN_ON)
}
fun Window.setScreenAlwaysAwake(isScreenAlwaysAwake: Boolean) {
if (isScreenAlwaysAwake) {
makeScreenAlwaysAwake()
} else {
makeScreenSleepable()
}
}
| 0
|
Kotlin
|
0
| 8
|
99ffc28fc0089beab09fcc7fa9a0c7dc2ec320a9
| 1,422
|
android-commons
|
Apache License 2.0
|
osiris-core/src/main/java/com/trendyol/osiris/EventBuilder.kt
|
Trendyol
| 363,866,880
| false
| null |
package com.trendyol.osiris
interface EventBuilder {
fun build(): List<Event<EventData>>
}
| 0
|
Kotlin
|
2
| 15
|
e6d0995c05a7267bbbdd5162fc7acc516efeaf39
| 97
|
Osiris
|
Apache License 2.0
|
libraries/database/src/androidTest/java/com/chesire/nekome/database/dao/SeriesDaoTests.kt
|
rmwthorne
| 330,431,997
| true
|
{"Kotlin": 497025, "Ruby": 7928, "JavaScript": 64}
|
package com.chesire.nekome.database.dao
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.chesire.nekome.core.flags.SeriesStatus
import com.chesire.nekome.core.flags.SeriesType
import com.chesire.nekome.core.flags.Subtype
import com.chesire.nekome.core.flags.UserSeriesStatus
import com.chesire.nekome.core.models.ImageModel
import com.chesire.nekome.database.RoomDB
import com.chesire.nekome.database.entity.SeriesEntity
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SeriesDaoTests {
private lateinit var db: RoomDB
private lateinit var seriesDao: SeriesDao
@Before
fun setup() {
db = Room
.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().context,
RoomDB::class.java
)
.fallbackToDestructiveMigration()
.build()
.also {
seriesDao = it.series()
}
}
@After
fun teardown() {
db.clearAllTables()
db.close()
}
@Test
fun noSeriesReturnsEmptyList() = runBlocking {
assertTrue(seriesDao.retrieve().isEmpty())
}
@Test
fun deleteWithModelRemovesFromDatabase() = runBlocking {
val model = createSeriesEntity()
seriesDao.insert(model)
assertTrue(seriesDao.retrieve().contains(model))
seriesDao.delete(model)
assertTrue(seriesDao.retrieve().isEmpty())
}
@Test
fun insertWithSingleModelReplacesMatchingItem() = runBlocking {
val model = createSeriesEntity()
seriesDao.insert(model)
assertTrue(seriesDao.retrieve().count() == 1)
seriesDao.insert(model)
assertTrue(seriesDao.retrieve().count() == 1)
}
@Test
fun insertWithListOfItemsAddsNewItems() = runBlocking {
seriesDao.insert(
listOf(
createSeriesEntity(id = 0),
createSeriesEntity(id = 1),
createSeriesEntity(id = 2)
)
)
assertTrue(seriesDao.retrieve().count() == 3)
}
@Test
fun insertWithListOfItemsReplacesMatchingItems() = runBlocking {
seriesDao.insert(
listOf(
createSeriesEntity(id = 0, userId = 0),
createSeriesEntity(id = 1),
createSeriesEntity(id = 2)
)
)
assertTrue(seriesDao.retrieve().count() == 3)
seriesDao.insert(
listOf(
createSeriesEntity(id = 0, userId = 1),
createSeriesEntity(id = 1),
createSeriesEntity(id = 2)
)
)
assertTrue(seriesDao.retrieve().count() == 3)
assertTrue(seriesDao.retrieve().first().userId == 1)
}
@Test
fun retrieveGetsAllCurrentItems() = runBlocking {
seriesDao.insert(
listOf(
createSeriesEntity(id = 0),
createSeriesEntity(id = 1),
createSeriesEntity(id = 2)
)
)
seriesDao.insert(
listOf(
createSeriesEntity(id = 3),
createSeriesEntity(id = 4),
createSeriesEntity(id = 5)
)
)
assertTrue(seriesDao.retrieve().count() == 6)
}
@Test
fun retrieveGetsAllCurrentItemsBasedOnType() = runBlocking {
seriesDao.insert(
listOf(
createSeriesEntity(id = 0, type = SeriesType.Anime),
createSeriesEntity(id = 1, type = SeriesType.Manga),
createSeriesEntity(id = 2, type = SeriesType.Anime),
createSeriesEntity(id = 3, type = SeriesType.Manga),
createSeriesEntity(id = 4, type = SeriesType.Anime),
createSeriesEntity(id = 5, type = SeriesType.Manga)
)
)
assertTrue(seriesDao.retrieve().count() == 6)
assertTrue(seriesDao.retrieve().filter { it.type == SeriesType.Anime }.count() == 3)
}
@Test
fun updateUpdatesAnyMatchingModel() = runBlocking {
seriesDao.insert(createSeriesEntity(id = 0, userId = 0))
assertTrue(seriesDao.retrieve().count() == 1)
seriesDao.update(createSeriesEntity(id = 0, userId = 1))
assertTrue(seriesDao.retrieve().first().userId == 1)
}
private fun createSeriesEntity(
id: Int = 0,
userId: Int = 0,
type: SeriesType = SeriesType.Unknown
) = SeriesEntity(
id,
userId,
type,
Subtype.Unknown,
"slug",
"title",
SeriesStatus.Unknown,
UserSeriesStatus.Unknown,
0,
0,
ImageModel.empty,
"",
""
)
}
| 0
| null |
0
| 0
|
88a808b7ad4131f298cffbd9de21e2c9aa085093
| 4,943
|
Nekome
|
Apache License 2.0
|
eip155/src/main/java/org/kethereum/eip155/EIP155.kt
|
jim-spa
| 119,239,943
| true
|
{"Kotlin": 188352}
|
package org.kethereum.eip155
import org.kethereum.model.SignatureData
/*
*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
*
*/
/**
* extracts the ChainID from SignatureData v
*
* @return ChainID or null when not EIP155 signed
*
*/
fun SignatureData.extractChainID() = if (v < 37) { // not EIP 155 signed
null
} else {
(v - 35) / 2
}
| 0
|
Kotlin
|
0
| 1
|
62c31ff39ee1211a06ab6dc17fba9974cde28797
| 366
|
kethereum
|
MIT License
|
app/src/main/java/com/renaro/iseeyou/home/HomeView.kt
|
renaro
| 110,175,345
| false
| null |
package com.renaro.iseeyou.home
import com.renaro.iseeyou.model.Reimbursement
/**
* Created by renarosantos1 on 11/11/17.
*/
interface HomeView{
fun getSelectedMonth() : String
fun getSelectedQuota() : String
fun showReimbursements(reimbursements: Array<Reimbursement>)
fun showLoading()
fun hideLoading()
fun openPdfFile(pdfUrl: String)
fun searchAgainSoon()
}
| 0
|
Kotlin
|
0
| 1
|
e6c4c0d2d8cf4a14525591e0fc416ab66331206f
| 396
|
iseeyou
|
MIT License
|
protocol/kotlin/src/solarxr_protocol/rpc/HeightRequest.kt
|
SlimeVR
| 456,320,520
| false
|
{"Rust": 790111, "Java": 650829, "TypeScript": 507384, "C++": 434772, "Kotlin": 356034, "PowerShell": 959, "Shell": 910, "Nix": 587}
|
// automatically generated by the FlatBuffers compiler, do not modify
package solarxr_protocol.rpc
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
class HeightRequest : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : HeightRequest {
__init(_i, _bb)
return this
}
companion object {
@JvmStatic
fun validateVersion() = Constants.FLATBUFFERS_22_10_26()
@JvmStatic
fun getRootAsHeightRequest(_bb: ByteBuffer): HeightRequest = getRootAsHeightRequest(_bb, HeightRequest())
@JvmStatic
fun getRootAsHeightRequest(_bb: ByteBuffer, obj: HeightRequest): HeightRequest {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
@JvmStatic
fun startHeightRequest(builder: FlatBufferBuilder) = builder.startTable(0)
@JvmStatic
fun endHeightRequest(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}
| 11
|
Rust
|
20
| 19
|
60f3146f914e2a9e35d759a8146be213e715d6d2
| 1,168
|
SolarXR-Protocol
|
Apache License 2.0
|
app/src/main/java/com/nuevo/gameness/data/model/users/ResetPasswordResponse.kt
|
arbabkh
| 873,814,880
| false
|
{"Kotlin": 538078}
|
package com.nuevo.gameness.data.model.users
import com.google.gson.annotations.SerializedName
data class ResetPasswordResponse(
@SerializedName("Data")
val data: User? = null,
@SerializedName("Success")
val success: Boolean? = null,
@SerializedName("Message")
val message: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
80d7b04385a2cd516b8157dbea19dd821c30fcc9
| 316
|
gameness-android
|
MIT License
|
src/main/kotlin/com/github/itasyurt/appsearch/client/api/impl/DefaultSuggestionsClient.kt
|
itasyurt
| 322,884,602
| false
| null |
package com.github.itasyurt.appsearch.client.api.impl
import com.fasterxml.jackson.databind.JsonNode
import com.github.itasyurt.appsearch.client.api.SuggestionsClient
import com.github.itasyurt.appsearch.client.api.util.util.json.convertToMap
import com.github.itasyurt.appsearch.client.domain.SuggestionsRequest
import com.github.itasyurt.appsearch.client.domain.SuggestionsResponse
import com.github.itasyurt.appsearch.client.domain.mapper
class DefaultSuggestionsClient(clientSettings: Map<String, Any>) : SuggestionsClient, DefaultHttpClient(clientSettings) {
override fun suggest(engineName: String, suggestionsRequest: SuggestionsRequest): SuggestionsResponse {
val requestMap = createRequestBodyMap(suggestionsRequest)
val bodyStr = mapper.writeValueAsString(requestMap)
val req = createGetRequestWithBody(PATH_FORMAT.format(engineName), bodyStr = bodyStr)
val resp = httpClient.execute(req)
return parseResponse(resp) {
val responseJson = mapper.readTree(resp.entity.content)
val meta = responseJson["meta"].convertToMap()
val suggestions = parseSuggestions(responseJson.get("results"))
SuggestionsResponse(suggestions = suggestions, meta = meta)
}
}
private fun parseSuggestions(results: JsonNode): List<String> {
return results["documents"].map {
it["suggestion"].textValue()
}
}
private fun createRequestBodyMap(suggestionsRequest: SuggestionsRequest): Map<String, Any> {
val requestMap = mutableMapOf<String, Any>()
requestMap["query"] = suggestionsRequest.query
if (suggestionsRequest.size != null) {
requestMap["size"] = suggestionsRequest.size
}
if (!suggestionsRequest.fields.isNullOrEmpty()) {
requestMap["types"] = mapOf(Pair("documents", mapOf(Pair("fields", suggestionsRequest.fields))))
}
return requestMap
}
companion object {
const val PATH_FORMAT = "engines/%s/query_suggestion"
}
}
| 0
|
Kotlin
|
1
| 3
|
8b6215f1b9333c05847a795a62a9b4e9f9e79947
| 2,069
|
app-search-kotlin
|
Apache License 2.0
|
mui-kotlin/src/jsMain/kotlin/mui/material/CircularProgress.classes.kt
|
karakum-team
| 387,062,541
| false
|
{"Kotlin": 2961484, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/material/CircularProgress")
package mui.material
import web.cssom.ClassName
external interface CircularProgressClasses {
/** Styles applied to the root element. */
var root: ClassName
/** Styles applied to the root element if `variant="determinate"`. */
var determinate: ClassName
/** Styles applied to the root element if `variant="indeterminate"`. */
var indeterminate: ClassName
/** Styles applied to the root element if `color="primary"`. */
var colorPrimary: ClassName
/** Styles applied to the root element if `color="secondary"`. */
var colorSecondary: ClassName
/** Styles applied to the svg element. */
var svg: ClassName
/** Styles applied to the `circle` svg path. */
var circle: ClassName
/** Styles applied to the `circle` svg path if `variant="determinate"`. */
var circleDeterminate: ClassName
/** Styles applied to the `circle` svg path if `variant="indeterminate"`. */
var circleIndeterminate: ClassName
/** Styles applied to the `circle` svg path if `disableShrink={true}`. */
var circleDisableShrink: ClassName
}
@JsName("default")
external val circularProgressClasses: CircularProgressClasses
| 0
|
Kotlin
|
5
| 35
|
d12f6b1ad1b215ad7d3d9f27e24d48ada9b7fe2d
| 1,272
|
mui-kotlin
|
Apache License 2.0
|
tgbotapi.api/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/api/bot/GetMyName.kt
|
InsanusMokrassar
| 163,152,024
| false
|
{"Kotlin": 2960030, "Shell": 373}
|
package dev.inmo.tgbotapi.extensions.api.bot
import dev.inmo.micro_utils.language_codes.IetfLang
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.requests.bot.GetMyName
suspend fun TelegramBot.getMyName(
languageCode: IetfLang? = null
) = execute(GetMyName(languageCode))
suspend fun TelegramBot.getMyName(
languageCode: String?
) = getMyName(languageCode ?.let(::IetfLang))
| 18
|
Kotlin
|
23
| 333
|
5cfc350c13aec77495a24e666de2ee8214d1c8f7
| 403
|
ktgbotapi
|
Apache License 2.0
|
app/src/main/java/com/zhufucdev/motion_emulator/ui/model/EmulationRef.kt
|
zhufucdev
| 550,925,935
| false
|
{"Kotlin": 227362}
|
package com.zhufucdev.motion_emulator.ui.model
import com.zhufucdev.me.stub.Data
import com.zhufucdev.me.stub.Emulation
import com.zhufucdev.motion_emulator.data.Cells
import com.zhufucdev.motion_emulator.data.Motions
import com.zhufucdev.motion_emulator.data.Traces
import com.zhufucdev.motion_emulator.extension.StoredBox
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToStream
import java.io.OutputStream
import java.text.DateFormat
@Serializable
data class EmulationRef(
override val id: String,
val name: String,
val trace: String,
val motion: String,
val cells: String,
val velocity: Double,
val repeat: Int,
val satelliteCount: Int,
) : Data {
override fun getDisplayName(format: DateFormat): String {
return name
}
@OptIn(ExperimentalSerializationApi::class)
override fun writeTo(stream: OutputStream) {
Json.encodeToStream(this, stream)
}
}
fun EmulationRef.emulation() = Emulation(
trace = StoredBox(trace, Traces),
motion = StoredBox(motion, Motions),
cells = StoredBox(cells, Cells),
repeat = repeat,
velocity = velocity,
satelliteCount = satelliteCount
)
| 16
|
Kotlin
|
15
| 225
|
5fdea55b038868a486a352525013e4ded4fb1cb8
| 1,295
|
MotionEmulator
|
Apache License 2.0
|
app/src/main/java/com/unitewikiapp/unitewiki/datas/RankRepository.kt
|
jhj0517
| 656,711,299
| false
| null |
package com.unitewikiapp.unitewiki.datas
import com.google.firebase.database.FirebaseDatabase
import com.unitewikiapp.unitewiki.di.RealTimeDataBase
import com.unitewikiapp.unitewiki.utils.Constants
import com.unitewikiapp.unitewiki.utils.LocaleStore
import com.unitewikiapp.unitewiki.utils.Response
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class RankRepository @Inject constructor(
private val rtdb:FirebaseDatabase,
private val localeStore: LocaleStore
) : RealTimeDataBase {
val locale = localeStore.findLocale()
suspend fun fetchRankingData(type:String): Response<ArrayList<PokemonRankData>> {
return try {
val ranksList = ArrayList<PokemonRankData>()
val ranks = rtdb.reference.child(Constants.POKEMON_RANKS+locale).child(type).get().await()
ranks.children.forEach { snap->
val data = snap.getValue(PokemonRankData::class.java)!!
ranksList.add(data)
}
Response.Success(ranksList)
}catch(e:Exception){
Response.Failure(e)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
985d51a0995fdddeb86e40438c51a16f3a1a488c
| 1,112
|
UniteWiki
|
Apache License 2.0
|
app/src/main/java/com/rohit/quizzon/ui/viewholder/InappPurchaseViewHolder.kt
|
rohitjakhar
| 381,639,764
| false
|
{"Kotlin": 119852}
|
package com.rohit.quizzon.ui.viewholder
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.android.billingclient.api.SkuDetails
import com.rohit.quizzon.databinding.ItemInappPurchaseBinding
class InappPurchaseViewHolder(
private val binding: ItemInappPurchaseBinding,
private val onButButtonClicked: (SkuDetails) -> Unit
) :
RecyclerView.ViewHolder(binding.root) {
fun onBind(inappPurchaseModel: SkuDetails) = binding.apply {
tvItemText.text = inappPurchaseModel.title
btnBuy.setOnClickListener {
onButButtonClicked(inappPurchaseModel)
}
}
companion object {
fun create(parent: ViewGroup, onButClicked: (SkuDetails) -> Unit): InappPurchaseViewHolder {
val mView = LayoutInflater.from(parent.context)
val binding = ItemInappPurchaseBinding.inflate(mView, parent, false)
return InappPurchaseViewHolder(binding = binding, onButClicked)
}
}
}
| 10
|
Kotlin
|
26
| 59
|
47363e1177f26bff263102cd1b16ca48ae9b8b0c
| 1,033
|
Quizzon
|
MIT License
|
restdoc-rpc-client/restdoc-restweb-client/src/main/kotlin/restdoc/client/restweb/EnvConfiguration.kt
|
wangyi1989
| 322,489,158
| true
|
{"Kotlin": 3251411, "Java": 410514, "Dockerfile": 1079, "Shell": 1000, "Python": 714}
|
package restdoc.client.restweb
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import restdoc.client.api.AgentConfigurationProperties
import restdoc.client.api.AgentImpl
@EnableConfigurationProperties(value = [AgentConfigurationProperties::class])
@Configuration
open class EnvConfiguration {
@Bean(name = ["restWebAgentImpl"])
open fun agentImpl(properties: AgentConfigurationProperties) = AgentImpl(properties)
}
| 0
| null |
0
| 0
|
9acc0445b1638633e6960700e2e1280fa735fa04
| 569
|
REST-doc
|
Apache License 2.0
|
compose-action-menu/src/androidMain/kotlin/nl/jacobras/composeactionmenu/IconActionItemPreviews.kt
|
jacobras
| 442,299,930
| false
|
{"Kotlin": 39373, "HTML": 396}
|
package nl.jacobras.composeactionmenu
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
@PreviewUiComponent
@Composable
private fun RegularIconActionPreview() {
IconActionItem(
item = RegularActionItem(
key = "search",
title = "OK",
iconVector = Icons.Filled.Search,
onClick = {}
),
contentColor = MaterialTheme.colorScheme.onSurface
)
}
@PreviewUiComponent
@Composable
private fun BlueIconActionPreview() {
IconActionItem(
item = RegularActionItem(
key = "search",
title = "OK",
iconVector = Icons.Filled.Search,
onClick = {}
),
contentColor = MaterialTheme.colorScheme.onSurface
)
}
@PreviewUiComponent
@Composable
private fun DisabledIconActionPreview() {
IconActionItem(
item = RegularActionItem(
key = "search",
title = "OK",
iconVector = Icons.Filled.Search,
enabled = false,
onClick = {}
),
contentColor = MaterialTheme.colorScheme.onSurface
)
}
@PreviewUiComponent
@Composable
private fun TextIconActionPreview() {
IconActionItem(
item = RegularActionItem(
key = "search",
title = "OK",
iconVector = null,
onClick = {}
),
contentColor = MaterialTheme.colorScheme.onSurface
)
}
@PreviewUiComponent
@Composable
private fun BlueTextIconActionPreview() {
IconActionItem(
item = RegularActionItem(
key = "search",
title = "OK",
iconVector = null,
onClick = {}
),
contentColor = MaterialTheme.colorScheme.onSurface
)
}
@PreviewUiComponent
@Composable
private fun DisabledTextIconActionPreview() {
IconActionItem(
item = RegularActionItem(
key = "search",
title = "OK",
iconVector = null,
enabled = false,
onClick = {}
),
contentColor = MaterialTheme.colorScheme.onSurface
)
}
| 4
|
Kotlin
|
2
| 80
|
de34c16f87ce48a2e086f1da251176f518734bad
| 2,227
|
ComposeActionMenu
|
MIT License
|
lib/src/main/java/com/github/eklipse2k8/charting/components/LimitLine.kt
|
eklipse2k8
| 403,391,938
| true
|
{"Kotlin": 945921, "Java": 57298}
|
package com.github.eklipse2k8.charting.components
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Paint
import com.github.eklipse2k8.charting.utils.Utils
/**
* The limit line is an additional feature for all Line-, Bar- and ScatterCharts. It allows the
* displaying of an additional line in the chart that marks a certain maximum / limit on the
* specified axis (x- or y-axis).
*
* @author <NAME>
*/
class LimitLine : ComponentBase {
/**
* Returns the limit that is set for this line.
*
* @return
*/
/** limit / maximum (the y-value or xIndex) */
var limit = 0f
private set
/** the width of the limit line */
private var mLineWidth = 2f
/**
* Returns the color that is used for this LimitLine
*
* @return
*/
/**
* Sets the linecolor for this LimitLine. Make sure to use getResources().getColor(...)
*
* @param color
*/
/** the color of the limit line */
var lineColor = Color.rgb(237, 91, 91)
/**
* Returns the color of the value-text that is drawn next to the LimitLine.
*
* @return
*/
/**
* Sets the color of the value-text that is drawn next to the LimitLine. Default:
* Paint.Style.FILL_AND_STROKE
*
* @param style
*/
/** the style of the label text */
var textStyle = Paint.Style.FILL_AND_STROKE
/**
* Returns the label that is drawn next to the limit line.
*
* @return
*/
/**
* Sets the label that is drawn next to the limit line. Provide "" if no label is required.
*
* @param label
*/
/** label string that is drawn next to the limit line */
var label = ""
/**
* returns the DashPathEffect that is set for this LimitLine
*
* @return
*/
/** the path effect of this LimitLine that makes dashed lines possible */
var dashPathEffect: DashPathEffect? = null
private set
/**
* Returns the position of the LimitLine label (value).
*
* @return
*/
/**
* Sets the position of the LimitLine value label (either on the right or on the left edge of the
* chart). Not supported for RadarChart.
*
* @param pos
*/
/** indicates the position of the LimitLine label */
var labelPosition = LimitLabelPosition.RIGHT_TOP
/** enum that indicates the position of the LimitLine label */
enum class LimitLabelPosition {
LEFT_TOP,
LEFT_BOTTOM,
RIGHT_TOP,
RIGHT_BOTTOM
}
/**
* Constructor with limit.
*
* @param limit
* - the position (the value) on the y-axis (y-value) or x-axis (xIndex) where this line should
* appear
*/
constructor(limit: Float) {
this.limit = limit
}
/**
* Constructor with limit and label.
*
* @param limit
* - the position (the value) on the y-axis (y-value) or x-axis (xIndex) where this line should
* appear
* @param label
* - provide "" if no label is required
*/
constructor(limit: Float, label: String) {
this.limit = limit
this.label = label
}
/**
* returns the width of limit line
*
* @return
*/
/**
* set the line width of the chart (min = 0.2f, max = 12f); default 2f NOTE: thinner line ==
* better performance, thicker line == worse performance
*
* @param width
*/
var lineWidth: Float
get() = mLineWidth
set(value) {
var width = value
if (width < 0.2f) width = 0.2f
if (width > 12.0f) width = 12.0f
mLineWidth = Utils.convertDpToPixel(width)
}
/**
* Enables the line to be drawn in dashed mode, e.g. like this "- - - - - -"
*
* @param lineLength the length of the line pieces
* @param spaceLength the length of space inbetween the pieces
* @param phase offset, in degrees (normally, use 0)
*/
fun enableDashedLine(lineLength: Float, spaceLength: Float, phase: Float) {
dashPathEffect = DashPathEffect(floatArrayOf(lineLength, spaceLength), phase)
}
/** Disables the line to be drawn in dashed mode. */
fun disableDashedLine() {
dashPathEffect = null
}
/**
* Returns true if the dashed-line effect is enabled, false if not. Default: disabled
*
* @return
*/
val isDashedLineEnabled: Boolean
get() = dashPathEffect != null
}
| 0
|
Kotlin
|
0
| 0
|
29d416f36d7fd1b6af13082c2ef6b7d6abe0cab8
| 4,196
|
ComposeChart
|
Apache License 2.0
|
app/src/main/java/bruhcollective/itaysonlab/psapp/core/models/dashboard/DashboardGameMediaItems.kt
|
iTaysonLab
| 653,867,198
| false
| null |
package bruhcollective.itaysonlab.psapp.core.models.dashboard
import android.os.Parcelable
import com.squareup.moshi.JsonClass
import kotlinx.parcelize.Parcelize
@JsonClass(generateAdapter = true)
@Parcelize
data class DashboardGameMediaItems (
val images: List<DashboardGameImage>
): Parcelable
| 0
|
Kotlin
|
0
| 1
|
33328d7bd7bf000179d619d8369fa3909da7a278
| 301
|
BruhStationApp
|
MIT License
|
src/main/kotlin/cn/har01d/notebook/vo/SystemStats.kt
|
power721
| 455,496,984
| false
|
{"Vue": 164653, "Kotlin": 149601, "TypeScript": 45280, "HTML": 39446, "JavaScript": 21584, "CSS": 5882, "Shell": 1465}
|
package cn.har01d.notebook.vo
data class SystemStats(
val user: UserStats,
val note: NoteStats,
val notebooks: Long,
val categories: Long,
val comments: Long,
val tags: Long,
)
data class NoteStats(
val total: Long,
val deleted: Long,
val views: Long,
val public: Long,
val secret: Long,
val private: Long,
)
data class UserStats(
val total: Long,
val online: Long,
val anonymous: Int,
)
| 0
|
Vue
|
0
| 0
|
e8abef8d38b3a98b7bb47988f5f97038878bfc97
| 511
|
notebook
|
MIT License
|
net.akehurst.kaf/service/configuration-map/src/commonMain/kotlin/ConfigurationMap.kt
|
dhakehurst
| 166,023,488
| false
| null |
/**
* Copyright (C) 2019 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* 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 net.akehurst.kaf.service.configuration.map
import net.akehurst.kaf.service.configuration.api.ConfigurationService
class ConfigurationMap(
val values:Map<String,Any> = emptyMap()
) : ConfigurationService {
override fun <T : Any> get(path: String, default:()->T): T {
return this.values[path] as T? ?: default()
}
}
| 0
|
Kotlin
|
0
| 0
|
f74c333396998ad2ead9e5cdd964f88ac4af44d4
| 984
|
net.akehurst.kaf
|
Apache License 2.0
|
tripleklay/src/main/kotlin/tripleklay/ui/Box.kt
|
cdietze
| 89,875,388
| false
| null |
package tripleklay.ui
import euklid.f.Dimension
import euklid.f.MathUtil
import klay.core.Clock
import klay.scene.GroupLayer
import klay.scene.LayerUtil
import react.Closeable
import react.Slot
import react.Value
import tripleklay.shaders.RotateYBatch
import tripleklay.util.Interpolator
import kotlin.reflect.KClass
/**
* A container that holds zero or one widget. The box delegates everything to its current contents
* (its preferred size is its content's preferred size, it sizes its contents to its size).
*/
open class Box
/** Creates a box with the specified starting contents. */
constructor(contents: Element<*>? = null) : Container.Mutable<Box>() {
/** A `Box` which draws its children clipped to their preferred size. */
class Clipped
/** Creates a clipped box with the specified starting contents. */
constructor(contents: Element<*>? = null) : Box() {
init {
set(contents)
}
override fun createLayer(): GroupLayer {
return GroupLayer(1f, 1f)
}
override fun wasValidated() {
layer.setSize(size().width, size().height)
}
}
/** Creates an empty clipped box. */
/** Manages transitions for [.transition]. */
abstract class Trans protected constructor(duration: Int) : Slot<Clock> {
/** Indicates whether this transition is in process. */
var active = Value(false)
protected var _ocontents: Element<*>? = null
protected var _ncontents: Element<*>? = null
private val _duration: Float = duration.toFloat() // ms
private var _elapsed: Float = 0.toFloat()
private var _box: Box? = null
private var _interp = Interpolator.LINEAR
private var _conn: Closeable? = null
/** Configures the interpolator to use for the transition. */
fun interp(interp: Interpolator): Trans {
_interp = interp
return this
}
internal fun start(box: Box, ncontents: Element<*>) {
if (active.get())
throw IllegalStateException(
"Cannot reuse transition until it has completed.")
_box = box
_ocontents = box.contents()
_ncontents = ncontents
_box!!.didAdd(_ncontents!!)
_ncontents!!.setLocation(_ocontents!!.x(), _ocontents!!.y())
_ncontents!!.setSize(_ocontents!!.size().width, _ocontents!!.size().height)
_ncontents!!.validate()
_conn = box.root()!!.iface.frame.connect(this)
_elapsed = -1f
init()
update(0f)
active.update(true)
}
override fun invoke(clock: Clock) {
// a minor hack which causes us to skip the frame on which we validated the new
// contents and generally did potentially expensive things; that keeps us from jumping
// into the transition with a big first time step
if (_elapsed == -1f)
_elapsed = 0f
else
_elapsed += clock.dt.toFloat()
val pct = minOf(_elapsed / _duration, 1f)
// TODO: interp!
update(_interp.apply(pct))
if (pct == 1f) {
_box!!.set(_ncontents) // TODO: avoid didAdd
_conn!!.close()
_box = null
cleanup()
_ocontents = null
_ncontents = null
active.update(false)
}
}
protected open fun init() {}
protected abstract fun update(pct: Float)
protected open fun cleanup() {}
}
/** A transition that fades from the old contents to the new. */
class Fade(duration: Int) : Trans(duration) {
override fun update(pct: Float) {
_ocontents!!.layer.setAlpha(1 - pct)
_ncontents!!.layer.setAlpha(pct)
}
override fun cleanup() {
_ocontents!!.layer.setAlpha(1f)
}
}
class Flip(duration: Int) : Trans(duration) {
private lateinit var _obatch: RotateYBatch
private lateinit var _nbatch: RotateYBatch
override fun init() {
// TODO: compute the location of the center of the box in screen coordinates, place
// the eye there in [0, 1] coords
val gfx = _ocontents!!.root()!!.iface.plat.graphics
val eye = LayerUtil.layerToScreen(
_ocontents!!.layer, _ocontents!!.size().width / 2, _ocontents!!.size().height / 2)
eye.x /= gfx.viewSize.width
eye.y /= gfx.viewSize.height
_obatch = RotateYBatch(gfx.gl, eye.x, eye.y, 1f)
_nbatch = RotateYBatch(gfx.gl, eye.x, eye.y, 1f)
_ocontents!!.layer.setBatch(_obatch)
_ncontents!!.layer.setBatch(_nbatch)
}
override fun update(pct: Float) {
_obatch.angle = MathUtil.PI * pct
_nbatch.angle = -MathUtil.PI * (1 - pct)
_ocontents!!.layer.setVisible(pct < 0.5f)
_ncontents!!.layer.setVisible(pct >= 0.5f)
}
override fun cleanup() {
_ocontents!!.layer.setBatch(null)
_ncontents!!.layer.setBatch(null)
}
}
init {
set(contents)
}
/** Returns the box's current contents. */
fun contents(): Element<*>? {
return _contents
}
/** Updates the box's contents. The previous contents, if any, is removed but not destroyed.
* To destroy the old contents and set the new, use `destroyContents().set(contents)`. */
fun set(contents: Element<*>?): Box {
if (contents !== _contents) set(contents, false)
return this
}
/** Performs an animated transition from the box's current contents to `contents`.
* @param trans describes and manages the transition (duration, style, etc.).
*/
fun transition(contents: Element<*>, trans: Trans): Box {
trans.start(this, contents)
return this
}
/** Clears out the box's current contents. */
fun clear(): Box {
return set(null)
}
/** Clears out the box's current contents and destroys it immediately. */
fun destroyContents(): Box {
return set(null as Element<*>?, true)
}
override fun stylesheet(): Stylesheet? {
return null // boxes provide no styles
}
override fun childCount(): Int {
return if (_contents == null) 0 else 1
}
override fun childAt(index: Int): Element<*> {
if (_contents == null || index != 0) throw IndexOutOfBoundsException()
return _contents!!
}
override fun iterator(): Iterator<Element<*>> {
return if (_contents == null)
emptyList<Element<*>>().iterator()
else
setOf(_contents!!).iterator()
}
override fun remove(child: Element<*>) {
if (_contents === child) clear()
}
override fun removeAt(index: Int) {
if (_contents == null || index != 0) throw IndexOutOfBoundsException()
clear()
}
override fun removeAll() {
clear()
}
override fun destroy(child: Element<*>) {
if (_contents === child) destroyContents()
}
override fun destroyAt(index: Int) {
if (_contents == null || index != 0) throw IndexOutOfBoundsException()
destroyContents()
}
override fun destroyAll() {
destroyContents()
}
override val styleClass: KClass<*>
get() = Box::class
override fun computeSize(ldata: LayoutData, hintX: Float, hintY: Float): Dimension {
return if (_contents == null) Dimension() else _contents!!.computeSize(hintX, hintY)
}
override fun layout(ldata: LayoutData, left: Float, top: Float,
width: Float, height: Float) {
if (_contents != null) {
_contents!!.setSize(width, height)
_contents!!.setLocation(left, top)
_contents!!.validate()
}
}
override // not used
val layout: Layout
get() = throw UnsupportedOperationException()
protected fun set(contents: Element<*>?, destroy: Boolean): Box {
if (_contents != null) {
didRemove(_contents!!, destroy)
}
_contents = contents
if (contents != null) {
didAdd(contents)
}
invalidate()
return this
}
protected var _contents: Element<*>? = null
}
/** Creates an empty box. */
| 0
|
Kotlin
|
0
| 4
|
72031aa267cd304a0612b31c871e2f5cf73d2c4c
| 8,540
|
klay
|
Apache License 2.0
|
python-multiplatform/src/commonMain/kotlin/python/multiplatform/Versions.kt
|
thisisthepy
| 868,537,806
| false
|
{"Kotlin": 12892, "Swift": 621}
|
package python.multiplatform
/*
* Supported versions of Python
*/
enum class Versions(val versionString: String) {
PYTHON_3_13_0("3.13.0");
companion object {
val currentVersion = valueOf(BuildConfig.pythonVersion)
fun valueOf(versionString: String): Versions {
val found = entries.find { it.versionString == versionString }
if (found == null) {
throw IllegalArgumentException("Unsupported Python version: $versionString")
}
return found
}
}
override fun toString(): String {
return versionString
}
val compactVersionString: String
get() = versionString.split(".").subList(0, 2).joinToString(".")
val majorVersion
get() = versionString.split(".")[0].toInt()
val minorVersion
get() = versionString.split(".")[1].toInt()
val getPatchVersion
get() = versionString.split(".")[2].toInt()
}
| 0
|
Kotlin
|
0
| 1
|
05638d20a9e32db40f2885a66a37b0cc2485cef0
| 960
|
python-multiplatform-mobile
|
MIT License
|
app/src/main/java/com/epita/pokimoni/room/PokemonData.kt
|
Dr-LYK
| 160,687,383
| false
| null |
package com.epita.pokimoni.room
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.PrimaryKey
import com.epita.pokimoni.model.TypeColor
@Entity(tableName = "pokemonData")
data class PokemonData(@PrimaryKey(autoGenerate = true)
var id: Long?,
@ColumnInfo(name = "index") var index: Int,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "type1") var type1: String,
@ColumnInfo(name = "type2") var type2: String?,
@ColumnInfo(name = "count") var count: Int) {
@Ignore
constructor(): this(null, 0, "", "", null, 0)
}
| 0
|
Kotlin
|
2
| 4
|
a7016bd9db2c339aaef00fad7c8c43b2723d6ae2
| 798
|
Pokimoni
|
MIT License
|
app/src/main/java/com/example/tmdbclient/presentation/di/core/CacheDataModule.kt
|
Suraj820
| 615,681,119
| false
|
{"Kotlin": 67882}
|
package com.example.tmdbclient.presentation.di.core
import com.example.tmdbclient.data.repository.artist.datasource.ArtistCacheDatasource
import com.example.tmdbclient.data.repository.artist.datasourceimpl.ArtistCacheDataSouceImpl
import com.example.tmdbclient.data.repository.movie.datasource.MovieCacheDataSource
import com.example.tmdbclient.data.repository.movie.datasourceimpl.MovieCacheDataSourceImpl
import com.example.tmdbclient.data.repository.tvshow.datasource.TvShowsCacheDataSource
import com.example.tmdbclient.data.repository.tvshow.datasourceimpl.TvShowCacheDataSourceImpl
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class CacheDataModule {
@Singleton
@Provides
fun provideMovieCacheDataSource():MovieCacheDataSource{
return MovieCacheDataSourceImpl()
}
@Singleton
@Provides
fun provideArtistCacheDataSource():ArtistCacheDatasource{
return ArtistCacheDataSouceImpl()
}
@Singleton
@Provides
fun provideTvShowCacheDataSource():TvShowsCacheDataSource{
return TvShowCacheDataSourceImpl()
}
}
| 0
|
Kotlin
|
0
| 0
|
d02e490b436894d04ef30d4f0de0208ab007b017
| 1,117
|
TMDBMovies
|
MIT License
|
app/src/main/java/com/example/nytimes/di/module/ApplicationModule.kt
|
Sushant-Hande
| 393,662,779
| false
| null |
package com.example.nytimes.di.module
import com.example.nytimes.network.apiservice.ApiService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
/**
* Created by shande on 07-08-2021
*/
@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule {
@Provides
fun provideBaseUrl() = "https://api.nytimes.com/svc/mostpopular/v2/"
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient = OkHttpClient
.Builder()
.build()
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient, BASE_URL: String): Retrofit =
Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build()
@Provides
@Singleton
fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
}
| 0
|
Kotlin
|
0
| 0
|
dd77217408655c6160fbfce5887ae913a9f75bc0
| 1,110
|
nytimes
|
Apache License 2.0
|
airwallex/src/main/java/com/airwallex/android/model/parser/NextActionParser.kt
|
nieqiyuan
| 390,658,464
| true
|
{"Kotlin": 562120}
|
package com.airwallex.android.model.parser
import com.airwallex.android.model.AirwallexJsonUtils
import com.airwallex.android.model.NextAction
import org.json.JSONObject
import java.math.BigDecimal
internal class NextActionParser : ModelJsonParser<NextAction> {
override fun parse(json: JSONObject): NextAction? {
return NextAction(
type = NextAction.NextActionType.fromValue(
AirwallexJsonUtils.optString(json, FIELD_TYPE)
),
data = AirwallexJsonUtils.optMap(json, FIELD_DATA),
dcc = json.optJSONObject(FIELD_DCC_DATA)?.let {
DccDataParser().parse(it)
},
url = AirwallexJsonUtils.optString(json, FIELD_URL),
method = AirwallexJsonUtils.optString(json, FIELD_METHOD),
)
}
private companion object {
private const val FIELD_TYPE = "type"
private const val FIELD_DATA = "data"
private const val FIELD_DCC_DATA = "dcc_data"
private const val FIELD_URL = "url"
private const val FIELD_METHOD = "method"
}
internal class DccDataParser : ModelJsonParser<NextAction.DccData> {
override fun parse(json: JSONObject): NextAction.DccData? {
return NextAction.DccData(
currency = AirwallexJsonUtils.optString(json, FIELD_CURRENCY),
amount = AirwallexJsonUtils.optDouble(json, FIELD_AMOUNT)?.let {
BigDecimal.valueOf(it)
},
currencyPair = AirwallexJsonUtils.optString(json, FIELD_CURRENCY_PAIR),
clientRate = AirwallexJsonUtils.optDouble(json, FIELD_CLIENT_RATE),
rateSource = AirwallexJsonUtils.optString(json, FIELD_RATE_SOURCE),
rateTimestamp = AirwallexJsonUtils.optString(json, FIELD_RATE_TIMESTAMP),
rateExpiry = AirwallexJsonUtils.optString(json, FIELD_RATE_EXPIRY)
)
}
private companion object {
private const val FIELD_CURRENCY = "currency"
private const val FIELD_AMOUNT = "amount"
private const val FIELD_CURRENCY_PAIR = "currency_pair"
private const val FIELD_CLIENT_RATE = "client_rate"
private const val FIELD_RATE_SOURCE = "rate_source"
private const val FIELD_RATE_TIMESTAMP = "rate_timestamp"
private const val FIELD_RATE_EXPIRY = "rate_expiry"
}
}
}
| 0
|
Kotlin
|
0
| 1
|
72b5befb79147a2f012d66d1136e9d37bb77950f
| 2,446
|
airwallex-payment-android
|
MIT License
|
src/vulkan/api/pipeline/graphics_pipeline.kt
|
pvmoore
| 166,660,032
| false
| null |
package vulkan.api.pipeline
import org.lwjgl.system.MemoryStack
import org.lwjgl.vulkan.*
import org.lwjgl.vulkan.VK10.*
import vulkan.api.descriptor.VkDescriptorSetLayout
import vulkan.common.RenderContext
import vulkan.common.SpecConstants
import vulkan.common.Transferable
import vulkan.common.log
import vulkan.maths.string
import vulkan.misc.VkPrimitiveTopology
import vulkan.misc.VkShaderStageFlags
import kotlin.test.assertNull
class GraphicsPipeline {
private lateinit var context:RenderContext
private var descriptorSetLayouts:Array<VkDescriptorSetLayout>? = null
private var pushConstantRanges:VkPushConstantRange.Buffer? = null
private data class ShaderInfo(val filename:String, val specConstants: SpecConstants?)
private var shaderProps = mapOf<String,String>()
private var shaderIncludes = listOf<String>()
private val shaders = HashMap<Int, ShaderInfo>()
private var subpass = 0
private val vertexInputState = VkPipelineVertexInputStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO)
private val inputAssemblyState = VkPipelineInputAssemblyStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO)
private val tessellationState = VkPipelineTessellationStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO)
private val viewportState = VkPipelineViewportStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO)
private val rasterisationState = VkPipelineRasterizationStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO)
.polygonMode(VK_POLYGON_MODE_FILL) // fill, line or point
.cullMode(VK_CULL_MODE_NONE) // none, front, back, front and back
.frontFace(VK_FRONT_FACE_CLOCKWISE) // counterclockwise or clockwise
.depthBiasEnable(false)
.rasterizerDiscardEnable(false)
.depthClampEnable(false)
.lineWidth(1f)
private val multisampleState = VkPipelineMultisampleStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO)
.rasterizationSamples(VK_SAMPLE_COUNT_1_BIT)
private val depthStencilState = VkPipelineDepthStencilStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO)
private val colorBlendState = VkPipelineColorBlendStateCreateInfo.calloc()
.sType(VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO)
.pAttachments(VkPipelineColorBlendAttachmentState.calloc(1).colorWriteMask(0xf))
private var dynamicState:VkPipelineDynamicStateCreateInfo? = null
lateinit var pipeline: VkPipeline
lateinit var layout: VkPipelineLayout
fun init(context: RenderContext) : GraphicsPipeline {
this.context = context
return this
}
fun destroy() {
vertexInputState.free()
inputAssemblyState.free()
tessellationState.free()
viewportState.free()
rasterisationState.free()
multisampleState.free()
depthStencilState.free()
colorBlendState.free()
dynamicState?.free()
pushConstantRanges?.free()
layout.destroy()
pipeline.destroy()
}
fun withShaderProperties(props:Map<String,String>, includes:List<String>):GraphicsPipeline {
this.shaderProps = props.toMap()
this.shaderIncludes = includes.toList()
return this
}
fun withShader(stage:VkShaderStageFlags, filename:String, specConstants: SpecConstants? = null):GraphicsPipeline {
shaders[stage] = ShaderInfo(filename, specConstants)
return this
}
fun withVertexInputState(vertex: Transferable, topology:VkPrimitiveTopology) : GraphicsPipeline {
inputAssemblyState
.topology(topology)
.flags(0) // reserved
.primitiveRestartEnable(false)
val bindings = VkVertexInputBindingDescription.calloc(1)
.binding(0)
.stride(vertex.size())
.inputRate(VK_VERTEX_INPUT_RATE_VERTEX) // vertex or instance
val attribs = VkVertexInputAttributeDescription.calloc(vertex.javaClass.declaredFields.size)
var offset = 0
vertex.javaClass.declaredFields.forEachIndexed { i, field ->
val (format,fieldsize) = when(field.type.name) {
"int" -> VK_FORMAT_R32_SINT to 4
"float" -> VK_FORMAT_R32_SFLOAT to 4
"org.joml.Vector2f" -> VK_FORMAT_R32G32_SFLOAT to 2*4
"org.joml.Vector3f" -> VK_FORMAT_R32G32B32_SFLOAT to 3*4
"org.joml.Vector4f" -> VK_FORMAT_R32G32B32A32_SFLOAT to 4*4
"org.joml.Vector2i" -> VK_FORMAT_R32G32_SINT to 2*4
"org.joml.Vector3i" -> VK_FORMAT_R32G32B32_SINT to 3*4
"org.joml.Vector4i" -> VK_FORMAT_R32G32B32A32_SINT to 4*4
else -> throw Error("Unknown format for vertex field ${field.type.name}")
}
attribs[i].run {
location(i)
binding(0)
format(format)
offset(offset)
}
offset += fieldsize
}
vertexInputState
.pVertexBindingDescriptions(bindings)
.pVertexAttributeDescriptions(attribs)
return this
}
fun withViewports(num:Int, callback:(VkViewport.Buffer)->Unit):GraphicsPipeline {
val viewports = VkViewport.calloc(num)
callback(viewports)
viewportState
.viewportCount(num)
.pViewports(viewports)
return this
}
fun withScissors(num:Int, callback:(VkRect2D.Buffer)->Unit):GraphicsPipeline {
val scissors = VkRect2D.calloc(num)
callback(scissors)
viewportState
.scissorCount(num)
.pScissors(scissors)
return this
}
fun withRasterisationState(callback:(VkPipelineRasterizationStateCreateInfo)->Unit):GraphicsPipeline {
callback(rasterisationState)
return this
}
fun withMultisampleState(callback:(VkPipelineMultisampleStateCreateInfo)->Unit):GraphicsPipeline {
callback(multisampleState)
return this
}
fun withDepthStencilState(callback:(VkPipelineDepthStencilStateCreateInfo)->Unit):GraphicsPipeline {
callback(depthStencilState)
return this
}
fun withColorBlendState(callback:(VkPipelineColorBlendStateCreateInfo)->Unit):GraphicsPipeline {
callback(colorBlendState)
return this
}
fun withStandardColorBlend() : GraphicsPipeline {
val attachment = VkPipelineColorBlendAttachmentState.calloc(1)
.blendEnable(true)
.srcColorBlendFactor(VK_BLEND_FACTOR_SRC_ALPHA)
.dstColorBlendFactor(VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA)
.srcAlphaBlendFactor(VK_BLEND_FACTOR_ONE)
.dstAlphaBlendFactor(VK_BLEND_FACTOR_ZERO)
.colorBlendOp(VK_BLEND_OP_ADD)
.alphaBlendOp(VK_BLEND_OP_ADD)
.colorWriteMask(VK_COLOR_COMPONENT_R_BIT or
VK_COLOR_COMPONENT_G_BIT or
VK_COLOR_COMPONENT_B_BIT or
VK_COLOR_COMPONENT_A_BIT)
colorBlendState.pAttachments(attachment)
return this
}
fun withDynamicState(callback:(VkPipelineDynamicStateCreateInfo)->Unit):GraphicsPipeline {
dynamicState = VkPipelineDynamicStateCreateInfo.calloc()
callback(dynamicState!!)
return this
}
fun withSubpass(subpass:Int):GraphicsPipeline {
this.subpass = subpass
return this
}
fun withDSLayouts(dsLayouts:Array<VkDescriptorSetLayout>):GraphicsPipeline {
this.descriptorSetLayouts = dsLayouts.copyOf()
return this
}
/** Simple constant range */
fun withPushConstants(firstIndex:Int, count:Int, stageFlags:VkShaderStageFlags):GraphicsPipeline {
assertNull(pushConstantRanges)
pushConstantRanges = VkPushConstantRange.calloc(1)
.stageFlags(stageFlags)
.offset(firstIndex*4)
.size(count*4)
return this
}
fun build():GraphicsPipeline {
assert(vertexInputState.vertexBindingDescriptionCount()>0)
assert(vertexInputState.vertexAttributeDescriptionCount()>0)
/** Pipeline Layout */
layout = context.device.createPipelineLayout(
descriptorSetLayouts!!,
pushConstantRanges
)
MemoryStack.stackPush().use { stack ->
val win = context.vk.graphics.windowSize
if(viewportState.viewportCount() == 0) {
log.info("Creating standard viewport: ${win.string()}")
val viewports = VkViewport.callocStack(1)
.x(0f)
.y(0f)
.width(win.x.toFloat())
.height(win.y.toFloat())
.minDepth(0.0f)
.maxDepth(1.0f)
viewportState
.viewportCount(1)
.pViewports(viewports)
}
if(viewportState.scissorCount()==0) {
log.info("Creating standard scissor: ${win.string()}")
val scissors = VkRect2D.callocStack(1)
scissors.extent().set(win.x, win.y)
viewportState
.scissorCount(1)
.pScissors(scissors)
}
val shaderStages = VkPipelineShaderStageCreateInfo.callocStack(shaders.size)
var i = 0
shaders.forEach { k, v ->
val shader = context.vk.shaders.get(v.filename, shaderProps, shaderIncludes)
val specInfo = v.specConstants?.let { specialisationInfo(it) }
shaderStages[i++].run {
sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO)
flags(0) // reserved
stage(k)
module(shader.handle)
pName(stack.UTF8("main"))
pSpecializationInfo(specInfo)
}
}
pipeline = context.device.createGraphicsPipeline(
layout,
context.renderPass!!,
shaderStages,
vertexInputState,
inputAssemblyState,
tessellationState,
viewportState,
rasterisationState,
multisampleState,
depthStencilState,
colorBlendState,
dynamicState
)
}
return this
}
}
| 0
|
Kotlin
|
0
| 1
|
eccc265d05f72d4dd1610cb8e47c753fafb8025d
| 10,914
|
vulkanlib
|
MIT License
|
app/src/main/java/com/umaplasticsfsm/features/activities/api/ActivityRepoProvider.kt
|
DebashisINT
| 740,356,583
| false
|
{"Kotlin": 13950763, "Java": 1000924}
|
package com.umaplasticsfsm.features.activities.api
import com.umaplasticsfsm.features.member.api.TeamApi
import com.umaplasticsfsm.features.member.api.TeamRepo
object ActivityRepoProvider {
fun activityRepoProvider(): ActivityRepo {
return ActivityRepo(ActivityApi.create())
}
fun activityImageRepoProvider(): ActivityRepo {
return ActivityRepo(ActivityApi.createImage())
}
}
| 0
|
Kotlin
|
0
| 0
|
2ccc871bdcf7df2d08825d0b9ded73b11495519e
| 410
|
UmaPlastics
|
Apache License 2.0
|
protocol/src/main/kotlin/io/kaxis/dtls/DTLSMessage.kt
|
barudisshu
| 806,368,620
| false
|
{"Kotlin": 1313792, "Java": 458139, "Shell": 28440, "Dockerfile": 956}
|
/*
* COPYRIGHT Cplier 2024
*
* The copyright to the computer program(s) herein is the property of
* Cplier Inc. The programs may be used and/or copied only with written
* permission from Cplier Inc. or in accordance with the terms and
* conditions stipulated in the agreement/contract under which the
* program(s) have been supplied.
*/
package io.kaxis.dtls
/**
* The message contract as defined by the DTLS specification.
* @author galudisu
*/
interface DTLSMessage {
/**
* Gets the number of bytes representing this message as defined by [TLS 1.2, Appendix A](https://tools.ietf.org/html/rfc5246#appendix-A)
* @return number of bytes
*/
val size: Int
/**
* Gets the byte array representation of this message as defined by [TLS 1.2, Appendix A](https://tools.ietf.org/html/rfc5246#appendix-A)
* @return the byte array
*/
fun toByteArray(): ByteArray?
/**
* Gets the message's content type.
* @return the type
*/
val contentType: ContentType
/**
* Gets the textual presentation of this message.
* @param indent line indentation
* @return textual presentation
*/
fun toString(indent: Int): String
}
| 0
|
Kotlin
|
0
| 0
|
f18e39e826792f145468f33d8751decc79769c07
| 1,170
|
kaxis
|
MIT License
|
crowdproj-votes-repo-in-memory/src/commonMain/kotlin/VoteRepoInMemory.kt
|
crowdproj
| 680,000,607
| false
|
{"Kotlin": 194373, "Shell": 439, "Dockerfile": 339}
|
package com.crowdproj.vote.repoinmemory
import com.benasher44.uuid.uuid4
import com.crowdproj.vote.common.helpers.errorRepoConcurrency
import com.crowdproj.vote.common.models.*
import com.crowdproj.vote.common.repo.DbVoteIdRequest
import com.crowdproj.vote.common.repo.DbVoteRequest
import com.crowdproj.vote.common.repo.DbVoteResponse
import com.crowdproj.vote.common.repo.IVoteRepository
import com.crowdproj.vote.repoinmemory.model.VoteEntity
import io.github.reactivecircus.cache4k.Cache
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
class VoteRepoInMemory(
initObjects: Collection<CwpVote> = emptyList(),
ttl: Duration = 2.minutes,
val randomUuid: () -> String = { uuid4().toString() },
) : IVoteRepository {
private val mutex: Mutex = Mutex()
private val cache = Cache.Builder<String, VoteEntity>()
.expireAfterWrite(ttl)
.build()
init {
initObjects.forEach {
save(it)
}
}
private fun save(ad: CwpVote) {
val entity = VoteEntity(ad)
if (entity.id == null) {
return
}
cache.put(entity.id!!, entity)
}
override suspend fun createVote(rq: DbVoteRequest): DbVoteResponse {
val key = randomUuid()
val vote = rq.vote.copy(id = CwpVoteId(key), lock = CwpVoteLock(randomUuid()))
val entity = VoteEntity(vote)
cache.put(key, entity)
return DbVoteResponse(
data = vote,
isSuccess = true,
)
}
override suspend fun readVote(rq: DbVoteIdRequest): DbVoteResponse {
val key = rq.id.takeIf { it != CwpVoteId.NONE }?.asString() ?: return resultErrorEmptyId
return cache.get(key)
?.let {
DbVoteResponse(
data = it.toInternal(),
isSuccess = true,
)
} ?: resultErrorNotFound
}
override suspend fun updateVote(rq: DbVoteRequest): DbVoteResponse {
val key = rq.vote.id.takeIf { it != CwpVoteId.NONE }?.asString() ?: return resultErrorEmptyId
val oldLock = rq.vote.lock.takeIf { it != CwpVoteLock.NONE }?.asString() ?: return resultErrorEmptyLock
val newVote = rq.vote.copy(lock = CwpVoteLock(randomUuid()))
val entity = VoteEntity(newVote)
return mutex.withLock {
val oldVote = cache.get(key)
when {
oldVote == null -> resultErrorNotFound
oldVote.lock != oldLock -> DbVoteResponse(
data = oldVote.toInternal(),
isSuccess = false,
errors = listOf(errorRepoConcurrency(CwpVoteLock(oldLock), oldVote.lock?.let { CwpVoteLock(it) }))
)
else -> {
cache.put(key, entity)
DbVoteResponse(
data = newVote,
isSuccess = true,
)
}
}
}
}
override suspend fun deleteVote(rq: DbVoteIdRequest): DbVoteResponse {
val key = rq.id.takeIf { it != CwpVoteId.NONE }?.asString() ?: return resultErrorEmptyId
val oldLock = rq.lock.takeIf { it != CwpVoteLock.NONE }?.asString() ?: return resultErrorEmptyLock
val newVoteEntity: VoteEntity = cache.get(key)?.copy(isAccepted = 0) ?: return resultErrorNotFound
return mutex.withLock {
val oldVote = cache.get(key)
when {
oldVote == null -> resultErrorNotFound
oldVote.lock != oldLock -> DbVoteResponse(
data = oldVote.toInternal(),
isSuccess = false,
errors = listOf(errorRepoConcurrency(CwpVoteLock(oldLock), oldVote.lock?.let { CwpVoteLock(it) }))
)
else -> {
cache.put(key, newVoteEntity)
DbVoteResponse(
data = newVoteEntity.toInternal(),
isSuccess = true,
)
}
}
}
}
companion object {
val resultErrorEmptyId = DbVoteResponse(
data = null,
isSuccess = false,
errors = listOf(
CwpVoteError(
code = "id-empty",
group = "validation",
field = "id",
message = "Id must not be null or blank"
)
)
)
val resultErrorNotFound = DbVoteResponse(
isSuccess = false,
data = null,
errors = listOf(
CwpVoteError(
code = "not-found",
field = "id",
message = "Not Found"
)
)
)
val resultErrorEmptyLock = DbVoteResponse(
data = null,
isSuccess = false,
errors = listOf(
CwpVoteError(
code = "lock-empty",
group = "validation",
field = "lock",
message = "Lock must not be null or blank"
)
)
)
}
}
| 0
|
Kotlin
|
1
| 0
|
c88bab0307427fe9a8c0f9305fe9e63609e3c6ca
| 5,314
|
crowdproj-ratings-votes
|
Apache License 2.0
|
app/src/main/java/hiendao/moviefinder/data/network/movie/MovieApi.kt
|
HienDao14
| 826,173,311
| false
|
{"Kotlin": 438834}
|
package hiendao.moviefinder.data.network.movie
import hiendao.moviefinder.data.network.movie.model.collection.Collection
import hiendao.moviefinder.data.network.movie.model.credit.Credits
import hiendao.moviefinder.data.network.movie.model.credit.MovieCredits
import hiendao.moviefinder.data.network.movie.model.credit.detail.CreditDetail
import hiendao.moviefinder.data.network.movie.model.detail.MovieDetailDTO
import hiendao.moviefinder.data.network.movie.model.list.MovieListResponse
import hiendao.moviefinder.data.network.movie.model.list.MovieListWithDateResponse
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface MovieApi {
//baseUrl: https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc
//Movie API
@GET("movie/popular")
suspend fun getPopularMovies(
@Query("page") page: Int?
): MovieListResponse
@GET("movie/now_playing")
suspend fun getNowPlayingMovies(
@Query("page") page: Int?
): MovieListWithDateResponse
@GET("movie/top_rated")
suspend fun getTopRatedMovies(
@Query("page") page: Int?
): MovieListResponse
@GET("movie/upcoming")
suspend fun getUpcomingMovies(
@Query("page") page: Int?
): MovieListWithDateResponse
@GET("trending/movie/{time_window}")
suspend fun getTrendingMovie(
@Path("time_window") timeWindow: String,
@Query("page") page: Int?
): MovieListResponse
@GET("movie/{movie_id}")
suspend fun getMovieDetailInfo(
@Path("movie_id") movieId: Int,
@Query("append_to_response") append: String? = "images,similar,videos"
): MovieDetailDTO
@GET("collection/{collection_id}")
suspend fun getMovieCollection(
@Path("collection_id") collectionId: Int
): Collection
@GET("movie/{movie_id}/credits")
suspend fun getCredits(
@Path("movie_id") movieId: Int
): Credits
@GET("person/{person_id}")
suspend fun getCreditDetail(
@Path("person_id") personId: Int,
@Query("append_to_response") append: String? = "movie_credits,external_ids"
): CreditDetail
@GET("person/{person_id}/movie_credits")
suspend fun getMovieCredits(
@Path("person_id") personId: Int
): MovieCredits
@GET("discover/movie")
suspend fun getMovieDiscover(
@Query("release_date.lte") releaseDateLte: String,
@Query("page") page: Int = 1,
@Query("with_genres") withGenres: String?,
@Query("sort_by") sortBy: String,
@Query("vote_count.gte") voteCountGte: Float?
): MovieListResponse
}
| 0
|
Kotlin
|
0
| 0
|
7f3f66b7a169ece9b34c7488455654c08353ee2d
| 2,683
|
Movie-Discover
|
MIT License
|
app/src/main/java/com/breezefieldsalesashavarifoods/features/dashboard/presentation/api/otpverifyapi/OtpVerificationRepo.kt
|
DebashisINT
| 855,784,708
| false
|
{"Kotlin": 15929080, "Java": 1029428}
|
package com.breezefieldsalesashavarifoods.features.dashboard.presentation.api.otpverifyapi
import com.breezefieldsalesashavarifoods.app.Pref
import com.breezefieldsalesashavarifoods.base.BaseResponse
import io.reactivex.Observable
/**
* Created by Saikat on 22-11-2018.
*/
class OtpVerificationRepo(val apiService: OtpVerificationApi) {
fun otpVerify(shopId: String, otp: String): Observable<BaseResponse> {
return apiService.otpVerify(Pref.session_token!!, Pref.user_id!!, shopId, otp)
}
}
| 0
|
Kotlin
|
0
| 0
|
b765ac8aab9525cb78147d55d129b1b8df1b059c
| 510
|
AshavariFoods
|
Apache License 2.0
|
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/types/media/VideoChatScheduled.kt
|
vendelieu
| 496,567,172
| false
|
{"Kotlin": 460733, "CSS": 356}
|
package eu.vendeli.tgbot.types.media
data class VideoChatScheduled(
val startDate: Int,
)
| 1
|
Kotlin
|
2
| 98
|
f466e59c663d7319d1bcb9fd526e52c666c5927f
| 95
|
telegram-bot
|
Apache License 2.0
|
core/src/main/kotlin/com/kemp/core/config/rendering/Dithering.kt
|
MovementSpeed
| 296,457,126
| false
| null |
package com.kemp.core.config.rendering
enum class Dithering {
NONE, TEMPORAL
}
| 0
|
Kotlin
|
0
| 1
|
9f2238b75989cfb877e20db263d962452b238424
| 83
|
kemp
|
The Unlicense
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Connectdevelop.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36756847}
|
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.Connectdevelop: ImageVector
get() {
if (_connectdevelop != null) {
return _connectdevelop!!
}
_connectdevelop = Builder(name = "Connectdevelop", 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(9.1563f, 4.1875f)
lineTo(8.875f, 4.6875f)
lineTo(2.625f, 15.5938f)
lineTo(2.3438f, 16.0938f)
lineTo(2.625f, 16.5938f)
lineTo(8.875f, 27.5f)
lineTo(9.1563f, 28.0f)
lineTo(22.8438f, 28.0f)
lineTo(23.125f, 27.5f)
lineTo(29.375f, 16.5938f)
lineTo(29.6563f, 16.0938f)
lineTo(29.375f, 15.5938f)
lineTo(23.125f, 4.6875f)
lineTo(22.8438f, 4.1875f)
close()
moveTo(11.5938f, 6.1875f)
lineTo(17.7188f, 6.1875f)
lineTo(13.1563f, 7.8125f)
close()
moveTo(20.7188f, 6.1875f)
lineTo(16.125f, 10.875f)
lineTo(13.9375f, 8.5938f)
close()
moveTo(10.2813f, 6.2813f)
lineTo(12.1563f, 8.1875f)
lineTo(10.25f, 8.875f)
lineTo(10.25f, 6.3438f)
close()
moveTo(21.8125f, 6.4688f)
lineTo(24.4375f, 11.0f)
lineTo(20.4063f, 15.2813f)
lineTo(16.8438f, 11.5938f)
close()
moveTo(9.25f, 8.0938f)
lineTo(9.25f, 9.2188f)
lineTo(8.4375f, 9.5f)
close()
moveTo(12.9063f, 8.9688f)
lineTo(15.4375f, 11.5938f)
lineTo(11.7188f, 15.375f)
lineTo(10.25f, 13.8125f)
lineTo(10.25f, 9.9375f)
close()
moveTo(9.25f, 10.2813f)
lineTo(9.25f, 12.75f)
lineTo(7.5938f, 10.9688f)
lineTo(7.6563f, 10.8438f)
close()
moveTo(7.0625f, 11.875f)
lineTo(9.25f, 14.2188f)
lineTo(9.25f, 17.9375f)
lineTo(7.0313f, 20.2188f)
lineTo(4.6563f, 16.0938f)
close()
moveTo(24.875f, 12.0f)
lineTo(23.5f, 18.4688f)
lineTo(21.0938f, 16.0f)
close()
moveTo(16.125f, 12.3125f)
lineTo(19.7188f, 16.0f)
lineTo(16.0f, 19.9375f)
lineTo(12.4063f, 16.125f)
close()
moveTo(25.6563f, 13.1563f)
lineTo(27.3438f, 16.0938f)
lineTo(25.0625f, 20.0625f)
lineTo(24.375f, 19.3438f)
close()
moveTo(10.25f, 15.2813f)
lineTo(11.0313f, 16.0938f)
lineTo(10.25f, 16.9063f)
close()
moveTo(20.4063f, 16.7188f)
lineTo(23.2813f, 19.6563f)
lineTo(22.9375f, 21.25f)
lineTo(17.2188f, 21.25f)
lineTo(16.6875f, 20.6875f)
close()
moveTo(11.7188f, 16.8438f)
lineTo(15.3125f, 20.6875f)
lineTo(14.75f, 21.25f)
lineTo(10.25f, 21.25f)
lineTo(10.25f, 18.3125f)
close()
moveTo(9.25f, 19.3438f)
lineTo(9.25f, 21.25f)
lineTo(7.625f, 21.25f)
lineTo(7.5313f, 21.125f)
close()
moveTo(24.125f, 20.5313f)
lineTo(24.5313f, 20.9688f)
lineTo(24.375f, 21.25f)
lineTo(23.9688f, 21.25f)
close()
moveTo(8.1875f, 22.25f)
lineTo(9.25f, 22.25f)
lineTo(9.25f, 24.0938f)
close()
moveTo(10.25f, 22.25f)
lineTo(13.8125f, 22.25f)
lineTo(10.3125f, 25.9688f)
lineTo(10.25f, 25.8438f)
close()
moveTo(15.1875f, 22.25f)
lineTo(16.7813f, 22.25f)
lineTo(20.2813f, 26.0f)
lineTo(11.6563f, 26.0f)
close()
moveTo(18.1563f, 22.25f)
lineTo(22.7188f, 22.25f)
lineTo(22.0938f, 25.25f)
lineTo(21.6563f, 26.0f)
close()
moveTo(23.75f, 22.25f)
lineTo(23.8125f, 22.25f)
lineTo(23.7188f, 22.4063f)
close()
}
}
.build()
return _connectdevelop!!
}
private var _connectdevelop: ImageVector? = null
| 15
|
Kotlin
|
20
| 460
|
651badc4ace0137c5541f859f61ffa91e5242b83
| 5,674
|
compose-icons
|
MIT License
|
app/src/main/java/com/example/blank/ui/recipes/RecipesViewModel.kt
|
olahdome
| 264,719,519
| false
| null |
package com.example.blank.ui.recipes
import co.zsmb.rainbowcake.base.JobViewModel
import javax.inject.Inject
class RecipesViewModel @Inject constructor(
private val recipesPresenter: RecipesPresenter
) : JobViewModel<RecipesViewState>(Loading) {
fun load() = execute {
viewState = RecipesReady(recipesPresenter.getData())
}
}
| 1
|
Kotlin
|
0
| 0
|
cd6f5f95f8aa10a7b38acddc8ad47f381e94fb3e
| 350
|
SmartScaleRainbowCakeKotlin
|
Apache License 2.0
|
src/main/kotlin/com/sourcegraph/cody/edit/actions/EditDismissAction.kt
|
sourcegraph
| 702,947,607
| false
| null |
package com.sourcegraph.cody.edit.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.sourcegraph.cody.edit.FixupService
// This differs from Cancel (and Undo) in a couple ways:
//
// - It doesn't send a message back to the server
// - If the edits are already applied, doesn't Undo
// - Useful outside the context of an active session
//
// So we have our own Action for it.
class EditDismissAction : InlineEditAction() {
override fun performAction(e: AnActionEvent, project: Project) {
FixupService.getInstance(project).getActiveSession()?.dismiss()
}
}
| 262
| null |
9
| 53
|
cea789eef7522940c5d9e7322a65cda6f2097c2d
| 632
|
jetbrains
|
Apache License 2.0
|
src/main/kotlin/sinon/index.kt
|
diklimchuk
| 127,769,288
| false
| null |
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE")
//@file:JsModule("sinon")
package sinon
external interface Event
external interface Document
@JsModule("sinon")
external val Sinon: SinonStatic = definedExternally
| 0
|
Kotlin
|
1
| 5
|
852586eae7c8ca7b7da137e71141348a7d6dbd76
| 360
|
Kotlin-js-di
|
Apache License 2.0
|
src/main/kotlin/sinon/index.kt
|
diklimchuk
| 127,769,288
| false
| null |
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE")
//@file:JsModule("sinon")
package sinon
external interface Event
external interface Document
@JsModule("sinon")
external val Sinon: SinonStatic = definedExternally
| 0
|
Kotlin
|
1
| 5
|
852586eae7c8ca7b7da137e71141348a7d6dbd76
| 360
|
Kotlin-js-di
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_FILE_IMAGE.kt
|
msrd0
| 363,665,023
| false
| null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
import de.msrd0.fontawesome.Style.REGULAR
/** Image File */
object FA_FILE_IMAGE: Icon {
override val name get() = "Image File"
override val unicode get() = "f1c5"
override val styles get() = setOf(SOLID, REGULAR)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M224 128L224 0H48C21.49 0 0 21.49 0 48v416C0 490.5 21.49 512 48 512h288c26.51 0 48-21.49 48-48V160h-127.1C238.3 160 224 145.7 224 128zM96 224c17.67 0 32 14.33 32 32S113.7 288 96 288S64 273.7 64 256S78.33 224 96 224zM318.1 439.5C315.3 444.8 309.9 448 304 448h-224c-5.9 0-11.32-3.248-14.11-8.451c-2.783-5.201-2.479-11.52 .7949-16.42l53.33-80C122.1 338.7 127.1 336 133.3 336s10.35 2.674 13.31 7.125L160 363.2l45.35-68.03C208.3 290.7 213.3 288 218.7 288s10.35 2.674 13.31 7.125l85.33 128C320.6 428 320.9 434.3 318.1 439.5zM256 0v128h128L256 0z"/></svg>"""
REGULAR -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M365.3 93.38l-74.63-74.64C278.6 6.742 262.3 0 245.4 0H64C28.65 0 0 28.65 0 64l.0065 384c0 35.34 28.65 64 64 64H320c35.2 0 64-28.8 64-64V138.6C384 121.7 377.3 105.4 365.3 93.38zM336 448c0 8.836-7.164 16-16 16H64.02c-8.838 0-16-7.164-16-16L48 64.13c0-8.836 7.164-16 16-16h160L224 128c0 17.67 14.33 32 32 32h79.1V448zM215.3 292c-4.68 0-9.051 2.34-11.65 6.234L164 357.8l-11.68-17.53C149.7 336.3 145.3 334 140.7 334c-4.682 0-9.053 2.34-11.65 6.234l-46.67 70c-2.865 4.297-3.131 9.82-.6953 14.37C84.09 429.2 88.84 432 93.1 432h196c5.163 0 9.907-2.844 12.34-7.395c2.436-4.551 2.17-10.07-.6953-14.37l-74.67-112C224.4 294.3 220 292 215.3 292zM128 288c17.67 0 32-14.33 32-32S145.7 224 128 224S96 238.3 96 256S110.3 288 128 288z"/></svg>"""
else -> null
}
}
| 1
|
Kotlin
|
0
| 0
|
35406669ca5592ee3480ccfba51a00d975ac07af
| 2,627
|
fontawesome-kt
|
Apache License 2.0
|
bot/orchestration/src/main/kotlin/ai/tock/bot/orchestration/bot/primary/RunOrchestrationStoryListener.kt
|
hlemorvan
| 282,865,501
| true
|
{"Kotlin": 4585095, "TypeScript": 763534, "HTML": 294788, "CSS": 188613, "JavaScript": 4807, "Shell": 3702}
|
/*
* Copyright (C) 2017/2020 e-voyageurs technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 ai.tock.bot.orchestration.bot.primary
import ai.tock.bot.connector.ConnectorType
import ai.tock.bot.definition.IntentAware
import ai.tock.bot.definition.StoryHandler
import ai.tock.bot.definition.StoryHandlerListener
import ai.tock.bot.engine.BotBus
import ai.tock.bot.orchestration.orchestrator.OrchestratorService
import ai.tock.bot.orchestration.shared.AskEligibilityToOrchestratorRequest
import ai.tock.bot.orchestration.shared.ResumeOrchestrationRequest
import ai.tock.bot.orchestration.shared.OrchestrationMetaData
import ai.tock.bot.orchestration.shared.OrchestrationTargetedBot
import ai.tock.bot.orchestration.shared.AvailableOrchestrationResponse
import ai.tock.bot.orchestration.shared.EligibilityOrchestrationResponse
import ai.tock.bot.orchestration.shared.OrchestrationResponse
import ai.tock.bot.orchestration.shared.SecondaryBotAction
import mu.KotlinLogging
/**
* Should pass control to orchestrator ?
*/
class RunOrchestrationStoryListener(
private val configuration: PrimaryBotConfiguration,
private val orchestrator: OrchestratorService,
private val orchestrationRepository: OrchestrationRepository = MongoOrchestrationRepository,
private val orchestrationEnabled: (() -> Boolean) = { true }
) : StoryHandlerListener {
private val logger = KotlinLogging.logger {}
override fun startAction(botBus: BotBus, handler: StoryHandler): Boolean = with(botBus) {
val currentOrchestration = orchestrationRepository.get(action.playerId)
return when {
currentOrchestration != null -> resumeOrchestration(currentOrchestration)
intent.inStartOrchestrationList() && orchestrationEnabled() -> startOrchestration()
else -> true // no need for orchestration, let's continue on this bot
}
}
private fun BotBus.startOrchestration(): Boolean {
logger.info { "Try to start an orchestration for intent ${intent?.wrappedIntent()?.name ?: "???"}" }
val botAction: SecondaryBotAction? = SecondaryBotAction.from(action)
if (botAction == null) {
logger.info { "Failed to start orchestration caused by an unhandled Tock action ${action.javaClass.name}" }
return true
}
return when (val eligibility = callOrchestrationForEligibility()) {
is EligibilityOrchestrationResponse -> handleEligibleOrchestration(eligibility, botAction)
else -> {
logger.info { "Fail to start an orchestration caused by a ${eligibility?.javaClass?.name?:"null"} eligibility from the orchestrator" }
true
}
}
}
private fun BotBus.handleEligibleOrchestration(
eligibility: EligibilityOrchestrationResponse,
botAction: SecondaryBotAction
): Boolean {
logger.info { "Eligibility with ${eligibility.targetBot} : ${eligibility.botResponse.indice}" }
val response = callOrchestrationForFirstAction(eligibility, botAction)
return when (response) {
is AvailableOrchestrationResponse -> {
logger.info { "Start an orchestration with ${response.targetBot}" }
orchestrationRepository.create(action.playerId, response.botResponse.metaData, response.targetBot)
send("Pour vous répondre je passe la main à mon collègue ${response.targetBot.botLabel} !")
response.botResponse.actions.forEach {
send(it.toAction(response.botResponse.metaData))
}
end()
false
}
else -> {
logger.info { "Fail to start an orchestration caused by a ${response.javaClass.name ?: "null"} response from the orchestrator" }
true
}
}
}
private fun BotBus.callOrchestrationForFirstAction(
eligibility: EligibilityOrchestrationResponse,
botAction: SecondaryBotAction
): OrchestrationResponse {
return orchestrator.resumeOrchestration(
ResumeOrchestrationRequest(
targetBot = eligibility.targetBot,
action = botAction,
metadata = OrchestrationMetaData(playerId = userId, applicationId = applicationId, recipientId = botId)
)
)
}
private fun BotBus.callOrchestrationForEligibility(): OrchestrationResponse? {
return configuration.getOrchestrationData(this)?.let { data ->
orchestrator.askOrchestration(
AskEligibilityToOrchestratorRequest(
eligibleTargetBots = targetConnectorType.getEligibleBots(),
data = data,
action = SecondaryBotAction.from(action),
metadata = OrchestrationMetaData(playerId = userId, applicationId = applicationId, recipientId = botId)
)
)
}
}
private fun BotBus.resumeOrchestration(orchestration: Orchestration): Boolean {
logger.info { "Try to resume the orchestration to ${orchestration.targetBot}" }
if (intent.inStopOrchestrationList()) {
logger.info { "End of the orchestration caused by the ${intent?.wrappedIntent()?.name ?: "???"} intent" }
orchestrationRepository.end(orchestration.playerId)
send("Your conversation with ${orchestration.targetBot.botLabel} is now over.")
handleAndSwitchStory(configuration.comebackStory)
return false
}
if (intent.inNoOrchestrationList()) {
logger.info { "End of the orchestration caused by the ${intent?.wrappedIntent()?.name ?: "???"} intent" }
orchestrationRepository.end(orchestration.playerId)
send("Your conversation with ${orchestration.targetBot.botLabel} is now over.")
return true
}
val botAction: SecondaryBotAction? = SecondaryBotAction.from(action)
if (botAction == null) {
logger.info { "End of the orchestration caused by an unhandled Tock action ${action.javaClass.name}" }
orchestrationRepository.end(orchestration.playerId)
send("Damn, the conversation with ${orchestration.targetBot.botLabel} was interrupted.")
return true
}
val response = orchestrator.resumeOrchestration(
ResumeOrchestrationRequest(
targetBot = orchestration.targetBot,
action = botAction,
metadata = OrchestrationMetaData(playerId = userId, applicationId = applicationId, recipientId = botId)
)
)
return when (response) {
is AvailableOrchestrationResponse -> {
logger.info { "Resume the orchestration to ${orchestration.targetBot}" }
response.botResponse.actions.forEach {
orchestrationRepository.update(orchestration.id, it)
send(it.toAction(response.botResponse.metaData))
}
end()
false
}
else -> {
logger.info { "End of the orchestration caused by a ${response.javaClass.name} response from the orchestrator" }
orchestrationRepository.end(orchestration.playerId)
if (orchestration.targetBot.fallbackStory != null) {
handleAndSwitchStory(orchestration.targetBot.fallbackStory)
} else {
end("Damn, the conversation with ${orchestration.targetBot.botLabel} was interrupted.")
handleAndSwitchStory(configuration.comebackStory)
}
false
}
}
}
private fun ConnectorType.getEligibleBots(): List<OrchestrationTargetedBot> = configuration.getEligibleTargetBots(this)
private fun IntentAware?.inStartOrchestrationList(): Boolean = this?.wrappedIntent() in configuration.startOrchestrationIntentList
private fun IntentAware?.inStopOrchestrationList(): Boolean = this?.wrappedIntent() in configuration.stopOrchestrationIntentList
private fun IntentAware?.inNoOrchestrationList(): Boolean = this?.wrappedIntent() in configuration.noOrchestrationIntentList
}
| 0
| null |
0
| 0
|
c179ba5a48a319375726feb4f2ff2a6113a51fa5
| 8,828
|
tock
|
Apache License 2.0
|
mediapickerk/src/main/java/api/luisangeldd/mediapicker/k/MediaPicker.kt
|
luisangeldd
| 697,934,501
| false
|
{"Kotlin": 89429}
|
package api.luisangeldd.mediapicker.h
import android.graphics.Bitmap
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.IconButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.BrokenImage
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Image
import androidx.compose.material.icons.rounded.PlayCircle
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
import androidx.compose.ui.unit.toIntRect
import androidx.compose.ui.util.lerp
import androidx.hilt.navigation.compose.hiltViewModel
import api.luisangeldd.mediapicker.h.data.model.Media
import api.luisangeldd.mediapicker.h.data.model.MediaUserV0
import api.luisangeldd.mediapicker.h.utils.IMAGE
import api.luisangeldd.mediapicker.h.utils.StateRequest
import api.luisangeldd.mediapicker.h.utils.StatusRequest
import api.luisangeldd.mediapicker.h.utils.VIDEO
import api.luisangeldd.mediapicker.h.utils.permissionsToRequest
import api.luisangeldd.mediapicker.h.utils.shimmerEffect
import coil.compose.AsyncImage
import coil.request.ImageRequest
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
/**
* <a href="https://m3.material.io/components/bottom-sheets/overview" class="external" target="_blank">Media Picker</a>.
*
* The media picker is used as an alternative, to the default file manager of the mobile device,
* it provides the content of the device such as Images and Videos, it recovers the bitmaps of the
* files and displays them in a LazyGrid allowing them to be selected and displayed the selected
* content in a Carousel. Like dialog boxes, and modal bottom sheets, the media picker, appears
* in front of the application content, disables all other functions of the application when it
* appears and remains on the screen until confirmed, dismissed or a required action is performed.
*
* A simple example of a modal bottom sheet looks like this:
*
* @param getMedia returns a list of Media type objects which allows recovering the Uri and File of the selected files.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MediaPicker(
getMedia: (List<MediaUser>) -> Unit
){
val mediaViewModel : MediaViewModel = hiltViewModel()
val isGranted = mediaViewModel.isGranted
val media by mediaViewModel.media.collectAsState()
val stateRequestMedia by mediaViewModel.stateRequestMedia.collectAsState()
val statusRequestMedia by mediaViewModel.statusRequestMedia.collectAsState()
val mediaSelected by mediaViewModel.mediaSelected.collectAsState()
val mediaSelectedUser by mediaViewModel.mediaSelectedUser.collectAsState()
val scope = rememberCoroutineScope()
val state = rememberLazyGridState()
val (isSelectedMode, onSelectedMode) = rememberSaveable { mutableStateOf(false) }
val index: MutableState<Set<Int>> = rememberSaveable { mutableStateOf(emptySet()) }
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
var edgeToEdgeEnabled by remember { mutableStateOf(false) }
val bottomSheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = true
)
val multiplePermissionResultLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestMultiplePermissions(),
onResult = { perms ->
if (perms[permissionsToRequest[0]] == true && perms[permissionsToRequest[1]] == true) {
scope.launch {
openBottomSheet = true
}
mediaViewModel.onPermissionResult(
isGranted = true
)
}
}
)
LaunchedEffect(key1 = mediaSelectedUser, block = {
getMedia(mediaSelectedUser)
})
Column (modifier = Modifier.fillMaxWidth() ){
when (mediaSelected.isNotEmpty()){
true ->{
MediaCarousel(mediaSelected) {
scope.launch {
index.value -= it
val data = mutableListOf<MediaUserV0>()
index.value.forEach {
data.add(MediaUserV0(item =it,media = media[it]))
}.let {
mediaViewModel.setMedia(data)
}
}
}
}
false ->{
}
}
LaunchButton {
multiplePermissionResultLauncher.launch(permissionsToRequest)
}
}
if (openBottomSheet) {
val windowInsets = if (edgeToEdgeEnabled)
WindowInsets(0) else BottomSheetDefaults.windowInsets
ModalBottomSheet(
onDismissRequest = { openBottomSheet = false },
sheetState = bottomSheetState,
windowInsets = windowInsets
) {
Scaffold(
topBar = {
TopBarMediaViewer(
title = "Media",
navIcon = {
scope.launch { bottomSheetState.hide() }.invokeOnCompletion {
if (!bottomSheetState.isVisible) {
openBottomSheet = false
}
if (mediaSelected.isEmpty()){
index.value = emptySet()
}
else {
if (mediaSelected.size != index.value.size){
//index.value = indexAtSelect
}
}
}
},
action = {
scope.launch {
index.value = emptySet()
mediaViewModel.setMedia(emptyList())
}
},
isNotEmpty = index.value.isNotEmpty()
)
},
content = { paddingInter ->
Box(Modifier.padding(paddingInter)){
if (isGranted.value){
when(stateRequestMedia){
StateRequest.IDLE -> {
if(media.isEmpty()) mediaViewModel.getMedia()
}
StateRequest.START -> {
GridOfMediaThumbnailLoad()
}
StateRequest.END -> {
when(statusRequestMedia){
StatusRequest.IDLE -> {}
StatusRequest.EMPTY -> {}
StatusRequest.NOT_EMPTY ->{
GridOfMediaThumbnail(
thumbnail = { uri, id, mime ->
mediaViewModel.getThumbnail(uri,id,mime)
},
media = media,
onSelectionMode = onSelectedMode,
itemsSelected = { data -> index.value = data},
state = state,
userScrollEnabled = true,
selectedIds = index
)
}
}
}
}
}
}
},
bottomBar = {
if (isSelectedMode) {
BottomAppBar (
actions = {
Box(modifier = Modifier.fillMaxWidth(), Alignment.CenterEnd) {
FilledTonalButton(onClick = {
scope.launch { bottomSheetState.hide() }.invokeOnCompletion {
if (!bottomSheetState.isVisible) {
openBottomSheet = false
}
val data = mutableListOf<MediaUserV0>()
index.value.forEach {
data.add(MediaUserV0(item =it,media = media[it]))
}.let {
mediaViewModel.setMedia(data)
}
}
}) {
Text(modifier = Modifier.padding(start = 5.dp),text = "Añadir (${index.value.size})")
}
}
},
contentPadding = PaddingValues(10.dp)
)
}
}
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TopBarMediaViewer(
title: String,
navIcon: () -> Unit,
action: () -> Unit,
isNotEmpty: Boolean
){
Column(horizontalAlignment = Alignment.CenterHorizontally) {
CenterAlignedTopAppBar(
navigationIcon = {
IconButton(onClick = navIcon) {
Icon(imageVector = Icons.Filled.Close, contentDescription = null)
}
},
title = {
Text(text = title)
},
actions = {
if (isNotEmpty) {
IconButton(onClick = action) {
Icon(imageVector = Icons.Filled.Delete, contentDescription = null)
}
}
}
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MediaCarousel(media:List<MediaUserV0>, removeItem: (Int) -> Unit){
val pagerState = rememberPagerState(initialPage = 0, initialPageOffsetFraction = 0f){media.size}
HorizontalPager(
contentPadding = PaddingValues(horizontal = 100.dp),
state = pagerState,
) { page ->
Box (
modifier = Modifier
.fillMaxWidth()
.graphicsLayer {
val pageOffset = (
(pagerState.currentPage - page) + pagerState
.currentPageOffsetFraction
).absoluteValue
lerp(
start = 0.85f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
).also { scale ->
scaleX = scale
scaleY = scale
}
alpha = lerp(
start = 0.5f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
)
},
contentAlignment = Alignment.Center
){
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(media[page].media.uriMedia)
.crossfade(true)
.build(),
placeholder = painterResource(R.drawable.image_load),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(200.dp)
)
Box (modifier = Modifier.size(200.dp), contentAlignment = Alignment.TopEnd){
FilledTonalIconButton(
modifier = Modifier
.size(40.dp)
.graphicsLayer {
val pageOffset = (
(pagerState.currentPage - page) + pagerState
.currentPageOffsetFraction
).absoluteValue
lerp(
start = 0.85f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
).also { scale ->
scaleX = scale
scaleY = scale
}
}
,
onClick = { removeItem(media[page].item) }
) {
Icon(
Icons.Rounded.Close,
tint = MaterialTheme.colorScheme.primary,
contentDescription = null
)
}
}
}
}
}
@Composable
private fun LaunchButton(launch: () -> Unit){
Box (modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center){
FilledTonalIconButton(
modifier = Modifier.size(100.dp),
onClick = launch
) {
Icon(modifier = Modifier.size(100.dp),imageVector = Icons.Rounded.Add, contentDescription = null)
}
}
}
@Composable
private fun GridOfMediaThumbnailLoad(){
LazyVerticalGrid(
columns = GridCells.Fixed( 3 ),
content = {
items(18){
Surface(
modifier = Modifier
.aspectRatio(1f)
.padding(3.dp),
tonalElevation = 3.dp
) {
Box(modifier = Modifier.shimmerEffect())
}
}
}
)
}
@Composable
private fun GridOfMediaThumbnail(
thumbnail: (Uri, Long, String) -> Bitmap,
media:List<Media>,
onSelectionMode: (Boolean) -> Unit,
itemsSelected: (Set<Int>) -> Unit,
state: LazyGridState,
userScrollEnabled: Boolean,
selectedIds: MutableState<Set<Int>> = rememberSaveable { mutableStateOf(emptySet()) }
){
val inSelectionMode by remember { derivedStateOf { selectedIds.value.isNotEmpty() } }
val autoScrollSpeed = remember { mutableFloatStateOf(0f) }
val (isDrag,onDrag) = rememberSaveable { mutableStateOf(false) }
onSelectionMode(selectedIds.value.isNotEmpty())
LaunchedEffect(autoScrollSpeed.floatValue) {
if (autoScrollSpeed.floatValue != 0f) {
while (isActive) {
state.scrollBy(autoScrollSpeed.floatValue)
delay(10)
}
}
}
itemsSelected(selectedIds.value)
LazyVerticalGrid(
columns = GridCells.Fixed( 3 ),
modifier = Modifier.photoGridDragHandler(
lazyGridState = state,
haptics = LocalHapticFeedback.current,
selectedIds = selectedIds,
autoScrollSpeed = autoScrollSpeed,
autoScrollThreshold = with(LocalDensity.current) { 40.dp.toPx() },
onDragStartListen = onDrag
),
state = state,
contentPadding = PaddingValues(horizontal = 3.dp),
userScrollEnabled = userScrollEnabled,
content = {
items(media.size, key = { it }){item ->
val selected by remember { derivedStateOf { selectedIds.value.contains(item) } }
MediaItem(
thumbnail = { thumbnail(media[item].uriMedia,media[item].idMedia,media[item].mimeType) },
inSelectionMode,
selected,
media[item].mimeType.split('/')[0],
Modifier
.then(
if (inSelectionMode) {
if (isDrag) {
Modifier
} else {
Modifier.toggleable(
value = selected,
interactionSource = remember { MutableInteractionSource() },
indication = null, // do not show a ripple
onValueChange = {
if (it) {
selectedIds.value += item
} else {
selectedIds.value -= item
}
}
)
}
} else {
Modifier.toggleable(
value = selected,
interactionSource = remember { MutableInteractionSource() },
indication = null, // do not show a ripple
onValueChange = {
if (it) {
selectedIds.value += item
} else {
selectedIds.value -= item
}
}
)
}
)
)
}
}
)
}
@Composable
private fun MediaItem(
thumbnail: () -> Bitmap,
inSelectionMode: Boolean,
selected: Boolean,
mime: String,
modifier: Modifier = Modifier
) {
Surface(
modifier = modifier
.aspectRatio(1f)
.padding(3.dp),
tonalElevation = 3.dp
) {
Box (contentAlignment = Alignment.Center) {
Image(
bitmap = thumbnail().asImageBitmap(),
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.matchParentSize(),
contentScale = ContentScale.Crop
)
if (inSelectionMode) {
Box(modifier = Modifier.fillMaxSize(),contentAlignment = Alignment.TopEnd) {
if (selected) {
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(3.dp)
Box(
Modifier
.fillMaxSize()
.background(Color.Black.copy(0.2f)))
Icon(
Icons.Filled.CheckCircle,
tint = MaterialTheme.colorScheme.primary,
contentDescription = null,
modifier = Modifier
.padding(4.dp)
.border(2.dp, bgColor, CircleShape)
.clip(CircleShape)
.background(bgColor)
)
} else {
Icon(
Icons.Filled.RadioButtonUnchecked,
tint = Color.White.copy(alpha = 0.7f),
contentDescription = null,
modifier = Modifier.padding(6.dp)
)
}
}
}
Icon(
modifier = Modifier.size(48.dp),
imageVector = when (mime){
IMAGE -> {
Icons.Rounded.Image
}
VIDEO -> {
Icons.Rounded.PlayCircle
}
else -> {
Icons.Rounded.BrokenImage
}
},
contentDescription = null
)
}
}
}
private fun Modifier.photoGridDragHandler(
lazyGridState: LazyGridState,
haptics: HapticFeedback,
selectedIds: MutableState<Set<Int>>,
autoScrollSpeed: MutableState<Float>,
autoScrollThreshold: Float,
onDragStartListen: (Boolean) -> Unit,
) = pointerInput(Unit) {
fun LazyGridState.gridItemKeyAtPosition(hitPoint: Offset): Int? =
layoutInfo.visibleItemsInfo.find { itemInfo ->
itemInfo.size.toIntRect().contains(hitPoint.round() - itemInfo.offset)
}?.key as? Int
var initialKey: Int? = null
var currentKey: Int? = null
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
onDragStartListen(true)
lazyGridState.gridItemKeyAtPosition(offset)?.let { key ->
if (!selectedIds.value.contains(key)) {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
initialKey = key
currentKey = key
selectedIds.value += key
}
}
},
onDragCancel = { initialKey = null; autoScrollSpeed.value = 0f ; onDragStartListen(false) },
onDragEnd = { initialKey = null; autoScrollSpeed.value = 0f; onDragStartListen(false) },
onDrag = { change, _ ->
if (initialKey != null) {
val distFromBottom =
lazyGridState.layoutInfo.viewportSize.height - change.position.y
val distFromTop = change.position.y
autoScrollSpeed.value = when {
distFromBottom < autoScrollThreshold -> autoScrollThreshold - distFromBottom
distFromTop < autoScrollThreshold -> -(autoScrollThreshold - distFromTop)
else -> 0f
}
lazyGridState.gridItemKeyAtPosition(change.position)?.let { key ->
if (currentKey != key) {
selectedIds.value = selectedIds.value
.minus(initialKey!!..currentKey!!)
.minus(currentKey!!..initialKey!!)
.plus((initialKey!!..key))
.plus((key..initialKey!!))
currentKey = key
}
}
}
}
)
}
| 0
|
Kotlin
|
0
| 0
|
9268867fd03ded31cb3484fbd580add934118112
| 26,408
|
MediaPicker
|
Apache License 2.0
|
src/main/kotlin/venus/riscv/formats/MULHUForm.kt
|
hiporox
| 98,627,941
| true
|
{"Kotlin": 124095, "HTML": 9018, "JavaScript": 2502, "CSS": 840}
|
package venus.riscv.formats
import venus.riscv.InstructionFormat
import venus.riscv.FieldEqual
import venus.riscv.InstructionField
val MULHUForm = InstructionFormat(listOf(
FieldEqual(InstructionField.OPCODE, 0b0110011),
FieldEqual(InstructionField.FUNCT3, 0b011),
FieldEqual(InstructionField.FUNCT7, 0b0000001)
))
| 0
|
Kotlin
|
0
| 0
|
606d6f8185b1646b5f5f9f512a1c702994e355b7
| 329
|
venus
|
MIT License
|
app/src/main/java/com/harvard/art/museums/data/pojo/Info.kt
|
pvulkov
| 190,898,492
| false
| null |
package com.harvard.art.museums.data.pojo
data class Info(
val page: Int,
val pages: Int,
val totalrecords: Int,
val totalrecordsperquery: Int,
var cur: String? = null,
val prev: String? = null,
val next: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
74d4d681fe8f276438c1a4cfdd332476f91b218d
| 279
|
Harvard-Art-Museums
|
Apache License 2.0
|
src/main/kotlin/tech/gdragon/listener/EventListener.kt
|
guacamoledragon
| 96,600,559
| false
|
{"Kotlin": 185022, "Clojure": 16441, "Shell": 5769, "HTML": 4662, "Just": 2918, "Dockerfile": 1530, "Makefile": 785, "Batchfile": 629}
|
package tech.gdragon.listener
import dev.minn.jda.ktx.messages.send
import io.github.oshai.kotlinlogging.KotlinLogging
import io.github.oshai.kotlinlogging.withLoggingContext
import io.opentelemetry.api.trace.StatusCode
import io.opentelemetry.api.trace.Tracer
import net.dv8tion.jda.api.entities.channel.ChannelType
import net.dv8tion.jda.api.entities.emoji.Emoji
import net.dv8tion.jda.api.events.guild.GuildJoinEvent
import net.dv8tion.jda.api.events.guild.GuildLeaveEvent
import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent
import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent
import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
import net.dv8tion.jda.api.requests.RestAction
import org.jetbrains.exposed.sql.transactions.transaction
import org.koin.core.component.KoinComponent
import tech.gdragon.BotUtils
import tech.gdragon.BotUtils.TRIGOMAN
import tech.gdragon.api.pawa.Pawa
import tech.gdragon.commands.InvalidCommand
import tech.gdragon.commands.handleCommand
import tech.gdragon.data.Datastore
import tech.gdragon.db.asyncTransaction
import tech.gdragon.db.dao.Guild
import tech.gdragon.db.dao.Recording
import tech.gdragon.db.now
import tech.gdragon.discord.message.ErrorEmbed
import tech.gdragon.discord.message.RecordingReply
import tech.gdragon.discord.message.RequestAccessReply
import tech.gdragon.koin.getStringProperty
class EventListener(val pawa: Pawa) : ListenerAdapter(), KoinComponent {
private val logger = KotlinLogging.logger {}
private val website: String = getKoin().getProperty("BOT_WEBSITE", "http://localhost:8080/")
override fun onCommandAutoCompleteInteraction(event: CommandAutoCompleteInteractionEvent) {
if (event.name == "recover" && event.focusedOption.name == "session-id") {
val partialSessionId = event.focusedOption.value
val choices = transaction {
val limit = 25
if (TRIGOMAN == event.user.idLong) {
Recording.findIdLike("$partialSessionId%", null, limit)
} else {
Recording.findIdLike("$partialSessionId%", event.guild!!.idLong, limit)
}.map { r -> r.id.value }
}
event
.replyChoiceStrings(choices)
.queue(null) {
logger.warn {
"Replying to `/recover` autocomplete request took longer than expected."
}
}
}
}
override fun onMessageContextInteraction(event: MessageContextInteractionEvent) {
if ((pawa.isStandalone || event.user.idLong == TRIGOMAN) && event.name == "Recover Recording") {
event.target.run {
val sessionIds = BotUtils.findSessionID(contentRaw)
val dataDirectory = getKoin().getStringProperty("BOT_DATA_DIR")
val datastore = getKoin().get<Datastore>()
val failedSessionIds = mutableSetOf<String>()
author
.openPrivateChannel()
.flatMap { channel ->
event.deferReply().queue()
val actions = sessionIds
.toSet()
.mapNotNull {
val recording = pawa.recoverRecording(dataDirectory, datastore, it)
// Side-effect for later
if (recording == null) {
failedSessionIds.add(it)
}
recording
}
.map { RecordingReply(it, pawa.config.appUrl).message }
.map(channel::sendMessage)
RestAction.allOf(actions + addReaction(Emoji.fromUnicode("👀")))
}
.queue({
val recovered = (sessionIds - failedSessionIds).joinToString("\n") { s -> ":white_check_mark: `$s`" }
val unrecovered = failedSessionIds.joinToString("\n") { s -> ":x: `$s`" }
val message = if (it.isEmpty()) {
addReaction(Emoji.fromUnicode("❌")).queue()
"No recordings found."
} else {
"""
${author.asMention} Please check your DMs :bow:
$recovered
$unrecovered
""".trimIndent()
}
event
.hook
.send(message)
.queue()
addReaction(Emoji.fromUnicode("✅")).queue()
},
{
event
.hook
.send("Failed to DM ${author.asMention} about recovered recordings.")
.queue()
})
}
} else {
val errorEmbed = ErrorEmbed(
"You cannot use \"Recover Recording\" command.",
"Join the support server and post your SessionID."
)
event
.reply(errorEmbed.message)
.setEphemeral(true)
.queue()
}
}
override fun onGuildJoin(event: GuildJoinEvent) {
withLoggingContext("guild" to event.guild.name) {
val guild = event.guild
asyncTransaction {
Guild
.findOrCreate(guild.idLong, guild.name)
.also {
it.active = true
}
BotUtils.updateActivity(event.guild)
}
logger.info { "Joined new server '${guild.name}', connected to ${event.jda.guilds.size} guilds." }
}
}
override fun onGuildLeave(event: GuildLeaveEvent) {
withLoggingContext("guild" to event.guild.name) {
asyncTransaction {
Guild
.findById(event.guild.idLong)
?.let {
it.active = false
it.unjoinedOn = now()
}
}
logger.info { "Server '${event.guild.name}' unjoined, connected to ${event.jda.guilds.size} guilds." }
}
}
fun onGuildVoiceJoin(event: GuildVoiceUpdateEvent) {
withLoggingContext("guild" to event.guild.name) {
val user = event.member.user
event.channelJoined?.let { voiceChannel ->
logger.debug { "${event.guild.name}#${voiceChannel.name} - ${user.name} joined voice channel" }
if (BotUtils.isSelfBot(user)) {
logger.debug { "${event.guild.name}#${voiceChannel.name} - ${user.name} is self-bot" }
return
}
// Update activity
BotUtils.updateActivity(event.guild)
if (pawa.isStandalone) {
BotUtils.autoRecord(pawa, event.guild, voiceChannel)
}
}
}
}
fun onGuildVoiceLeave(event: GuildVoiceUpdateEvent) {
withLoggingContext("guild" to event.guild.name) {
event.channelLeft?.let { voiceChannel ->
logger.debug {
"${event.guild.name}#${voiceChannel.name} - ${event.member.effectiveName} left voice channel"
}
if (BotUtils.isSelfBot(event.member.user).not()) {
val save = pawa.autoSave(event.guild.idLong)
BotUtils.autoStop(event.guild, voiceChannel, save)
}
}
}
}
fun onGuildVoiceMove(event: GuildVoiceUpdateEvent) {
withLoggingContext("guild" to event.guild.name) {
val user = event.member.user
val voiceChannelJoined = event.channelJoined
val voiceChannelLeft = event.channelLeft
if (voiceChannelJoined != null && voiceChannelLeft != null) {
logger.debug { "${event.guild.name}#${voiceChannelLeft.name} - ${user.name} left voice channel" }
logger.debug { "${event.guild.name}#${voiceChannelJoined.name} - ${user.name} joined voice channel" }
// Update activity
BotUtils.updateActivity(event.guild)
if (BotUtils.isSelfBot(user).not()) {
val save = pawa.autoSave(event.guild.idLong)
BotUtils.autoStop(event.guild, voiceChannelLeft, save)
if (pawa.isStandalone) {
BotUtils.autoRecord(pawa, event.guild, voiceChannelJoined)
}
}
}
}
}
override fun onGuildVoiceUpdate(event: GuildVoiceUpdateEvent) {
when {
// Joining a channel without bot being connected
event.channelLeft == null -> onGuildVoiceJoin(event)
// Leaving a channel and connecting to no channel == leave
event.channelLeft != null && event.voiceState.channel == null -> onGuildVoiceLeave(event)
// Leaving a channel and connecting to another == move
event.channelLeft != null && event.voiceState.channel != null -> onGuildVoiceMove(event)
else -> super.onGuildVoiceUpdate(event)
}
}
fun onGuildMessageReceived(event: MessageReceivedEvent) {
val tracer = getKoin().get<Tracer>()
val span = tracer.spanBuilder("Event Message Received").startSpan()
span.run {
setAttribute("discord-user", event.author.idLong)
setAttribute("guild", event.guild.idLong)
setAttribute("text-channel", event.channel.idLong)
}
span.makeCurrent().use {
event.member?.let {
if (BotUtils.isSelfBot(it.user)) {
span.end()
return
}
}
val prefix = try {
BotUtils.getPrefix(event.guild)
} catch (e: Exception) {
span.recordException(e)
span.setStatus(StatusCode.ERROR)
logger.error(e) {
"Attempting to fetch prefix for ${event.guild.idLong}, failed!"
}
span.end()
return
}
withLoggingContext("guild" to event.guild.name, "text-channel" to event.channel.name) {
val rawContent = event.message.contentDisplay.lowercase()
val inMaintenance = getKoin().getProperty("BOT_MAINTENANCE", "false").toBoolean()
val defaultChannel = BotUtils.defaultTextChannel(event.guild) ?: event.channel
val hasPrefix = rawContent.startsWith(prefix)
if (hasPrefix && inMaintenance) {
BotUtils.sendMessage(
defaultChannel,
":poop: _Currently running an update...\n\nIf you have any questions please visit the support server: ${website}_"
)
logger.warn { "Trying to use while running an update" }
} else if (hasPrefix) {
try {
handleCommand(span, event, pawa, prefix, rawContent)
// Update activity
BotUtils.updateActivity(event.guild)
} catch (e: InvalidCommand) {
BotUtils.sendMessage(defaultChannel, ":no_entry_sign: _Usage: `${e.usage(prefix)}`_")
logger.warn { "[$rawContent] ${e.reason}" }
}
}
}
}
span.end()
}
override fun onModalInteraction(event: ModalInteractionEvent) {
if (event.modalId == "request-access") {
val request = event.getValue("request-body")?.asString.orEmpty()
val sessionId = event.getValue("session-id")?.asString.orEmpty()
event.jda
.openPrivateChannelById(TRIGOMAN)
.flatMap { channel ->
val requestReply = RequestAccessReply(event.user, request, sessionId)
channel.sendMessageEmbeds(requestReply.embed)
}
.queue()
event
.reply("Your request has been submitted!\nJoin support server https://discord.gg/gkvsNw8")
.setEphemeral(true)
.queue()
}
}
private fun onPrivateMessageReceived(event: MessageReceivedEvent) {
if (event.author.isBot.not()) {
val message = """
For more information on ${event.jda.selfUser.asMention}, please visit https://www.pawa.im.
""".trimIndent()
event
.channel
.sendMessage(message)
.queue()
}
}
override fun onMessageReceived(event: MessageReceivedEvent) {
when {
event.isFromType(ChannelType.PRIVATE) -> onPrivateMessageReceived(event)
event.isFromGuild -> onGuildMessageReceived(event)
else -> super.onMessageReceived(event)
}
}
/**
* Always add recording prefix when recording and if possible.
*/
override fun onGuildMemberUpdateNickname(event: GuildMemberUpdateNicknameEvent) {
if (BotUtils.isSelfBot(event.user)) {
if (event.guild.audioManager.isConnected) {
logger.debug {
"${event.guild}#: Attempting to change nickname from ${event.oldNickname} -> ${event.newNickname}"
}
BotUtils.recordingStatus(event.member, true)
}
}
}
override fun onSlashCommandInteraction(event: SlashCommandInteractionEvent) {
val commandName = event.interaction.name
event.guild?.let(BotUtils::updateActivity)
withLoggingContext("command" to commandName) {
tech.gdragon.commands.logger.info {
"Executing command: $commandName"
}
super.onSlashCommandInteraction(event)
}
}
}
| 5
|
Kotlin
|
18
| 45
|
b8c0377b5e00a4a9f850dec0727dc880b314d56a
| 12,648
|
throw-voice
|
Apache License 2.0
|
app/src/main/java/com/example/cadastro/data/PessoaRepository.kt
|
daniel6rufino
| 862,129,124
| false
|
{"Kotlin": 17196}
|
package com.example.cadastro.data
import com.example.cadastro.data.Pessoa
import com.example.cadastro.data.PessoaDao
import kotlinx.coroutines.flow.Flow
class PessoaRepository(private val pessoaDao: PessoaDao) {
val todasAsPessoas: Flow<List<Pessoa>> = pessoaDao.getAllPessoas()
suspend fun inserir(pessoa: Pessoa) {
pessoaDao.insert(pessoa)
}
suspend fun deletar(pessoa: Pessoa) {
pessoaDao.delete(pessoa)
}
suspend fun atualizar(pessoa: Pessoa) {
pessoaDao.update(pessoa)
}
}
| 0
|
Kotlin
|
0
| 0
|
6b85e650472cc7e5ab4a48a5f32c42c395956121
| 536
|
APP_Cadastro_Pessoa_Completo
|
Apache License 2.0
|
file/src/main/java/com/zj/file/util/ZToastUtils.kt
|
zhujiang521
| 441,401,448
| false
|
{"Kotlin": 241982, "Java": 1900}
|
package com.zj.file.util
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import android.widget.Toast
private var mToast: Toast? = null
fun View.showToast(msg: String) {
context.showToast(msg)
}
fun View.showToast(resId: Int) {
context.showToast(resId)
}
fun Context?.showToast(text: String?) {
if (this == null) return
if (!TextUtils.isEmpty(text)) {
if (Thread.currentThread() === Looper.getMainLooper().thread) {
showToast(this, text, Toast.LENGTH_SHORT)
} else {
Handler(this.mainLooper).post { showToast(this, text, Toast.LENGTH_SHORT) }
}
}
}
fun Context?.showToast(resId: Int) {
if (this == null) return
if (Thread.currentThread() === Looper.getMainLooper().thread) {
showToast(this, resId, Toast.LENGTH_SHORT)
} else {
Handler(this.mainLooper).post { showToast(this, resId, Toast.LENGTH_SHORT) }
}
}
fun Context?.showLongToast(text: String?) {
if (this == null) return
if (!TextUtils.isEmpty(text)) {
if (Thread.currentThread() === Looper.getMainLooper().thread) {
showToast(this, text, Toast.LENGTH_LONG)
} else {
Handler(this.mainLooper).post { showToast(this, text, Toast.LENGTH_LONG) }
}
}
}
fun Context?.showLongToast(resId: Int) {
if (this == null) return
if (Thread.currentThread() === Looper.getMainLooper().thread) {
showToast(this, resId, Toast.LENGTH_LONG)
} else {
Handler(this.mainLooper).post { showToast(this, resId, Toast.LENGTH_LONG) }
}
}
private fun showToast(context: Context?, text: String?, duration: Int) {
if (TextUtils.isEmpty(text)) return
cancelToast()
if (mToast == null) {
mToast = Toast.makeText(context, null as CharSequence?, duration)
}
mToast?.apply {
setText(text)
this.duration = duration
show()
}
}
private fun showToast(context: Context?, res: Int, duration: Int) {
cancelToast()
if (mToast == null) {
mToast = Toast.makeText(context, res, duration)
} else {
mToast?.setText(res)
mToast?.duration = duration
}
mToast?.show()
}
fun cancelToast() {
mToast?.cancel()
}
| 0
|
Kotlin
|
1
| 3
|
39350e08ee757cd3d1b7fe00cf5adeb2262c6645
| 2,306
|
ZFileManager
|
Apache License 2.0
|
app/src/main/java/cz/cvut/fukalhan/main/challenges/fragment/ChallengesFragment.kt
|
fukalhan
| 339,833,283
| false
| null |
package cz.cvut.fukalhan.main.challenges.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.google.android.material.tabs.TabLayoutMediator
import cz.cvut.fukalhan.R
import cz.cvut.fukalhan.main.challenges.adapter.ChallengesAdapter
import cz.cvut.fukalhan.repository.challenges.state.ChallengeState
import kotlinx.android.synthetic.main.fragment_challenges.*
import kotlinx.android.synthetic.main.profile_user_info.*
class ChallengesFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_challenges, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setView()
}
private fun setView() {
challengesViewPager.adapter = ChallengesAdapter(this)
TabLayoutMediator(challengesTabLayout, challengesViewPager) { tab, position ->
tab.text = when (position) {
0 -> "REQUESTED"
1 -> "ACTIVE"
2 -> "COMPLETED"
else -> throw IllegalStateException()
}
}.attach()
}
fun acceptChallenge(challengeId: String) {
val action = ChallengesFragmentDirections.acceptChallenge(challengeState = ChallengeState.ACCEPTED, challengeId = challengeId)
findNavController().navigate(action)
}
}
| 0
|
Kotlin
|
0
| 1
|
8fe031719fce121959249439e06565727d7ae14f
| 1,636
|
Runemies
|
Apache License 2.0
|
video-clip/app/src/main/java/work/wander/videoclip/ui/home/HomeViewModel.kt
|
awallace87
| 793,807,511
| false
|
{"Kotlin": 426138}
|
package work.wander.videoclip.ui.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import work.wander.videoclip.data.recordings.VideoRecordingsRepository
import work.wander.videoclip.data.recordings.entity.VideoRecordingEntity
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.inject.Inject
import kotlin.time.DurationUnit
import kotlin.time.toDuration
data class PreviousRecordingItem(
val videoRepositoryId: Long,
val durationInMillis: Long,
val sizeInBytes: Long,
val captureStartedAtEpochMillis: Long,
val thumbnailPath: String,
val videoFilePath: String,
val recordingStatus: VideoRecordingEntity.RecordingStatus = VideoRecordingEntity.RecordingStatus.INITIAL,
) {
fun captureStartedFormatted(): String =
CAPTURE_STARTED_FORMATTER.format(Date(captureStartedAtEpochMillis))
fun durationFormatted(): String {
val duration = durationInMillis.toDuration(DurationUnit.MILLISECONDS)
return String.format(
DURATION_TIME_FORMAT,
duration.inWholeHours,
duration.inWholeMinutes % 60,
duration.inWholeSeconds % 60,
duration.inWholeMilliseconds % 1000
)
}
fun formatSizeInMb(): String {
val sizeInMb = sizeInBytes / (1024.0 * 1024.0)
return String.format("%.2f MB", sizeInMb)
}
companion object {
private const val CAPTURE_STARTED_FORMAT = "MMMM d, yyyy - HH:mm"
private const val DURATION_TIME_FORMAT = "%02d:%02d:%02d:%03d"
private val CAPTURE_STARTED_FORMATTER =
SimpleDateFormat(CAPTURE_STARTED_FORMAT, Locale.getDefault())
}
}
@HiltViewModel
class HomeViewModel @Inject constructor(
videoRecordingsRepository: VideoRecordingsRepository,
) : ViewModel() {
private val previousRecordings = videoRecordingsRepository.getPreviousRecordings()
.map { recordings ->
recordings.map { recording ->
PreviousRecordingItem(
videoRepositoryId = recording.id,
durationInMillis = recording.recordedDurationMillis,
sizeInBytes = recording.sizeInBytes,
captureStartedAtEpochMillis = recording.timeCapturedEpochMillis,
thumbnailPath = recording.thumbnailFilePath,
videoFilePath = recording.videoFilePath,
recordingStatus = recording.recordingStatus
)
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = emptyList()
)
fun getPreviousRecordings() = previousRecordings
}
| 0
|
Kotlin
|
0
| 0
|
15c903724884cd6fb69588913eb6385387e9c056
| 2,924
|
android-sample-apps
|
Apache License 2.0
|
src/jvmMain/kotlin/ru/tanexc/application/presentation/features/api/chatApi/chatApi.kt
|
Tanexc
| 667,134,735
| false
| null |
package ru.tanexc.application.presentation.features.api.chatApi
import constants.Api.GET_CHAT
import constants.Api.GET_NEW_CHAT
import constants.Api.POST_MESSAGE_INTO_CHAT
import domain.model.Message
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.flow.collect
import org.koin.ktor.ext.inject
import ru.tanexc.application.domain.use_cases.chat_use_cases.ChatCreateUseCase
import ru.tanexc.application.domain.use_cases.chat_use_cases.ChatGetByClientIdUseCase
import ru.tanexc.application.domain.use_cases.chat_use_cases.ChatGetByIdUseCase
import ru.tanexc.application.domain.use_cases.chat_use_cases.ChatInsertMessageUseCase
import util.RespondData
import util.State
import util.exceptions.DataIsNull
import util.exceptions.InvalidData
fun Routing.chatApi() {
val chatCreateUseCase: ChatCreateUseCase by inject()
val chatGetByIdUseCase: ChatGetByIdUseCase by inject()
val chatGetByClientIdUseCase: ChatGetByClientIdUseCase by inject()
val chatInsertMessageUseCase: ChatInsertMessageUseCase by inject()
get(GET_CHAT) {
try {
val clientId: String = call.request.queryParameters["clientId"] ?: throw InvalidData()
chatGetByClientIdUseCase(clientId).collect {
when (it) {
is State.Success -> {
call.respond(RespondData(data = it.data))
}
is State.Error -> {
throw DataIsNull()
}
else -> {}
}
}
} catch (e: Exception) {
call.respond(RespondData(message = e.message))
}
}
get(GET_NEW_CHAT) {
try {
val clientId: String = call.request.queryParameters["clientId"] ?: throw InvalidData()
val userName: String = call.request.queryParameters["userName"] ?: throw InvalidData()
chatCreateUseCase(clientId, userName).collect {
when (it) {
is State.Success -> {
call.respond(RespondData(data = it.data))
}
is State.Error -> {
throw DataIsNull()
}
else -> {}
}
}
} catch (e: Exception) {
call.respond(RespondData(message = e.message))
}
}
post(POST_MESSAGE_INTO_CHAT) {
try {
val chatId: Long = call.request.queryParameters["chatId"]?.toLong() ?: throw InvalidData()
val message: Message = call.receive()
chatGetByIdUseCase(chatId).collect {
when (it) {
is State.Success -> {
it.data?.let { chat ->
chatInsertMessageUseCase(chat, message).collect { state ->
when (state) {
is State.Success -> {
call.respond(RespondData(state.data))
}
is State.Error -> {
throw DataIsNull()
}
else -> {}
}
}
}?: throw DataIsNull()
}
is State.Error -> {
throw DataIsNull()
}
else -> {}
}
}
} catch (e: Exception) {
call.respond(RespondData(message = e.message))
}
}
}
| 0
|
Kotlin
|
0
| 2
|
d8219c60de5c350c7b6b1d5031166deb0063e557
| 3,793
|
ComposeWebCakes
|
Apache License 2.0
|
compose-multiplatform-common/legacy/src/commonMain/kotlin/com/huanshankeji/compose/ui/ModifierOrAttrsScope.kt
|
huanshankeji
| 570,509,992
| false
|
{"Kotlin": 117843}
|
package com.huanshankeji.compose.ui
//import androidx.compose.ui.Modifier
import com.huanshankeji.compose.ui.color.Color
import com.huanshankeji.compose.ui.unit.HeightOrWidth
import com.huanshankeji.compose.ui.unit.Length
import com.huanshankeji.compose.ui.unit.LengthOrPercentage
typealias NotNullModifierOrAttrs<TElement> = ModifierOrAttrsScope<TElement>.() -> Unit
typealias ModifierOrAttrs<TElement> = NotNullModifierOrAttrs<TElement>?
@Suppress("NOTHING_TO_INLINE")
inline fun <TElement : Element> modifierOrAttrs(noinline modifierOrAttrs: NotNullModifierOrAttrs<TElement>) =
modifierOrAttrs
operator fun <TElement : Element> NotNullModifierOrAttrs<TElement>.plus(other: ModifierOrAttrs<TElement>): ModifierOrAttrs<TElement> =
if (other === null) this
else {
{
this@plus()
other()
}
}
expect abstract class Element
expect class ModifierOrAttrsScope<out TElement : Element> {
fun style(builder: StyleScope.() -> Unit)
}
/**
* Keep in mind that the functions in this class call functions in
* [org.jetbrains.compose.web.css.StyleScope] and [androidx.compose.ui.Modifier] under the hood
* so their visual results are not consistent.
* As different orders of `Modifier` function calls produce different results,
* different orders of function calls in this class produce different results on desktop and Android.
* They do produce the same results on web as long as no former property is overriden by a latter one,
* as different orders of CSS properties do in the HTML `style` attribute.
*/
expect class StyleScope {
fun margin(value: Length)
fun height(value: HeightOrWidth)
fun width(value: HeightOrWidth)
fun backgroundColor(color: Color)
/**
* Currently inconsistent, adds inner border on desktop and Android and outer padding on web.
*/
fun platformBorder(width: Length, color: Color)
fun outerBorder(width: Length, color: Color)
fun roundedCornerOuterBorder(width: Length, color: Color, cornerRadius: LengthOrPercentage)
}
fun StyleScope.height(value: LengthOrPercentage) =
height(HeightOrWidth.Numeric(value))
fun StyleScope.width(value: LengthOrPercentage) =
width(HeightOrWidth.Numeric(value))
private const val PADDING_MESSAGE =
"This function is a placeholder for code completion. " +
"Use `margin` to add space around the composable, which is equivalent to `Modifier.padding`. " +
"Set `margin` in the inner composable to add inner padding."
@Deprecated(PADDING_MESSAGE)
fun StyleScope.padding(value: LengthOrPercentage): Unit =
throw NotImplementedError(PADDING_MESSAGE)
/*
/** An alternative immutable design like [Modifier]. */
expect class ModifierOrAttrsImmutable<T : Element> {
fun padding(): ModifierOrAttrsImmutable<T>
}
*/
| 10
|
Kotlin
|
0
| 8
|
eb1ada7d629f3aa8831df4588653d87530e2635b
| 2,818
|
compose-multiplatform-material
|
Apache License 2.0
|
app/src/main/java/dorin_roman/app/kongfujava/ui/components/topbar/components/MenuButton.kt
|
roma321m
| 555,795,950
| false
|
{"Kotlin": 480911}
|
package dorin_roman.app.kongfujava.ui.components.topbar.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import dorin_roman.app.kongfujava.R
import dorin_roman.app.kongfujava.ui.theme.onTopBar
import dorin_roman.app.kongfujava.ui.theme.spacing
@Composable
fun MenuButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Icon(
modifier = modifier
.padding(MaterialTheme.spacing.large)
.size(40.dp)
.clickable {
onClick()
},
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(id = R.string.top_bar_menu),
tint = MaterialTheme.colors.onTopBar,
)
}
| 0
|
Kotlin
|
1
| 2
|
3c4f89aae10ca3f86e2cb6c1b0ecef3cb47729cd
| 1,138
|
Kong-Fu-Java
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/adjustments/api/model/prisonapi/Adjudication.kt
|
ministryofjustice
| 607,762,818
| false
|
{"Kotlin": 236404, "Shell": 1421, "Dockerfile": 1382}
|
package uk.gov.justice.digital.hmpps.adjustments.api.model.prisonapi
import java.time.LocalDateTime
data class Adjudication(
val adjudicationNumber: Long,
val reportTime: LocalDateTime? = null,
val agencyIncidentId: Long,
val agencyId: String? = null,
val partySeq: Long,
)
| 1
|
Kotlin
|
0
| 0
|
06af2147354dee5c5985aa7a7bcfee9d3dce0cd7
| 286
|
hmpps-adjustments-api
|
MIT License
|
app/src/main/java/com/example/databinding/Favorite.kt
|
pswaminathan
| 437,073,744
| false
| null |
package com.example.databinding
import com.squareup.moshi.JsonClass
import java.util.Date
data class Favorite(
val id: Int,
val userId: Int,
val updatedAt: Date,
val markedForRemoval: Boolean)
@JsonClass(generateAdapter = true)
class Updates(val additions: List<Int>?, val deletions: List<Int>?, val updatedAt: Date)
| 2
|
Kotlin
|
1
| 1
|
8400a3421f199e9a39006cfed2c5eea152d4572d
| 352
|
bazel-kt-databinding-crash
|
MIT License
|
src/main/kotlin/edu/uiowa/domain/game/models/type/Type.kt
|
matthewdargan
| 162,233,314
| false
| null |
package edu.uiowa.domain.game.models.type
import tornadofx.ViewModel
/**
* The class used to incorporate each GameType enum with
* its corresponding ViewModel object in the GUI.
*
* @param gameType
* the GameType enum
* @return the corresponding ViewModel for each GameType enum
*/
data class Type(val gameType: GameType) : ViewModel()
| 0
|
Kotlin
|
0
| 0
|
5f79540550132904a6b45a109c81ae4c40794b54
| 357
|
TicTacToe-JavaFX
|
MIT License
|
app/src/main/java/pk/sufiishq/app/feature/player/PlayerState.kt
|
sufiishq
| 427,931,739
| false
|
{"Kotlin": 950135}
|
/*
* Copyright 2022-2023 SufiIshq
*
* 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 pk.sufiishq.app.feature.player
enum class PlayerState {
IDLE,
LOADING,
PLAYING,
PAUSE,
}
| 3
|
Kotlin
|
0
| 2
|
254eeb6c2b1cad21d2f971d8b49ba3327d446bb5
| 714
|
sufiishq-mobile
|
Apache License 2.0
|
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/V8.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.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.SimpleIcons
public val SimpleIcons.V8: ImageVector
get() {
if (_v8 != null) {
return _v8!!
}
_v8 = Builder(name = "V8", defaultWidth = 24.0.dp, defaultHeight = 24.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) {
moveTo(6.832f, 6.0f)
curveToRelative(0.0f, -0.161f, 0.008f, -0.322f, 0.023f, -0.479f)
curveToRelative(0.019f, -0.207f, 0.07f, -0.401f, 0.112f, -0.599f)
lineToRelative(-0.694f, -1.377f)
lineTo(0.0f, 3.545f)
lineToRelative(2.182f, 3.818f)
horizontalLineToRelative(1.527f)
lineToRelative(2.097f, 3.98f)
arcToRelative(6.534f, 6.534f, 0.0f, false, true, 1.727f, -2.745f)
arcTo(5.123f, 5.123f, 0.0f, false, true, 6.832f, 6.0f)
close()
moveTo(10.365f, 19.663f)
lineTo(12.0f, 22.637f)
lineToRelative(1.637f, -2.975f)
curveToRelative(-0.535f, 0.138f, -1.079f, 0.234f, -1.637f, 0.234f)
reflectiveCurveToRelative(-1.101f, -0.096f, -1.635f, -0.233f)
close()
moveTo(17.728f, 3.545f)
lineToRelative(-0.717f, 1.258f)
curveToRelative(0.056f, 0.238f, 0.112f, 0.476f, 0.134f, 0.726f)
arcToRelative(5.148f, 5.148f, 0.0f, false, true, -0.677f, 3.07f)
arcToRelative(6.565f, 6.565f, 0.0f, false, true, 1.727f, 2.746f)
lineToRelative(2.097f, -3.981f)
horizontalLineToRelative(1.527f)
lineTo(24.0f, 3.545f)
horizontalLineToRelative(-6.272f)
close()
moveTo(17.846f, 12.007f)
arcToRelative(6.0f, 6.0f, 0.0f, false, false, -2.073f, -3.31f)
arcTo(4.64f, 4.64f, 0.0f, false, false, 12.0f, 1.363f)
arcTo(4.635f, 4.635f, 0.0f, false, false, 7.363f, 6.0f)
arcToRelative(4.62f, 4.62f, 0.0f, false, false, 0.865f, 2.697f)
arcTo(5.988f, 5.988f, 0.0f, false, false, 6.0f, 13.363f)
arcToRelative(6.01f, 6.01f, 0.0f, false, false, 3.814f, 5.592f)
arcToRelative(6.02f, 6.02f, 0.0f, false, false, 4.375f, -0.003f)
arcToRelative(6.006f, 6.006f, 0.0f, false, false, 3.657f, -6.945f)
close()
moveTo(12.0f, 4.227f)
curveToRelative(1.129f, 0.0f, 2.046f, 0.917f, 2.046f, 2.045f)
arcToRelative(2.046f, 2.046f, 0.0f, false, true, -4.092f, 0.0f)
curveToRelative(0.0f, -1.128f, 0.918f, -2.045f, 2.046f, -2.045f)
close()
moveTo(12.0f, 15.683f)
arcToRelative(2.32f, 2.32f, 0.0f, false, true, 0.0f, -4.637f)
curveToRelative(1.282f, 0.0f, 2.318f, 1.037f, 2.318f, 2.318f)
reflectiveCurveTo(13.282f, 15.683f, 12.0f, 15.683f)
close()
}
}
.build()
return _v8!!
}
private var _v8: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,853
|
compose-icons
|
MIT License
|
aws-globalaccelerator-endpointgroup/src/test/kotlin/software/amazon/globalaccelerator/arns/AcceleratorArnTest.kt
|
DJ-C
| 271,874,034
| true
|
{"Kotlin": 174746}
|
package software.amazon.globalaccelerator.arns
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class AcceleratorArnTest {
@Test
fun validAcceleratorArn() {
val arn = "arn:aws:globalaccelerator::444607872184:accelerator/48e89142-d196-4918-8e71-63685e3fbff9"
val result = AcceleratorArn(arn).acceleratorArn
Assertions.assertEquals(result, arn)
}
@Test
fun invalidAcceleratorArn1() {
val arn = "arn:globalaccelerator::444607872184:accelerator/48e89142-d196-4918-8e71-63685e3fbff9"
val exception = Assertions.assertThrows(RuntimeException::class.java) {
AcceleratorArn(arn).acceleratorArn
}
Assertions.assertEquals("Invalid Accelerator ARN $arn", exception.message)
}
@Test
fun invalidAcceleratorArn2() {
val arn = "arn:aws:globalaccelerat::444607872184:accelerator/48e89142-d196-4918-8e71-63685e3fbff9"
val exception = Assertions.assertThrows(RuntimeException::class.java) {
AcceleratorArn(arn).acceleratorArn
}
Assertions.assertEquals("Invalid Accelerator ARN $arn", exception.message)
}
@Test
fun nullAcceleratorArn() {
val arn = null
val exception = Assertions.assertThrows(RuntimeException::class.java) {
AcceleratorArn(arn).acceleratorArn
}
Assertions.assertEquals("Accelerator ARN cannot be null or empty $arn", exception.message)
}
}
| 0
|
Kotlin
|
0
| 0
|
28e547deb0a9f246393bd91ee29ea010d9ef2800
| 1,474
|
aws-cloudformation-resource-providers-globalaccelerator-1
|
Apache License 2.0
|
src/main/kotlin/io/openfuture/api/controller/api/TransactionApiController.kt
|
cdeyoung
| 138,206,144
| true
|
{"JavaScript": 89328, "Kotlin": 68707, "CSS": 46726, "FreeMarker": 9522, "HTML": 1762}
|
package io.openfuture.api.controller.api
import io.openfuture.api.annotation.CurrentUser
import io.openfuture.api.domain.PageRequest
import io.openfuture.api.domain.PageResponse
import io.openfuture.api.domain.scaffold.TransactionDto
import io.openfuture.api.entity.auth.User
import io.openfuture.api.service.ScaffoldService
import io.openfuture.api.service.TransactionService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/scaffolds/{address}/transactions")
class TransactionApiController(
private val service: TransactionService,
private val scaffoldService: ScaffoldService
) {
@GetMapping
fun getAll(@CurrentUser user: User, @PathVariable address: String,
pageRequest: PageRequest): PageResponse<TransactionDto> {
val scaffold = scaffoldService.get(address, user)
val transactions = service.getAll(scaffold, pageRequest).map { TransactionDto(it) }
return PageResponse(transactions)
}
}
| 0
|
JavaScript
|
0
| 0
|
0859c6fc19d40dfff829f7417d79186b825d3c81
| 1,193
|
open-api
|
Apache License 2.0
|
crashPilot/src/main/java/com/lzcalderaro/crashPilot/src/controller/CpLog.kt
|
lzcalderaro
| 743,990,532
| false
|
{"Kotlin": 19606}
|
package com.lzcalderaro.crashpilot.src.controller
import android.util.Log
import com.lzcalderaro.crashpilot.api.Request
import com.lzcalderaro.crashpilot.dto.Application
import com.lzcalderaro.crashpilot.dto.Tag
import com.lzcalderaro.crashpilot.list.ErrorTypes
import com.lzcalderaro.crashpilot.src.utils.Payload
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import com.lzcalderaro.crashpilot.dto.Throwable as ThrowablePayload
object CpLog {
fun e(tag: String, msg: String, tr:Throwable? = null) {
sendRequest(ErrorTypes.ERROR,tag, msg, tr)
}
fun d(tag: String, msg: String, tr:Throwable? = null) {
sendRequest(ErrorTypes.DEBUG,tag, msg, tr)
}
fun v(tag: String, msg: String, tr:Throwable? = null) {
sendRequest(ErrorTypes.VERBOSE,tag, msg, tr)
}
fun i(tag: String, msg: String, tr:Throwable? = null) {
sendRequest(ErrorTypes.INFO,tag, msg, tr)
}
fun w(tag: String, msg: String, tr:Throwable? = null) {
sendRequest(ErrorTypes.WARNING,tag, msg, tr)
}
private fun sendRequest(type:ErrorTypes, tag: String, msg: String, tr:Throwable?) {
when(type) {
ErrorTypes.ERROR -> Log.e(tag, msg, tr)
ErrorTypes.DEBUG -> Log.d(tag, msg, tr)
ErrorTypes.VERBOSE -> Log.v(tag, msg, tr)
ErrorTypes.INFO -> Log.i(tag, msg, tr)
ErrorTypes.WARNING -> Log.w(tag, msg, tr)
}
runBlocking(Dispatchers.IO) {
var trPayload: ThrowablePayload? = null
var applicationPayload: Application? = null
if (tr != null) {
trPayload = Payload.getThrowable(tr)
applicationPayload = Payload.getApplication(tr)
}
val payload = Tag(
type = type.name,
tag = tag,
message = msg,
throwable = trPayload,
timestamp = Payload.getCurrentDate(),
device = Payload.getDevice(),
application = applicationPayload
)
Request.send(payload)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6b17b6d786a7ff151bb3336df39ae2dafa78baf7
| 2,139
|
crashPilot
|
MIT License
|
app/src/test/java/com/omo/rememberme/domain/usecases/people/InsertNewPersonTest.kt
|
omer358
| 810,455,324
| false
|
{"Kotlin": 179513}
|
package com.omo.rememberme.domain.usecases.people
import com.omo.rememberme.domain.model.People
import com.omo.rememberme.domain.repository.PeopleRepository
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class InsertNewPersonTest {
@Mock
private lateinit var peopleRepository: PeopleRepository
private lateinit var insertNewPerson: InsertNewPerson
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
insertNewPerson = InsertNewPerson(peopleRepository)
}
@Test
fun `invoke should call insertNewPerson on repository`() = runBlocking {
val person = People(
id = 0L,
firstName = "John",
secondName = "Doe",
place = "Park",
time = "12:00 PM",
note = "Met at the park",
gender = "Male",
avatar = 1
)
insertNewPerson(person)
verify(peopleRepository).insertNewPerson(person)
}
}
| 2
|
Kotlin
|
0
| 0
|
bdb595b0c70eb5bdea6d080ad19bc75f8e597ba4
| 1,209
|
Remember-Me
|
MIT License
|
Mobilex/src/commonMain/kotlin/au/com/crazybean/mobilex/kurir/modules/creation/CreationScene.kt
|
crazybeanstudio
| 205,679,708
| true
|
{"Kotlin": 151199, "Swift": 40340, "Ruby": 2160}
|
package au.com.crazybean.mobilex.kurir.modules.creation
import au.com.crazybean.mobilex.kurir.modules.base.Scene
interface CreationScene : Scene {
fun showCreation()
}
| 0
|
Kotlin
|
0
| 0
|
7b4e96434246eb1ddae81a6e8688ffc182cf17ce
| 173
|
kurir-x
|
Apache License 2.0
|
app/src/main/java/edu/hm/cs/ma/todoguru/task/subTask/SubTaskAdapter.kt
|
theexiile1305
| 258,480,340
| false
|
{"Kotlin": 167794, "HTML": 6557}
|
package edu.hm.cs.ma.todoguru.task.subTask
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import edu.hm.cs.ma.todoguru.database.SubTask
import edu.hm.cs.ma.todoguru.databinding.SubtaskViewHolderBinding
import timber.log.Timber
class SubTaskAdapter(
private val listener: Listener
) : ListAdapter<SubTask, SubTaskAdapter.ViewHolder>(
SubTaskDiffCallBack()
) {
interface Listener {
fun onDeleteClick(subTask: SubTask)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder.from(parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind(getItem(position), listener)
class ViewHolder private constructor(private val binding: SubtaskViewHolderBinding) :
RecyclerView.ViewHolder(binding.root) {
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = SubtaskViewHolderBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
fun bind(subTask: SubTask, listener: Listener) {
binding.subTask = subTask
binding.listener = listener
binding.executePendingBindings()
}
}
class SubTaskDiffCallBack : DiffUtil.ItemCallback<SubTask>() {
override fun areItemsTheSame(oldItem: SubTask, newItem: SubTask): Boolean {
Timber.d("Check if two items has the same data")
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: SubTask, newItem: SubTask): Boolean {
Timber.d("Used to replace two items")
return oldItem == newItem
}
}
}
| 27
|
Kotlin
|
1
| 2
|
09a2f27f21c9eaacb1fad0130480f4521837d36c
| 1,956
|
todo-guru
|
MIT License
|
app/src/internal/java/com/duckduckgo/app/flipper/FlipperPluginPoint.kt
|
hojat72elect
| 822,396,044
| false
|
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.app.flipper
import com.duckduckgo.common.utils.plugins.PluginPoint
import com.duckduckgo.di.DaggerSet
import com.duckduckgo.di.scopes.AppScope
import com.facebook.flipper.core.FlipperPlugin
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import dagger.SingleInstanceIn
import dagger.multibindings.Multibinds
private class FlipperPluginPluginPoint(
private val plugins: DaggerSet<FlipperPlugin>,
) : PluginPoint<FlipperPlugin> {
override fun getPlugins(): Collection<FlipperPlugin> {
return plugins
}
}
@Module
@ContributesTo(AppScope::class)
abstract class FlipperPluginModule {
@Multibinds
abstract fun bindEmptySettingInternalFeaturePlugins(): DaggerSet<FlipperPlugin>
@Module
@ContributesTo(AppScope::class)
class SettingInternalFeaturePluginModuleExt {
@Provides
@SingleInstanceIn(AppScope::class)
fun provideSettingInternalFeaturePlugins(
plugins: DaggerSet<FlipperPlugin>,
): PluginPoint<FlipperPlugin> {
return FlipperPluginPluginPoint(plugins)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b89591136b60933d6a03fac43a38ee183116b7f8
| 1,143
|
DuckDuckGo
|
Apache License 2.0
|
app/src/main/java/com/patloew/oeffitracker/data/model/Ticket.kt
|
patloew
| 424,648,383
| false
|
{"Kotlin": 218998}
|
package com.patloew.oeffitracker.data.model
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.time.LocalDate
/* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
@Entity
@Parcelize
data class Ticket(
val name: String,
val price: Long,
val deduction: Long?,
val startDate: LocalDate,
val endDate: LocalDate,
val createdTimestamp: Long,
@PrimaryKey(autoGenerate = true) val id: Long = 0
) : Parcelable
| 0
|
Kotlin
|
0
| 5
|
188e508ce6db5a7515472a0f592f9b8f6855aabf
| 1,048
|
OeffiTracker
|
Apache License 2.0
|
app/src/main/java/com/patloew/oeffitracker/data/model/Ticket.kt
|
patloew
| 424,648,383
| false
|
{"Kotlin": 218998}
|
package com.patloew.oeffitracker.data.model
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.time.LocalDate
/* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
@Entity
@Parcelize
data class Ticket(
val name: String,
val price: Long,
val deduction: Long?,
val startDate: LocalDate,
val endDate: LocalDate,
val createdTimestamp: Long,
@PrimaryKey(autoGenerate = true) val id: Long = 0
) : Parcelable
| 0
|
Kotlin
|
0
| 5
|
188e508ce6db5a7515472a0f592f9b8f6855aabf
| 1,048
|
OeffiTracker
|
Apache License 2.0
|
1675.Minimize Deviation in Array.kt
|
sarvex
| 842,260,390
| false
|
{"Kotlin": 1775678, "PowerShell": 418}
|
internal class Solution {
fun minimumDeviation(nums: IntArray): Int {
val q: PriorityQueue<Int> = PriorityQueue { a, b -> b - a }
var mi: Int = MAX_VALUE
for (v in nums) {
var v = v
if (v % 2 == 1) {
v = v shl 1
}
q.offer(v)
mi = min(mi, v)
}
var ans: Int = q.peek() - mi
while (q.peek() % 2 === 0) {
val x: Int = q.poll() / 2
q.offer(x)
mi = min(mi, x)
ans = Math.min(ans, q.peek() - mi)
}
return ans
}
}
| 0
|
Kotlin
|
0
| 0
|
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
| 504
|
kotlin-leetcode
|
MIT License
|
src/main/kotlin/bridge/CountDisplay.kt
|
xmmmmmovo
| 318,367,991
| false
| null |
/*
* Copyright (c) xmmmmmovo 2021.
*/
package bridge
class CountDisplay(displayImpl: DisplayImpl) : Display(displayImpl) {
fun multiDisplay(times: Int) {
open()
for (i in 0 until times) {
print()
}
close()
}
}
| 0
|
Kotlin
|
0
| 0
|
b9007e601c749451bfb4d7b0e059cfd5ffb6ae02
| 265
|
DesignPatterns
|
Apache License 2.0
|
src/main/kotlin/mbo/dev/springnative/domain/role/RoleService.kt
|
mbogner
| 559,374,643
| false
| null |
package mbo.dev.springnative.domain.role
import mbo.dev.springnative.domain.CrudService
import mbo.dev.springnative.domain.EntityService
@EntityService
class RoleService(repo: RoleRepository) : CrudService<Role>(repo) {
}
| 0
|
Kotlin
|
0
| 0
|
8567b2b8ca725a3b6f190a30e4f358c785abf090
| 224
|
spring-native-sample
|
Apache License 2.0
|
app/src/main/java/com/phelat/splash/di/scopes/ForApplication.kt
|
PHELAT
| 135,176,443
| false
|
{"Kotlin": 83388}
|
package com.phelat.splash.di.scopes
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ForApplication
| 0
|
Kotlin
|
1
| 2
|
8493fdf5b67a9e425839427cf7f43c9565c34e0b
| 142
|
Splash
|
Apache License 2.0
|
src/main/kotlin/com/glancebar/apiboilerplate/actuator/WWWHealthIndicator.kt
|
yisen-cai
| 321,651,755
| false
| null |
package com.glancebar.apiboilerplate.actuator
import org.springframework.boot.actuate.health.AbstractHealthIndicator
import org.springframework.boot.actuate.health.Health
import org.springframework.stereotype.Component
import java.io.IOException
import java.net.InetAddress
import java.net.UnknownHostException
/**
* A health indicator
* @author YISEN
* @date 2020/12/22
*/
@Component
class WWWHealthIndicator : AbstractHealthIndicator() {
override fun doHealthCheck(builder: Health.Builder?) {
if (ping()) {
builder?.withDetail("message", "当前服务可以访问万维网")?.up()
} else {
builder?.withDetail("message", "当前无法访问万维网")?.outOfService()
}
}
fun ping(): Boolean {
try {
return InetAddress.getByName(BUILD_HOST).isReachable(TIME_OUT)
} catch (e: UnknownHostException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return false
}
companion object {
private const val BUILD_HOST = "www.baidu.com"
private const val TIME_OUT = 3000
}
}
| 1
|
Kotlin
|
0
| 1
|
beb48202163b6bd39001661969a2a640bc359734
| 1,122
|
api-boilerplate
|
Apache License 2.0
|
app/src/main/java/com/hfut/schedule/ui/ComposeUI/Settings/MonetColorItem.kt
|
Chiu-xaH
| 705,508,343
| false
|
{"Kotlin": 397747}
|
package com.hfut.schedule.ui.ComposeUI.Settings
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.hfut.schedule.R
import com.hfut.schedule.ui.MonetColor.MonetUI
@Composable
fun MonetColorItem() {
Card(
elevation = CardDefaults.cardElevation(
defaultElevation = 3.dp
),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp, vertical = 5.dp),
shape = MaterialTheme.shapes.medium
){
}
ListItem(
headlineContent = { Text(text = "莫奈取色") },
leadingContent = {
Icon(
painterResource(R.drawable.color),
contentDescription = "Localized description",
)
}
)
// Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Start) {
// Spacer(modifier = Modifier.width(30.dp))
MonetUI()
// }
Spacer(modifier = Modifier.height(5.dp))
}
| 0
|
Kotlin
|
0
| 1
|
47346f061697b8208d380c9059e5c64234571e2e
| 1,673
|
HFUT-Schedule
|
Apache License 2.0
|
waltid-crypto/src/jsMain/kotlin/crypto/crypto.kt
|
walt-id
| 701,058,624
| false
|
{"Kotlin": 1678078, "Vue": 327142, "TypeScript": 92029, "JavaScript": 11176, "Dockerfile": 5028, "Shell": 1651, "CSS": 404}
|
@JsModule("crypto")
@JsNonModule
external object crypto{
fun sign(algorithm: String?, data: ByteArray, key: String): ByteArray
fun verify(algorithm: String?, data: ByteArray, key: String, signature: ByteArray): Boolean
}
| 22
|
Kotlin
|
19
| 72
|
c839d5e81c6e8798b812e890c95a376041641e56
| 228
|
waltid-identity
|
Apache License 2.0
|
core/common/src/main/java/com/luan/teste/common/extensions/ResourceExtensions.kt
|
luangs7
| 475,285,813
| false
| null |
package com.luan.teste.common.extensions
import com.luan.teste.common.base.ApiResult
fun <T> ApiResult<T>.isSuccess():Boolean = this is ApiResult.Success
fun <T> ApiResult<T>.isError():Boolean = this is ApiResult.Error
| 0
|
Kotlin
|
0
| 0
|
af40cb051d592fbaab59154a499ba98aab0c4a2f
| 222
|
GithubComposable
|
Apache License 2.0
|
lab3/src/main/kotlin/jpa/HibernateUtil.kt
|
band-of-four
| 152,893,488
| false
| null |
package jpa
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.SessionFactory
import org.hibernate.cfg.Configuration
import User
import Group
import RequestResult
object HibernateUtil {
private var sessionFactory: SessionFactory? = null
fun getSessionFactory(): SessionFactory? {
if (sessionFactory == null) {
try {
val configuration = Configuration().configure()
configuration.addAnnotatedClass(User::class.java)
configuration.addAnnotatedClass(RequestResult::class.java)
configuration.addAnnotatedClass(Group::class.java)
val builder = StandardServiceRegistryBuilder().applySettings(configuration.properties)
sessionFactory = configuration.buildSessionFactory(builder.build())
} catch (e: Exception) {
e.printStackTrace()
}
}
return sessionFactory
}
}
| 0
|
Kotlin
|
0
| 4
|
f20d2c076d9281c4696ab1d33b649c721fb3b011
| 884
|
pipchansky
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/tugcearas/customnavigationbar/MainActivity.kt
|
TugceAras
| 593,292,147
| false
| null |
package com.tugcearas.customnavigationbar
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.tugcearas.customnavigationbar.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
click()
}
private fun click(){
binding.mainButton.setOnClickListener {
startActivity(Intent(this,SecondScreen::class.java))
}
}
}
| 0
|
Kotlin
|
0
| 6
|
7160099f98cc4052f589e2ad5659b1d40ad986e5
| 695
|
CustomBottomNavigationBar
|
MIT License
|
app/src/test/kotlin/com/thundermaps/apilib/android/api/responses/models/ResultTest.kt
|
SaferMe
| 240,105,080
| false
| null |
package com.thundermaps.apilib.android.api.responses.models
import org.junit.Assert
import org.junit.Test
class ResultTest {
@Test
fun `test Initial state before and after converting`() {
val initialState = Result.Initial
initialState.verify()
val convertedState = initialState.convert {} as Result.Initial
convertedState.verify()
}
@Test
fun `test Success state`() {
val successState = Result.Success(5)
successState.verify()
Assert.assertEquals(5, successState.getNullableData())
val convertedState = successState.convert { listOf(it) } as Result.Success<List<Int>>
convertedState.verify()
Assert.assertEquals(listOf(5), convertedState.getNullableData())
}
@Test
fun `test Loading state has data`() {
val loadingState = Result.Loading(5)
loadingState.verify()
Assert.assertEquals(5, loadingState.getNullableData())
val convertedState = loadingState.convert { listOf(it) } as Result.Loading<List<Int>>
convertedState.verify()
Assert.assertEquals(listOf(5), convertedState.getNullableData())
}
@Test
fun `test Loading state has no data`() {
val loadingState = Result.Loading(null)
loadingState.verify()
Assert.assertNull(loadingState.getNullableData())
val convertedState = loadingState.convert { } as Result.Loading<*>
convertedState.verify()
Assert.assertNull(convertedState.getNullableData())
}
@Test
fun `test Error state has data`() {
val exception = Exception("Error")
val errorState = Result.Error(5, exception)
errorState.verify()
Assert.assertEquals(5, errorState.getNullableData())
val convertedState = errorState.convert { listOf(it) } as Result.Error<List<Int>>
convertedState.verify()
Assert.assertEquals(listOf(5), convertedState.getNullableData())
}
@Test
fun `test Error state has no data`() {
val exception = Exception("Error")
val errorState = Result.Error(null, exception)
errorState.verify()
Assert.assertNull(errorState.getNullableData())
val convertedState = errorState.convert { } as Result.Error<*>
convertedState.verify()
Assert.assertNull(convertedState.getNullableData())
}
private fun <T : Any> Result<T>.verify() {
when (this) {
is Result.Initial -> {
Assert.assertFalse(isSuccess)
Assert.assertFalse(isLoading)
Assert.assertFalse(isError)
}
is Error -> {
Assert.assertFalse(isSuccess)
Assert.assertFalse(isLoading)
Assert.assertTrue(isError)
}
is Result.Success -> {
Assert.assertTrue(isSuccess)
Assert.assertFalse(isLoading)
Assert.assertFalse(isError)
}
is Result.Loading -> {
Assert.assertFalse(isSuccess)
Assert.assertTrue(isLoading)
Assert.assertFalse(isError)
}
else -> {
}
}
}
}
| 2
|
Kotlin
|
0
| 0
|
e10d64c126cb13e56e5089e8bedd249534dc2ccf
| 3,227
|
saferme-api-client-android
|
MIT License
|
server/src/main/kotlin/org/kryptonmc/krypton/entity/ai/memory/ExpirableMemory.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kryptonmc.krypton.entity.ai.memory
import org.kryptonmc.nbt.CompoundTag
import org.kryptonmc.nbt.compound
import org.kryptonmc.serialization.nbt.NbtOps
class ExpirableMemory<T : Any>(override val value: T?, private var ttl: Long) : Memory<T> {
override fun tick() {
ttl--
}
override fun save(key: MemoryKey<in T>, data: CompoundTag.Builder): CompoundTag.Builder {
return data.compound(key.key().asString()) {
if (value != null) put("value", key.codec.encodeStart(value, NbtOps.INSTANCE).result().get())
putLong("ttl", ttl)
}
}
override fun toString(): String = "ExpirableMemory(value=$value, ttl=$ttl)"
}
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 1,423
|
Krypton
|
Apache License 2.0
|
app/src/main/java/com/paonesoni/overlaymap/MapsActivity.kt
|
paonesoni
| 533,621,569
| false
|
{"Kotlin": 12853}
|
package com.paonesoni.overlaymap
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.content.ContextCompat
import com.paonesoni.overmap.datapath.PathData
import com.paonesoni.overmap.datapath.PathStyle
import com.paonesoni.overmap.view.OverMap
import com.google.android.gms.maps.model.LatLng
import com.paonesoni.overlaymap.databinding.ActivityMapsBinding
import com.google.android.gms.maps.*
import java.util.ArrayList
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private lateinit var binding: ActivityMapsBinding
private lateinit var customizeMap :OverMap
private var points = ArrayList<PathData>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMapsBinding.inflate(layoutInflater)
setContentView(binding.root)
customizeMap = binding.customizeMap
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
val styleOne = PathStyle(pathColor = Color.YELLOW, pathShadowColor = Color.GRAY,
capStartColor = Color.RED, capEndColor = Color.RED, pathWidth = 10f,
pathShadowWidth = 10f, capSize = 20f)
val styleTwo = PathStyle(pathColor = ContextCompat.getColor(this,R.color.blue),
pathShadowColor = ContextCompat.getColor(this,R.color.blue_light),
capStartColor = ContextCompat.getColor(this,R.color.black),
capEndColor = ContextCompat.getColor(this,R.color.black),
pathWidth = 5f, pathShadowWidth = 15f, capSize = 15f)
points.add(PathData(LatLng(19.007606, 72.817380), LatLng(18.994460, 72.845875)))
points.add(PathData(LatLng(19.041524, 72.865273), LatLng(19.035682, 72.930333), styleOne ))
points.add(PathData(LatLng(19.085006, 72.848965), LatLng(19.058399, 72.874199), styleTwo))
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
val latLong = LatLng(19.048501, 72.857892)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLong, 13f))
mMap.setOnCameraMoveListener {
// customizeMap.arch(PathData(LatLng(19.007606, 72.817380), LatLng(19.069756, 72.875916)), mMap)
customizeMap.arch(points, googleMap)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9b82121a4e551e5a7aad952e66d654f966dfde7e
| 2,455
|
OverMap
|
Apache License 2.0
|
src/main/kotlin/com/willoutwest/kalahari/scene/camera/Uvw.kt
|
wbknez
| 217,644,047
| false
| null |
package com.willoutwest.kalahari.scene.camera
import com.willoutwest.kalahari.math.Point3
import com.willoutwest.kalahari.math.Vector3
/**
* Represents an orthonormal viewing basis.
*
* @property u
* The u coordinate axis.
* @property v
* The v coordinate axis.
* @property w
* The w coordinate axis.
*/
data class Uvw(val u: Vector3 = Vector3.X.clone(),
val v: Vector3 = Vector3.Y.clone(),
val w: Vector3 = Vector3.Z.clone()) : Cloneable {
/**
* Constructor.
*
* @param uvw
* The basis to copy from.
*/
constructor(uvw: Uvw?)
: this(uvw!!.u.clone(), uvw.v.clone(), uvw.w.clone())
public override fun clone(): Uvw = Uvw(this)
/**
* Checks for and removes any singularity that results from the view
* direction being either parallel or anti-parallel to the up vector.
*
* Technically, the singularity occurs whenever two of the three
* components of both the eye and look-at points are the same. However,
* the textbook - and thus this project - is primarily concerned with
* problems relating to the y-axis, and so this method explicitly
* hardcodes the boundary cases of looking vertically up or down.
*
* @param eye
* The eye point to use.
* @param lookAt
* The look-at point to look at.
* @return A reference to this orthonormal viewing basis for easy chaining.
*/
fun removeSingularity(eye: Point3, lookAt: Point3): Uvw {
val x = eye.x.compareTo(lookAt.x)
val y = eye.y.compareTo(lookAt.y)
val z = eye.z.compareTo(lookAt.z)
if (x == 0 && z == 0 && y != 0) {
if (y > 0) {
this.u.set(Vector3.Z)
this.v.set(Vector3.X)
this.w.set(Vector3.Y)
}
else {
this.u.set(Vector3.X)
this.v.set(Vector3.Z)
this.w.set(Vector3.Y)
.negateSelf()
}
}
return this
}
/**
* Updates this orthonormal viewing basis based on the specified parameters.
*
* @param eye
* The eye point to use.
* @param lookAt
* The look-at point to use.
* @param up
* The vector that represents "up" in the coordinate basis to use.
* @return A reference to this orthonormal viewing basis for easy chaining.
*/
fun updateBasis(eye: Point3, lookAt: Point3, up: Vector3): Uvw {
this.w.set(eye)
.minusSelf(lookAt.x, lookAt.y, lookAt.z)
.normalizeSelf()
this.u.set(up)
.crossSelf(w)
.normalizeSelf()
this.v.set(w)
.crossSelf(u)
return this.removeSingularity(eye, lookAt)
}
}
| 0
|
Kotlin
|
0
| 0
|
46b1b3de9474dda22291a33b93a9b40b634c29c0
| 2,845
|
kalahari
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.