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
platform/navigation/navigator/kernel/implementation/src/main/kotlin/aa/weather/navigation/navigator/NavigatorModule.kt
marwinxxii
608,084,351
false
null
package aa.weather.navigation.navigator import aa.weather.component.di.AppPlugin import aa.weather.component.di.AppPluginKey import aa.weather.navigation.navigator.screen.api.ScreenNavigatorProvider import dagger.Binds import dagger.Module import dagger.Provides import dagger.multibindings.IntoMap import javax.inject.Singleton @Module private interface PrivateNavigatorModule { @Binds @IntoMap @AppPluginKey(ScreenNavigatorProvider::class) fun bindsNavigatorPlugin(instance: ScreenNavigatorProvider): AppPlugin @Binds @Singleton fun bindScreenNavigatorProvider( instance: ViewModelScreenNavigatorProvider, ): ScreenNavigatorProvider } @Module(includes = [PrivateNavigatorModule::class]) object NavigatorModule { @Provides fun provideNavigator(plugins: NavigationPlugins) = FragmentNavigator(plugins) }
0
Kotlin
0
0
9d056070987da45ca1bf496f98ca54c8c5cfef97
856
weather-app
Apache License 2.0
app/src/main/java/com/babylon/wallet/android/utils/BigDecimalExtensions.kt
radixdlt
513,047,280
false
{"Kotlin": 4329774, "HTML": 215350, "Java": 18496, "Ruby": 2757, "Shell": 1962}
@file:Suppress("MagicNumber") package com.babylon.wallet.android.utils import java.math.BigDecimal import java.math.RoundingMode fun BigDecimal.toRETDecimalString(): String = setScale(18, RoundingMode.HALF_UP).toPlainString()
4
Kotlin
11
6
61fec2927d38fd134cef97947a65ab2fa532ae41
229
babylon-wallet-android
Apache License 2.0
connectors/jdbc-connector/src/main/java/com/orbitalhq/connectors/jdbc/BaseJdbcOperationInvoker.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.connectors.jdbc import com.orbitalhq.connectors.collectionTypeOrType import com.orbitalhq.connectors.config.jdbc.JdbcConnectionConfiguration import com.orbitalhq.connectors.resultType import com.orbitalhq.models.DataSource import com.orbitalhq.models.OperationResult import com.orbitalhq.models.TypedInstance import com.orbitalhq.query.QueryContextEventDispatcher import com.orbitalhq.query.RemoteCall import com.orbitalhq.query.ResponseMessageType import com.orbitalhq.query.SqlExchange import com.orbitalhq.schemas.Parameter import com.orbitalhq.schemas.RemoteOperation import com.orbitalhq.schemas.Schema import com.orbitalhq.schemas.Service import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import lang.taxi.query.TaxiQlQuery import org.jooq.DSLContext import org.postgresql.jdbc.PgArray import org.postgresql.util.PGobject import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.util.LinkedCaseInsensitiveMap import java.time.Duration import java.time.Instant abstract class BaseJdbcOperationInvoker( protected val connectionFactory: JdbcConnectionFactory, ) { protected fun jdbcTemplate(connectionName: String): NamedParameterJdbcTemplate { return connectionFactory.jdbcTemplate(connectionName) } protected fun sqlDsl(connectionName: String): DSLContext { val config = connectionFactory.config(connectionName) return connectionFactory.dsl(config) } abstract suspend fun invoke( service: Service, operation: RemoteOperation, parameters: List<Pair<Parameter, TypedInstance>>, eventDispatcher: QueryContextEventDispatcher, queryId: String, verb: UpsertVerb? ): Flow<TypedInstance> protected fun convertToTypedInstances( resultList: List<MutableMap<String, Any>>, query: TaxiQlQuery, schema: Schema, datasource: DataSource ): Flow<TypedInstance> { val resultTypeName = query.resultType() val resultTaxiType = collectionTypeOrType(schema.taxi.type(resultTypeName)) val typedInstances = resultList .map { columnMap -> TypedInstance.from( schema.type(resultTaxiType), convertColumnMapToGeneralPurposeTypes(columnMap), schema, source = datasource, evaluateAccessors = false ) } return typedInstances.asFlow() } /** * TODO This shouldn't be needed.. * The TypedInstance generation relies on the map being an insensitive one, so we need to utilize LinkedCaseInsensitiveMap. */ private fun convertColumnMapToGeneralPurposeTypes(columnMap: Map<String, Any>): LinkedCaseInsensitiveMap<Any> { val result = LinkedCaseInsensitiveMap<Any>() columnMap.forEach { val value = when (it.value) { is PGobject -> it.value.toString() is PgArray -> ((it.value as PgArray).array as Array<String>).toList() else -> it.value } result[it.key] = value } return result } fun buildOperationResult( service: Service, operation: RemoteOperation, parameters: List<TypedInstance>, sql: String, jdbcUrl: String, elapsed: Duration, recordCount: Int, verb: String = "SELECT" ): OperationResult { val remoteCall = buildRemoteCall(service, jdbcUrl, operation, sql, elapsed, recordCount, verb) return OperationResult.fromTypedInstances( parameters, remoteCall ) } private fun buildRemoteCall( service: Service, jdbcUrl: String, operation: RemoteOperation, sql: String, elapsed: Duration, recordCount: Int, verb: String ) = RemoteCall( service = service.name, address = jdbcUrl, operation = operation.name, responseTypeName = operation.returnType.name, requestBody = sql, durationMs = elapsed.toMillis(), timestamp = Instant.now(), // If we implement streaming database queries, this will change responseMessageType = ResponseMessageType.FULL, // Feels like capturing the results are a bad idea. Can revisit if there's a use-case response = null, exchange = SqlExchange( sql = sql, recordCount = recordCount, verb = verb ), ) protected fun getConnectionConfigAndTemplate(service: Service): Pair<JdbcConnectionConfiguration, NamedParameterJdbcTemplate> { val connectionName = service.firstMetadata(JdbcConnectorTaxi.Annotations.DatabaseOperation.NAME).params["connection"] as String return connectionFactory.config(connectionName) to connectionFactory.jdbcTemplate(connectionName) } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
4,788
orbital
Apache License 2.0
appModules/navigation/src/commonMain/kotlin/dev/reprator/screens/Screens.kt
TheReprator
781,077,991
false
{"Kotlin": 399028, "Swift": 5325, "HTML": 357, "JavaScript": 92}
package dev.reprator.screens import com.slack.circuit.runtime.screen.Screen @Parcelize object SplashScreen : AccountBookScreen(name = "SplashScreen()") @Parcelize object SettingsScreen : AccountBookScreen(name = "Settings()") @Parcelize object DevSettingsScreen : AccountBookScreen(name = "DevelopmentSettings()") @Parcelize object DevLogScreen : AccountBookScreen(name = "DevelopmentLog()") @Parcelize data class LanguageScreen(val id: Long) : AccountBookScreen(name = "LanguageScreen()") { override val arguments get() = mapOf("id" to id) } @Parcelize data class UrlScreen(val url: String) : AccountBookScreen(name = "UrlScreen()") { override val arguments get() = mapOf("url" to url) } abstract class AccountBookScreen(val name: String) : Screen { open val arguments: Map<String, *>? = null }
1
Kotlin
0
0
1468ecc36c791f643973d0fadae9f6154d726b84
814
ExpenseManagment
Apache License 2.0
api/src/main/kotlin/com/ssu/commerce/auth/domain/PointAccountRepository.kt
ssu-commerce
478,587,254
false
{"Kotlin": 20966}
package com.ssu.commerce.auth.domain import org.springframework.data.jpa.repository.JpaRepository import java.util.UUID interface PointAccountRepository : JpaRepository<PointAccount, Long> { fun findByAccount_AccountId(accountId: UUID): PointAccount }
4
Kotlin
1
0
58b37295dac5d6f47aa968c027bb01b9e7207d47
258
auth-server
MIT License
herminedb-driver/src/main/kotlin/org/hermine/internal/db/driver/OperationGroupImpl.kt
pull-vert
136,531,074
false
{"Java": 1537434, "Kotlin": 45389}
/* * Copyright 2018 HermineDB's author : Frédéric Montariol. Use of this source code is governed by the Apache 2.0 license. */ package org.hermine.internal.db.driver import jdk.incubator.sql2.* import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.future.asDeferred import mu.KotlinLogging import java.time.Duration import java.util.concurrent.CompletionStage import java.util.function.* import java.util.function.Function import java.util.logging.Logger import java.util.stream.Collector // Place definition above class declaration to make field static private val logger = KotlinLogging.logger {} private val DEFAULT_COLLECTOR: Collector<*, *, *> = Collector.of( Supplier { null }, BiConsumer { _, _: Any? -> }, BinaryOperator { _, _ -> null }, Function { _: Nothing? -> null }) private val DEFAULT_CONDITION = CompletableDeferred(true) internal open class OperationGroupImpl<S, T> : AbstractOperation<T>, OperationGroup<S, T> { // used only by Session. Will break if used by any other class. constructor() : super() constructor(session: SessionImpl, group: OperationGroupImpl<T, *>) : super(session, group) protected var condition: Deferred<Boolean> = DEFAULT_CONDITION lateinit var submission: SubmissionImpl<T> var accumulator: Any? = null var isIndependent: Boolean = false var isParallel: Boolean = false protected var collector: Collector<*, *, *> = DEFAULT_COLLECTOR /** * Completed when this OperationGroup is no longer held. Completion of this * OperationGroup depends on held. * * @see #submit, * @see #releaseProhibitingMoreMembers, * @see #submitHoldingForMoreMembers */ private val held = CompletableDeferred<Unit>() private val parentJob = Job() /** * Last operation. Mutable until not isHeld(). */ protected var lastOp: Deferred<S?>? = null override fun parallel(): OperationGroupImpl<S, T> { if (isImmutable() || isParallel) throw IllegalStateException("TODO") isParallel = true return this } override fun independent(): OperationGroupImpl<S, T> { if (isImmutable() || isIndependent) throw IllegalStateException("TODO") isIndependent = true return this } override fun conditional(condition: CompletionStage<Boolean>?): OperationGroupImpl<S, T> { if (isImmutable() || condition == null) throw IllegalStateException("TODO") this.condition = condition.asDeferred() return this } override fun collect(c: Collector<S, *, T>?): OperationGroupImpl<S, T> { if (isImmutable() || collector !== DEFAULT_COLLECTOR) throw IllegalStateException("TODO") if (c == null) throw IllegalArgumentException("TODO") collector = c return this } override fun catchOperation(): AbstractOperation<S> { if (!isHeld()) throw IllegalStateException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> arrayRowCountOperation(sql: String?): ArrayRowCountOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> rowCountOperation(sql: String?): ParameterizedRowCountOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") // return ParameterizedRowCountOperationImpl(session, this, sql) } override fun operation(sql: String?): AbstractOperation<S> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> outOperation(sql: String?): OutOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> rowOperation(sql: String?): ParameterizedRowOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> rowPublisherOperation(sql: String?): ParameterizedRowPublisherOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> multiOperation(sql: String?): MultiOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") if (sql == null) throw IllegalArgumentException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun endTransactionOperation(trans: TransactionCompletion): AbstractOperation<TransactionOutcome> { if (!isHeld()) throw IllegalStateException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun <R : S> localOperation(): LocalOperation<R> { if (!isHeld()) throw IllegalStateException("TODO") throw UnsupportedOperationException("Not supported yet.") } override fun logger(logger: Logger): OperationGroup<S, T> { throw UnsupportedOperationException("Will use other Logger") } // Override Operation methods override fun timeout(minTime: Duration): OperationGroupImpl<S, T> { super.timeout(minTime) return this } override fun onError(handler: Consumer<Throwable>): OperationGroupImpl<S, T> { super.onError(handler) return this } override fun submit(): SubmissionImpl<T> { logger.debug { "OperationGroupImpl#submit" } if (isImmutable()) throw IllegalStateException("TODO") accumulator = collector.supplier().get() held.complete(Unit) // start all operations startOpJobs() return super.submit() } override fun close() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } // Internal methods internal fun submitOperation(op: AbstractOperation<S>): SubmissionImpl<S> { logger.debug { "OperationGroupImpl#submitOperation" } val newLastOp = op.follows(lastOp, context, isParallel, isIndependent, parentJob) lastOp = newLastOp return SubmissionImpl(this::cancel, newLastOp) } override suspend fun operate(): T? { logger.debug { "OperationGroupImpl#operate" } return if (condition.await()) { held.join() // wait until submit or releaseProhibitingMoreMembers (collector.finisher() as Function<Any?, Any>) .apply(accumulator) as T } else { null } } fun isHeld() = !held.isCompleted private fun startOpJobs() { for ((index, opJob) in parentJob.children.withIndex()) { val start = opJob.start() // true if job was not started, false if job was already started or completed logger.debug { "start $index child operation job = $start" } } } }
0
Java
0
2
719c2202bdb00c1503c9b2844e3c4d2c308f359d
7,542
herminedb
Apache License 2.0
ArtSpace/app/src/main/java/com/example/artspace/MainActivity.kt
ydv-ankit
666,011,142
false
null
package com.example.artspace import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.artspace.ui.theme.ArtSpaceTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ArtSpaceTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ArtSpaceApp() } } } } } @Composable fun ArtSpaceApp(modifier: Modifier = Modifier) { var imageNumber by remember { mutableStateOf(1) } var picNumber = when(imageNumber) { 1 -> R.drawable.pic_1 2 -> R.drawable.pic_2 3 -> R.drawable.pic_3 4 -> R.drawable.pic_4 5 -> R.drawable.pic_5 6 -> R.drawable.pic_6 7 -> R.drawable.pic_7 else -> R.drawable.pic_8 } Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(20.dp) ) { Image( painter = painterResource(id = picNumber), contentDescription = null, modifier = Modifier .fillMaxWidth() .fillMaxSize(0.7F) .padding(5.dp) ) Row { Button(onClick = { if(imageNumber != 1) imageNumber -= 1 else imageNumber = 8 }, modifier = Modifier .padding(20.dp) .width(150.dp)) { Text(text = "Previous") } Button(onClick = { if(imageNumber >= 8) imageNumber = 1 else imageNumber += 1 }, modifier = Modifier .padding(20.dp) .width(150.dp)) { Text(text = "Next") } } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { ArtSpaceTheme { ArtSpaceApp() } }
0
Kotlin
0
0
f78ac2a28e6e93094a13d599d5ba0f9ec3998d7c
3,206
kotlin-apps-practice
MIT License
app/src/main/java/com/sama/users/domain/UserDeviceRegistrations.kt
sama-app
363,692,054
false
null
package com.sama.users.domain import com.sama.common.DomainEntity import com.sama.common.NotFoundException import com.sama.common.ValueObject import java.util.UUID @DomainEntity data class UserDeviceRegistrations(val userId: UserId, val deviceRegistrations: Set<DeviceRegistration>) { val isRegistered = deviceRegistrations.isNotEmpty() fun register(deviceId: UUID, firebaseRegistrationToken: String): UserDeviceRegistrations { val deviceRegistration = DeviceRegistration(deviceId, firebaseRegistrationToken) return copy(deviceRegistrations = deviceRegistrations + deviceRegistration) } fun unregister(deviceId: UUID): UserDeviceRegistrations { val deviceRegistration = deviceRegistrations.find { it.deviceId == deviceId } ?: throw NotFoundException(UserDeviceRegistrations::class, deviceId) return copy(deviceRegistrations = deviceRegistrations - deviceRegistration) } } @ValueObject data class DeviceRegistration(val deviceId: UUID, val firebaseRegistrationToken: String)
0
Kotlin
1
2
a73319e26a22bf09aeb6bcc1cc2feaf3723ba0b9
1,043
sama-service
Apache License 2.0
app/src/main/java/com/fenghuang/caipiaobao/helper/span/NumberTypefaceSpan.kt
tracyly
262,531,465
false
{"Java": 1886821, "Kotlin": 1650417, "HTML": 41991}
package com.fenghuang.caipiaobao.helper.span import android.graphics.Paint import android.graphics.Typeface import android.text.TextPaint import android.text.style.TypefaceSpan /** * * author : Peter * date : 2019/7/3013:39 * desc : 自定义数字字体Span */ class NumberTypefaceSpan(family: String, private val newType: Typeface) : TypefaceSpan(family) { override fun updateDrawState(ds: TextPaint) { applyCustomTypeFace(ds, newType) } override fun updateMeasureState(paint: TextPaint) { applyCustomTypeFace(paint, newType) } private fun applyCustomTypeFace(paint: Paint, tf: Typeface) { val oldStyle: Int val old = paint.typeface oldStyle = old?.style ?: 0 val fake = oldStyle and tf.style.inv() if (fake and Typeface.BOLD != 0) { paint.isFakeBoldText = true } if (fake and Typeface.ITALIC != 0) { paint.textSkewX = -0.25f } paint.typeface = tf } }
1
null
1
1
b4f57b41ba0018299d47be4d7705f0dfb1b8cf04
1,000
cpb2.0
Apache License 2.0
packages/SystemUI/src/com/android/systemui/mediaprojection/appselector/data/RecentTaskThumbnailLoader.kt
liu-wanshun
595,904,109
true
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.mediaprojection.appselector.data import com.android.systemui.dagger.qualifiers.Background import com.android.systemui.shared.recents.model.ThumbnailData import com.android.systemui.shared.system.ActivityManagerWrapper import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext interface RecentTaskThumbnailLoader { suspend fun loadThumbnail(taskId: Int): ThumbnailData? } class ActivityTaskManagerThumbnailLoader @Inject constructor( @Background private val coroutineDispatcher: CoroutineDispatcher, private val activityManager: ActivityManagerWrapper ) : RecentTaskThumbnailLoader { override suspend fun loadThumbnail(taskId: Int): ThumbnailData? = withContext(coroutineDispatcher) { val thumbnailData = activityManager.getTaskThumbnail(taskId, /* isLowResolution= */ false) if (thumbnailData.thumbnail == null) null else thumbnailData } }
0
Java
1
2
e99201cd9b6a123b16c30cce427a2dc31bb2f501
1,619
platform_frameworks_base
Apache License 2.0
native_library/android/FirebaseANE/DynamicLinks/src/main/java/com/tuarua/firebase/dynamiclinks/extensions/FreAndroidParameters.kt
morristech
190,721,056
true
{"ActionScript": 600651, "Swift": 387718, "Kotlin": 345447, "Shell": 118960, "Objective-C": 70526, "Java": 61410, "Batchfile": 18834, "PowerShell": 15037, "C": 2596}
/* * Copyright 2018 Tua Rua Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuarua.firebase.dynamiclinks.extensions import android.net.Uri import com.adobe.fre.FREObject import com.google.firebase.dynamiclinks.DynamicLink import com.google.firebase.dynamiclinks.DynamicLink.AndroidParameters.* import com.tuarua.frekotlin.Int import com.tuarua.frekotlin.String import com.tuarua.frekotlin.get @Suppress("FunctionName") fun AndroidParameters(freObject: FREObject?): DynamicLink.AndroidParameters? { val rv = freObject ?: return null val packageName = String(rv["packageName"]) val fallbackUrl = String(rv["fallbackUrl"]) val minimumVersion = Int(rv["minimumVersion"]) val builder: DynamicLink.AndroidParameters.Builder builder = when (packageName) { null -> Builder() else -> Builder(packageName) } if (fallbackUrl != null) builder.setFallbackUrl(Uri.parse(fallbackUrl)) if (minimumVersion != null) builder.setMinimumVersion(minimumVersion) return builder.build() }
0
ActionScript
0
0
75b2f39cc3a3f25563d7741e92f8a12d3c1eace4
1,560
Firebase-ANE
Apache License 2.0
src/test/kotlin/com/coditory/gradle/manifest/base/SystemProperties.kt
coditory
250,088,548
false
null
package com.coditory.gradle.manifest.base import java.util.Properties object SystemProperties { fun <T> withSystemProperties(properties: Map<String, String>, call: () -> T): T { val backup = toMap(System.getProperties()) setSystemProperties(properties) try { return call() } finally { setSystemProperties(backup) } } fun <T> withoutSystemProperties(call: () -> T): T { val backup = toMap(System.getProperties()) System.getProperties().clear() try { return call() } finally { setSystemProperties(backup) } } private fun toMap(properties: Properties): Map<String, String> { return properties.toMap() .map { it.key.toString() to it.value.toString() } .toMap() } private fun setSystemProperties(map: Map<String, String>) { map.forEach { System.getProperties().setProperty(it.key, it.value) } } }
1
Kotlin
1
9
8aab42b33567d3a7c01dc3c83085d3cfb692daf9
1,017
gradle-manifest-plugin
MIT License
peacock-support/src/main/kotlin/com/peacock/support/authentication/resolver/AuthenticationCodeResolver.kt
peacock-123
828,176,906
false
{"Kotlin": 74462}
package com.peacock.support.authentication.resolver import com.peacock.core.domain.vo.Email import com.peacock.support.authentication.AuthCode interface AuthenticationCodeResolver { fun resolve( code: AuthCode, redirectUri: String?, ): Email }
0
Kotlin
0
0
7b46858ebad85d005b7e87a69c92d5150f072b04
270
peacock-server
MIT License
app/src/main/java/com/krykun/movieapp/feature/moviedetails/view/ErrorView.kt
JekaK
508,341,591
false
{"Kotlin": 470505}
package com.krykun.movieapp.feature.moviedetails.view import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.krykun.movieapp.R @Composable fun ErrorView() { Box( modifier = Modifier .fillMaxSize() .background(colorResource(id = R.color.container_background)), contentAlignment = Alignment.Center ) { Text( text = "ERROR", fontSize = 32.sp, fontWeight = FontWeight.Bold, color = Color.White ) } }
0
Kotlin
0
7
b46b296c16e23a6394e382a7d30b34176d443d90
939
MoviesApp
Apache License 2.0
src/test/kotlin/g0901_1000/s0996_number_of_squareful_arrays/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0996_number_of_squareful_arrays import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun numSquarefulPerms() { assertThat(Solution().numSquarefulPerms(intArrayOf(1, 17, 8)), equalTo(2)) } @Test fun numSquarefulPerms2() { assertThat(Solution().numSquarefulPerms(intArrayOf(2, 2, 2)), equalTo(1)) } }
0
Kotlin
20
43
471d45c60f669ea1a2e103e6b4d8d54da55711df
465
LeetCode-in-Kotlin
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Steak.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Steak: ImageVector get() { if (_steak != null) { return _steak!! } _steak = Builder(name = "Steak", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.0f, 0.0f) arcTo(10.011f, 10.011f, 0.0f, false, false, 0.0f, 10.0f) curveToRelative(0.0f, 5.327f, 4.206f, 10.0f, 9.0f, 10.0f) arcToRelative(4.341f, 4.341f, 0.0f, false, true, 3.781f, 1.762f) arcTo(5.772f, 5.772f, 0.0f, false, false, 17.5f, 24.0f) arcTo(6.508f, 6.508f, 0.0f, false, false, 24.0f, 17.5f) curveTo(24.0f, 11.588f, 19.772f, 0.0f, 10.0f, 0.0f) close() moveTo(4.0f, 10.0f) arcTo(5.967f, 5.967f, 0.0f, false, true, 5.287f, 6.3f) lineTo(6.3f, 5.287f) arcTo(5.967f, 5.967f, 0.0f, false, true, 10.0f, 4.0f) curveToRelative(0.132f, 0.0f, 0.252f, 0.026f, 0.381f, 0.033f) lineTo(4.02f, 10.394f) curveTo(4.012f, 10.263f, 4.0f, 10.135f, 4.0f, 10.0f) close() moveTo(4.692f, 12.894f) lineTo(12.939f, 4.647f) arcTo(8.026f, 8.026f, 0.0f, false, true, 14.7f, 5.717f) lineTo(5.891f, 14.523f) arcTo(6.23f, 6.23f, 0.0f, false, true, 4.692f, 12.894f) close() moveTo(10.332f, 16.082f) arcTo(10.679f, 10.679f, 0.0f, false, false, 9.0f, 16.0f) arcToRelative(3.511f, 3.511f, 0.0f, false, true, -1.185f, -0.229f) lineTo(16.284f, 7.3f) arcToRelative(14.054f, 14.054f, 0.0f, false, true, 1.149f, 1.679f) close() moveTo(12.798f, 16.788f) lineTo(18.498f, 11.088f) arcToRelative(20.7f, 20.7f, 0.0f, false, true, 0.751f, 2.077f) lineToRelative(-4.723f, 4.723f) arcTo(7.765f, 7.765f, 0.0f, false, false, 12.8f, 16.788f) close() moveTo(19.638f, 18.776f) lineTo(18.776f, 19.638f) arcTo(2.47f, 2.47f, 0.0f, false, true, 17.5f, 20.0f) arcToRelative(1.531f, 1.531f, 0.0f, false, true, -1.38f, -0.534f) lineToRelative(3.725f, -3.725f) arcTo(11.848f, 11.848f, 0.0f, false, true, 20.0f, 17.5f) arcTo(2.47f, 2.47f, 0.0f, false, true, 19.638f, 18.776f) close() } } .build() return _steak!! } private var _steak: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,501
icons
MIT License
utils/src/commonMain/kotlin/com/badoo/reaktive/utils/clock/Clock.kt
badoo
174,194,386
false
null
package com.badoo.reaktive.utils.clock interface Clock { val uptimeMillis: Long val uptimeNanos: Long }
8
Kotlin
49
956
c712c70be2493956e7057f0f30199994571b3670
115
Reaktive
Apache License 2.0
app/src/main/kotlin/io/cintroy/www/bus/injection/scopes/PerFragment.kt
cintory
164,553,090
false
null
package io.cintroy.www.bus.injection.scopes import javax.inject.Scope /** * Created by Cintory on 2019/10/12 10:39 * Email:<EMAIL> */ @Scope internal annotation class PerFragment
0
Kotlin
0
0
8973ea9b79a840720f3ac51f852cdcd5b64ad33e
184
Bus
Apache License 2.0
src/main/kotlin/VisibilityModifiers.kt
CogitoCoder
533,452,617
false
null
fun main() { val objOuter: Outer = Outer() // println(objOuter.a) -> private, can be accessible only in that class // println(objOuter.b) -> protected, only visible in subclasses println(objOuter.c) // internal, same as public within a module println(objOuter.d) // public val objSubclass: Subclass = Subclass() // println(objSubclass.a) -> private, can be accessible only in that class // println(objSubclass.b) -> protected, only visible in subclasses println(objSubclass.c) // internal, same as public within a module println(objSubclass.d) // public } open class Outer { private val a = 1 protected open val b = 2 internal open val c = 3 val d = 4 // public by default protected class Nested { public val e: Int = 5 } } class Subclass : Outer() { // a is not visible // b, c and d are visible // Nested and e are visible override val b = 5 // 'b' is protected override val c = 7 // 'c' is internal } class Unrelated(o: Outer) { // o.a, o.b are not visible // o.c and o.d are visible (same module) // Outer.Nested is not visible, and Nested::e is not visible either } // Table of visibility modifiers along with accessibility // MODIFIERS | TOP LEVEL DECLARATIONS | CLASS MEMBERS // ------------------------------------------------------------ // public | everywhere | everywhere // private | within a file | within a class // protected | N/A | only in subclasses // internal | within a module | within a module
0
Kotlin
0
5
f3293e91212e973945a96f6ae90f2c442acb9298
1,629
Kotlin_Tutorial
MIT License
app/src/main/java/com/vinicius/githubapi/remote/network/GithubException.kt
KhomDrake
471,202,847
false
{"Kotlin": 122985}
package com.vinicius.androidexercises.remote.network import java.io.IOException abstract class GithubException() : IOException() class InvalidQException : GithubException() class PageNumberTooLarge : GithubException() class DefaultException : GithubException()
0
Kotlin
0
0
54ff30b6598f469be66ef2cbbfe7eff815114d5f
265
android-exercises
X.Net License
app/src/main/java/com/example/wishlist/WishlistItem.kt
jwong1209
538,741,849
false
null
class WishlistItem( val itemName: String, val number: String, val url: String) { }
1
Kotlin
0
0
e7c450294eec7fdafaa7baa04e822007eac56c05
94
Wishlist
Apache License 2.0
app/src/main/java/bzh/zelyon/listdetail/model/Region.kt
zelyon
169,545,180
false
null
package bzh.zelyon.listdetail.model import androidx.room.* import bzh.zelyon.listdetail.BuildConfig import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName @Entity(tableName = "region") data class Region( @PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") @Expose var id: Long = 0, @ColumnInfo(name = "label") @SerializedName("label") @Expose var label: String = "", @ColumnInfo(name = "image") @SerializedName("image") @Expose var image: String = "" ) { fun getMap() = BuildConfig.baseUrl + URL + "map/" + image companion object { const val URL = "api/got/region/" } @androidx.room.Dao interface Dao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(regions: List<Region>) @Query("SELECT * " + "FROM region") fun getAll(): List<Region> @Query("SELECT * " + "FROM region " + "WHERE id = :id " + "LIMIT 1") fun getById(id: Long): Region } }
0
Kotlin
0
0
c770df9d8584605694d34ca9dc929f6520ce2523
1,059
ListDetail
Apache License 2.0
app/src/main/java/com/vitorpamplona/amethyst/service/MoneroDataSource.kt
retrnull
827,005,629
false
{"Kotlin": 5175042, "HTML": 836484, "Java": 189063, "C++": 76000, "Dockerfile": 30817, "CMake": 8487, "Makefile": 2641, "Shell": 1488}
/** * Copyright (c) 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.vitorpamplona.amethyst.service import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow object MoneroDataSource { private lateinit var moneroService: WalletService fun status() = flow { emitAll(moneroService.statusStateFlow) } fun connectionStatus() = flow { emitAll(moneroService.connectionStatusStateFlow) } fun walletHeight() = flow { emitAll(moneroService.walletHeightStateFlow) } fun daemonHeight() = flow { emitAll(moneroService.daemonHeightStateFlow) } fun balance() = flow { emitAll(moneroService.balanceStateFlow) } fun lockedBalance() = flow { emitAll(moneroService.lockedBalanceStateFlow) } fun transactions() = flow { emitAll(moneroService.transactions) } fun setMoneroService(service: WalletService) { moneroService = service } }
5
Kotlin
3
34
d33428614279300c503770c10a4305ca2a4d5ab6
2,136
garnet
MIT License
app/src/main/java/com/engency/blackjack/ScoreOverview.kt
ScoutingRudyardKipling
148,063,240
false
{"Kotlin": 51145}
package com.engency.blackjack import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import com.engency.blackjack.network.GroupsResponse import com.engency.blackjack.network.NetworkHelper import com.engency.blackjack.network.ServerTeamScore import com.engency.blackjack.stores.ScoreStore /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [ScoreOverview.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [ScoreOverview.newInstance] factory method to * create an instance of this fragment. * */ class ScoreOverview : Fragment(), SwipeRefreshLayout.OnRefreshListener { private lateinit var properties: GroupPropertyManager private lateinit var scoreStore: ScoreStore private lateinit var lvScores: ListView private lateinit var srlScores: SwipeRefreshLayout private var scoreAdapter: ScoreAdapter? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val v: View = inflater.inflate(R.layout.fragment_score_overview, container, false) srlScores = v.findViewById(R.id.srl_scores) srlScores.setOnRefreshListener(this) lvScores = v.findViewById(R.id.lv_scores) scoreAdapter = ScoreAdapter(activity!!.applicationContext, scoreStore.getAllSorted()) lvScores.adapter = scoreAdapter return v } override fun onAttach(context: Context) { super.onAttach(context) this.properties = GroupPropertyManager(context) this.scoreStore = ScoreStore(context) } override fun onStart() { super.onStart() reloadListview() onRefresh() } override fun onRefresh() { NetworkHelper.listScores( properties.get("token")!!, success = { response: GroupsResponse -> this.scoreStore.clear(); this.scoreStore.addAllFromServer(response.scores); reloadListview() }, failure = { this.srlScores.isRefreshing = false } ) } private fun reloadListview() { if (this.properties.has("token")) { scoreAdapter?.setData(scoreStore.getAllSorted()) scoreAdapter?.notifyDataSetChanged() this.srlScores.isRefreshing = false } } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment ScoreOverview. */ @JvmStatic fun newInstance() = ScoreOverview() } }
8
Kotlin
0
2
0c0d790c03980e09bfed49910daa229a109c8a6a
2,928
BlackJackClient
MIT License
kotlin-electron/src/jsMain/generated/electron/utility/Net.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron.utility typealias Net = electron.core.Net
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
114
kotlin-wrappers
Apache License 2.0
codegen/smithy-aws-swift-codegen/src/main/kotlin/software/amazon/smithy/aws/swift/codegen/restxml/AWSHttpProtocolRestXMLCustomizations.kt
awslabs
278,475,105
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.smithy.aws.swift.codegen.restxml import software.amazon.smithy.aws.swift.codegen.AWSHttpProtocolCustomizations import software.amazon.smithy.aws.swift.codegen.AWSHttpRequestXMLEncoder import software.amazon.smithy.aws.swift.codegen.AWSHttpResponseXMLDecoder import software.amazon.smithy.swift.codegen.integration.ClientProperty class AWSHttpProtocolRestXMLCustomizations : AWSHttpProtocolCustomizations() { override fun getClientProperties(): List<ClientProperty> { val properties = mutableListOf<ClientProperty>() val requestEncoderOptions = mutableMapOf<String, String>() val responseDecoderOptions = mutableMapOf<String, String>() // TODO: Subject to change when we figure out which strategy to use for XML // TODO: Subject to change if Foundation dependency is removed requestEncoderOptions["dateEncodingStrategy"] = ".secondsSince1970" responseDecoderOptions["dateDecodingStrategy"] = ".secondsSince1970" responseDecoderOptions["trimValueWhitespaces"] = "false" responseDecoderOptions["removeWhitespaceElements"] = "true" properties.add(AWSHttpRequestXMLEncoder(requestEncoderOptions)) properties.add(AWSHttpResponseXMLDecoder(responseDecoderOptions)) return properties } }
75
Kotlin
12
161
f9ff097e413cba9260ecf4c087664e1c65a38527
1,429
aws-sdk-swift
Apache License 2.0
common/src/main/kotlin/juuxel/adorn/lib/AdornTags.kt
SiongSng
379,790,081
true
{"Kotlin": 357071, "Java": 13797, "Shell": 1583}
package juuxel.adorn.lib import juuxel.adorn.AdornCommon import juuxel.adorn.platform.PlatformBridges import net.minecraft.block.Block import net.minecraft.item.Item import net.minecraft.tag.Tag import net.minecraft.util.Identifier object AdornTags { val CHAIRS = blockAndItem(AdornCommon.id("chairs")) val TABLES = blockAndItem(AdornCommon.id("tables")) val DRAWERS = blockAndItem(AdornCommon.id("drawers")) val KITCHEN_COUNTERS = blockAndItem(AdornCommon.id("kitchen_counters")) val KITCHEN_CUPBOARDS = blockAndItem(AdornCommon.id("kitchen_cupboards")) val KITCHEN_BLOCKS = blockAndItem(AdornCommon.id("kitchen_blocks")) val SOFAS = blockAndItem(AdornCommon.id("sofas")) val POSTS = blockAndItem(AdornCommon.id("posts")) val PLATFORMS = blockAndItem(AdornCommon.id("platforms")) val STEPS = blockAndItem(AdornCommon.id("steps")) val WOODEN_POSTS = blockAndItem(AdornCommon.id("wooden_posts")) val WOODEN_PLATFORMS = blockAndItem(AdornCommon.id("wooden_platforms")) val WOODEN_STEPS = blockAndItem(AdornCommon.id("wooden_steps")) val STONE_POSTS = blockAndItem(AdornCommon.id("stone_posts")) val STONE_PLATFORMS = blockAndItem(AdornCommon.id("stone_platforms")) val STONE_STEPS = blockAndItem(AdornCommon.id("stone_steps")) val SHELVES = blockAndItem(AdornCommon.id("shelves")) val WOODEN_SHELVES = blockAndItem(AdornCommon.id("wooden_shelves")) val CHIMNEYS = blockAndItem(AdornCommon.id("chimneys")) val STONE_RODS = item(Identifier("c", "stone_rods")) fun init() {} private fun block(id: Identifier): Tag.Identified<Block> = PlatformBridges.tags.block(id).toIdentified(id) private fun item(id: Identifier): Tag.Identified<Item> = PlatformBridges.tags.item(id).toIdentified(id) private fun blockAndItem(id: Identifier) = TagPair( block(id), item(id) ) private fun <T> Tag<T>.toIdentified(id: Identifier): Tag.Identified<T> = if (this is Tag.Identified<T>) this else object : Tag<T> by this, Tag.Identified<T> { override fun getId() = id } data class TagPair(val block: Tag.Identified<Block>, val item: Tag.Identified<Item>) }
0
null
0
0
0179c07871d32dc44ce0ec04c9cb94aed3cd2ab6
2,214
Adorn
MIT License
src/main/kotlin/com/nekofar/milad/intellij/gridsome/cli/GridsomeCliProjectModuleBuilder.kt
KartanHQ
599,509,782
false
{"Kotlin": 2861}
package com.nekofar.milad.intellij.gridsome.cli import com.intellij.ide.util.projectWizard.WebTemplateNewProjectWizard import com.intellij.ide.wizard.GeneratorNewProjectWizardBuilderAdapter class GridsomeCliProjectModuleBuilder : GeneratorNewProjectWizardBuilderAdapter(WebTemplateNewProjectWizard( GridsomeCliProjectGenerator() ))
1
Kotlin
0
0
a24f2ce2990984c56a4130715027a534d74a2f27
338
intellij-gridsome
Apache License 2.0
src/commonTest/kotlin/org/tix/integrations/shared/custom/CustomRequestMethodTest.kt
ncipollo
336,920,234
false
{"Kotlin": 601503}
package org.tix.integrations.shared.custom import io.ktor.http.* import kotlin.test.Test import kotlin.test.expect class CustomRequestMethodTest { @Test fun toHttpMethod() { val expected = listOf(HttpMethod.Delete, HttpMethod.Get, HttpMethod.Post, HttpMethod.Put) expect(expected) { CustomRequestMethod.values().map { it.toHttpMethod() } } } }
8
Kotlin
0
3
02f87c827c1159af055f5afc5481afd45c013703
393
tix-core
MIT License
feature4a/src/main/java/com/example/feature4a/di/Feature4aActivityModule.kt
ChicK00o
194,475,938
false
null
package com.example.feature4a.di import android.support.v7.app.AppCompatActivity import com.example.core_utils.di.BaseActivityModule import com.example.core_utils.di.ActivityScope import com.example.feature4a.Feature4aActivity import dagger.Binds import dagger.Module @Module(includes = arrayOf(BaseActivityModule::class)) abstract class Feature4aActivityModule { @Binds @ActivityScope internal abstract fun appCompatActivity(feature4aActivity: Feature4aActivity): AppCompatActivity }
0
Kotlin
0
1
83626707c0559443c90d60afb009d9dd5ba29b5f
498
android-multi-module-playground
MIT License
android/player/src/test/java/com/intuit/playerui/android/renderer/HydrationScopeTest.kt
player-ui
513,673,239
false
{"TypeScript": 1216687, "Kotlin": 940522, "Swift": 571596, "Starlark": 119515, "C++": 43679, "JavaScript": 11082, "Shell": 10507, "Ruby": 5513, "MDX": 2317, "Smarty": 2143, "CSS": 1627, "Just": 1552}
package com.intuit.playerui.android.renderer import android.view.View import android.widget.TextView import com.intuit.playerui.android.AndroidPlayer import com.intuit.playerui.android.AssetContext import com.intuit.playerui.android.asset.SuspendableAsset import com.intuit.playerui.core.asset.Asset import com.intuit.playerui.core.bridge.Node import com.intuit.playerui.core.bridge.runtime.serialize import com.intuit.playerui.core.bridge.serialization.serializers.NodeSerializer import com.intuit.playerui.core.flow.forceTransition import com.intuit.playerui.core.player.state.inProgressState import com.intuit.playerui.j2v8.bridge.runtime.J2V8 import com.intuit.playerui.plugins.coroutines.flowScope import com.intuit.playerui.utils.makeFlow import com.intuit.playerui.utils.start import com.intuit.playerui.utils.test.runBlockingTest import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json.Default.encodeToString import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class HydrationScopeTest : BaseRenderableAssetTest() { private var completed: Boolean = false inner class TestAsset(assetContext: AssetContext) : SuspendableAsset<Node>(assetContext, NodeSerializer()) { override suspend fun initView(data: Node): View = TextView(context) override suspend fun View.hydrate(data: Node) { hydrationScope.launch { delay(500) completed = true } } val currentHydrationScope get() = hydrationScope } override val asset: Asset = J2V8.create().serialize( mapOf( "id" to "some-id", "type" to "test", ), ) as Asset override val player by lazy { AndroidPlayer().apply { registerAsset("test", ::TestAsset) } } override val assetContext: AssetContext by lazy { AssetContext(mockContext, asset, player, ::TestAsset) } @BeforeEach fun setup() { // Need to start flow for flowScope to be valid player.start(makeFlow(encodeToString(NodeSerializer(), asset))) } @Test fun `test awaiting async view stub doesn't cancel parent scope`() = runBlocking { val test = TestAsset(assetContext) val asyncView = test.render(mockContext) as SuspendableAsset.AsyncViewStub test.currentHydrationScope.cancel("hello") assertNull(asyncView.awaitView()) } @Test fun `test hydration scope can launch coroutines`() = runBlocking { val test = TestAsset(assetContext) val asyncView = test.render(mockContext) as SuspendableAsset.AsyncViewStub asyncView.awaitView() waitForCompleted() } @Test fun `test existing hydration scope is cancelled on re-render`() = runBlocking { val test = TestAsset(assetContext) test.render(mockContext) val currentHydrationScope = test.currentHydrationScope assertTrue(currentHydrationScope.isActive) player.recycle() test.render(mockContext) assertFalse(currentHydrationScope.isActive) } @Test fun `test hydration scope is refreshed on re-render`() = runBlocking { val test = TestAsset(assetContext) test.render(mockContext) val firstHydrationScope = test.currentHydrationScope assertTrue(firstHydrationScope.isActive) player.recycle() test.render(mockContext) val secondHydrationScope = test.currentHydrationScope assertTrue(secondHydrationScope.isActive) assertFalse(firstHydrationScope.isActive) assertNotEquals(firstHydrationScope, secondHydrationScope) } @Test fun `test hydration scope is cancelled on flow end`() = runBlocking { val test = TestAsset(assetContext) test.render(mockContext) player.inProgressState?.forceTransition("") assertFalse(player.flowScope!!.isActive) assertFalse(test.currentHydrationScope.isActive) assertFalse(completed) } @Test fun `test hydration scope is cancelled on player release`() = runBlocking { val test = TestAsset(assetContext) test.render(mockContext) player.release() assertFalse(player.flowScope!!.isActive) assertFalse(test.currentHydrationScope.isActive) assertFalse(completed) } private fun waitForCompleted(count: Int = 5, delay: Long = 500) { waitForCondition(count, delay) { completed } } private fun waitForCondition(count: Int = 5, delay: Long = 500, conditions: () -> Boolean = { true }) { var counter = 0 while (!conditions() && counter++ < count) runBlockingTest { delay(delay) } assertTrue(conditions()) } }
78
TypeScript
45
71
12b4867a6996848ec14ccefbdbe74360052bf3a5
5,112
player
MIT License
app/src/main/java/com/vcheck/sdk/core/util/utils/common_utils.kt
VCheckOrg
791,853,873
false
{"Kotlin": 332989, "Java": 13291}
package com.vcheck.sdk.core.util.utils import android.annotation.SuppressLint import android.content.Context import android.media.Image import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import androidx.core.content.ContextCompat.getSystemService import androidx.core.graphics.ColorUtils import java.io.File @SuppressLint("MissingPermission") fun vibrateDevice(context: Context, duration: Long) { val vibrator = getSystemService(context, Vibrator::class.java) vibrator?.let { if (Build.VERSION.SDK_INT >= 26) { it.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE)) } else { @Suppress("DEPRECATION") it.vibrate(100) } } } fun getFolderSizeLabel(file: File): String { val size = getFolderSize(file).toDouble() / 1000.0 // Get size and convert bytes into KB. return if (size >= 1024) { (size / 1024).toString() + " MB" } else { "$size KB" } } fun getFolderSize(file: File): Long { var size: Long = 0 if (file.isDirectory && file.listFiles() != null && file.listFiles()!!.isNotEmpty()) { for (child in file.listFiles()!!) { size += getFolderSize(child) } } else { size = file.length() } return size } fun fillBytes(planes: Array<Image.Plane>, yuvBytes: Array<ByteArray?>) { for (i in planes.indices) { val buffer = planes[i].buffer if (yuvBytes[i] == null) { yuvBytes[i] = ByteArray(buffer.capacity()) } buffer[yuvBytes[i]!!] } } fun isColorDark(color: Int): Boolean { return ColorUtils.calculateLuminance(color) < 0.5 }
0
Kotlin
0
0
88ddb5aba95f38020853cdf5b1c898455af0d1c3
1,710
vycheck_android
MIT License
common/grid/src/test/kotlin/com/curtislb/adventofcode/common/grid/EmptyGridTest.kt
curtislb
226,797,689
false
{"Kotlin": 1905641}
package com.curtislb.adventofcode.common.grid import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows /** * Tests the [EmptyGrid] object. */ class EmptyGridTest { private lateinit var grid: Grid<Any> @BeforeEach fun setUp() { grid = emptyGrid() } @Test fun height_isZero() { assertThat(grid.height).isEqualTo(0) } @Test fun width_isZero() { assertThat(grid.width).isEqualTo(0) } @Test fun get_indices_bothZero() { assertThrows<IndexOutOfBoundsException> { grid[0, 0] } } @Test fun get_indices_rowIndexZero() { assertThrows<IndexOutOfBoundsException> { grid[0, 1] } } @Test fun get_indices_colIndexZero() { assertThrows<IndexOutOfBoundsException> { grid[1, 0] } } @Test fun get_indices_bothNonzero() { assertThrows<IndexOutOfBoundsException> { grid[1, 2] } } @Test fun row_indexZero() { assertThrows<IndexOutOfBoundsException> { grid.row(0) } } @Test fun row_indexNonzero() { assertThrows<IndexOutOfBoundsException> { grid.row(1) } } @Test fun column_indexZero() { assertThrows<IndexOutOfBoundsException> { grid.column(0) } } @Test fun column_indexNonzero() { assertThrows<IndexOutOfBoundsException> { grid.column(1) } } @Test fun rows_isEmpty() { assertThat(grid.rows()).isEmpty() } @Test fun columns_isEmpty() { assertThat(grid.columns()).isEmpty() } @Test fun equals_self() { assertThat(grid).isEqualTo(grid) } @Test fun equals_emptyGrid() { val other = emptyGrid<Any>() assertThat(grid).isEqualTo(other) } @Test fun equals_emptyImmutableGrid() { val other = gridOf<Any>() assertThat(grid).isEqualTo(other) } @Test fun equals_emptyMutableGrid() { val other = mutableGridOf<Any>() assertThat(grid).isEqualTo(other) } @Test fun equals_nullGrid() { val other: Grid<Any>? = null assertThat(grid).isNotEqualTo(other) } @Test fun equals_nonEmptyGrid() { val other = gridOf(listOf(0)) assertThat(grid).isNotEqualTo(other) } @Test fun hashCode_isConsistent() { val grid = emptyGrid<Any>() assertThat(grid.hashCode()) .isEqualTo(grid.hashCode()) .isEqualTo(emptyGrid<Any>().hashCode()) } @Test fun toString_isCorrect() { assertThat(grid.toString()).isEqualTo("[]") } }
0
Kotlin
1
1
addf5ae8d002d30abf1ab816e23502a296debc4e
2,693
AdventOfCode
MIT License
core/src/main/java/br/com/moov/core/result/Result.kt
alex-tavella
79,517,727
false
null
/* * 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. */ package br.com.moov.core.result sealed class Result<out Data, out Error> { data class Ok<out Data>(val value: Data) : Result<Data, Nothing>() data class Err<out Error>(val error: Error) : Result<Nothing, Error>() fun isSuccess(): Boolean { return this is Ok } fun isError(): Boolean { return !isSuccess() } fun getOrNull(): Data? { return when (this) { is Err -> null is Ok -> value } } fun errorOrNull(): Error? { return when (this) { is Err -> error is Ok -> null } } fun <Data2> map(transform: (Data) -> Data2): Result<Data2, Error> { return when (this) { is Ok -> Ok(transform(value)) is Err -> this } } fun <Error2> mapError(transform: (Error) -> Error2): Result<Data, Error2> { return when (this) { is Ok -> this is Err -> Err(transform(error)) } } fun onSuccess(action: (Data) -> Unit): Result<Data, Error> { if (this is Ok) action(value) return this } fun onError(action: (Error) -> Unit): Result<Data, Error> { if (this is Err) action(error) return this } }
3
Kotlin
1
0
5f14670bddfbbdc0da1a3d394193dc87f9ea1996
1,848
MooV
Apache License 2.0
app/src/main/java/com/example/clock/viewmodel/ClockViewModel.kt
lliukhi
846,473,979
false
{"Kotlin": 29272}
package com.example.clock.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.switchMap import com.example.clock.data.model.Clock import com.example.clock.data.repository.ClockRepository class ClockViewModel : ViewModel() { private val clockData = MutableLiveData<String>() var clockList = ArrayList<Clock>() val clockLiveData :LiveData<List<Clock>> = clockData.switchMap { ClockRepository.searchClock() } fun updateClock(timeZone: String) { clockData.value = timeZone } }
0
Kotlin
0
0
052d41922b28e8e95c9f34b9620798a4d1838b5e
637
clock
Apache License 2.0
notifications/src/main/java/io/karte/android/notifications/internal/wrapper/MessageWrapper.kt
tmk815
405,880,429
true
{"Kotlin": 688922, "Java": 20411, "Ruby": 10189, "Shell": 3734, "Groovy": 710, "CSS": 157}
// // Copyright 2020 PLAID, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 io.karte.android.notifications.internal.wrapper import io.karte.android.notifications.KarteAttributes import org.json.JSONObject private const val KEY_ATTRIBUTES = "krt_attributes" internal const val KEY_PUSH_NOTIFICATION_FLAG = "krt_push_notification" internal const val KEY_MASS_PUSH_NOTIFICATION_FLAG = "krt_mass_push_notification" internal const val KEY_EVENT_VALUES = "krt_event_values" internal const val KEY_CAMPAIGN_ID = "krt_campaign_id" internal const val KEY_SHORTEN_ID = "krt_shorten_id" internal class MessageWrapper(val data: Map<String, String>) { val attributes: KarteAttributes? by lazy { data[KEY_ATTRIBUTES]?.let { runCatching { KarteAttributes().load(JSONObject(it)) }.getOrNull() } } val isTargetPush = data[KEY_PUSH_NOTIFICATION_FLAG]?.toBoolean() ?: false val isMassPush = data[KEY_MASS_PUSH_NOTIFICATION_FLAG]?.toBoolean() ?: false val isKartePush = isTargetPush || isMassPush val eventValues = data[KEY_EVENT_VALUES] val campaignId = data[KEY_CAMPAIGN_ID] val shortenId = data[KEY_SHORTEN_ID] }
0
null
0
0
3b6ba3ee7e8b4ca1298b12f0819e6b8b0efb8017
1,696
karte-android-sdk
Apache License 2.0
shared/src/iosMain/kotlin/util/platform.kt
hyeok713
664,711,285
false
null
package util actual fun getPlatformName(): String = "iOS"
0
Kotlin
0
0
4daab9cac93d28ef0f91517562a5259d8c618015
59
compose-multiplatform-ios-android-template
Apache License 2.0
utbot-core/src/main/kotlin/org/utbot/common/ClassLoaderUtil.kt
UnitTestBot
480,810,501
false
null
package org.utbot.common import java.net.URLClassLoader /** * Checks that the class given by its binary name is on classpath of this classloader. * * Note: if the specified class is on classpath, `true` is returned even when * superclass (or implemented interfaces) aren't on the classpath. */ fun URLClassLoader.hasOnClasspath(classBinaryName: String): Boolean { val classFqn = classBinaryName.replace('.', '/').plus(".class") return this.findResource(classFqn) != null }
397
Kotlin
32
91
f9c95348acb59c1b4fc212ecb36e6b2968e9ac5a
487
UTBotJava
Apache License 2.0
src/main/kotlin/com/innopolis/innoqueue/webclients/firebase/service/NotificationTextFormerService.kt
InnoQueue
614,501,046
false
{"Kotlin": 241002, "HTML": 2611, "Python": 1208, "Dockerfile": 799, "Shell": 440, "Procfile": 86}
package com.innopolis.innoqueue.webclients.firebase.service import com.innopolis.innoqueue.webclients.firebase.model.FirebaseRecipients import com.innopolis.innoqueue.webclients.firebase.model.TitleBody interface NotificationTextFormerService { fun getTitleBody(firebaseRecipients: FirebaseRecipients, isPersonal: Boolean): TitleBody }
25
Kotlin
0
1
e02530d0a57d077572d1f75013b0beb995b35f18
342
backend
MIT License
src/main/kotlin/com/innopolis/innoqueue/webclients/firebase/service/NotificationTextFormerService.kt
InnoQueue
614,501,046
false
{"Kotlin": 241002, "HTML": 2611, "Python": 1208, "Dockerfile": 799, "Shell": 440, "Procfile": 86}
package com.innopolis.innoqueue.webclients.firebase.service import com.innopolis.innoqueue.webclients.firebase.model.FirebaseRecipients import com.innopolis.innoqueue.webclients.firebase.model.TitleBody interface NotificationTextFormerService { fun getTitleBody(firebaseRecipients: FirebaseRecipients, isPersonal: Boolean): TitleBody }
25
Kotlin
0
1
e02530d0a57d077572d1f75013b0beb995b35f18
342
backend
MIT License
misk-admin/src/main/kotlin/misk/web/dashboard/DashboardNavbarStatus.kt
cashapp
113,107,217
false
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
package misk.web.dashboard import misk.web.dashboard.ValidWebEntry.Companion.slugify /** * Banner text to show below the dashboard navbar * 0 or 1 [DashboardNavbarStatus] should be bound per dashboard */ @Deprecated("DashboardNavbarStatus will not be supported in Misk Dashboards v2 and will be deleted shortly. Use custom UI to surface status information.") data class DashboardNavbarStatus( val dashboard_slug: String, val status: String ) : ValidWebEntry(valid_slug = dashboard_slug) @Deprecated("DashboardNavbarStatus will not be supported in Misk Dashboards v2 and will be deleted shortly. Use custom UI to surface status information.") inline fun <reified DA : Annotation> DashboardNavbarStatus( status: String ) = DashboardNavbarStatus( dashboard_slug = slugify<DA>(), status = status )
169
Kotlin
169
400
13dcba0c4e69cc2856021270c99857e7e91af27d
810
misk
Apache License 2.0
src/main/kotlin/me/luna/trollhack/module/modules/render/HungerOverlay.kt
NotMonika
509,752,527
false
{"Kotlin": 2035807, "Java": 168054, "GLSL": 91098}
package me.luna.trollhack.module.modules.render import me.luna.trollhack.event.events.render.RenderOverlayEvent import me.luna.trollhack.event.listener import me.luna.trollhack.module.Category import me.luna.trollhack.module.Module import me.luna.trollhack.util.extension.fastCeil import me.luna.trollhack.util.graphics.GlStateUtils import me.luna.trollhack.util.items.foodValue import me.luna.trollhack.util.items.saturation import net.minecraft.client.gui.Gui import net.minecraft.client.gui.ScaledResolution import net.minecraft.init.MobEffects import net.minecraft.item.ItemFood import net.minecraft.util.ResourceLocation import net.minecraftforge.client.GuiIngameForge import net.minecraftforge.client.event.RenderGameOverlayEvent import org.lwjgl.opengl.GL11.glColor4f import kotlin.math.cos import kotlin.math.floor import kotlin.math.min internal object HungerOverlay : Module( name = "HungerOverlay", description = "Displays a helpful overlay over your hunger bar.", category = Category.RENDER ) { private val saturationOverlay = setting("Saturation Overlay", true) private val foodHungerOverlay = setting("Food Hunger Overlay", true) private val foodSaturationOverlay = setting("Food Saturation Overlay", true) private val icons = ResourceLocation("trollhack/textures/hungeroverlay.png") init { listener<RenderOverlayEvent.Post> { if (it.type != RenderGameOverlayEvent.ElementType.FOOD) return@listener val time = (System.currentTimeMillis() % 5000L) / 2500f val flashAlpha = -0.5f * cos(time * 3.1415927f) + 0.5f val stats = mc.player.foodStats val resolution = ScaledResolution(mc) val left = resolution.scaledWidth / 2 + 82 val top = resolution.scaledHeight - GuiIngameForge.right_height + 10 val item = mc.player.heldItemMainhand.item val foodValue = (item as? ItemFood)?.foodValue ?: 0 val saturation = (item as? ItemFood)?.saturation ?: 0.0f val newHungerValue = min(stats.foodLevel + foodValue, 20) val newSaturationValue = min((stats.saturationLevel + saturation), newHungerValue.toFloat()) GlStateUtils.blend(true) if (foodHungerOverlay.value && foodValue > 0) { drawHungerBar(stats.foodLevel, newHungerValue, left, top, flashAlpha) } if (saturationOverlay.value) { drawSaturationBar(0f, stats.saturationLevel, left, top, 1f) } if (foodSaturationOverlay.value && saturation > 0.0f) { drawSaturationBar(floor(stats.saturationLevel), newSaturationValue, left, top, flashAlpha) } mc.textureManager.bindTexture(Gui.ICONS) } } private fun drawHungerBar(start: Int, end: Int, left: Int, top: Int, alpha: Float) { val textureX = if (mc.player.isPotionActive(MobEffects.HUNGER)) 88 else 52 mc.textureManager.bindTexture(Gui.ICONS) drawBarHalf((start / 2f).toInt(), (end / 2f), left, top, textureX, alpha) } private fun drawSaturationBar(start: Float, end: Float, left: Int, top: Int, alpha: Float) { mc.textureManager.bindTexture(icons) drawBarFourth((start / 2f).toInt(), (end / 2f), left, top, alpha) } private fun drawBarHalf(start: Int, end: Float, left: Int, top: Int, textureX: Int, alpha: Float) { glColor4f(1f, 1f, 1f, alpha) for (currentBar in start..(end).fastCeil()) { val remainBars = min((floor((end - currentBar) * 2f) / 2f), 1f) val posX = left - (currentBar * 8) when (remainBars) { 1.0f -> mc.ingameGUI.drawTexturedModalRect(posX, top, textureX, 27, 9, 9) 0.5f -> mc.ingameGUI.drawTexturedModalRect(posX, top, textureX + 9, 27, 9, 9) } } glColor4f(1f, 1f, 1f, 1f) } private fun drawBarFourth(start: Int, end: Float, left: Int, top: Int, alpha: Float) { glColor4f(1f, 1f, 1f, alpha) for (currentBar in start..(end).fastCeil()) { val remainBars = min((floor((end - currentBar) * 4f) / 4f), 1f) val posX = left - (currentBar * 8) when (remainBars) { 1.00f -> mc.ingameGUI.drawTexturedModalRect(posX, top, 27, 0, 9, 9) 0.75f -> mc.ingameGUI.drawTexturedModalRect(posX, top, 18, 0, 9, 9) 0.50f -> mc.ingameGUI.drawTexturedModalRect(posX, top, 9, 0, 9, 9) 0.25f -> mc.ingameGUI.drawTexturedModalRect(posX, top, 0, 0, 9, 9) } } glColor4f(1f, 1f, 1f, 1f) } }
0
Kotlin
0
0
543ac418b69e0c7359cde487e828b4c3d2260241
4,661
MorisaHack
Do What The F*ck You Want To Public License
src/main/kotlin/com/example/arthur/testesReactive/repository/TaskRepository.kt
arthur-sh
370,512,400
false
null
package com.example.arthur.testesReactive.repository import com.example.arthur.testesReactive.domain.Task import org.springframework.data.mongodb.repository.Query import org.springframework.data.mongodb.repository.ReactiveMongoRepository import org.springframework.stereotype.Repository import reactor.core.publisher.Flux import reactor.core.publisher.Mono @Repository interface TaskRepository: ReactiveMongoRepository<Task, String> { fun findByName(name: String): Mono<Task> fun countByName(name: String): Mono<Long> fun deleteByName(name: String): Mono<Long> }
0
Kotlin
0
0
5bb4f9276f952d7dd527d2edc81fec5797c4a92f
576
KotlinWebfluxTests
MIT License
filesystem/src/jvmMain/kotlin/nio/NioSync.kt
illarionov
848,247,126
false
{"Kotlin": 1163678, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
/* * Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package at.released.weh.filesystem.nio import arrow.core.Either import arrow.core.left import at.released.weh.filesystem.error.BadFileDescriptor import at.released.weh.filesystem.error.SyncError import at.released.weh.filesystem.internal.delegatefs.FileSystemOperationHandler import at.released.weh.filesystem.op.Messages.fileDescriptorNotOpenMessage import at.released.weh.filesystem.op.sync.SyncFd internal class NioSync( private val fsState: NioFileSystemState, ) : FileSystemOperationHandler<SyncFd, SyncError, Unit> { override fun invoke(input: SyncFd): Either<SyncError, Unit> { val channel = fsState.get(input.fd) ?: return BadFileDescriptor(fileDescriptorNotOpenMessage(input.fd)).left() return channel.sync(input.syncMetadata) } }
1
Kotlin
0
3
8960e9ee5feb1ef319446725f4ca60e55d5b1c83
1,052
wasi-emscripten-host
Apache License 2.0
src/jvmMain/kotlin/org/duangsuse/bin/ByteStreamImpl.kt
duangsuse-valid-projects
233,615,277
false
null
package org.duangsuse.bin import org.duangsuse.bin.type.Buffer import org.duangsuse.bin.type.Cnt import org.duangsuse.bin.type.IdxRange import org.duangsuse.bin.type.Nat8 import java.io.InputStream import java.io.OutputStream class InStreamNat8Reader(private val in_stream: InputStream, private val mark_size: Cnt = 0): Nat8Reader, MarkReset, Closeable { override fun read(): Nat8 = in_stream.read() override fun readTo(buffer: Buffer, indices: IdxRange) { in_stream.read(buffer, indices.first, indices.size) } override fun mark() { in_stream.mark(mark_size) } override fun reset() { in_stream.reset() } override val estimate: Cnt get() = in_stream.available() override fun skip(n: Cnt) { in_stream.skip(n.toLong()) } override fun close() { in_stream.close() } } class OutStreamNat8Writer(private val out_stream: OutputStream): Nat8Writer, Flushable, Closeable { override fun write(x: Nat8) { out_stream.write(x) } override fun writeFrom(buffer: Buffer, indices: IdxRange) { out_stream.write(buffer, indices.first, indices.size) } override fun flush() { out_stream.flush() } override fun close() { out_stream.close() } }
0
Kotlin
0
3
48d877686a1255815910cae1ef20901fbc608ae9
1,157
SomeAXML
Apache License 2.0
app/src/main/java/org/ignisus/mangobet/MainActivity.kt
mangobet
709,247,514
false
{"Kotlin": 16274}
package org.ignisus.mangobet import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import org.ignisus.mangobet.ui.theme.MangoBetTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MangoBetTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "hi $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { MangoBetTheme { Greeting("Android") } }
0
Kotlin
0
0
ddab19e45f1863812f18a9f767dc5a410bd2ac06
1,308
mangobet-mobile
Creative Commons Zero v1.0 Universal
build/assets/compose/vitaminassets/flags/Tt.kt
Decathlon
511,157,831
false
{"Kotlin": 4443549, "HTML": 226066, "Swift": 163852, "TypeScript": 60822, "CSS": 53872, "JavaScript": 33103, "Handlebars": 771}
package com.decathlon.vitamin.compose.vitaminassets.flags import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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.group import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.decathlon.vitamin.compose.vitaminassets.FlagsGroup public val FlagsGroup.Tt: ImageVector get() { if (_tt != null) { return _tt!! } _tt = Builder(name = "Tt", defaultWidth = 28.0.dp, defaultHeight = 20.0.dp, viewportWidth = 28.0f, viewportHeight = 20.0f).apply { group { path(fill = SolidColor(Color(0xFFFFFFFF)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(0.0f, 2.25f) verticalLineTo(0.0179f) lineTo(28.0f, 0.0f) curveTo(28.0f, 0.0f, 28.0f, 1.1454f, 28.0f, 2.25f) lineTo(28.0f, 20.0179f) curveTo(28.0f, 20.0179f, 27.1046f, 20.0179f, 26.0f, 20.0179f) horizontalLineTo(2.0f) curveTo(0.8954f, 20.0179f, 0.0f, 20.0179f, 0.0f, 20.0179f) verticalLineTo(2.25f) close() } path(fill = SolidColor(Color(0xFFED233C)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(0.0f, 0.0179f) lineTo(28.0f, 0.0f) lineTo(28.0f, 20.0179f) horizontalLineTo(0.0f) verticalLineTo(0.0179f) close() } path(fill = SolidColor(Color(0xFFFFFFFF)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(15.9636f, 20.0072f) lineTo(0.0043f, 1.0606f) lineTo(0.0f, 0.0179f) lineTo(12.0859f, 0.0218f) lineTo(28.0f, 19.0023f) lineTo(28.0f, 20.0179f) lineTo(15.9636f, 20.0072f) close() } path(fill = SolidColor(Color(0xFF262626)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(17.9933f, 20.009f) lineTo(1.0f, 0.0f) horizontalLineTo(10.0f) lineTo(26.7615f, 20.0179f) lineTo(17.9933f, 20.009f) close() } } } .build() return _tt!! } private var _tt: ImageVector? = null
1
Kotlin
5
33
c2c9cfa43128d412b7b2841cabd76952a13db2e1
3,641
vitamin-design
Apache License 2.0
feature/webview/src/main/kotlin/org/bmsk/feature/webview/navigation/WebViewNavGraphImpl.kt
AndroidStudy-bmsk
632,254,827
false
{"Kotlin": 119717}
package org.bmsk.feature.webview.navigation import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import org.bmsk.feature.webview.WebViewRoute import org.bmsk.lifemash.feature.topic.api.WebViewNavGraph import org.bmsk.lifemash.feature.topic.api.WebViewNavGraphInfo import javax.inject.Inject class WebViewNavGraphImpl @Inject constructor() : WebViewNavGraph { override fun buildNavGraph(navGraphBuilder: NavGraphBuilder, navInfo: WebViewNavGraphInfo) { navGraphBuilder.composable( route = WebViewRoute.createWebViewRoute("{url}"), arguments = listOf( navArgument("url") { type = NavType.StringType }, ), ) { navBackStackEntry -> val url = navBackStackEntry.arguments?.getString("url") ?: "" WebViewRoute(url = url) } } }
1
Kotlin
1
0
3e0d37ea57a8cb8877bd65130e249ceeea897d51
976
LifeMash-NewsApp
MIT License
plugins/kotlin-dataframe/testData/testUtils.kt
Kotlin
259,256,617
false
{"Kotlin": 8227503, "Java": 17608, "JavaScript": 11483, "CSS": 3083, "HTML": 137, "Shell": 73}
import org.jetbrains.kotlinx.dataframe.* import org.jetbrains.kotlinx.dataframe.annotations.* import org.jetbrains.kotlinx.dataframe.api.* import org.jetbrains.kotlinx.dataframe.io.* inline fun <reified T> DataFrame<T>.compareSchemas(strict: Boolean = false) { val schema = schema() val compileTimeSchema = compileTimeSchema() val compare = compileTimeSchema.compare(schema) require(if (strict) compare.isEqual() else compare.isSuperOrEqual()) { buildString { appendLine("Comparison result: $compare") appendLine("Runtime:") appendLine(schema.toString()) appendLine("Compile:") appendLine(compileTimeSchema.toString()) } } }
235
Kotlin
60
833
54d00e69ae7c06ff254c6591242413eaf7894f01
722
dataframe
Apache License 2.0
src/test/kotlin/com/yapp/web2/domain/remind/service/RemindServiceTest.kt
YAPP-19th
399,059,127
false
null
//package com.yapp.web2.domain.remind.service // //import com.yapp.web2.domain.account.entity.Account //import com.yapp.web2.domain.account.repository.AccountRepository //import com.yapp.web2.domain.bookmark.entity.Bookmark //import com.yapp.web2.domain.bookmark.entity.Remind //import com.yapp.web2.domain.bookmark.repository.BookmarkRepository //import com.yapp.web2.domain.remind.entity.dto.ReadRemindListRequest //import com.yapp.web2.domain.remind.entity.dto.RemindCycleRequest //import com.yapp.web2.domain.remind.entity.dto.RemindToggleRequest //import com.yapp.web2.exception.custom.RemindCycleValidException //import com.yapp.web2.infra.fcm.FirebaseService //import com.yapp.web2.security.jwt.JwtProvider //import com.yapp.web2.util.RemindCycleUtil //import io.mockk.every //import io.mockk.impl.annotations.InjectMockKs //import io.mockk.impl.annotations.MockK //import io.mockk.junit5.MockKExtension //import io.mockk.verify //import org.assertj.core.api.Assertions.assertThat //import org.junit.jupiter.api.BeforeEach //import org.junit.jupiter.api.Test //import org.junit.jupiter.api.assertAll //import org.junit.jupiter.api.assertThrows //import org.junit.jupiter.api.extension.ExtendWith //import org.springframework.data.repository.findByIdOrNull //import java.time.LocalDate // //@ExtendWith(MockKExtension::class) //internal class RemindServiceTest { // // @InjectMockKs // private lateinit var remindService: RemindService // // @MockK // private lateinit var bookmarkRepository: BookmarkRepository // // @MockK // private lateinit var accountRepository: AccountRepository // // @MockK // private lateinit var jwtProvider: JwtProvider // // @MockK // private lateinit var firebaseService: FirebaseService // // private lateinit var account: Account // private lateinit var bookmark1: Bookmark // private lateinit var bookmark2: Bookmark // private lateinit var bookmarkList: List<Bookmark> // // @BeforeEach // fun setup() { // account = Account("test@gmail.com") // bookmark1 = Bookmark(1L, 2L, "https://www.naver.com") // bookmark2 = Bookmark(1L, 2L, "https://www.google.com") // bookmarkList = listOf(bookmark1, bookmark2) // } // // @Test // fun `리마인드 알람 설정을 OFF 한다`() { // // given // val request = RemindToggleRequest(false) // // // mock // every { bookmarkRepository.findAllByUserId(any()) } returns bookmarkList // every { bookmarkRepository.save(any()) } returns bookmark1 // every { accountRepository.findByIdOrNull(any()) } returns account // every { jwtProvider.getIdFromToken(any()) } returns 1L // // // when // remindService.changeRemindToggle(request, "token") // // // then // assertAll( // { assertThat(account.remindToggle).isEqualTo(false) }, // { bookmarkList.stream().forEach { // assertThat(it.remindTime).isNull() // } } // ) // } // // @Test // fun `리마인드 주기를 변경한다`() { // // given // val request1 = RemindCycleRequest(RemindCycleUtil.THIRTY_DAYS.days) // // // mock // every { accountRepository.findByIdOrNull(any()) } returns account // every { jwtProvider.getIdFromToken(any()) } returns 1L // // // when // remindService.updateRemindAlarmCycle(request1, "token") // // // then // assertThat(account.remindCycle).isEqualTo(30) // } // // @Test // fun `리마인드 주기가 3, 7, 14, 30일이 아니면 에러를 반환한다`() { // // given // val request1 = RemindCycleRequest(4) // val request2 = RemindCycleRequest(11) // // // mock // every { accountRepository.findByIdOrNull(any()) } returns account // every { jwtProvider.getIdFromToken(any()) } returns 1L // // // when & then // assertAll( // { assertThrows<RemindCycleValidException> { remindService.updateRemindAlarmCycle(request1, "token") } }, // { assertThrows<RemindCycleValidException> { remindService.updateRemindAlarmCycle(request2, "token") } } // ) // } // // @Test // fun `웹푸쉬 발송 후 Client가 확인하지 않은 리마인드 리스트를 조회한다`() { // // } // // @Test // fun `Client가 리마인드를 확인했다는 처리를 진행한다`() { // // given // val bookmarkIdList: MutableList<String> = mutableListOf("61bdbbaa72b0f85372ad57c8", "16cdaa73j0f23785ad57c9") // val request = ReadRemindListRequest(bookmarkIdList) // // // mock // every { bookmarkRepository.findByIdOrNull("61bdbbaa72b0f85372ad57c8") } returns bookmark1 // every { bookmarkRepository.findByIdOrNull("16cdaa73j0f23785ad57c9") } returns bookmark2 // every { bookmarkRepository.save(any()) } returns bookmark1 // // // when // remindService.remindCheckUpdate(request) // // // then // assertAll( // { verify(exactly = bookmarkIdList.size) { bookmarkRepository.save(any()) } }, // { assertThat(bookmark1.remindCheck).isTrue() }, // { assertThat(bookmark2.remindCheck).isTrue() } // ) // } // // @Test // fun `리마인드 북마크 조회 시 발송 시각이 오늘이 아닌 리마인드들은 삭제한다`() { // // given // val reminds: MutableList<Remind> = mutableListOf( // Remind("2022-01-01"), // Remind("2022-01-02"), // Remind("2022-01-03"), // Remind("2022-01-04"), // Remind(LocalDate.now().toString()), // ) // val bookmark = Bookmark(1L, 1L, "test") // bookmark.remindList = reminds // val bookmarks: List<Bookmark> = listOf(bookmark) // // every { bookmarkRepository.findAllTodayRemindBookmarks(any()) } returns bookmarks // // // when // val actual: List<Bookmark> = remindService.getRemindBookmark() // // // then // assertAll( // { assertThat(actual[0].remindList.size).isEqualTo(1) }, // { assertThat(actual[0].remindList[0].remindTime).isEqualTo(LocalDate.now().toString()) } // ) // } //}
10
Kotlin
1
7
ecc6a3da2a66dceb1a25a4cfe9ed699f0325180a
6,033
Web-Team-2-Backend
Apache License 2.0
app/src/main/java/za/co/dubedivine/journalapp/firebaseSyncService/FirebaseSyncService.kt
dubeboy
139,355,314
false
{"Kotlin": 43699}
package za.co.dubedivine.journalapp.firebaseSyncService import android.arch.lifecycle.LiveData import android.support.v7.preference.PreferenceManager import android.util.Log import android.widget.Toast import za.co.dubedivine.journalapp.executors.AppExecutors import com.google.firebase.firestore.FirebaseFirestore import za.co.dubedivine.journalapp.database.AppDatabase import za.co.dubedivine.journalapp.database.JournalEntry import za.co.dubedivine.journalapp.ui.settings.PreferenceSettingFragment.Companion.PREF_EMAIL import java.util.concurrent.Executor import java.util.HashMap class FirebaseSyncService : com.firebase.jobdispatcher.JobService() { private var exec: Executor? = AppExecutors.networkIO() private var journals: LiveData<List<JournalEntry>>? = null override fun onStopJob(job: com.firebase.jobdispatcher.JobParameters?): Boolean { journals = null exec = null Log.d("FirebaseSyncService", "stopping job") // jobFinished(job!!, false) return true } override fun onStartJob(job: com.firebase.jobdispatcher.JobParameters?): Boolean { if(exec == null) exec = AppExecutors.networkIO() Log.d("FirebaseSyncService", "starting job") exec?.execute { val database = AppDatabase.getInstance(this.application) journals = database.journalDao().loadAllTasks() val pref = PreferenceManager.getDefaultSharedPreferences(this) val email = pref.getString(PREF_EMAIL, "") val map = HashMap<String, Any>() journals?.observeForever { val db = FirebaseFirestore.getInstance() val collection = db.collection("Journals") it?.forEach { map.put("title", it.title) map.put("body", it.body) map.put("email", email) map.put("created_at", it.createdAt) map.put("modified_at", it.modifiedAt) map.put("mood", it.mood) } collection.add(map) } } return true } }
0
Kotlin
0
0
1b874bea7a367ddcf565b71434139c8ed5ecaf09
2,141
ALCJournalAPP
MIT License
sample/shared/shared/src/commonMain/kotlin/com/arkivanov/sample/shared/counters/PreviewCountersComponent.kt
arkivanov
437,015,897
false
{"Kotlin": 700677}
package com.arkivanov.sample.shared.counters import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.router.stack.ChildStack import com.arkivanov.decompose.value.MutableValue import com.arkivanov.decompose.value.Value import com.arkivanov.sample.shared.PreviewComponentContext import com.arkivanov.sample.shared.counters.counter.CounterComponent import com.arkivanov.sample.shared.counters.counter.PreviewCounterComponent class PreviewCountersComponent : CountersComponent, ComponentContext by PreviewComponentContext { override val childStack: Value<ChildStack<*, CounterComponent>> = MutableValue( ChildStack( configuration = Unit, instance = PreviewCounterComponent(), ) ) override fun onBackClicked() {} override fun onBackClicked(toIndex: Int) {} }
8
Kotlin
84
2,207
8af551e8895951a5082a5d2750335713d673f80b
865
Decompose
Apache License 2.0
app/src/main/java/org/discovr/mobile/movies/data/repository/MovieRepository.kt
asatger
711,133,406
false
{"Kotlin": 35858}
package org.discovr.mobile.movies.data.repository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import org.discovr.mobile.core.data.remote.mappers.toDomain import org.discovr.mobile.core.data.util.networkBoundResource import org.discovr.mobile.core.domain.Page import org.discovr.mobile.core.domain.Resource import org.discovr.mobile.movies.data.remote.MovieRemoteService import org.discovr.mobile.movies.data.remote.mappers.toDomain import org.discovr.mobile.movies.domain.MovieSummary class MovieRepository( private val movieRemoteService: MovieRemoteService ) { private val nowPlayingMoviesCache: MutableMap<Int, Page<MovieSummary>> = mutableMapOf() fun getNowPlaying(page: Int): Flow<Resource<Page<MovieSummary>, Throwable>> = networkBoundResource( query = { flowOf(this.nowPlayingMoviesCache[page] ?: Page.empty(page)) }, fetch = { this.movieRemoteService.getNowPlaying(page) }, saveFetchResult = { this.nowPlayingMoviesCache[page] = it.toDomain { remote -> remote.toDomain() } }, shouldFetch = { it?.results.isNullOrEmpty() } ) }
0
Kotlin
0
0
68bbb4e74cfc25b3d0b974f0e30a55ff64e2404b
1,170
discovr
MIT License
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/Serverless.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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.CssGgIcons public val CssGgIcons.Serverless: ImageVector get() { if (_serverless != null) { return _serverless!! } _serverless = Builder(name = "Serverless", 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(11.7872f, 6.0f) horizontalLineTo(5.0f) verticalLineTo(9.0f) horizontalLineTo(10.6953f) lineTo(11.7872f, 6.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.9674f, 11.0f) horizontalLineTo(5.0f) verticalLineTo(14.0f) horizontalLineTo(8.8754f) lineTo(9.9674f, 11.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.0038f, 14.0f) lineTo(12.0957f, 11.0f) horizontalLineTo(20.0f) verticalLineTo(14.0f) horizontalLineTo(11.0038f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.1475f, 16.0f) horizontalLineTo(5.0f) verticalLineTo(19.0f) horizontalLineTo(7.0556f) lineTo(8.1475f, 16.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.1839f, 19.0f) lineTo(10.2759f, 16.0f) horizontalLineTo(20.0f) verticalLineTo(19.0f) horizontalLineTo(9.1839f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.8236f, 9.0f) lineTo(13.9156f, 6.0f) horizontalLineTo(20.0f) verticalLineTo(9.0f) horizontalLineTo(12.8236f) close() } } .build() return _serverless!! } private var _serverless: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
3,902
compose-icons
MIT License
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/Serverless.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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.CssGgIcons public val CssGgIcons.Serverless: ImageVector get() { if (_serverless != null) { return _serverless!! } _serverless = Builder(name = "Serverless", 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(11.7872f, 6.0f) horizontalLineTo(5.0f) verticalLineTo(9.0f) horizontalLineTo(10.6953f) lineTo(11.7872f, 6.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.9674f, 11.0f) horizontalLineTo(5.0f) verticalLineTo(14.0f) horizontalLineTo(8.8754f) lineTo(9.9674f, 11.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.0038f, 14.0f) lineTo(12.0957f, 11.0f) horizontalLineTo(20.0f) verticalLineTo(14.0f) horizontalLineTo(11.0038f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.1475f, 16.0f) horizontalLineTo(5.0f) verticalLineTo(19.0f) horizontalLineTo(7.0556f) lineTo(8.1475f, 16.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.1839f, 19.0f) lineTo(10.2759f, 16.0f) horizontalLineTo(20.0f) verticalLineTo(19.0f) horizontalLineTo(9.1839f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.8236f, 9.0f) lineTo(13.9156f, 6.0f) horizontalLineTo(20.0f) verticalLineTo(9.0f) horizontalLineTo(12.8236f) close() } } .build() return _serverless!! } private var _serverless: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
3,902
compose-icons
MIT License
kotlin/src/x2022/day5/Day5.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package day5 import readInput fun parseStackInput(stackInput: List<String>): List<ArrayDeque<Char>> { val stacks = stackInput[0].split(" ").mapNotNull { it.ifEmpty { null }?.toInt() }.map { ArrayDeque<Char>() } stackInput.drop(1).forEach { it.chunked(4).forEachIndexed { i, its -> val c = its[1] if (!c.isWhitespace()) { stacks[i].addLast(c) } } } return stacks } fun parseInput(input: List<String>): Pair<List<String>, List<String>> { var moves = false val parts = input.groupBy { if (it.isEmpty()) { moves = true } when (moves) { true -> if (it.isEmpty()) "empty" else "moves" false -> "stacks" } } return Pair( parts["stacks"]?.reversed() ?: throw Exception("invalid input"), parts["moves"] ?: throw Exception("invalid input") ) } fun partOne(stacks: List<ArrayDeque<Char>>, movesInput: List<String>) { for (mi in movesInput) { val mp = mi.split(" ") val qty = mp[1].toInt() val from = mp[3].toInt() val to = mp[5].toInt() val src = stacks[from - 1] val dst = stacks[to - 1] for (i in 1..qty) { dst.addLast(src.removeLast()) } } println(stacks.fold("") { out, stack -> out + stack.last() }) } fun partTwo(stacks: List<ArrayDeque<Char>>, movesInput: List<String>) { for (mi in movesInput) { val mp = mi.split(" ") val qty = mp[1].toInt() val from = mp[3].toInt() val to = mp[5].toInt() val src = stacks[from - 1] val dst = stacks[to - 1] val tmp = ArrayDeque<Char>() for (i in 1..qty) { tmp.addFirst(src.removeLast()) } for (i in tmp) { dst.addLast(i) } } println(stacks.fold("") { out, stack -> out + stack.last() }) } fun main() { val (stackInput, movesInput) = parseInput(readInput("day5")) partOne(parseStackInput(stackInput), movesInput) partTwo(parseStackInput(stackInput), movesInput) }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
2,137
adventOfCode
Apache License 2.0
app/src/main/java/com/thiruppathik/beercraft/ui/CartActivity.kt
thiruppathi3
140,655,572
false
{"Kotlin": 30110}
package com.thiruppathik.beercraft.ui import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.view.View import android.widget.Toast import com.thiruppathik.beercraft.Injection import com.thiruppathik.beercraft.R import com.thiruppathik.beercraft.db.BeerLocalCache import com.thiruppathik.beercraft.db.Cart import kotlinx.android.synthetic.main.activity_cart.* /** * Created by Thiruppathi.K on 6/23/2018. */ class CartActivity : AppCompatActivity(), CartItemClickListener { var adapter: CartAdapter? = null private val cache: BeerLocalCache init { cache = Injection.provideCache(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cart) listview.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) adapter = CartAdapter(null, this) listview.adapter = adapter refreshCartData(); } override fun onItemClick(position: Int, beer: Cart?) { var cart = Cart(beer!!.id, beer.abv, beer.ibu, beer.name, beer.style, beer.ounces) Injection.provideCache(this).deleteCartDataById(cart, { runOnUiThread { Toast.makeText(this, "Item deleted from cart", Toast.LENGTH_SHORT).show() } refreshCartData() }) } private fun refreshCartData() { cache.clearCartData() { runOnUiThread { adapter!!.items = it adapter!!.notifyDataSetChanged() if (it != null && it.size > 0) { listview.visibility = View.VISIBLE emptyview.visibility = View.GONE } else { listview.visibility = View.GONE emptyview.visibility = View.VISIBLE } } } } }
0
Kotlin
0
0
2260309af392bb17e034e54aa57812a48cbcfe9b
1,975
beer_craft
MIT License
components/accounts/tests/barinek/bigstar/accounts/AccountsControllerTest.kt
nagavejju
129,252,081
true
{"Kotlin": 18795, "HTML": 18}
package barinek.bigstar.accounts import com.fasterxml.jackson.databind.ObjectMapper import io.barinek.bigstar.jdbc.DataSourceConfig import io.barinek.bigstar.rest.BasicApp import io.barinek.bigstar.rest.RestTemplate import org.eclipse.jetty.server.Handler import org.eclipse.jetty.server.handler.HandlerList import org.eclipse.jetty.servlet.ServletContextHandler import org.eclipse.jetty.servlet.ServletHolder import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.springframework.context.annotation.Configuration import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter import org.springframework.web.context.ContextLoaderListener import org.springframework.web.context.WebApplicationContext import org.springframework.web.context.support.AnnotationConfigWebApplicationContext import org.springframework.web.servlet.DispatcherServlet import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter open class AccountsControllerTest() { var app: TestApp = TestApp() @Before fun setUp() { DataSourceConfig().getJdbcTemplate().execute("delete from accounts") app.start() } @After fun tearDown() { app.stop() } @Test fun testGetMetrics() { DataSourceConfig().getJdbcTemplate().update(""" insert into accounts (name, total_contract_value) values ('John\'s Grocery, Inc.', 6000000), ('Hamburg Inn No. 2', 0), ('Record Collector', 1400000) """) val port = 8081 val response = RestTemplate().doGet("http://localhost:$port/api/accounts") val accounts = ObjectMapper().readValue(response, List::class.java) assertEquals(3, accounts.size) System.out.println(accounts) } /// class TestApp : BasicApp() { override fun getPort(): Int { return 8081 } override fun handlerList(): HandlerList { val list = HandlerList() list.addHandler(getServletContextHandler(getContext())) return list } private fun getServletContextHandler(context: WebApplicationContext): Handler { return ServletContextHandler().apply { contextPath = "/" addServlet(ServletHolder(DispatcherServlet(context)), "/*") addEventListener(ContextLoaderListener(context)) } } private fun getContext(): WebApplicationContext { return AnnotationConfigWebApplicationContext().apply { setConfigLocation("io.barinek.bigstar.accounts,io.barinek.bigstar.jdbc,barinek.bigstar.accounts") } } } @Configuration @EnableWebMvc open class WebConfig : WebMvcConfigurerAdapter() { override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) { converters.add(MappingJackson2HttpMessageConverter(ObjectMapper())) } } }
0
Kotlin
0
0
2db7acc17bb1e10d9d7541ad9ba80d0d929375d9
3,193
bigstar
Apache License 2.0
core/src/main/kotlin/dd4/core/util/Extentions.kt
fromage-fraser
492,221,484
false
null
package dd4.core.util import java.util.Locale fun String.upperCaseFirst(): String = this.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
0
Kotlin
0
0
385d143b62623ad6f4c7036e5edc0f2c2e9b2474
227
dd4-tools
MIT License
app/src/main/java/pro/fateev/diary/extensions/FormattingExtensions.kt
PoisonousJohn
669,796,348
false
null
/* * Copyright 2023 Ivan Fateev * * 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 pro.fateev.diary.extensions import android.content.Context import android.text.format.DateFormat import java.util.Date object FormattingExtensions { fun Date.formatShort(context: Context): String { val dateFormat = DateFormat.getDateFormat(context) return dateFormat.format(this) } }
0
Kotlin
0
0
00ca68a811349160af03d5e0f85852317a18e24a
915
EasyDiary
Apache License 2.0
app/src/main/java/com/umaplasticsfsm/app/xmlmodel/UserLocationList.kt
DebashisINT
740,356,583
false
{"Kotlin": 13950763, "Java": 1000924}
package com.umaplasticsfsm.app.xmlmodel import com.umaplasticsfsm.features.location.UserLocationDataEntity /** * Created by Kinsuk on 16-01-2019. */ class UserLocationList { //@JacksonXmlElementWrapper(useWrapping = false) var userLocationDataEntities : List<UserLocationDataEntity>? =null }
0
Kotlin
0
0
2ccc871bdcf7df2d08825d0b9ded73b11495519e
304
UmaPlastics
Apache License 2.0
app/src/main/java/com/hi/dhl/pokemon/data/mapper/Mapper.kt
hi-dhl
279,366,649
false
null
package com.hi.dhl.pokemon.data.mapper /** * <pre> * author: dhl * date : 2020/7/11 * desc : * </pre> */ interface Mapper<I, O> { fun map(input: I): O }
0
Kotlin
243
1,528
ed204eaefa6f2929c04f3de668ae5d23db13f5d9
177
PokemonGo
Apache License 2.0
src/jsMain/kotlin/presentation/features/settings/components/RegistrationForm.kt
Tanexc
667,134,735
false
null
package presentation.features.settings.components import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import domain.model.User import presentation.style.icons.filled.IconFilledVisibility import presentation.style.icons.filled.IconFilledVisibilityOff import presentation.style.strings.Strings import presentation.style.strings.Strings.name import presentation.style.strings.Strings.password import presentation.style.strings.Strings.registration import presentation.style.strings.Strings.requiredField import presentation.style.strings.Strings.surname import presentation.style.strings.applicationResources import presentation.style.ui.theme.Typography import util.State import util.validators.PasswordValidator.isValid @Composable fun RegistrationForm( onSubmit: (name: String, surname: String, login: String, password: String) -> Unit ) { var name by remember { mutableStateOf("") } var surname by remember { mutableStateOf("") } var login by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var passwordRepeat by remember { mutableStateOf("") } val wrongPassword by remember { mutableStateOf(false) } val simplePassword by remember { mutableStateOf(false) } val isSubmited by remember { mutableStateOf(false) } var isPasswordVisible by remember { mutableStateOf(false) } val isFormValid by remember { derivedStateOf { name != "" && surname != "" && login != "" && password != "" && passwordRepeat == password } } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth() ) { Text( applicationResources(registration), style = Typography.titleLarge, textAlign = TextAlign.Start, modifier = Modifier.fillMaxWidth() ) Spacer(Modifier.size(8.dp)) OutlinedTextField( value = name, onValueChange = { name = it.trim() }, label = { Text(applicationResources(Strings.name)) }, singleLine = true, isError = name == "" && isSubmited, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next ), supportingText = { if (name.isEmpty()) Text(applicationResources(requiredField)) }, modifier = Modifier.width(TextFieldDefaults.MinWidth), trailingIcon = { if (name.isNotBlank()) IconButton(onClick = { name = "" }) { Icon(Icons.Filled.Clear, null) } } ) Spacer(Modifier.size(8.dp)) OutlinedTextField( value = surname, onValueChange = { surname = it.trim() }, label = { Text(applicationResources(Strings.surname)) }, singleLine = true, isError = surname == "" && isSubmited, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next ), supportingText = { if (surname.isEmpty()) Text(applicationResources(requiredField)) }, modifier = Modifier.width(TextFieldDefaults.MinWidth), trailingIcon = { if (surname.isNotBlank()) IconButton(onClick = { surname = "" }) { Icon(Icons.Filled.Clear, null) } } ) Spacer(Modifier.size(8.dp)) OutlinedTextField( value = login, onValueChange = { login = it.trim() }, label = { Text(applicationResources(Strings.login)) }, singleLine = true, isError = login == "" && isSubmited, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next ), supportingText = { if (login.isEmpty()) Text(applicationResources(requiredField)) }, modifier = Modifier.width(TextFieldDefaults.MinWidth), trailingIcon = { if (login.isNotBlank()) IconButton(onClick = { login = "" }) { Icon(Icons.Filled.Clear, null) } } ) AnimatedVisibility(name != "" && surname != "" && login != "") { Column { Spacer(Modifier.size(8.dp)) OutlinedTextField( value = password, onValueChange = { password = it }, label = { Text(applicationResources(Strings.password)) }, singleLine = true, isError = isSubmited && (password.isEmpty() || !password.isValid()), supportingText = { if (passwordRepeat.isEmpty()) Text(applicationResources(requiredField)) else if (!password.isValid()) Text(applicationResources(Strings.simplePassword)) }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Next ), modifier = Modifier.width(TextFieldDefaults.MinWidth), visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) { Icon( if (isPasswordVisible) IconFilledVisibility else IconFilledVisibilityOff, null ) } } ) Spacer(Modifier.size(8.dp)) OutlinedTextField( value = passwordRepeat, onValueChange = { passwordRepeat = it }, label = { Text(applicationResources(Strings.repeatPassword)) }, singleLine = true, isError = isSubmited && (passwordRepeat.isEmpty() || passwordRepeat != password), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ), supportingText = { if (passwordRepeat.isEmpty()) Text(applicationResources(requiredField)) else if (password != passwordRepeat) Text(applicationResources(Strings.wrongPassword)) }, modifier = Modifier.width(TextFieldDefaults.MinWidth), visualTransformation = if (isPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) { Icon( if (isPasswordVisible) IconFilledVisibility else IconFilledVisibilityOff, null ) } } ) } } Spacer(Modifier.size(32.dp)) Button( enabled = isFormValid, onClick = { onSubmit(name, surname, login, password) } ) { Text(applicationResources(Strings.send)) } } }
0
Kotlin
0
3
27bc23f5ab9dbc8ec7da5fc7812555bbbcaeb0a7
8,611
ComposeWebCakes
Apache License 2.0
ulyp-ui/src/main/kotlin/com/ulyp/ui/looknfeel/ThemeManager.kt
0xaa4eb
393,146,539
false
{"Java": 742834, "Kotlin": 89669, "CSS": 5953}
package com.ulyp.ui.looknfeel import com.ulyp.ui.SceneRegistry import org.springframework.stereotype.Service @Service class ThemeManager() { private lateinit var sceneRegistry: SceneRegistry var currentTheme: Theme = Theme.DARK fun changeTheme(theme: Theme) { sceneRegistry.scenes().forEach { scene -> scene.stylesheets.removeIf { it.startsWith("themes/") && it.endsWith("css") && it.contains("ulyp", ignoreCase = true) } scene.stylesheets.removeIf { it.contains("ulyp") } scene.stylesheets.addAll(0, theme.cssPaths) } this.currentTheme = theme } fun setSceneRegistry(value: SceneRegistry) { this.sceneRegistry = value } }
5
Java
2
14
fbc91a84d75983d608ba37b4722ae1269e89dd09
799
ulyp
Apache License 2.0
src/main/kotlin/io/aethibo/features/articles/data/repository/ArticlesRepositoryImpl.kt
primepixel
726,740,875
false
{"Kotlin": 66411}
package io.aethibo.features.articles.data.repository import io.aethibo.core.config.DatabaseFactory.dbQuery import io.aethibo.core.exceptions.NotFoundResponse import io.aethibo.features.articles.data.table.Articles import io.aethibo.features.articles.data.table.ArticlesTags import io.aethibo.features.articles.data.table.Favorites import io.aethibo.features.articles.domain.model.Article import io.aethibo.features.articles.domain.repository.ArticlesRepository import io.aethibo.features.tags.data.table.Tags import io.aethibo.features.users.data.table.Follows import io.aethibo.features.users.data.table.Users import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.SqlExpressionBuilder.inList class ArticlesRepositoryImpl : ArticlesRepository { private suspend fun findWithConditional(where: Op<Boolean>, limit: Int, offset: Long): List<Article> = dbQuery { Articles.join(Users, JoinType.INNER, additionalConstraint = { Articles.author eq Users.id }) .select { where } .limit(limit, offset) .orderBy(Articles.createdAt, SortOrder.ASC) .map { row -> val slug = row[Articles.slug] val favoritesCount = Favorites.select { Favorites.slug eq slug }.count() val tagList = Tags.join( ArticlesTags, JoinType.INNER, additionalConstraint = { Tags.id eq ArticlesTags.tag }, ) .select { ArticlesTags.slug eq slug } .map { it[Tags.name] } Articles.toDomain(row, Users.toDomain(row)) .copy( favorited = favoritesCount > 0, favoritesCount = favoritesCount, tagList = tagList, ) } } override suspend fun findByTag(tag: String, limit: Int, offset: Long): List<Article> { val slugs = dbQuery { Tags.join(ArticlesTags, JoinType.INNER, additionalConstraint = { Tags.id eq ArticlesTags.tag }) .select { Tags.name eq tag } .map { it[ArticlesTags.slug] } } return findWithConditional((Articles.slug inList slugs), limit, offset) } override suspend fun findByFavorited(favorited: String, limit: Int, offset: Long): List<Article> { val slugs = dbQuery { Favorites.join(Users, JoinType.INNER, additionalConstraint = { Favorites.user eq Users.id }) .slice(Favorites.slug) .select { Users.username eq favorited } .map { it[Favorites.slug] } } return findWithConditional((Articles.slug inList slugs), limit, offset) } override suspend fun create(article: Article): Article? { dbQuery { Articles.insert { row -> row[slug] = article.slug!! row[title] = article.title!! row[description] = article.description!! row[body] = article.body row[createdAt] = System.currentTimeMillis() row[updatedAt] = System.currentTimeMillis() row[author] = article.author?.id!! } article.tagList.map { tag -> Tags.slice(Tags.id) .select { Tags.name eq tag } .map { row -> row[Tags.id].value } .firstOrNull() ?: Tags.insertAndGetId { it[name] = tag }.value }.also { ArticlesTags.batchInsert(it) { tagId -> this[ArticlesTags.tag] = tagId this[ArticlesTags.slug] = article.slug!! } } } return findBySlug(article.slug!!) } override suspend fun findAll(limit: Int, offset: Long): List<Article> { return dbQuery { Articles.join(Users, JoinType.INNER, additionalConstraint = { Articles.author eq Users.id }) .selectAll() .limit(limit, offset) .orderBy(Articles.createdAt, SortOrder.ASC) .map { row -> val favoritesCount = Favorites.select { Favorites.slug eq row[Articles.slug] }.count() Articles.toDomain(row, Users.toDomain(row)) .copy( favoritesCount = favoritesCount, tagList = Tags.join( ArticlesTags, JoinType.INNER, additionalConstraint = { Tags.id eq ArticlesTags.tag }, ) .select { ArticlesTags.slug eq row[Articles.slug] } .map { it[Tags.name] }, ) } } } override suspend fun findFeed(email: String, limit: Int, offset: Long): List<Article> { val authors = dbQuery { Follows.join(Users, JoinType.INNER, additionalConstraint = { Follows.follower eq Users.id }) .slice(Follows.user) .select { Users.email eq email } .map { it[Follows.user] } } return findWithConditional((Articles.author inList authors), limit, offset) } override suspend fun findBySlug(slug: String): Article? { return findWithConditional( where = (Articles.slug eq slug), limit = 1, offset = 0 ).firstOrNull() } override suspend fun findByAuthor(author: String, limit: Int, offset: Long): List<Article> { return findWithConditional((Users.username eq author), limit, offset) } override suspend fun update(slug: String, article: Article): Article? { return dbQuery { Articles.update({ Articles.slug eq slug }) { row -> if (article.slug != null) { row[Articles.slug] = article.slug } if (article.title != null) { row[title] = article.title } if (article.description != null) { row[description] = article.description } row[body] = article.body row[updatedAt] = System.currentTimeMillis() if (article.author != null) { row[author] = article.author.id!! } } if (article.slug != null) { Favorites.update({ Favorites.slug eq slug }) { row -> row[Favorites.slug] = slug } } Favorites.select { Favorites.slug eq article.slug!! }.count() }.let { findBySlug(article.slug!!)?.copy(favoritesCount = it) } } override suspend fun favorite(userId: Long, slug: String): Long { return dbQuery { Favorites.insert { row -> row[Favorites.slug] = slug row[user] = userId }.let { Favorites.select { Favorites.slug eq slug }.count() } } } override suspend fun unfavorite(userId: Long, slug: String): Long { val article = findBySlug(slug) ?: throw NotFoundResponse() return dbQuery { Favorites.deleteWhere { Favorites.slug eq article.slug!! and (user eq userId) }.let { Favorites.select { Favorites.slug eq article.slug!! }.count() } } } override suspend fun delete(slug: String) { dbQuery { Articles.deleteWhere { Articles.slug eq slug } Favorites.deleteWhere { Favorites.slug eq slug } } } }
0
Kotlin
0
0
0d6a5d26de40aec4ef72f908b0e29a38dfbf3627
7,906
Atlas
Apache License 2.0
detekt-rules/src/test/resources/cases/DataClassContainsFunctionsPositive.kt
redwarp
114,749,379
true
{"Kotlin": 658863, "Groovy": 1433, "HTML": 698}
@file:Suppress("unused") package cases data class DataClassWithFunctions(val i: Int) { // reports 2 fun f1() {} fun f2() {} data class NestedDataClassWithConversionFunction(val i : Int) { // reports 1 fun toDataClassWithOverriddenMethods() = DataClassWithOverriddenMethods(i) } }
0
Kotlin
0
1
ef0416cae794782d00fbc358d12fa5f24fed9bd3
290
detekt
Apache License 2.0
platforms/core-configuration/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/KotlinGrammar.kt
gradle
302,322
false
{"Groovy": 33309780, "Java": 30797028, "Kotlin": 3552953, "C++": 888505, "JavaScript": 76180, "HTML": 15779, "CSS": 13668, "Shell": 12214, "XSLT": 7121, "C": 5785, "Scala": 2817, "Gherkin": 192, "Python": 58, "Brainfuck": 54}
/* * Copyright 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.execution import org.jetbrains.kotlin.lexer.KtTokens.ANDAND import org.jetbrains.kotlin.lexer.KtTokens.ARROW import org.jetbrains.kotlin.lexer.KtTokens.AT import org.jetbrains.kotlin.lexer.KtTokens.CLASS_KEYWORD import org.jetbrains.kotlin.lexer.KtTokens.COLON import org.jetbrains.kotlin.lexer.KtTokens.COLONCOLON import org.jetbrains.kotlin.lexer.KtTokens.COMMA import org.jetbrains.kotlin.lexer.KtTokens.DOT import org.jetbrains.kotlin.lexer.KtTokens.EQ import org.jetbrains.kotlin.lexer.KtTokens.EQEQ import org.jetbrains.kotlin.lexer.KtTokens.EQEQEQ import org.jetbrains.kotlin.lexer.KtTokens.EXCLEQ import org.jetbrains.kotlin.lexer.KtTokens.EXCLEQEQEQ import org.jetbrains.kotlin.lexer.KtTokens.GT import org.jetbrains.kotlin.lexer.KtTokens.GTEQ import org.jetbrains.kotlin.lexer.KtTokens.LBRACKET import org.jetbrains.kotlin.lexer.KtTokens.LT import org.jetbrains.kotlin.lexer.KtTokens.LTEQ import org.jetbrains.kotlin.lexer.KtTokens.MUL import org.jetbrains.kotlin.lexer.KtTokens.NULL_KEYWORD import org.jetbrains.kotlin.lexer.KtTokens.OROR import org.jetbrains.kotlin.lexer.KtTokens.QUEST import org.jetbrains.kotlin.lexer.KtTokens.RBRACKET import org.jetbrains.kotlin.lexer.KtTokens.SAFE_ACCESS import org.jetbrains.kotlin.lexer.KtTokens.SEMICOLON internal val kotlinGrammar: KotlinGrammar by lazy(LazyThreadSafetyMode.PUBLICATION) { KotlinGrammar() } @Suppress("MemberVisibilityCanBePrivate") internal class KotlinGrammar : Combinator(true, true) { // basic building blocks val annotationMarker = token(AT) * notWhiteSpace() val simpleIdentifier by debug { symbol() } val label by debug { simpleIdentifier * token(AT) } val comparisonOperator by debug { token(LT) + token(GT) + token(LTEQ) + token(GTEQ) } val equalityOperator by debug { token(EXCLEQ) + token(EXCLEQEQEQ) + token(EQEQ) + token(EQEQEQ) } val memberAccessOperator by debug { token(DOT) + token(SAFE_ACCESS) + token(COLONCOLON) } val semi = token(SEMICOLON) val semis = oneOrMore(semi) val literalConstant = booleanLiteral + integerLiteral + floatLiteral + characterLiteral + token(NULL_KEYWORD) // recursive parsers var type by reference<Any>() var annotation by reference<Any>() var fileAnnotation by reference<Any>() var parenthesizedUserType by reference<Any>() var expression by reference<Any>() var primaryExpression by reference<Any?>() var directlyAssignableExpression by reference<Any>() var assignableExpression by reference<Any>() // regular parsers val collectionLiteral = bracket( optional( expression * zeroOrMore(token(COMMA) * expression) * optional(token(COMMA)) ) ) val parenthesizedType by debug { paren(type) } val parenthesizedExpression by debug { paren(expression) } val valueArgument by debug { optional(annotation) * optional(simpleIdentifier * token(EQ)) * optional(token(MUL)) * expression } val valueArguments by debug { paren( optional( valueArgument * zeroOrMore(token(COMMA) * valueArgument) * optional(token(COMMA)) ) ) } val userType by debug { simpleIdentifier * zeroOrMore(token(DOT) * simpleIdentifier) } val unaryPrefix by debug { annotation + label } val assignment by debug { directlyAssignableExpression * token(EQ) * expression } val statement by debug { zeroOrMore(label + annotation) * (assignment + expression) } val statements: Parser<Any> by debug { optional(statement * zeroOrMore(semis * statement)) * optional(semis) } val indexingSuffix by debug { bracket( expression * zeroOrMore(token(COMMA) * expression * optional(token(COMMA))) ) } val navigationSuffix: Parser<Any> by debug { memberAccessOperator * (simpleIdentifier + parenthesizedExpression + token(CLASS_KEYWORD)) } val postfixUnarySuffix = valueArguments + indexingSuffix + navigationSuffix val postfixUnaryExpression by debug { primaryExpression * zeroOrMore(postfixUnarySuffix) } val prefixUnaryExpression by debug { zeroOrMore(unaryPrefix) * postfixUnaryExpression } val infixFunctionCall by debug { prefixUnaryExpression * zeroOrMore(simpleIdentifier * prefixUnaryExpression) } val genericCallLikeComparison by debug { infixFunctionCall * zeroOrMore(valueArguments) } val comparison by debug { genericCallLikeComparison * zeroOrMore(comparisonOperator * genericCallLikeComparison) } val equality by debug { comparison * zeroOrMore(equalityOperator * comparison) } val conjunction by debug { equality * zeroOrMore(token(ANDAND) * equality) } val disjunction = conjunction * zeroOrMore(token(OROR) * conjunction) val definitelyNonNullableType = (userType + parenthesizedUserType) * token(MUL) * (userType + parenthesizedUserType) val constructorInvocation by debug { userType * valueArguments } val unescapedAnnotation by debug { constructorInvocation + userType } val listOfUnescapedAnnotations by debug { token(LBRACKET) * oneOrMore(unescapedAnnotation) * token(RBRACKET) } val annotationUseSiteTarget by debug { (symbol("field") + symbol("property") + symbol("get") + symbol("set") + symbol("receiver") + symbol("param") + symbol("setparam") + symbol("delgate")) * token(COLON) } val singleAnnotation by debug { annotationMarker * optional(annotationUseSiteTarget) * unescapedAnnotation } val multiAnnotation by debug { annotationMarker * optional(annotationUseSiteTarget) * listOfUnescapedAnnotations } val parameter by debug { simpleIdentifier * token(COLON) * type } val functionTypeParameters by debug { paren( optional(parameter + type) * zeroOrMore(token(COMMA) * (parameter + type)) * optional(token(COMMA)) ) } val typeReference = userType + symbol("dynamic") val nullableType = (typeReference + parenthesizedType) * oneOrMore(token(QUEST)) val receiverType by debug { parenthesizedType + nullableType + typeReference } val functionType = optional(receiverType * token(DOT)) * functionTypeParameters * token(ARROW) * type val callableReference by debug { optional(receiverType) * token(COLONCOLON) * (simpleIdentifier + token(CLASS_KEYWORD)) } val assignableSuffix by debug { indexingSuffix + navigationSuffix } init { type = functionType + parenthesizedType + nullableType + typeReference + definitelyNonNullableType annotation = singleAnnotation + multiAnnotation fileAnnotation = annotationMarker * symbol("file") * token(COLON) * (unescapedAnnotation + listOfUnescapedAnnotations) parenthesizedUserType = paren(userType + parenthesizedUserType) expression = debugReference { disjunction } primaryExpression = debugReference { parenthesizedExpression + callableReference + simpleIdentifier + literalConstant + stringLiteral + collectionLiteral } directlyAssignableExpression = debugReference { (postfixUnaryExpression * assignableSuffix) + simpleIdentifier + paren(directlyAssignableExpression) } assignableExpression = debugReference { prefixUnaryExpression + paren(assignableExpression) } } private fun <T> debugReference(parserBuilder: () -> Parser<T>): Parser<T> { val a by debug(parserBuilder) return a } }
2,663
Groovy
4552
15,640
3fde2e4dd65124d0f3b2ef42f7e93446ccd7cced
8,575
gradle
Apache License 2.0
BasicStateCodelab/app/src/main/java/com/example/basicstatecodelab/WellnessViewModal.kt
zaidazaize
665,764,719
false
null
package com.example.basicstatecodelab import androidx.compose.runtime.toMutableStateList import androidx.lifecycle.ViewModel import com.example.basicstatecodelab.models.WellnessTask class WellnessViewModal : ViewModel() { private val _task = getWellnessTask().toMutableStateList() val task: List<WellnessTask> get() = _task fun removeTask(task: WellnessTask) { _task.remove(task) } fun changeTaskChecked(item: WellnessTask, checked: Boolean) { _task.find { it.id == item.id }?.let { task -> task.checked = checked } } private fun getWellnessTask() = List(30) { i -> WellnessTask(i, "Task $i") } }
0
Kotlin
0
0
c69a75fcd18d917dda4a427aefa0326a3a54686c
673
androidTestProjects
MIT License
src/backend/ci/core/stream/api-stream/src/main/kotlin/com/tencent/devops/stream/pojo/StreamBuildBranch.kt
Florence-y
466,159,327
true
{"Kotlin": 32055720, "Java": 5630945, "Vue": 5114034, "Go": 2452911, "JavaScript": 1705688, "Lua": 782810, "Dart": 551043, "TypeScript": 401445, "Shell": 395465, "SCSS": 382534, "C++": 149772, "HTML": 134571, "CSS": 92893, "Python": 50689, "C": 33502, "Smarty": 27962, "Less": 24714, "Objective-C": 18613, "Dockerfile": 15989, "Makefile": 13614, "Swift": 8479, "Batchfile": 8125, "Ruby": 6807, "Starlark": 3608, "PowerShell": 824, "VBScript": 189}
package com.tencent.devops.stream.pojo import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty @ApiModel("仓库中所有已构建的分支列表") data class StreamBuildBranch( @ApiModelProperty("分支名") val branchName: String, @ApiModelProperty("项目ID") val gitProjectId: Long, @ApiModelProperty("源项目ID") val sourceGitProjectId: Long? )
0
Kotlin
0
2
58baee8fabd09ff8e42885162a3b894bab1577da
366
bk-ci
MIT License
geary-papermc-bridge/src/main/kotlin/com/mineinabyss/geary/papermc/configlang/systems/ConditionsToRoles.kt
MineInAbyss
592,086,123
false
{"Kotlin": 153813}
package com.mineinabyss.geary.papermc.configlang.systems import com.mineinabyss.geary.annotations.optin.UnsafeAccessors import com.mineinabyss.geary.papermc.commons.events.configurable.components.EventCondition import com.mineinabyss.geary.papermc.commons.events.configurable.components.EventConditions import com.mineinabyss.geary.papermc.configlang.helpers.parseEntity import com.mineinabyss.geary.systems.GearyListener import com.mineinabyss.geary.systems.accessors.Pointers class ConditionsToRoles : GearyListener() { val Pointers.triggers by get<EventConditions>().whenSetOnTarget() @OptIn(UnsafeAccessors::class) override fun Pointers.handle() { val entity = target.entity try { triggers.expressions.forEach { expression -> val (cause, condition, effect) = expression.replace(" ", "").split("->").takeIf { it.size == 3 } ?: error("Expression needs to be formatted as 'cause -> condition -> effect'") cause == "any" || error("Only 'any' is currently supported as a cause.") entity.setRelation( EventCondition(entity = entity.parseEntity(condition).id), entity.parseEntity(effect) ) } } finally { entity.remove<EventConditions>() } } }
2
Kotlin
0
1
8bfbacb7ba25d52baf868339c4f40e9ee733d100
1,351
geary-papermc
MIT License
src/main/kotlin/org/nissy/plugins/kotlin/inspection/MainInspection.kt
takete2
633,756,751
false
null
package org.nissy.plugins.kotlin.inspection import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.components.ServiceManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.impl.source.tree.LeafPsiElement import org.nissy.plugins.kotlin.Config import org.nissy.plugins.kotlin.SingleRecord import org.nissy.plugins.kotlin.inspection.common.LateInitInspection import org.nissy.plugins.kotlin.inspection.common.OSIntNestingInspection import org.nissy.plugins.kotlin.inspection.project.method.MethodCallInspection import org.nissy.plugins.kotlin.services.KtCodeSytleProjectService import org.intellij.markdown.flavours.gfm.table.GitHubTableMarkerProvider.Companion.contains import org.jetbrains.kotlin.j2k.ast.LBrace import org.jetbrains.kotlin.j2k.ast.LambdaExpression import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType /** * 项目规约代码检查开始的地方 */ class MainInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return MainInspectionVisitorVoid(holder) } } class MainInspectionVisitorVoid(holder: ProblemsHolder) : KtVisitorVoid() { private var holder: ProblemsHolder init { this.holder = holder } override fun visitKtElement(element: KtElement) { super.visitKtElement(element) if (org.nissy.plugins.kotlin.Config.TEST_MODE) { println("value:" + element.text + " type" + element.toString()) } } override fun visitProperty(property: KtProperty) { super.visitProperty(property) if (ServiceManager.getService( holder.project, KtCodeSytleProjectService::class.java ).config.realTimeScan ) { LateInitInspection.getLateInitInsp(property, SingleRecord.currentFileName) } } override fun visitReferenceExpression(expression: KtReferenceExpression) { super.visitReferenceExpression(expression) if (ServiceManager.getService( holder.project, KtCodeSytleProjectService::class.java ).config.realTimeScan ) { LateInitInspection.getLateInitInsp(null, SingleRecord.currentFileName)?.recordCheck(expression) } } override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { super.visitDotQualifiedExpression(expression) if (ServiceManager.getService( holder.project, KtCodeSytleProjectService::class.java ).config.realTimeScan ) { LateInitInspection.getLateInitInsp(null, SingleRecord.currentFileName)?.report(expression, holder) } } override fun visitCallExpression(expression: KtCallExpression) { super.visitCallExpression(expression) if (ServiceManager.getService( holder.project, KtCodeSytleProjectService::class.java ).config.realTimeScan ) { MethodCallInspection(expression, holder) } } override fun visitBlockExpression(expression: KtBlockExpression) { super.visitBlockExpression(expression) if (ServiceManager.getService( holder.project, KtCodeSytleProjectService::class.java ).config.realTimeScan ) { OSIntNestingInspection(expression, holder) } } fun judgeScan(holder: ProblemsHolder,element: KtElement): Boolean { return ServiceManager.getService( holder.project, KtCodeSytleProjectService::class.java ).config.realTimeScan && element.containingFile.name.contains("kts") } }
0
Kotlin
0
1
0c8ef04eb27912e3f001e69fb53634165b6a9b5d
3,858
KtCodeHelper
Apache License 2.0
composeApp/src/commonMain/kotlin/com/calvin/box/movie/feature/vod/VodListScreen.kt
lhzheng880828
834,021,637
false
{"Kotlin": 588223, "JavaScript": 198922, "Java": 116056, "Ruby": 2141, "Swift": 1155, "HTML": 334, "CSS": 102}
package com.calvin.box.movie.feature.vod import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import cafe.adriel.voyager.navigator.tab.Tab import cafe.adriel.voyager.navigator.tab.TabOptions import com.calvin.box.movie.bean.Class import com.calvin.box.movie.bean.Vod import com.calvin.box.movie.model.VideoModel import com.calvin.box.movie.navigation.LocalNavigation import com.calvin.box.movie.screens.EmptyScreenContent import com.calvin.box.movie.ui.screens.tabsview.HomeTabViewModel import io.github.aakira.napier.Napier import io.kamel.image.KamelImage import io.kamel.image.asyncPainterResource import moviebox.composeapp.generated.resources.Res import moviebox.composeapp.generated.resources.ic_home_tab import org.jetbrains.compose.resources.painterResource data class VodListScreen(val category: Class, val viewModel: HomeTabViewModel) : Tab { @Composable override fun Content() { val navigator = LocalNavigation.current val homeResult by viewModel.homeResult.collectAsState() val categoryVodList by viewModel.loadCategoryContent(category).collectAsState(emptyList()) val objects = if(category.typeId == "Home") {homeResult.list} else {categoryVodList} AnimatedContent(objects.isNotEmpty()) { objectsAvailable -> if (objectsAvailable) { ObjectGrid( objects = objects, onObjectClick = { vodObj -> Napier.d { "vod item clicked" } val videoModel = VideoModel(id = vodObj.vodId, description = vodObj.vodTag, sources = vodObj.vodPlayUrl, subtitle = "", thumb = vodObj.vodPic, title = vodObj.vodName) navigator.goToVideoPlayerScreen(videoModel) } ) } else { EmptyScreenContent(Modifier.fillMaxSize()) } } } override val options: TabOptions @Composable get() { val image = painterResource(Res.drawable.ic_home_tab) return remember { TabOptions(index = 2u, title = category.typeName, icon = image) } } } @Composable private fun ObjectGrid( objects: List<Vod>, onObjectClick: (Vod) -> Unit, modifier: Modifier = Modifier, ) { LazyRow() { } LazyVerticalGrid( columns = GridCells.Adaptive(180.dp), modifier = modifier.fillMaxSize(), contentPadding = PaddingValues(8.dp) ) { items(objects, key = { it.vodId }) { obj -> ObjectFrame( obj = obj, onClick = { onObjectClick(obj) }, ) } } } @Composable private fun ObjectFrame( obj: Vod, onClick: () -> Unit, modifier: Modifier = Modifier, ) { Column( modifier .padding(8.dp) .clickable { onClick() } ) { KamelImage( resource = asyncPainterResource(data = obj.vodPic), contentDescription = obj.vodName, contentScale = ContentScale.Crop, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .background(Color.LightGray), ) Spacer(Modifier.height(2.dp)) Text(obj.vodName, style = MaterialTheme.typography.subtitle1.copy(fontWeight = FontWeight.Bold)) Text(obj.vodTag, style = MaterialTheme.typography.body2) Text(obj.vodYear, style = MaterialTheme.typography.caption) } } private const val TAG = "VodListScreen"
0
Kotlin
0
0
4c4916dc84d2b4ecfe8814b37014be379c38c22d
4,726
MovieBox
Apache License 2.0
kotlin/src/katas/kotlin/adventofcode/day8/Part1.kt
serpro69
336,764,380
true
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 820074, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 10881, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2661, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "HiveQL": 643, "Gherkin": 221}
package katas.kotlin.adventofcode.day8 import java.io.* fun main() { val digits = File("src/katas/kotlin/adventofcode/day8/input.txt").readText().map { it.toString().toInt() } val width = 25 val height = 6 val layerSize = width * height val layer = digits.chunked(layerSize) .minBy { layer -> layer.count { it == 0 } }!! println(layer) println(layer.count { it == 1 } * layer.count { it == 2 }) }
0
null
0
0
ff190e3e6f587848859a469a7ee84d49fa72f1c4
436
katas
The Unlicense
code/jvm/src/main/kotlin/aguDataSystem/server/service/prediction/PredictionService.kt
AGU-Data-System
765,690,492
false
{"Kotlin": 723386, "TypeScript": 153702, "JavaScript": 1600, "CSS": 925, "Shell": 889, "HTML": 267}
package aguDataSystem.server.service.prediction import aguDataSystem.server.domain.agu.AGUBasicInfo import aguDataSystem.server.domain.alerts.AlertCreationDTO import aguDataSystem.server.domain.load.ScheduledLoadCreationDTO import aguDataSystem.server.domain.measure.GasMeasure import aguDataSystem.server.domain.provider.ProviderType import aguDataSystem.server.repository.Transaction import aguDataSystem.server.repository.TransactionManager import aguDataSystem.server.service.alerts.AlertsService import aguDataSystem.server.service.chron.FetchService import aguDataSystem.server.service.chron.models.prediction.ConsumptionRequestModel import aguDataSystem.server.service.chron.models.prediction.TemperatureRequestModel import aguDataSystem.server.service.prediction.models.PredictionResponseModel import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.time.DayOfWeek import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import kotlin.math.abs import kotlin.math.roundToInt import kotlin.random.Random /** * Service for the prediction of gas consumption of the AGUs. */ @Service class PredictionService( private val transactionManager: TransactionManager, private val fetchService: FetchService, private val alertsService: AlertsService ) { /** * Schedules the training chron task. * * Still sketchy, needs to be implemented */ fun trainAGUs() { val aguList = transactionManager.run { it.aguRepository.getAGUsBasicInfo() } aguList.forEach { agu -> trainAGU(agu) } } /** * Trains the model for an AGU * * @param agu The AGU to train the model for */ private fun trainAGU(agu: AGUBasicInfo) { var temps: List<TemperatureRequestModel> = emptyList() var consumptions: List<ConsumptionRequestModel> = emptyList() transactionManager.run { tm -> logger.info("Fetching providers for AGU for training model: {}", agu.cui) val aguProviders = tm.providerRepository.getProviderByAGU(agu.cui) logger.info("Fetching temperature and gas measures for AGU: {}", agu.cui) aguProviders.forEach { provider -> when (provider.getProviderType()) { ProviderType.TEMPERATURE -> temps = getTemperaturePredictions(tm, provider.id, false) ProviderType.GAS -> consumptions = fetchGasConsumptions(tm, provider.id) } } } if (temps.size < NUMBER_OF_DAYS || consumptions.size < NUMBER_OF_DAYS) { logger.error("Not enough data to train AGU: {}", agu.cui) return } logger.info("Generating training model for AGU: {}", agu.cui) val training = fetchService.generateTraining(temps, consumptions) if (training != null) { transactionManager.run { logger.info("Saving training model for AGU: {}", agu.cui) it.aguRepository.updateTrainingModel(agu.cui, training) } } else { logger.error("Failed to generate training model for AGU: {}", agu.cui) } } /** * Receives an AGU and gets/stores the predictions for the next n days and calculate when loads are needed for this AGU * * @param agu The AGU to process */ fun processAGU(agu: AGUBasicInfo) { transactionManager.run { transaction -> logger.info("Fetching providers for AGU: {}", agu.cui) val temperatureProvider = transaction.providerRepository.getProviderByAGUAndType(agu.cui, ProviderType.TEMPERATURE) ?: throw Exception("No temperature provider found for AGU: ${agu.cui}") val gasProvider = transaction.providerRepository.getProviderByAGUAndType(agu.cui, ProviderType.GAS) ?: throw Exception("No gas provider found for AGU: ${agu.cui}") logger.info("Fetching temperature, and gas consumptions for AGU: {}", agu.cui) val temps = getTemperaturePredictions(transaction, temperatureProvider.id, true) val consumptions = fetchGasConsumptions(transaction, gasProvider.id) if (temps.size < (NUMBER_OF_DAYS + TEMP_NUMBER_OF_DAYS) || consumptions.size < NUMBER_OF_DAYS) { logger.warn("Not enough data to predict consumption for AGU: {}", agu.cui) return@run } logger.info("Fetching training model for AGU: {}", agu.cui) val training = transaction.aguRepository.getTraining(agu.cui) if (training == null) { logger.warn("No training model found for AGU: {}", agu.cui) return@run } logger.info("Generating gas consumption predictions for AGU: {}", agu.cui) val predictions = fetchService.generatePredictions( futureTemps = temps, consumptions = consumptions, training = training ).map { prediction -> PredictionResponseModel(prediction.date, abs(prediction.consumption)) } if (predictions.isNotEmpty()) { val completeAGU = transaction.aguRepository.getAGUByCUI(agu.cui) ?: throw Exception("AGU not found: ${agu.cui}") val predictedLevels: List<Int> if (completeAGU.loadVolume < BIG_AGU_LIMIT_LOAD_VOLUME) { predictedLevels = manageLoads(transaction, agu, predictions) } else { logger.info("AGU {} is to small to have automatic scheduling of loads", agu.cui) val tanks = transaction.tankRepository.getAGUTanks(agu.cui) if (tanks.isEmpty()) { logger.error("No tanks found for AGU: {}", agu.cui) } val currentLevel = getCombinedCurrentLevel(transaction, agu.cui, gasProvider.id) predictedLevels = mutableListOf() predictions.forEachIndexed { index, prediction -> var totalLevel = if (index == 0) currentLevel else predictedLevels[index - 1] totalLevel = (totalLevel - prediction.consumption).roundToInt() predictedLevels.add(totalLevel) } } savePredictions(transaction, agu, predictedLevels, gasProvider.id) } else { logger.error("Failed to generate gas consumption predictions for AGU: {}", agu.cui) } } } /** * Fetches the gas consumptions for the AGU * * @param transaction the transaction to use * @param providerId the ID of the gas provider * * @return the gas consumptions */ private fun fetchGasConsumptions(transaction: Transaction, providerId: Int): List<ConsumptionRequestModel> { var levelList = transaction.gasRepository.getGasMeasures(providerId, NUMBER_OF_DAYS + 1, LocalTime.MIDNIGHT).toMutableList() if (levelList.size < NUMBER_OF_DAYS + 1) { val lastGasMeasure = levelList.lastOrNull() if (lastGasMeasure != null) { var lastLevel = lastGasMeasure.level var lastTimestamp = lastGasMeasure.timestamp var lastPredictionFor = lastGasMeasure.predictionFor levelList.removeAll(levelList) levelList.add(lastGasMeasure) for (i in 1..NUMBER_OF_DAYS) { lastLevel = (lastLevel * Random.nextDouble(0.95, 1.0)).roundToInt() lastTimestamp = lastTimestamp.minusDays(1) lastPredictionFor = lastPredictionFor.minusDays(1) levelList.add( GasMeasure( timestamp = lastTimestamp, level = lastLevel, predictionFor = lastPredictionFor, tankNumber = lastGasMeasure.tankNumber, ) ) } } else { logger.error("No gas measures found for provider: {}", providerId) return emptyList() } } levelList = levelList.sortedBy { it.timestamp }.toMutableList() return levelList.map { gasMeasure -> gasMeasure.level.toDouble() } // reduce the error .zipWithNext { a, b -> b - a } // calculate the consumption for each day .mapIndexed { idx, consumption -> ConsumptionRequestModel( consumption.roundToInt(), levelList[idx].timestamp.toLocalDate() ) }.also { logger.info("Gas Consumptions: {}", it) } } /** * Gets the temperature predictions for a provider needed for the prediction microservice. * * @param tm The transaction manager * @param providerId The provider id * @return The temperature predictions */ private fun getTemperaturePredictions( tm: Transaction, providerId: Int, prediction: Boolean ): List<TemperatureRequestModel> { val futureTemps = tm.temperatureRepository.getPredictionTemperatureMeasures(providerId, TEMP_NUMBER_OF_DAYS).map { temp -> TemperatureRequestModel( min = temp.min, max = temp.max, timeStamp = temp.predictionFor.toLocalDate() ) }.toMutableList() if (futureTemps.size < TEMP_NUMBER_OF_DAYS) { val lastTemp = futureTemps.lastOrNull() //The last if (lastTemp != null) { var daysToFill = TEMP_NUMBER_OF_DAYS - futureTemps.size var increment = 1L while (daysToFill > 0) { futureTemps.add( TemperatureRequestModel( min = (lastTemp.min * Random.nextDouble(0.95, 1.05)).roundToInt(), max = (lastTemp.max * Random.nextDouble(0.95, 1.05)).roundToInt(), timeStamp = LocalDate.parse(lastTemp.timeStamp).plusDays(increment) ) ) daysToFill-- increment++ } } else { logger.error("No temperature predictions found for provider: {}", providerId) return emptyList() } } val previousTemps = tm.temperatureRepository.getPastTemperatureMeasures(providerId, NUMBER_OF_DAYS).mapIndexed { idx, temp -> TemperatureRequestModel( min = temp.min, max = temp.max, timeStamp = temp.timestamp.toLocalDate() ) }.toMutableList() if (previousTemps.size < NUMBER_OF_DAYS) { val lastTemp = previousTemps.firstOrNull() ?: futureTemps.firstOrNull() if (lastTemp != null) { var daysToFill = NUMBER_OF_DAYS - previousTemps.size var decrement = 1L while (daysToFill > 0) { previousTemps.add( TemperatureRequestModel( min = (lastTemp.min * Random.nextDouble(0.95, 1.05)).roundToInt(), max = (lastTemp.max * Random.nextDouble(0.95, 1.05)).roundToInt(), timeStamp = LocalDate.parse(lastTemp.timeStamp).minusDays(decrement) ) ) daysToFill-- decrement++ } } else { logger.error("No temperature measures found for provider: {}", providerId) return emptyList() } } if (!prediction) { return previousTemps.sortedBy { it.timeStamp } } return (previousTemps + futureTemps).sortedBy { it.timeStamp } } /** * Manages the loads for the AGU * Either schedules a load if the predicted level is below the minimum level or removes a load if it's not needed anymore * * @param transaction the transaction to use * @param agu the AGU to manage the loads for * @param predictions the predictions to manage the loads for * * @return the predicted levels after taking the loads into account */ private fun manageLoads( transaction: Transaction, agu: AGUBasicInfo, predictions: List<PredictionResponseModel> ): List<Int> { val fullAGU = transaction.aguRepository.getAGUByCUI(agu.cui) ?: throw Exception("AGU not found: ${agu.cui}") val minLevel = fullAGU.levels.min val gasProvider = transaction.providerRepository.getProviderByAGUAndType(agu.cui, ProviderType.GAS) ?: throw Exception("No gas provider found for AGU: ${agu.cui}") val currentLevel = getCombinedCurrentLevel(transaction, agu.cui, gasProvider.id) val predictedLevels = mutableListOf<Int>() predictions.forEachIndexed { index, prediction -> val date = LocalDate.now().plusDays(index.toLong()) var totalLevel = if (index == 0) currentLevel else predictedLevels[index - 1] totalLevel = (totalLevel - prediction.consumption).roundToInt() val loadForDay = transaction.loadRepository.getLoadForDay(agu.cui, date) val loadAmount = loadForDay?.amount ?: 0.0 val percentageAmountOfLoad = (fullAGU.loadVolume * loadAmount).toInt() totalLevel += percentageAmountOfLoad if (totalLevel > (minLevel + LOAD_REMOVAL_MARGIN) && loadForDay != null) { transaction.loadRepository.removeLoad(loadForDay.id) // Call in alert saying we removed a load because it was not needed (we can also put the details about the AGU and the load) alertsService.createAlert( AlertCreationDTO( aguId = agu.cui, title = "Scheduled Load removed for AGU: ${agu.name}", message = "A load was removed because it was not needed" ) ) totalLevel -= percentageAmountOfLoad } else if (totalLevel <= (minLevel + LOAD_REMOVAL_MARGIN)) { if (loadForDay != null) { // Call in alert because even with a load in said day the level is below the minimum threshold alertsService.createAlert( AlertCreationDTO( aguId = agu.cui, title = "Predicted Gas level for AGU: ${agu.name} ", message = "Predicted Gas level is below the minimum threshold" ) ) } else { val adjustedDate = adjustForWeekend(date) transaction.loadRepository.scheduleLoad( ScheduledLoadCreationDTO( aguCui = agu.cui, date = adjustedDate, isManual = false ) ) totalLevel += fullAGU.loadVolume } } predictedLevels.add(totalLevel) } return predictedLevels } /** * Saves the predicted levels obtained in the manageLoads function to the database. * The obtained levels are distributed among the tanks of the AGU in proportion to their capacity * * @param transaction the transaction to use * @param agu the AGU to save the predictions for * @param predictedLevels the predicted levels to save * @param gasProviderId the ID of the gas provider */ private fun savePredictions( transaction: Transaction, agu: AGUBasicInfo, predictedLevels: List<Int>, gasProviderId: Int ) { val tanks = transaction.tankRepository.getAGUTanks(agu.cui) if (tanks.isEmpty()) { logger.error("No tanks found for AGU: {}", agu.cui) return } val totalCapacity = tanks.sumOf { it.capacity } predictedLevels.forEachIndexed { index, predictedLevel -> val tankLevels = mutableListOf<GasMeasure>() tanks.forEach { tank -> val tankLevel = (predictedLevel * tank.capacity / totalCapacity) tankLevels.add( GasMeasure( timestamp = LocalDateTime.now(), predictionFor = LocalDateTime.of(LocalDate.now().plusDays(index.toLong()), END_OF_DAY), level = tankLevel, tankNumber = tank.number ) ) } transaction.gasRepository.addGasMeasuresToProvider(gasProviderId, tankLevels) } } /** * Adjusts the date to the previous Friday if it's a Saturday or Sunday * * @param date the date to adjust * * @return the adjusted date */ private fun adjustForWeekend(date: LocalDate): LocalDate { return when (date.dayOfWeek) { DayOfWeek.SATURDAY -> date.minusDays(1) DayOfWeek.SUNDAY -> date.minusDays(2) else -> date } } /** * Gets the combined current level of all tanks of an AGU * * @param transaction the transaction to use * @param cui the CUI of the AGU * @param providerId the ID of the gas provider * * @return the combined current level */ private fun getCombinedCurrentLevel(transaction: Transaction, cui: String, providerId: Int): Int { val tanks = transaction.tankRepository.getAGUTanks(cui) if (tanks.isEmpty()) { logger.error("No tanks found for AGU: {}", cui) return 0 } val tankLevels = transaction.gasRepository.getLatestMeasures(cui, providerId) val totalCapacity = tanks.sumOf { it.capacity } val weightedSum = tankLevels.sumOf { it.level * tanks.first { tank -> tank.number == it.tankNumber }.capacity } return weightedSum / totalCapacity } companion object { private val logger = LoggerFactory.getLogger(FetchService::class.java) private val END_OF_DAY = LocalTime.of(23, 59, 59) const val NUMBER_OF_DAYS = 9 const val TEMP_NUMBER_OF_DAYS = 5 const val BIG_AGU_LIMIT_LOAD_VOLUME = 60 const val LOAD_REMOVAL_MARGIN = 5 } }
0
Kotlin
0
1
d15ebfbd457a375a173090a15531d292c86aaafe
18,605
AGU-Data-System
MIT License
src/main/kotlin/s4got10dev/crypto/exchange/interfaces/rest/controller/WalletController.kt
s4got10dev
774,954,841
false
{"Kotlin": 220989}
package s4got10dev.crypto.exchange.interfaces.rest.controller import java.net.URI import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Mono import s4got10dev.crypto.exchange.application.service.WalletService import s4got10dev.crypto.exchange.infrastructure.auth.AuthPrincipal import s4got10dev.crypto.exchange.interfaces.rest.API_V1_WALLETS_GET_BY_ID import s4got10dev.crypto.exchange.interfaces.rest.adapter.WalletAdapter import s4got10dev.crypto.exchange.interfaces.rest.model.CreateWalletRequest import s4got10dev.crypto.exchange.interfaces.rest.model.DepositRequest import s4got10dev.crypto.exchange.interfaces.rest.model.WalletResponse import s4got10dev.crypto.exchange.interfaces.rest.model.WithdrawalRequest import s4got10dev.crypto.exchange.interfaces.rest.openapi.WalletApi @RestController class WalletController( private val walletService: WalletService, private val walletAdapter: WalletAdapter ) : WalletApi { override fun createWallet(authPrincipal: AuthPrincipal?, wallet: CreateWalletRequest): Mono<ResponseEntity<Void>> { return walletAdapter.createWalletCommand(authPrincipal?.userId, wallet) .flatMap { command -> walletService.createWallet(command) } .map { ResponseEntity.created(URI(API_V1_WALLETS_GET_BY_ID.replace("{id}", it.walletId.toString()))).build() } } override fun getWallet(authPrincipal: AuthPrincipal?, id: String): Mono<ResponseEntity<WalletResponse>> { return walletAdapter.walletQuery(authPrincipal?.userId, id) .flatMap { walletService.getWallet(it) } .map { ResponseEntity.ok().body(WalletResponse.from(it)) } } override fun getWallets(authPrincipal: AuthPrincipal?): Mono<ResponseEntity<List<WalletResponse>>> { return walletAdapter.walletsQuery(authPrincipal?.userId) .flatMap { walletService.getWallets(it) } .map { ResponseEntity.ok().body(it.map { wallet -> WalletResponse.from(wallet) }) } } override fun deposit( authPrincipal: AuthPrincipal?, id: String, request: DepositRequest ): Mono<ResponseEntity<WalletResponse>> { return walletAdapter.depositCommand(id, request) .flatMap { walletService.deposit(it) } .map { ResponseEntity.ok().body(WalletResponse.from(it)) } } override fun withdrawal( authPrincipal: AuthPrincipal?, id: String, request: WithdrawalRequest ): Mono<ResponseEntity<WalletResponse>> { return walletAdapter.withdrawCommand(id, request) .flatMap { walletService.withdraw(it) } .map { ResponseEntity.ok().body(WalletResponse.from(it)) } } }
0
Kotlin
0
0
db2433e2aa44cfa23745be8c2448a8c117dfdc50
2,660
crypto-exchange
MIT License
network-protection/network-protection-internal/src/main/java/com/duckduckgo/networkprotection/internal/network/NetPInternalEnvDataStore.kt
duckduckgo
78,869,127
false
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2023 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.networkprotection.internal.network import android.content.SharedPreferences import com.duckduckgo.data.store.api.SharedPreferencesProvider import javax.inject.Inject class NetPInternalEnvDataStore @Inject constructor( sharedPreferencesProvider: SharedPreferencesProvider, ) { private val preferences: SharedPreferences by lazy { sharedPreferencesProvider.getSharedPreferences(FILENAME, multiprocess = true, migrate = false) } fun overrideVpnStaging(endpoint: String?) { if (endpoint == null) { preferences.edit().remove(KEY_STAGING_ENVIRONMENT).apply() } else { preferences.edit().putString(KEY_STAGING_ENVIRONMENT, endpoint).apply() } } fun getVpnStagingEndpoint(): String { return preferences.getString(KEY_STAGING_ENVIRONMENT, DEFAULT_STAGING_ENVIRONMENT) ?: DEFAULT_STAGING_ENVIRONMENT } companion object { private const val FILENAME = "com.duckduckgo.netp.internal.env.store.v1" private const val KEY_STAGING_ENVIRONMENT = "KEY_STAGING_ENVIRONMENT" private const val DEFAULT_STAGING_ENVIRONMENT = "https://staging1.netp.duckduckgo.com" } }
67
Kotlin
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
1,797
Android
Apache License 2.0
spinner/src/main/java/com/lavergne/spinner/SpinnerDialog.kt
remylavergne
210,926,819
false
null
package com.lavergne.spinner import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.ArrayAdapter import android.widget.ListView import android.widget.Toast import androidx.annotation.LayoutRes import androidx.appcompat.widget.SearchView import androidx.fragment.app.DialogFragment class SpinnerDialog(private val itemListener: SearchItem) : DialogFragment(), SearchView.OnQueryTextListener { private var searchView: SearchView? = null private var listView: ListView? = null private var items: List<String> = emptyList() private var title: String? = null private var closeButton: String? = null private var customLayout: Int? = null var dialogIsAlreadyOpen: Boolean = false private set private var _hint: Hint? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val layoutInflater = LayoutInflater.from(activity) val rootView = layoutInflater.inflate(R.layout.search_dialog_layout, null) // Fill list item in RootView setDataInListView(rootView) // Create the Dialog val alertDialog = AlertDialog.Builder(activity) alertDialog.setView(rootView) this.title?.let { alertDialog.setTitle(it) } alertDialog.setPositiveButton( this.closeButton ?: "Generic positive button" ) { dialog, _ -> dialog.cancel() } dialogOpened() return alertDialog.create() } /** * Private Methods */ private fun setDataInListView(rootView: View?) { this.searchView = rootView?.findViewById(R.id.search_field) this.listView = rootView?.findViewById(R.id.items) this.listView?.adapter = ArrayAdapter( requireContext(), this.customLayout ?: R.layout.simple_list_item, this.items ) // Made the list auto filterable this.listView?.isTextFilterEnabled = true this.searchView?.setOnQueryTextListener(this) // Click event on list this.listView?.setOnItemClickListener { _, _, position, _ -> this.listView?.adapter?.let { adapter -> // Item val item = adapter.getItem(position) as String // Check Item if (hintExist() && item == this._hint?.text && !hintSelectable()) { this._hint?.toastMessage?.let { message -> Toast.makeText(context, message, Toast.LENGTH_LONG) .show() } } else { this.itemListener.onItemClicked(item) dialog?.cancel() dialogClosed() } } } } private fun dialogClosed() { this.dialogIsAlreadyOpen = false } private fun dialogOpened() { this.dialogIsAlreadyOpen = true } private fun hintExist(): Boolean { return this._hint != null && !this._hint?.text.isNullOrEmpty() } private fun hintSelectable(): Boolean { return this._hint?.isSelectable ?: true // Selectable by default } /** * Public Methods */ fun setTitle(text: String) { this.title = text } fun setButtonText(text: String) { this.closeButton = text } fun updateItems(items: List<String>) { this.items = items } fun updateListLayout(@LayoutRes layout: Int) { this.customLayout = layout } fun updateHint(hint: Hint) { this._hint = hint } /** * Implementations */ override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { val filter = when { !newText.isNullOrEmpty() -> newText else -> null } (this.listView?.adapter as? ArrayAdapter<*>)?.filter?.filter(filter) return true } /** * Interfaces */ interface SearchItem { fun onItemClicked(item: String) } /** * Lifecycle */ override fun onStop() { dialogClosed() super.onStop() } override fun onDestroy() { dialogClosed() super.onDestroy() } }
0
Kotlin
0
3
a668cb72a0df8d32549af35395d8901c1f211f5e
4,446
spinner-android
MIT License
app/src/main/java/com/example/borutoapp/navigation/NavGraph.kt
renato-viana
493,854,743
false
null
package com.example.borutoapp.navigation import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.example.borutoapp.presentation.screen.splash.SplashScreen import com.example.borutoapp.presentation.screen.welcome.WelcomeScreen import com.example.borutoapp.util.Constants.DETAILS_ARGUMENT_KEY import com.google.accompanist.pager.ExperimentalPagerApi @ExperimentalPagerApi @Composable fun SetupNavGraph(navController: NavHostController) { NavHost( navController = navController, startDestination = Screen.Welcome.route ) { composable(route = Screen.Splash.route) { SplashScreen(navController = navController) } composable(route = Screen.Welcome.route) { WelcomeScreen(navController = navController) } composable(route = Screen.Home.route) { } composable( route = Screen.Details.route, arguments = listOf(navArgument(DETAILS_ARGUMENT_KEY) { type = NavType.IntType }) ) { } composable(route = Screen.Search.route) { } } }
0
Kotlin
0
0
937e08cecde47248a818c2938cd7cdbc3b6857d8
1,321
borutoapp
Apache License 2.0
ktx-radix-tool/ktx-radix-tool-test/src/main/java/io/arkitik/ktx/radix/tool/test/dto/TestClassData.kt
arkitik
305,525,406
false
null
package io.arkitik.ktx.radix.tool.test.dto /** * Created By [*<NAME> *](https://www.linkedin.com/in/iloom/) * Created At 30, **Fri Oct, 2020** * Project *ktx-radix* [https://arkitik.io] */ data class TestClassData( val scenarios: List<TestScenario>, )
1
Kotlin
1
0
fc6f66dadecf3ebec5cad051ece06a37828889fb
261
ktx-radix
Apache License 2.0
app/src/main/kotlin/info/dvkr/screenstream/ui/fragment/SettingsFragment.kt
EmadAlhdad
271,803,225
true
{"Kotlin": 244406, "HTML": 4698}
package info.dvkr.screenstream.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.elvishew.xlog.XLog import com.google.android.material.tabs.TabLayoutMediator import info.dvkr.screenstream.R import info.dvkr.screenstream.data.other.getLog import info.dvkr.screenstream.databinding.FragmentSettingsBinding class SettingsFragment : Fragment() { private var _binding: FragmentSettingsBinding? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentSettingsBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.vpFragmentSettings.adapter = object : FragmentStateAdapter(this) { override fun getItemCount(): Int = 4 override fun createFragment(position: Int): Fragment = when (position) { 0 -> SettingsInterfaceFragment() 1 -> SettingsImageFragment() 2 -> SettingsSecurityFragment() 3 -> SettingsAdvancedFragment() else -> throw IllegalArgumentException("FragmentStateAdapter.getItem: unexpected position: $position") } } TabLayoutMediator(binding.tlFragmentSettings, binding.vpFragmentSettings) { tab, position -> tab.text = when (position) { 0 -> requireContext().getString(R.string.pref_settings_interface) 1 -> requireContext().getString(R.string.pref_settings_image) 2 -> requireContext().getString(R.string.pref_settings_security) 3 -> requireContext().getString(R.string.pref_settings_advanced) else -> throw IllegalArgumentException("TabLayoutMediator: unexpected position: $position") } }.attach() } override fun onStart() { super.onStart() XLog.d(getLog("onStart", "Invoked")) } override fun onStop() { XLog.d(getLog("onStop", "Invoked")) super.onStop() } }
0
Kotlin
0
1
bdf30c94feb2d6be214eb237348560441cc889c1
2,496
ScreenStream.Emadalhdad
MIT License
app/src/main/java/com/dm/materialcomponents/TextInputActivity.kt
DenysZP
143,293,945
false
null
package com.dm.materialcomponents import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_text_input.* class TextInputActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_text_input) outlineBoxErrorTextInput.error = "Error text" } }
0
Kotlin
0
0
69b524e79ec79220ce3bfbf6cea7f86f8494370b
433
MaterialComponentsSample
Apache License 2.0
representasjon/src/test/kotlin/no/nav/helse/sparkel/representasjon/RepresentasjonRiverTest.kt
navikt
341,650,641
false
{"Kotlin": 746878, "Shell": 1607, "Dockerfile": 168}
package no.nav.helse.sparkel.representasjon import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import io.mockk.every import io.mockk.mockk import java.util.UUID import no.nav.helse.rapids_rivers.testsupport.TestRapid import org.intellij.lang.annotations.Language import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test internal class RepresentasjonRiverTest { private val representasjonClient: RepresentasjonClient = mockk(relaxed = true) private val rapid: TestRapid = TestRapid().apply { RepresentasjonRiver(this, representasjonClient) } private val objectMapper = ObjectMapper() @Test fun `svarer ut behov for fullmakt`() { every { representasjonClient.hentFullmakt(any()) } returns objectMapper.readTree("""{"fullmakt": "yes"}""") rapid.sendTestMessage(behov()) val svar = rapid.inspektør.message(0) val løsning = svar.fullmaktløsning() assertEquals(1, løsning?.size()) } @Test fun `svarer med oppslagFeilet ved feil mot fullmakt-api`() { every { representasjonClient.hentFullmakt(any()) } returns null rapid.sendTestMessage(behov()) val svar = rapid.inspektør.message(0) val løsning = svar.fullmaktløsning() assertEquals(1, løsning?.size()) assertTrue(løsning["oppslagFeilet"].asBoolean()) } @Language("JSON") fun behov() = """ { "@event_name" : "fullmakt", "@id" : "${UUID.randomUUID()}", "@opprettet" : "2020-05-18", "fødselsnummer" : "fnr" } """.trimIndent() private fun JsonNode.fullmaktløsning() = this.path("@løsning")["fullmakt"] }
0
Kotlin
1
0
afebdda216f9bfc86789534a80ad59f07373bc8e
1,799
helse-sparkelapper
MIT License
src/main/kotlin/no/nav/tjenestepensjon/simulering/v2025/tjenestepensjon/v1/service/klp/KLPTjenestepensjonClient.kt
navikt
184,583,998
false
{"Kotlin": 338844, "Dockerfile": 97}
package no.nav.tjenestepensjon.simulering.v2025.tjenestepensjon.v1.service.klp import io.github.oshai.kotlinlogging.KotlinLogging import no.nav.tjenestepensjon.simulering.ping.PingResponse import no.nav.tjenestepensjon.simulering.ping.Pingable import no.nav.tjenestepensjon.simulering.v2025.tjenestepensjon.v1.domain.SimulertTjenestepensjon import no.nav.tjenestepensjon.simulering.v2025.tjenestepensjon.v1.dto.request.SimulerTjenestepensjonRequestDto import no.nav.tjenestepensjon.simulering.v2025.tjenestepensjon.v1.exception.TjenestepensjonSimuleringException import no.nav.tjenestepensjon.simulering.v2025.tjenestepensjon.v1.service.TjenestepensjonV2025Client import no.nav.tjenestepensjon.simulering.v2025.tjenestepensjon.v1.service.TjenestepensjonV2025Client.Companion.TJENESTE import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClientRequestException import org.springframework.web.reactive.function.client.WebClientResponseException import org.springframework.web.reactive.function.client.bodyToMono @Service class KLPTjenestepensjonClient(private val klpWebClient: WebClient) : TjenestepensjonV2025Client, Pingable { private val log = KotlinLogging.logger {} override fun simuler(request: SimulerTjenestepensjonRequestDto): Result<SimulertTjenestepensjon> { try { val response = klpWebClient .post() .uri(SIMULER_PATH) .bodyValue(KLPMapper.mapToRequest(request)) .retrieve() .bodyToMono<KLPSimulerTjenestepensjonResponse>() .block() return response?.let { Result.success(KLPMapper.mapToResponse(it)) } ?: Result.failure(TjenestepensjonSimuleringException("No response body")) } catch (e: WebClientResponseException) { val errorMsg = "Failed to simulate tjenestepensjon 2025 hos KLP ${ e.responseBodyAsString}" log.error(e) { errorMsg } return Result.failure(TjenestepensjonSimuleringException(errorMsg)) } catch (e: WebClientRequestException){ log.error(e) { "Failed to send request to simulate tjenestepensjon 2025 hos KLP med url ${e.uri}" } return Result.failure(TjenestepensjonSimuleringException("Failed to send request to simulate tjenestepensjon 2025 hos KLP")) } } override fun ping(): PingResponse { return PingResponse(PROVIDER, TJENESTE, "Støttes ikke") } companion object { private const val SIMULER_PATH = "/api/oftp/simulering/3200" private const val PING_PATH = "" private const val PROVIDER = "KLP" } }
8
Kotlin
0
0
f9180440c8a800035dffbb5363af7918072c6ac9
2,724
tjenestepensjon-simulering
MIT License
core/remote/src/main/kotlin/com/theophiluskibet/remote/model/CharacterResponse.kt
kibettheophilus
811,054,900
false
{"Kotlin": 66991}
/** * MIT License * * Copyright (c) 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.theophiluskibet.remote.model import kotlinx.serialization.Serializable @Serializable data class CharacterResponse( val info: Info, val results: List<CharacterDto>, ) @Serializable data class Info( val count: Int, val next: String, val pages: Int, // @Contextual // val prev: Any ) @Serializable data class CharacterDto( val created: String, val episode: List<String>, val gender: String, val id: Int, val image: String, val location: Location, val name: String, val origin: Origin, val species: String, val status: String, val type: String, val url: String, ) @Serializable data class Location( val name: String, val url: String, ) @Serializable data class Origin( val name: String, val url: String, )
3
Kotlin
0
2
ae20b26772d6c543fdf03c6bdfab33fe880970d8
1,940
koin-playground
MIT License
src/test/kotlin/chapter4/solutions/ex8/listing.kt
DavidGomesh
680,857,367
false
{"Kotlin": 159910}
package chapter4.solutions.ex8 //tag::init[] sealed class Partial<out A, out B> data class Failures<out A>(val get: List<A>) : Partial<A, Nothing>() data class Success<out B>(val get: B) : Partial<Nothing, B>() //end::init[]
0
Kotlin
0
0
6701481feba3a38cd96262c888e3f61e09bc85e6
227
fp-kotlin
MIT License
trixnity-core/src/commonMain/kotlin/net/folivo/trixnity/core/model/events/m/key/verification/VerificationStartEventContent.kt
benkuly
330,904,570
false
null
package net.folivo.trixnity.core.model.events.m.key.verification import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator import net.folivo.trixnity.core.model.events.RelatesTo import net.folivo.trixnity.core.model.events.m.key.verification.SasMethod.DECIMAL import net.folivo.trixnity.core.model.events.m.key.verification.SasMethod.EMOJI /** * @see <a href="https://spec.matrix.org/unstable/client-server-api/#mkeyverificationstart">matrix spec</a> */ @OptIn(ExperimentalSerializationApi::class) @Serializable @JsonClassDiscriminator("method") sealed interface VerificationStartEventContent : VerificationStep { val fromDevice: String val nextMethod: VerificationMethod? /** * @see <a href="https://spec.matrix.org/unstable/client-server-api/#mkeyverificationstartmsasv1">matrix spec</a> */ @Serializable @SerialName("m.sas.v1") data class SasStartEventContent( @SerialName("from_device") override val fromDevice: String, @SerialName("hashes") val hashes: Set<String> = setOf("sha256"), @SerialName("key_agreement_protocols") val keyAgreementProtocols: Set<String> = setOf("curve25519-hkdf-sha256"), @SerialName("message_authentication_codes") val messageAuthenticationCodes: Set<String> = setOf("hkdf-hmac-sha256"), @SerialName("short_authentication_string") val shortAuthenticationString: Set<SasMethod> = setOf(DECIMAL, EMOJI), @SerialName("m.relates_to") override val relatesTo: RelatesTo.Reference?, @SerialName("transaction_id") override val transactionId: String?, ) : VerificationStartEventContent { @SerialName("next_method") override val nextMethod: VerificationMethod? = null } }
0
Kotlin
3
24
b469cde81341e70b31e7143972ca1dadcc70817d
1,906
trixnity
Apache License 2.0
app/src/main/kotlin/com/gonodono/smssender/data/SmsSenderDatabase.kt
gonodono
615,690,160
false
{"Kotlin": 33831}
package com.gonodono.smssender.data import androidx.room.Database import androidx.room.RoomDatabase @Database( entities = [Message::class, SendTask::class], version = 1, exportSchema = false ) abstract class SmsSenderDatabase : RoomDatabase() { abstract val messageDao: MessageDao abstract val sendTaskDao: SendTaskDao }
0
Kotlin
0
0
cfa895e5de2f74e662aa68c0d68b7638b8b3af40
344
sms-sender
MIT License
src/Day02.kt
alexladeira
573,196,827
false
null
fun main() { val finalValues = mapOf("X" to 1, "Y" to 2, "Z" to 3) val sum = readInput("Day02").fold(0) { acc, s -> val values = s.split(" ").toMutableList() values[1] = updateSecondValue(values) when { "A" == values[0] && "Z" == values[1] || "C" == values[0] && "Y" == values[1] || "B" == values[0] && "X" == values[1] -> acc + finalValues[values[1]]!! "A" == values[0] && "X" == values[1] || "C" == values[0] && "Z" == values[1] || "B" == values[0] && "Y" == values[1] -> acc + finalValues[values[1]]!! + 3 else -> acc + finalValues[values[1]]!! + 6 } } print(sum) } fun updateSecondValue(values: List<String>): String { return if (values[1] == "X") { val lose = mapOf("A" to "Z", "B" to "X", "C" to "Y") lose[values[0]]!! } else if (values[1] == "Y") { val draw = mapOf("A" to "X", "B" to "Y", "C" to "Z") draw[values[0]]!! } else { val win = mapOf("A" to "Y", "B" to "Z", "C" to "X") win[values[0]]!! } }
0
Kotlin
0
0
facafc2d92de2ad2b6264610be4159c8135babcb
1,058
aoc-2022-in-kotlin
Apache License 2.0
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/liquids/general/BaseFluidPlaceable.kt
frozolotl
206,179,330
true
{"Kotlin": 789585}
package net.cydhra.technocracy.foundation.liquids.general import java.awt.Color class BaseFluidPlaceable(fluidName: String, color: Color, opaqueTexture: Boolean) : BaseFluid(fluidName, color, opaqueTexture = opaqueTexture)
0
Kotlin
0
0
5edb6a699cd39417c4a313d56bacd39077bb23eb
233
Technocracy
MIT License
app/src/main/java/com/kylecorry/weight_tracker/ui/WeightListItemMapper.kt
kylecorry31
656,392,429
false
null
package com.kylecorry.weight_tracker.ui import android.content.Context import com.kylecorry.ceres.list.ListItem import com.kylecorry.ceres.list.ListItemMapper import com.kylecorry.ceres.list.ListMenuItem import com.kylecorry.sol.time.Time.toZonedDateTime import com.kylecorry.sol.units.Reading import com.kylecorry.weight_tracker.R import com.kylecorry.weight_tracker.domain.LoggedWeight import com.kylecorry.weight_tracker.infrastructure.preferences.UserSettings class WeightListItemMapper( private val context: Context, private val settings: UserSettings, private val formatter: FormatService, private val onDelete: (Reading<LoggedWeight>) -> Unit ) : ListItemMapper<Reading<LoggedWeight>> { override fun map(value: Reading<LoggedWeight>): ListItem { return ListItem( value.value.id, formatter.formatWeight(value.value.weight.convertTo(settings.units)), formatter.formatDate(value.time.toZonedDateTime()), menu = listOf( ListMenuItem(context.getString(R.string.delete)) { onDelete(value) } ) ) } }
0
Kotlin
0
0
2ff4ecaa92a58339334d963b18170a14a93e2220
1,118
Weight-Tracker
MIT License
app/src/main/java/com/example/emojigarden/LoginVm.kt
mongodb-developer
323,881,786
false
null
package com.example.emojigarden import android.app.Application import android.util.Log import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.AndroidViewModel import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue /** * Methods to: * 1. Login anonymously with MongoDb Realm Sync * 2. Send initial data to MongoDB Realm Sync * * A bit of state to ensure initial data isn't attempted to be sent unless you're logged in. */ class LoginVm(application: Application) : AndroidViewModel(application) { private val TAG = LoginVm::class.java.simpleName var showGarden : Boolean by mutableStateOf(getApplication<EmojiGardenApplication>().realmModule.isInitialized()) private set fun login() = getApplication<EmojiGardenApplication>().realmModule.loginAnonSyncedRealm( onSuccess = ::initializeData, // If login succeeds, initialize data within the app onFailure = { Log.d(TAG, "Failed to login") } // Just log failures ) private fun initializeData() { getApplication<EmojiGardenApplication>().realmModule.initializeCollectionIfEmpty() showGarden = true } }
0
Kotlin
4
4
9c304ba4b9dcf904d40f160c2e37845156ffbd3c
1,186
EmojiGarden
Apache License 2.0
src/test/kotlin/jsonsql/integration/AliasTest.kt
tim-patterson
131,454,972
false
null
package jsonsql.integration import org.junit.platform.runner.JUnitPlatform import org.junit.runner.RunWith import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe @RunWith(JUnitPlatform::class) object AliasTest: Spek({ describe("Column Aliases") { it("basic with as") { testQuery("select a from (select rownum as a from json 'test_data/nested.json' limit 3);", """ 1.0 2.0 3.0 """.trimIndent()) } it("basic without as") { testQuery("select a from (select rownum a from json 'test_data/nested.json' limit 3);", """ 1.0 2.0 3.0 """.trimIndent()) } } describe("Table Aliases") { it("basic") { testQuery("select my_tbl.rownum, rownum from json 'test_data/nested.json' as my_tbl where my_tbl.rownum > 1 limit 3;", """ 2.0 | 2.0 3.0 | 3.0 4.0 | 4.0 """.trimIndent()) } it("lateral view unqualified") { testQuery("select foo.rownum, arrayval from json 'test_data/nested.json' foo lateral view arrayval limit 5;", """ 1.0 | a1 1.0 | a2 1.0 | a3 2.0 | b1 2.0 | b2 """.trimIndent()) } it("lateral view qualified") { testQuery("select foo.rownum, arrayval from json 'test_data/nested.json' foo lateral view foo.arrayval order by rownum, arrayval limit 5;", """ 1.0 | a1 1.0 | a2 1.0 | a3 2.0 | b1 2.0 | b2 """.trimIndent()) } } })
1
Kotlin
1
3
1fc28152476ad9ebcc2b1aefce1c2c6636a98083
1,787
jsonsql
MIT License
src/main/kotlin/com/github/carrot372/namlan/tokenizer/Tokenizer.kt
carrot372
491,486,114
false
null
/* * Copyright (c) 2022. carrot * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.carrot372.namlan.tokenizer import com.github.carrot372.namlan.* object Lexer { fun lexing(text: String) { val tokenizer = Tokenizer(text) do { val token = tokenizer.nextToken() println(token) } while (token !is EOFToken) } } private operator fun Regex.contains(char: Char?): Boolean { return if (char == null) { false } else { matches(char.toString()) } } class Tokenizer(private val input: String) { private fun isWhiteSpace(char: Char?): Boolean { return if(char == null) false else Regex("\\s").matches(char.toString()) } private val ch: Char? get() = input.getOrNull(p) private var p: Int = 0 private var position: Int = 0 private fun incP(): Int { if (p < input.length) { p++ } return p } private fun isEnd(): Boolean { return p == input.length } private fun ensureSetPosition(token: Token): Token { position = p return token } fun nextToken(): Token { if (isEnd()) return EOFToken() while (isWhiteSpace(ch)) { incP() position = p } val startPosition = position return when (ch) { // math '+' -> { incP() ensureSetPosition(PlusToken()) } '-' -> { incP() ensureSetPosition(MinusToken()) } '*' -> { incP() ensureSetPosition(MultiToken()) } '/' -> { incP() ensureSetPosition(DiviToken()) } '<' -> { incP() return when (ch) { '=' -> { incP() position += p LessEqualToken() } else -> { position += p LessToken() } } } '>' -> { incP() return when (ch) { '=' -> { p++ GreatEqualToken() } else -> { GreatToken() } } } '=' -> { incP() when (ch) { '=' -> { incP() position += p return EqualToken() } else -> { position += p return AssignToken() } } } '!' -> { incP() return when (ch) { '=' -> { incP() position += p NotEqualToken() } else -> { position += p BangToken() } } } ',' -> { incP() position = p CommaToken() } '(' -> { incP() position = p LParenToken() } ')' -> { incP() position = p RParenToken() } '{' -> { incP() position = p LBraceToken() } '}' -> { incP() position = p RBraceToken() } ';' -> { incP() position = p SemiColonToken() } in Regex("[1-9]") -> { incP() while (ch in Regex("\\d")) { incP() } ensureSetPosition(NumberToken(input.slice(startPosition until p))) } else -> return when { isEnd() -> { EOFToken() } ch in Regex("[a-zA-Z_]") -> { while (ch in Regex("[a-zA-Z_]")) { incP() } when (val text = input.slice(startPosition until p)) { "Function" -> ensureSetPosition(FunctionToken()) "return" -> ensureSetPosition(ReturnToken()) "True" -> ensureSetPosition(TrueToken()) "False" -> ensureSetPosition(FalseToken()) "If" -> ensureSetPosition(IfToken()) "Else" -> ensureSetPosition(ElseToken()) "While" -> ensureSetPosition(WhileToken()) "For" -> ensureSetPosition(ForToken()) "When" -> ensureSetPosition(WhenToken()) "Then" -> ensureSetPosition(ThenToken()) else -> ensureSetPosition(IdentifierToken(text)) } } else -> { incP() ensureSetPosition(IllegalToken(input.slice(startPosition until p))) } } } } }
0
Kotlin
0
0
4095c211d625c5639ffb43d024ee14b3161de3e3
6,203
Namlan-for-Minecraft
Apache License 2.0
data/src/main/java/com/vr/data/di/DataModule.kt
vidalrmrz
280,246,328
false
null
package com.vr.data.di import com.vr.data.repositories.SearchRepositoryImpl import com.vr.domain.repositories.SearchRepository import org.koin.dsl.module val dataModule = module { single<SearchRepository> { SearchRepositoryImpl(get()) } }
0
Kotlin
0
0
2538e56cf63937fa22ba30462429389d85666f5b
244
mecali
Apache License 2.0
src/main/kotlin/org/jitsi/nlj/util/ClockUtils.kt
jitsi
165,715,677
false
null
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("ClockUtils") package org.jitsi.nlj.util import java.time.Duration import java.time.Instant import org.jitsi.utils.TimeUtils @JvmField val NEVER: Instant = Instant.MIN fun Instant.formatMilli(): String = TimeUtils.formatTimeAsFullMillis(this.epochSecond, this.nano) fun Duration.formatMilli(): String = TimeUtils.formatTimeAsFullMillis(this.seconds, this.nano)
8
null
51
33
62df6da57f86dc8943b239dbea738f1fc1c9d534
986
jitsi-media-transform
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/utility/DevicePermissionHandlerHandlerDetails.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron.utility typealias DevicePermissionHandlerHandlerDetails = electron.core.DevicePermissionHandlerHandlerDetails
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
182
kotlin-wrappers
Apache License 2.0
feature/data/src/main/java/com/montfel/gamerguide/feature/data/mapper/PlatformsMapper.kt
Montfel
537,669,918
false
{"Kotlin": 40222, "Ruby": 2789}
package com.montfel.gamerguide.feature.data.mapper import com.montfel.gamerguide.feature.data.model.dto.PlatformsDto import com.montfel.gamerguide.feature.domain.model.Platforms internal fun PlatformsDto.toDomain() = Platforms( platform = platform.toDomain(), releasedAt = releasedAt )
6
Kotlin
0
2
5083aaadc959447bebe18c71e2f1a856343be9e1
296
gamer-guide
MIT License
gateway/src/main/kotlin/org/heeheepresso/gateway/user/UserService.kt
HeeHeePresso
758,780,391
false
{"Kotlin": 7433}
package org.heeheepresso.gateway.user import org.heeheepresso.gateway.user.api.UserApiService import org.springframework.stereotype.Service import java.util.concurrent.ConcurrentHashMap @Service class UserService( private val userApi: UserApiService ) { private val userRoleCache = ConcurrentHashMap<String, UserRole>() fun getUserRole(userId: String): UserRole? { return when { userRoleCache.containsKey(userId) -> userRoleCache[userId] else -> userApi.getUserRole(userId) } } }
2
Kotlin
0
0
cb1ba900780188af461b390f307e435d4595e6f8
538
Backend
Apache License 2.0
app/src/main/java/com/benjaminwan/composelocation/loclib/IOnLocationListener.kt
PhoneTools
392,888,257
false
null
package com.benjaminwan.composelocation.loclib import android.location.Location interface IOnLocationListener { fun onLocationChanged(location: Location)//位置信息 fun onSatellitesChanged(satellites: List<Satellite>)//卫星列表 fun onNmeaChanged(nmea: Nmea)//原始GPS信息 fun onFirstFix(firstFixTimeMs: Int)//初次定位时间 毫秒 fun onGpsProviderChanged(isEnable: Boolean)//定位开关 }
0
Kotlin
0
5
5b8ccba06e8161c6130f77a6d34d92d2bda3ea18
378
ComposeLocation
Apache License 2.0
src/main/kotlin/no/nav/lydia/ia/sak/domene/spørreundersøkelse/SpørsmålOgSvaralternativer.kt
navikt
444,072,054
false
{"Kotlin": 916949, "Python": 5547, "Shell": 1074, "Dockerfile": 207}
package no.nav.lydia.ia.sak.domene.spørreundersøkelse import java.util.UUID data class SpørsmålOgSvaralternativer( val spørsmålId: UUID, val spørsmåltekst: String, val svaralternativer: List<Svaralternativ>, val flervalg: Boolean, )
1
Kotlin
0
1
8a748ea749c30455dacd7f07c993addbacce53f8
238
lydia-api
MIT License