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
compose/ui/ui/src/skikoMain/kotlin/androidx/compose/ui/scene/CanvasLayersComposeScene.skiko.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.scene import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionContext import androidx.compose.runtime.CompositionLocalContext import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.InternalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.InternalKeyEvent import androidx.compose.ui.input.pointer.PointerButton import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.PointerInputEvent import androidx.compose.ui.input.pointer.PointerType import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.node.RootNodeOwner import androidx.compose.ui.platform.PlatformContext import androidx.compose.ui.platform.setContent import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.round import androidx.compose.ui.util.fastAny import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastForEachReversed import androidx.compose.ui.viewinterop.InteropView import androidx.compose.ui.window.getDialogScrimBlendMode import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Dispatchers /** * Constructs a multi-layer [ComposeScene] using the specified parameters. Unlike * [PlatformLayersComposeScene], this version doesn't employ [ComposeSceneContext.createPlatformLayer] * to position a new [LayoutNode] tree. Rather, it keeps track of the added layers on its own in * order to render (and also divide input among them) everything on a single canvas. * * After [ComposeScene] will no longer needed, you should call [ComposeScene.close] method, so * all resources and subscriptions will be properly closed. Otherwise, there can be a memory leak. * * @param density Initial density of the content which will be used to convert [Dp] units. * @param layoutDirection Initial layout direction of the content. * @param size The size of the [ComposeScene]. Default value is `null`, which means the size will be * determined by the content. * @param coroutineContext Context which will be used to launch effects ([LaunchedEffect], * [rememberCoroutineScope]) and run recompositions. * @param composeSceneContext The context to share resources between multiple scenes and provide * a way for platform interaction. * @param invalidate The function to be called when the content need to be recomposed or * re-rendered. If you draw your content using [ComposeScene.render] method, in this callback you * should schedule the next [ComposeScene.render] in your rendering loop. * @return The created [ComposeScene]. * * @see ComposeScene */ @InternalComposeUiApi fun CanvasLayersComposeScene( density: Density = Density(1f), layoutDirection: LayoutDirection = LayoutDirection.Ltr, size: IntSize? = null, // TODO: Remove `Dispatchers.Unconfined` as a default coroutineContext: CoroutineContext = Dispatchers.Unconfined, composeSceneContext: ComposeSceneContext = ComposeSceneContext.Empty, invalidate: () -> Unit = {}, ): ComposeScene = CanvasLayersComposeSceneImpl( density = density, layoutDirection = layoutDirection, size = size, coroutineContext = coroutineContext, composeSceneContext = composeSceneContext, invalidate = invalidate ) private class CanvasLayersComposeSceneImpl( density: Density, layoutDirection: LayoutDirection, size: IntSize?, coroutineContext: CoroutineContext, composeSceneContext: ComposeSceneContext, invalidate: () -> Unit = {}, ) : BaseComposeScene( coroutineContext = coroutineContext, composeSceneContext = composeSceneContext, invalidate = invalidate ) { private val mainOwner = RootNodeOwner( density = density, layoutDirection = layoutDirection, size = size, coroutineContext = compositionContext.effectCoroutineContext, platformContext = composeSceneContext.platformContext, snapshotInvalidationTracker = snapshotInvalidationTracker, inputHandler = inputHandler, ) override var density: Density = density set(value) { check(!isClosed) { "density set after ComposeScene is closed" } field = value mainOwner.density = value } override var layoutDirection: LayoutDirection = layoutDirection set(value) { check(!isClosed) { "layoutDirection set after ComposeScene is closed" } field = value mainOwner.layoutDirection = value } override var size: IntSize? = size set(value) { check(!isClosed) { "size set after ComposeScene is closed" } check(value == null || (value.width >= 0f && value.height >= 0)) { "Size of ComposeScene cannot be negative" } field = value mainOwner.size = value forEachLayer { it.owner.size = value } } override val focusManager: ComposeSceneFocusManager = ComposeSceneFocusManager( focusOwner = { focusedOwner.focusOwner } ) private val layers = mutableListOf<AttachedComposeSceneLayer>() private val _layersCopyCache = CopiedList { it.addAll(layers) } private val _ownersCopyCache = CopiedList { it.add(mainOwner) for (layer in layers) { it.add(layer.owner) } } private inline fun forEachLayer(action: (AttachedComposeSceneLayer) -> Unit) = _layersCopyCache.withCopy { it.fastForEach(action) } private inline fun forEachLayerReversed(action: (AttachedComposeSceneLayer) -> Unit) = _layersCopyCache.withCopy { it.fastForEachReversed(action) } private inline fun forEachOwner(action: (RootNodeOwner) -> Unit) = _ownersCopyCache.withCopy { it.fastForEach(action) } private var focusedLayer: AttachedComposeSceneLayer? = null private val focusedOwner get() = focusedLayer?.owner ?: mainOwner private var gestureOwner: RootNodeOwner? = null private var lastHoverOwner: RootNodeOwner? = null init { onOwnerAppended(mainOwner) } override fun close() { check(!isClosed) { "ComposeScene is already closed" } onOwnerRemoved(mainOwner) mainOwner.dispose() forEachLayer { it.close() } super.close() } override fun calculateContentSize(): IntSize { check(!isClosed) { "calculateContentSize called after ComposeScene is closed" } return mainOwner.measureInConstraints(Constraints()) } override fun invalidatePositionInWindow() { check(!isClosed) { "invalidatePositionInWindow called after ComposeScene is closed" } mainOwner.invalidatePositionInWindow() } override fun createComposition(content: @Composable () -> Unit): Composition { return mainOwner.setContent( compositionContext, { compositionLocalContext }, content = content ) } override fun hitTestInteropView(position: Offset): InteropView? { forEachLayerReversed { layer -> if (layer.isInBounds(position)) { return layer.owner.hitTestInteropView(position) } else if (layer == focusedLayer) { return null } } return mainOwner.hitTestInteropView(position) } override fun processPointerInputEvent(event: PointerInputEvent) { when (event.eventType) { PointerEventType.Press -> processPress(event) PointerEventType.Release -> processRelease(event) PointerEventType.Move -> processMove(event) PointerEventType.Enter -> processMove(event) PointerEventType.Exit -> processMove(event) PointerEventType.Scroll -> processScroll(event) } // Clean gestureOwner when there is no pressed pointers/buttons if (!event.isGestureInProgress) { gestureOwner = null } } override fun processKeyEvent(internalKeyEvent: InternalKeyEvent): Boolean = focusedLayer?.onKeyEvent(internalKeyEvent) ?: mainOwner.onKeyEvent(internalKeyEvent) override fun measureAndLayout() { forEachOwner { it.measureAndLayout() } } override fun draw(canvas: Canvas) { forEachOwner { it.draw(canvas) } } /** * Find hovered owner for position of first pointer. */ private fun hoveredOwner(event: PointerInputEvent): RootNodeOwner { val position = event.pointers.first().position return layers.lastOrNull { it.isInBounds(position) }?.owner ?: mainOwner } /** * Check if [focusedLayer] blocks input for this owner. */ private fun isInteractive(owner: RootNodeOwner?): Boolean { if (owner == null || focusedLayer == null) { return true } if (owner == mainOwner) { return false } for (layer in layers) { if (layer == focusedLayer) { return true } if (layer.owner == owner) { return false } } return true } private fun processPress(event: PointerInputEvent) { val currentGestureOwner = gestureOwner if (currentGestureOwner != null) { currentGestureOwner.onPointerInput(event) return } val position = event.pointers.first().position forEachLayerReversed { layer -> // If the position of in bounds of the owner - send event to it and stop processing if (layer.isInBounds(position)) { // The layer doesn't have any offset from [mainOwner], so we don't need to // convert event coordinates here. layer.owner.onPointerInput(event) gestureOwner = layer.owner return } // Input event is out of bounds - send click outside notification layer.onOutsidePointerEvent(event) // if the owner is in focus, do not pass the event to underlying owners if (layer == focusedLayer) { return } } mainOwner.onPointerInput(event) gestureOwner = mainOwner } private fun processRelease(event: PointerInputEvent) { // Send Release to gestureOwner even if is not hovered or under focusedOwner gestureOwner?.onPointerInput(event) if (!event.isGestureInProgress) { val owner = hoveredOwner(event) if (isInteractive(owner)) { processHover(event, owner) } else if (gestureOwner == null) { // If hovered owner is not interactive, then it means that // - It's not focusedOwner // - It placed under focusedOwner or not exist at all // In all these cases the even happened outside focused owner bounds focusedLayer?.onOutsidePointerEvent(event) } } } private fun processMove(event: PointerInputEvent) { var owner = when { // All touch events or mouse with pressed button(s) event.isGestureInProgress -> gestureOwner // Do not generate Enter and Move event.eventType == PointerEventType.Exit -> null // Find owner under mouse position else -> hoveredOwner(event) } // Even if the owner is not interactive, hover state still need to be updated if (!isInteractive(owner)) { owner = null } if (processHover(event, owner)) { return } owner?.onPointerInput(event.copy(eventType = PointerEventType.Move)) } /** * Updates hover state and generates [PointerEventType.Enter] and [PointerEventType.Exit] * events. Returns true if [event] is consumed. */ private fun processHover(event: PointerInputEvent, owner: RootNodeOwner?): Boolean { if (event.pointers.fastAny { it.type != PointerType.Mouse }) { // Track hover only for mouse return false } // Cases: // - move from outside to the window (owner != null, lastMoveOwner == null): Enter // - move from the window to outside (owner == null, lastMoveOwner != null): Exit // - move from one point of the window to another (owner == lastMoveOwner): Move // - move from one popup to another (owner != lastMoveOwner): [Popup 1] Exit, [Popup 2] Enter if (owner == lastHoverOwner) { // Owner wasn't changed return false } lastHoverOwner?.onPointerInput(event.copy(eventType = PointerEventType.Exit)) owner?.onPointerInput(event.copy(eventType = PointerEventType.Enter)) lastHoverOwner = owner // Changing hovering state replaces Move event, so treat it as consumed return true } private fun processScroll(event: PointerInputEvent) { val owner = hoveredOwner(event) if (isInteractive(owner)) { owner.onPointerInput(event) } } override fun createLayer( density: Density, layoutDirection: LayoutDirection, focusable: Boolean, compositionContext: CompositionContext, ): ComposeSceneLayer = AttachedComposeSceneLayer( density = density, layoutDirection = layoutDirection, focusable = focusable, compositionContext = compositionContext, ) private fun onOwnerAppended(owner: RootNodeOwner) { semanticsOwnerListener?.onSemanticsOwnerAppended(owner.semanticsOwner) } private fun onOwnerRemoved(owner: RootNodeOwner) { if (owner == lastHoverOwner) { lastHoverOwner = null } if (owner == gestureOwner) { gestureOwner = null } semanticsOwnerListener?.onSemanticsOwnerRemoved(owner.semanticsOwner) } private fun attachLayer(layer: AttachedComposeSceneLayer) { check(!isClosed) { "attachLayer called after ComposeScene is closed" } layers.add(layer) if (layer.focusable) { requestFocus(layer) } onOwnerAppended(layer.owner) inputHandler.onPointerUpdate() updateInvalidations() } private fun detachLayer(layer: AttachedComposeSceneLayer) { check(!isClosed) { "detachLayer called after ComposeScene is closed" } layers.remove(layer) releaseFocus(layer) onOwnerRemoved(layer.owner) inputHandler.onPointerUpdate() updateInvalidations() } private fun requestFocus(layer: AttachedComposeSceneLayer) { if (isInteractive(layer.owner)) { focusedLayer = layer // Exit event to lastHoverOwner will be sent via synthetic event on next frame } } private fun releaseFocus(layer: AttachedComposeSceneLayer) { if (layer == focusedLayer) { focusedLayer = layers.lastOrNull { it.focusable } // Enter event to new focusedOwner will be sent via synthetic event on next frame } } private inner class AttachedComposeSceneLayer( density: Density, layoutDirection: LayoutDirection, focusable: Boolean, private val compositionContext: CompositionContext, ) : ComposeSceneLayer { val owner = RootNodeOwner( density = density, layoutDirection = layoutDirection, coroutineContext = compositionContext.effectCoroutineContext, size = [email protected], platformContext = object : PlatformContext by composeSceneContext.platformContext { /** * Popup/Dialog shouldn't delegate focus to the parent. */ override val parentFocusManager: FocusManager get() = PlatformContext.Empty.parentFocusManager // TODO: Figure out why real requestFocus is required // even with empty parentFocusManager }, snapshotInvalidationTracker = snapshotInvalidationTracker, inputHandler = inputHandler, ) private var composition: Composition? = null private var outsidePointerCallback: (( eventType: PointerEventType, button: PointerButton? ) -> Unit)? = null private var isClosed = false override var density: Density by owner::density override var layoutDirection: LayoutDirection by owner::layoutDirection /* * We cannot set [owner.bounds] as default value because real bounds will be available * not immediately, so it will change [lastHoverOwner] for a few frames. * This scenario is important when user code relies on hover events to show tooltips. */ override var boundsInWindow: IntRect by mutableStateOf(IntRect.Zero) @Deprecated( message = "Should not be used in this implementation", level = DeprecationLevel.ERROR ) override var compositionLocalContext: CompositionLocalContext? = null override var scrimColor: Color? by mutableStateOf(null) override var focusable: Boolean = focusable set(value) { field = value if (value) { requestFocus(this) } else { releaseFocus(this) } inputHandler.onPointerUpdate() updateInvalidations() } private val background: Modifier get() = scrimColor?.let { Modifier.drawBehind { drawRect( color = it, blendMode = getDialogScrimBlendMode( composeSceneContext.platformContext.isWindowTransparent ) ) } } ?: Modifier private var onPreviewKeyEvent: ((InternalKeyEvent) -> Boolean)? = null private var onKeyEvent: ((InternalKeyEvent) -> Boolean)? = null init { attachLayer(this) } override fun close() { if (isClosed) return detachLayer(this) composition?.dispose() composition = null owner.dispose() isClosed = true } override fun setKeyEventListener( onPreviewKeyEvent: ((InternalKeyEvent) -> Boolean)?, onKeyEvent: ((InternalKeyEvent) -> Boolean)?, ) { this.onPreviewKeyEvent = onPreviewKeyEvent this.onKeyEvent = onKeyEvent } fun onKeyEvent(internalKeyEvent: InternalKeyEvent): Boolean { return onPreviewKeyEvent?.invoke(internalKeyEvent) == true || owner.onKeyEvent(internalKeyEvent) || onKeyEvent?.invoke(internalKeyEvent) == true } override fun setOutsidePointerEventListener( onOutsidePointerEvent: ((eventType: PointerEventType, button: PointerButton?) -> Unit)?, ) { outsidePointerCallback = onOutsidePointerEvent } override fun setContent(content: @Composable () -> Unit) { check(!isClosed) { "AttachedComposeSceneLayer is closed" } composition?.dispose() composition = owner.setContent( parent = [email protected], { /* * Do not use `compositionLocalContext` here - composition locals already * available from `compositionContext` and explicitly overriding it might cause * issues. See https://github.com/JetBrains/compose-multiplatform/issues/4558 */ null } ) { owner.setRootModifier(background) content() } } override fun calculateLocalPosition(positionInWindow: IntOffset): IntOffset = positionInWindow // [ComposeScene] is equal to window in this implementation. fun isInBounds(position: Offset) = boundsInWindow.contains(position.round()) fun onOutsidePointerEvent(event: PointerInputEvent) { if (!event.isMouseOrSingleTouch()) { return } outsidePointerCallback?.invoke(event.eventType, event.button) } } } private val PointerInputEvent.isGestureInProgress get() = pointers.fastAny { it.down } private fun PointerInputEvent.isMouseOrSingleTouch() = button != null || pointers.size == 1 private class CopiedList<T>( private val populate: (MutableList<T>) -> Unit ) : MutableList<T> by mutableListOf() { inline fun withCopy( block: (List<T>) -> Unit ) { // In case of recursive calls, allocate new list val copy = if (isEmpty()) this else mutableListOf() populate(copy) try { block(copy) } finally { copy.clear() } } }
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
22,609
compose
Apache License 2.0
data/remote/lists/src/commonTest/kotlin/dev/alvr/katana/data/remote/lists/repositories/ListsRepositoryTest.kt
alvr
446,535,707
false
{"Kotlin": 458492, "Swift": 594}
package dev.alvr.katana.data.remote.lists.repositories import app.cash.turbine.test import arrow.core.left import arrow.core.right import dev.alvr.katana.common.tests.invoke import dev.alvr.katana.common.tests.shouldBeLeft import dev.alvr.katana.common.tests.shouldBeRight import dev.alvr.katana.data.remote.lists.sources.CommonListsRemoteSource import dev.alvr.katana.data.remote.lists.sources.MockCommonListsRemoteSource import dev.alvr.katana.data.remote.lists.sources.anime.AnimeListsRemoteSource import dev.alvr.katana.data.remote.lists.sources.anime.MockAnimeListsRemoteSource import dev.alvr.katana.data.remote.lists.sources.manga.MangaListsRemoteSource import dev.alvr.katana.data.remote.lists.sources.manga.MockMangaListsRemoteSource import dev.alvr.katana.domain.base.failures.Failure import dev.alvr.katana.domain.lists.failures.ListsFailure import dev.alvr.katana.domain.lists.models.MediaCollection import dev.alvr.katana.domain.lists.models.entries.MediaEntry import dev.alvr.katana.domain.lists.models.lists.MediaList import dev.alvr.katana.domain.lists.models.lists.fakeMediaList import dev.alvr.katana.domain.lists.repositories.ListsRepository import io.kotest.core.spec.style.FreeSpec import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.flow.flowOf import org.kodein.mock.Mocker import org.kodein.mock.UsesFakes import org.kodein.mock.UsesMocks @UsesFakes(MediaList::class) @UsesMocks( CommonListsRemoteSource::class, AnimeListsRemoteSource::class, MangaListsRemoteSource::class, ) internal class ListsRepositoryTest : FreeSpec() { private val mocker = Mocker() private val commonSource = MockCommonListsRemoteSource(mocker) private val animeSource = MockAnimeListsRemoteSource(mocker) private val mangaSource = MockMangaListsRemoteSource(mocker) private val repo: ListsRepository = ListsRepositoryImpl(commonSource, animeSource, mangaSource) init { "collecting anime collection flow" { val collection = MediaCollection<MediaEntry.Anime>(emptyList()) mocker.every { animeSource.animeCollection } returns flowOf(collection.right()) repo.animeCollection.test(5.seconds) { awaitItem().shouldBeRight(collection) awaitComplete() } mocker.verify { animeSource.animeCollection } } "collecting manga collection flow" { val collection = MediaCollection<MediaEntry.Manga>(emptyList()) mocker.every { mangaSource.mangaCollection } returns flowOf(collection.right()) repo.mangaCollection.test(5.seconds) { awaitItem().shouldBeRight(collection) awaitComplete() } mocker.verify { mangaSource.mangaCollection } } "successfully updating list" { mocker.everySuspending { commonSource.updateList(isAny()) } returns Unit.right() repo.updateList(fakeMediaList()).shouldBeRight(Unit) mocker.verifyWithSuspend { commonSource.updateList(isAny()) } } listOf( ListsFailure.UpdatingList to ListsFailure.UpdatingList.left(), Failure.Unknown to Failure.Unknown.left(), ).forEach { (expected, failure) -> "failure updating the list ($expected)" { mocker.everySuspending { repo.updateList(isAny()) } returns failure repo.updateList(fakeMediaList()).shouldBeLeft(expected) mocker.verifyWithSuspend { repo.updateList(fakeMediaList()) } } } } override fun extensions() = listOf(mocker()) }
4
Kotlin
0
49
c07257f57ba171d5486d9d56cffd8354f84d484f
3,639
katana
Apache License 2.0
app/src/test/java/RabbitTest.kt
Leon406
381,644,086
false
null
import java.nio.charset.StandardCharsets import me.leon.encode.base.BASE64_DICT import me.leon.encode.base.base64 fun main() { // http://cdn.esjson.com/esjson/js/encryencode/rabbit.js?v=202003311412 // test.test(new Rabbit()); // 小于128位,不足 补 o val key = "6666666666666666".toByteArray(StandardCharsets.UTF_8) val data = "I Love You 521".toByteArray(StandardCharsets.UTF_8) val paddingData = ByteArray(16) .mapIndexed { index, byte -> if (index < data.size) data[index] else byte } .toByteArray() val rab = Rabbit() val ecrypt2 = rab.encryptMessage("I Love You 521", "6666666666666666", null, false) println(("Salted__" + String(ecrypt2)).base64()) println(rab.decryptMessage(ecrypt2, "6666666666666666", "6666666666666666", false)) println(paddingData.contentToString()) println(paddingData.size) val iv: ByteArray? = null val rabbit = Rabbit2() // test.test(rabbit) rabbit.reset() rabbit.setupKey(key) if (iv != null) rabbit.setupIV(iv) val crypt = rabbit.crypt(paddingData) println(crypt.base64(BASE64_DICT)) rabbit.reset() rabbit.setupKey(key) if (iv != null) rabbit.setupIV(iv) rabbit.crypt(crypt) println(String(crypt)) }
1
Kotlin
57
242
176db4f550a37c7acfd54a302a276b8617b645cf
1,279
ToolsFx
ISC License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/NoAdultContentOutlined.kt
karakum-team
387,062,541
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/NoAdultContentOutlined") @file:JsNonModule package mui.icons.material @JsName("default") external val NoAdultContentOutlined: SvgIconComponent
0
Kotlin
3
31
b23d946ab3392e7a1ec017176ae48b952334fc75
226
mui-kotlin
Apache License 2.0
app/src/main/java/com/example/movplayv3/data/model/tvshow/TvShow.kt
Aldikitta
514,876,509
false
{"Kotlin": 850016}
package com.example.movplayv3.data.model.tvshow import com.example.movplayv3.data.model.DetailPresentable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class TvShow( override val id: Int, @Json(name = "poster_path") override val posterPath: String?, override val overview: String, @Json(name = "first_air_date") val firstAirDate: String?, @Json(name = "genre_ids") val genreIds: List<Int>, @Json(name = "original_name") val originalName: String?, @Json(name = "original_language") val originalLanguage: String, @Json(name = "origin_country") val originCountry: List<String>?, val name: String?, @Json(name = "backdrop_path") override val backdropPath: String?, val popularity: Float?, @Json(name = "vote_count") override val voteCount: Int, @Json(name = "vote_average") override val voteAverage: Float ) : DetailPresentable { override val adult: Boolean? = null override val title: String = name.orEmpty() }
1
Kotlin
12
77
8344e2a5cf62289c2b56494bf4ecd5227e26de31
1,067
MovplayV3
Apache License 2.0
data/source/remote/src/main/java/com/xently/data/source/remote/di/NetworkModule.kt
morristech
376,544,553
false
null
package com.xently.data.source.remote.di import android.content.SharedPreferences import com.xently.common.di.qualifiers.EncryptedSharedPreference import com.xently.common.di.qualifiers.retrofit.RequestHeadersInterceptor import com.xently.common.utils.JSON_CONVERTER import com.xently.common.utils.TOKEN_VALUE_SHARED_PREFERENCE_KEY import com.xently.common.utils.isReleaseBuild import com.xently.common.utils.web.HeaderKeys.ACCEPT_LANGUAGE import com.xently.common.utils.web.HeaderKeys.AUTHORIZATION import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) object NetworkModule { @Provides @Singleton @RequestHeadersInterceptor fun provideRequestHeadersInterceptors(@EncryptedSharedPreference preferences: SharedPreferences): Interceptor { return Interceptor { chain -> val authorization = preferences.getString(TOKEN_VALUE_SHARED_PREFERENCE_KEY, "") val request = chain.request() val requestBuilder = request.newBuilder() .addHeader(ACCEPT_LANGUAGE, Locale.getDefault().language) // Add authorization header iff it wasn't already added by the incoming request if (request.header(AUTHORIZATION).isNullOrBlank()) { requestBuilder.addHeader( AUTHORIZATION, if (authorization.isNullOrBlank()) "" else "Bearer $authorization" ) } return@Interceptor chain.proceed(requestBuilder.build()) } } @Provides @Singleton fun provideLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor().apply { level = (if (!isReleaseBuild()) { HttpLoggingInterceptor.Level.BODY } else HttpLoggingInterceptor.Level.NONE) redactHeader(AUTHORIZATION) // Prevents header content logging } } @Provides @Singleton fun provideOkHttpClient( loggingInterceptor: HttpLoggingInterceptor, @RequestHeadersInterceptor headerInterceptor: Interceptor ): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(headerInterceptor) .addInterceptor(loggingInterceptor) .connectTimeout(60L, TimeUnit.SECONDS) .readTimeout(30L, TimeUnit.SECONDS) .writeTimeout(15L, TimeUnit.SECONDS) .build() } @Provides @Singleton fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl("http://10.0.2.2:8000/api/v1/") .addConverterFactory(GsonConverterFactory.create(JSON_CONVERTER)) .client(okHttpClient) .build() } }
0
null
0
0
779dd3f9fbdf7dd98501c76b5e686aa69f536d5d
3,097
news
Apache License 2.0
MoonGetter-YourUpload/src/main/java/com/ead/lib/moongetter/yourupload/factory/YourUploadFactory.kt
darkryh
784,974,283
false
{"Kotlin": 181189}
package com.ead.lib.moongetter.yourupload.factory import com.ead.lib.moongetter.models.Server import com.ead.lib.moongetter.yourupload.YourUpload object YourUploadFactory : Server.Factory { override val belongedClass: Class<out Server> = YourUpload::class.java override val pattern: String = """https?://.*yourupload\.com/embed/.*""" }
0
Kotlin
1
3
512014603726b9df9a6e04def0a41caedfc40a44
345
MoonGetter
MIT License
data/src/main/java/com/sobhanmp/data/repository/NoteRepositoryImpl.kt
Sobhan-mp
576,544,174
false
{"Kotlin": 24684}
package com.sobhanmp.data.repository import com.sobhanmp.data.local.dao.NoteDao import com.sobhanmp.data.local.db.NoteDatabase import com.sobhanmp.data.mapper.toNoteEntity import com.sobhanmp.data.mapper.toNoteModel import com.sobhanmp.domain.model.NoteModel import com.sobhanmp.domain.repository.NoteRepository import com.sobhanmp.domain.util.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class NoteRepositoryImpl @Inject constructor( private val noteDatabase: NoteDatabase ) : NoteRepository { private val dao = noteDatabase.dao override suspend fun saveNewNote(note: NoteModel): Flow<Resource<Unit>> { return flow<Resource<Unit>> { emit(Resource.Loading(true)) val result = dao.insertNewNote(note.toNoteEntity()) if (result > 0) { emit(Resource.Success<Unit>(null)) } else { emit(Resource.Error<Unit>("Failed to save the note")) } emit(Resource.Loading(false)) } } override suspend fun updateNote(note: NoteModel): Flow<Resource<Unit>> { return flow { emit(Resource.Loading(true)) val result = dao.updateNote(note.toNoteEntity(note.id)) if (result > 0) { emit(Resource.Success<Unit>(null)) } else { emit(Resource.Error<Unit>("Failed to update the note")) } emit(Resource.Loading(false)) } } override suspend fun deleteNote(note: NoteModel): Flow<Resource<Unit>> { return flow { emit(Resource.Loading(true)) val result = dao.deleteNote(note.toNoteEntity(note.id)) if (result > 0) { emit(Resource.Success<Unit>(null)) } else { emit(Resource.Error<Unit>("Failed to update the note")) } emit(Resource.Loading(false)) } } override suspend fun getNotesList(): Flow<Resource<List<NoteModel>>> { return flow { emit(Resource.Loading(true)) val result = dao.getNotes() emit(Resource.Success<List<NoteModel>>(result.map { it.toNoteModel() })) emit(Resource.Loading(false)) } } }
0
Kotlin
0
1
bdacbc12e089257868594393b0a4a40398829ea3
2,306
SimpleNoteApp
Apache License 2.0
feature/schedule/src/commonMain/kotlin/club/nito/feature/schedule/detail/ScheduleDetailScreenUiState.kt
2rabs
711,156,470
false
{"Kotlin": 295089, "Swift": 29338, "Shell": 1287, "HTML": 269, "Makefile": 246}
package club.nito.feature.schedule.detail import club.nito.core.common.NitoDateFormatter import club.nito.core.domain.model.ParticipantSchedule import club.nito.core.model.FetchMultipleContentResult import club.nito.core.model.FetchSingleContentResult import club.nito.core.model.participant.ParticipantStatus import club.nito.core.model.participant.ParticipantUser import club.nito.core.model.schedule.ScheduleWithPlace public data class ScheduleDetailScreenUiState( val dateFormatter: NitoDateFormatter, val participantSchedule: FetchSingleContentResult<ParticipantSchedule>, val scheduleWithPlace: FetchSingleContentResult<ScheduleWithPlace>, val users: FetchMultipleContentResult<ParticipantUser>, val myParticipantStatus: ParticipantStatus, )
28
Kotlin
0
2
1de250cab39787072a28234a6b3ac1ce32db6036
770
nito-app
MIT License
mobile/src/main/java/rs/readahead/washington/mobile/views/adapters/reports/ReportsFilesRecyclerViewAdapter.kt
Horizontal-org
193,379,924
false
{"Java": 1621257, "Kotlin": 1441445}
package rs.readahead.washington.mobile.views.adapters.reports import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.content.res.ResourcesCompat import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.hzontal.tella_vault.VaultFile import com.hzontal.utils.MediaFile.isAudioFileType import com.hzontal.utils.MediaFile.isImageFileType import com.hzontal.utils.MediaFile.isVideoFileType import rs.readahead.washington.mobile.R import rs.readahead.washington.mobile.views.interfaces.IReportAttachmentsHandler open class ReportsFilesRecyclerViewAdapter( private val iAttachmentsMediaHandler: IReportAttachmentsHandler, ) : RecyclerView.Adapter<ReportsFilesRecyclerViewAdapter.GridAttachmentsViewHolder>() { private var listAttachment: ArrayList<VaultFile> = arrayListOf() init { val file = VaultFile() file.type = VaultFile.Type.UNKNOWN insertAttachment(file) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GridAttachmentsViewHolder { return GridAttachmentsViewHolder(parent) } fun insertAttachment(newAttachment: VaultFile) { if (newAttachment.type != VaultFile.Type.UNKNOWN) { if (!listAttachment.contains(newAttachment)) { listAttachment.add(0, newAttachment) notifyItemInserted(0) } } else { listAttachment.add(0, newAttachment) notifyItemInserted(0) } } fun getFiles(): ArrayList<VaultFile> { val listFiles: ArrayList<VaultFile> = arrayListOf() for (file in listAttachment) { if (file.type != VaultFile.Type.UNKNOWN) listFiles.add(file) } return listFiles } private fun removeFile(position: Int) { listAttachment.removeAt(position) iAttachmentsMediaHandler.removeFiles() notifyItemRemoved(position) } override fun getItemCount(): Int { return listAttachment.size } override fun onBindViewHolder(holder: GridAttachmentsViewHolder, position: Int) { holder.bind( vaultFile = listAttachment[position] ) } open inner class GridAttachmentsViewHolder(val view: View) : RecyclerView.ViewHolder(view) { constructor(parent: ViewGroup) : this( LayoutInflater.from(parent.context).inflate(R.layout.item_report_files, parent, false) ) protected lateinit var icAttachmentImg: ImageView private lateinit var filePreviewImg: ImageView private lateinit var fileNameTextView: TextView private lateinit var removeBtn: View protected val context: Context by lazy { view.context } fun bind(vaultFile: VaultFile?) { view.apply { fileNameTextView = findViewById(R.id.fileNameTextView) filePreviewImg = findViewById(R.id.attachmentImg) removeBtn = findViewById(R.id.remove) icAttachmentImg = findViewById(R.id.icAttachmentImg) } if (vaultFile!!.type != VaultFile.Type.UNKNOWN) { removeBtn.setOnClickListener { removeFile(position = layoutPosition) } if (isImageFileType(vaultFile.mimeType)) { this.showImageInfo(vaultFile) } else if (isAudioFileType(vaultFile.mimeType)) { this.showAudioInfo() fileNameTextView.text = vaultFile.name } else if (isVideoFileType(vaultFile.mimeType)) { this.showVideoInfo(vaultFile) } else { fileNameTextView.text = vaultFile.name this.showDocInfo() } } else { removeBtn.visibility = View.GONE showAddLink() } } private fun showVideoInfo(vaultFile: VaultFile) { filePreviewImg.loadImage(vaultFile.thumb) icAttachmentImg.setBackgroundResource(R.drawable.ic_play) } private fun showAudioInfo() { icAttachmentImg.setBackgroundResource(R.drawable.ic_audio_w_small) } private fun showDocInfo() { icAttachmentImg.setBackgroundResource(R.drawable.ic_reports) } private fun showImageInfo(vaultFile: VaultFile) { filePreviewImg.loadImage(vaultFile.thumb) } fun ImageView.loadImage(thumb: ByteArray) { Glide.with(this) .load(thumb) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(this) } private fun showAddLink() { filePreviewImg.background = ResourcesCompat.getDrawable(context.resources, R.drawable.transparent_solid, null) filePreviewImg.setImageResource(R.drawable.upload_box_btn) filePreviewImg.setOnClickListener { iAttachmentsMediaHandler.addFiles() } } } }
16
Java
17
55
5dd19f8c9a810c165d2d8ec8947cc9d5d4620bab
5,307
Tella-Android
Apache License 2.0
defitrack-rest/defitrack-balance/src/main/java/io/defitrack/balance/l1/AvaxBalanceService.kt
decentri-fi
426,174,152
false
null
package io.defitrack.balance.l1 import io.defitrack.balance.BalanceService import io.defitrack.balance.TokenBalance import io.defitrack.common.network.Network import io.defitrack.evm.contract.BlockchainGatewayProvider import io.defitrack.token.ERC20Resource import org.springframework.stereotype.Service @Service class AvaxBalanceService( blockchainGatewayProvider: BlockchainGatewayProvider, erC20Service: ERC20Resource ) : BalanceService(blockchainGatewayProvider, erC20Service) { override suspend fun getTokenBalances(user: String): List<TokenBalance> { return emptyList() } override fun getNetwork(): Network = Network.AVALANCHE override fun nativeTokenName(): String { return "AVAX" } }
16
Kotlin
6
5
e4640223e69c30f986b8b4238e026202b08a5548
739
defi-hub
MIT License
simple/src/main/kotlin/io/nichijou/oops/simple/App.kt
iota9star
148,626,401
false
null
package io.nichijou.oops.simple import android.app.Application import com.squareup.leakcanary.LeakCanary class App : Application() { override fun onCreate() { super.onCreate() LeakCanary.install(this) } }
0
Kotlin
1
11
81cfcfe281cd659e07c14defcafbcaee19cfed19
219
oops-android-kt
Apache License 2.0
app/src/main/java/com/cornellappdev/scoop/ui/viewmodel/PostScreenViewModel.kt
cuappdev
453,555,762
false
null
package com.cornellappdev.scoop.ui.viewmodel import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cornellappdev.scoop.data.models.Ride import kotlinx.coroutines.launch import java.io.IOException class PostScreenViewModel() : ViewModel() { data class PostScreenUiState( val ride: Ride = Ride(), val message: String = "" ) var postUiState = mutableStateOf(PostScreenUiState()) private set fun postTrip() = viewModelScope.launch { try { postUiState.value = postUiState.value.copy( ) } catch (e: IOException) { // Can have a more elaborate error state than just a string. This is // just a simple example. Get creative 😃! postUiState.value = postUiState.value.copy( message = e.stackTraceToString() ) } } }
6
Kotlin
0
0
ad0fb09cda1bf2b9c0cbcd6382c9fdb9190dca52
948
scoop-android
MIT License
android/app/src/main/kotlin/com/example/vaccine/MainActivity.kt
AbhishekBhamare
367,886,822
false
{"Dart": 25038, "HTML": 1985, "CSS": 709, "Swift": 404, "Kotlin": 124, "Objective-C": 38}
package com.example.vaccine import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
2
2671bf2ac71b22caef3f88198a7751ddd39848df
124
vaccine_center_tracker_app_in_flutter
MIT License
wearos/src/main/kotlin/com/boswelja/smartwatchextensions/extensions/ui/ExtensionsScreen.kt
boswelja
103,805,743
false
{"Kotlin": 496889}
package com.boswelja.smartwatchextensions.extensions.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.widget.ConfirmationOverlay import com.boswelja.smartwatchextensions.R import com.boswelja.smartwatchextensions.batterysync.ui.BatterySyncChip import com.boswelja.smartwatchextensions.common.ui.showConfirmationOverlay import com.boswelja.smartwatchextensions.phonelocking.ui.PhoneLockingChip import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.androidx.compose.getViewModel /** * A Composable for displaying available Extensions. * @param modifier [Modifier]. * @param extensionModifier A [Modifier] to be applied to each Extension Composable. * @param contentPadding The padding around the content. */ @Composable fun Extensions( modifier: Modifier = Modifier, extensionModifier: Modifier = Modifier, contentPadding: Dp = 8.dp ) { Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(contentPadding) ) { val view = LocalView.current val coroutineScope = rememberCoroutineScope() val viewModel: ExtensionsViewModel = getViewModel() val phoneLockingEnabled by viewModel.phoneLockingEnabled.collectAsState() val phoneName by viewModel.phoneName .collectAsState(stringResource(R.string.default_phone_name), Dispatchers.IO) BatterySyncChip( modifier = extensionModifier, phoneName = phoneName ) PhoneLockingChip( modifier = extensionModifier, enabled = phoneLockingEnabled, phoneName = phoneName ) { coroutineScope.launch { val result = viewModel.requestLockPhone() if (result) { view.showConfirmationOverlay( type = ConfirmationOverlay.SUCCESS_ANIMATION, message = view.context.getString( com.boswelja.smartwatchextensions.phonelocking.R.string.lock_phone_success ) ) } else { view.showConfirmationOverlay( type = ConfirmationOverlay.FAILURE_ANIMATION, message = view.context.getString( com.boswelja.smartwatchextensions.batterysync.R.string.phone_not_connected ) ) } } } } }
11
Kotlin
0
25
ec7e9ad4c98e18a9a4b5c07f1d39f6c0b1fbfd65
2,959
SmartwatchExtensions
Apache License 2.0
ParkingPermitApp/app/src/main/java/com/example/parkingpermitapp/data/BitmapFunctions.kt
ZeroTolerance225
789,532,216
false
{"Kotlin": 127055, "HTML": 125618, "Python": 62253, "Java": 56037, "CSS": 10518, "Dockerfile": 217}
package com.example.parkingpermitapp.data import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.ImageFormat import android.graphics.Matrix import android.graphics.Paint import android.graphics.Rect import android.graphics.YuvImage import android.util.Log import androidx.camera.core.ImageProxy import com.example.parkingpermitapp.domain.DetectionResult import java.io.ByteArrayOutputStream //**************************************************** // Class containing functions to create a bitmap * // from an ImageProxy object and to Gray out every * // thing outside the object detection bounding box * // of a bitmap. * //**************************************************** class BitmapFunctions { fun imageProxyToBitmap(imageProxy: ImageProxy): Bitmap { val yBuffer = imageProxy.planes[0].buffer // Y val uBuffer = imageProxy.planes[1].buffer // U val vBuffer = imageProxy.planes[2].buffer // V val ySize = yBuffer.remaining() val uSize = uBuffer.remaining() val vSize = vBuffer.remaining() val nv21 = ByteArray(ySize + uSize + vSize) // U and V are swapped yBuffer.get(nv21, 0, ySize) vBuffer.get(nv21, ySize, vSize) uBuffer.get(nv21, ySize + vSize, uSize) val yuvImage = YuvImage(nv21, ImageFormat.NV21, imageProxy.width, imageProxy.height, null) val out = ByteArrayOutputStream() yuvImage.compressToJpeg(Rect(0, 0, imageProxy.width, imageProxy.height), 100, out) val imageBytes = out.toByteArray() return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) } companion object { fun grayOutBitmapOutsideBoundingBox( source: Bitmap, detectionResult: DetectionResult, rotation: Int ): Bitmap { val orientedBitmap = rotateBitmap(source, rotation) // Create a mutable copy of the source bitmap val bitmapCopy = orientedBitmap.copy(Bitmap.Config.ARGB_8888, true) val canvas = Canvas(bitmapCopy) val paint = Paint().apply { color = Color.GRAY } // Calculate the bounding box coordinates val centerX = detectionResult.x * source.width val centerY = detectionResult.y * source.height val width = detectionResult.width * source.width val height = detectionResult.height * source.height val topLeftX = centerX - (width / 2) val topLeftY = centerY - (height / 2) val bottomRightX = centerX + (width / 2) val bottomRightY = centerY + (height / 2) Log.d("Source Bitmap Dim", "Cropped Bitmap topLX ${topLeftX} Cropped Bitmap topLY ${topLeftY}") Log.d("Source Bitmap Dim", "Cropped Bitmap botRX ${bottomRightX} Cropped Bitmap botRY ${bottomRightY}") // Gray out the top portion of the image canvas.drawRect(0f, 0f, source.width.toFloat(), topLeftY.toFloat(), paint) // Gray out the bottom portion of the image canvas.drawRect( 0f, bottomRightY, source.width.toFloat(), source.height.toFloat(), paint ) // Gray out the left portion of the image canvas.drawRect( 0f, topLeftY, topLeftX, bottomRightY, paint ) // Gray out the right portion of the image canvas.drawRect( bottomRightX, topLeftY, source.width.toFloat(), bottomRightY, paint ) return bitmapCopy } private fun rotateBitmap(source: Bitmap, rotationDegrees: Int): Bitmap { val matrix = Matrix() matrix.postRotate(rotationDegrees.toFloat()) return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true) } } }
0
Kotlin
0
0
6895e28195b37cf8b6d6fda47a61c25bdece67aa
4,203
Capstone-License-Plate-Reader
Microsoft Public License
app/src/main/java/com/gdscedirne/toplan/data/di/GenerativeModelModule.kt
meetOzan
752,327,037
false
{"Kotlin": 373416}
package com.gdscedirne.toplan.data.di import com.gdscedirne.toplan.BuildConfig import com.gdscedirne.toplan.common.Constants.GEMINI_MODEL import com.google.ai.client.generativeai.GenerativeModel import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object GenerativeModelModule { @Provides @Singleton fun provideGenerativeModel(): GenerativeModel { return GenerativeModel( modelName = GEMINI_MODEL, apiKey = BuildConfig.GEMINI_API_KEY ) } }
0
Kotlin
0
2
dbb909a9bcfc30d153866f83d0439142cd86a236
644
TopLAN
MIT License
src/main/kotlin/dev/rakiiii/healthycoroutines/containers/SimpleDeferredImpl.kt
Rakiiii
866,412,180
false
{"Kotlin": 137712}
/* * Copyright 2024-today <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.rakiiii.healthycoroutines.containers import dev.rakiiii.healthycoroutines.api.SimpleDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.selects.SelectClause1 /** Wraps [Deferred] into [SimpleDeferred] to hide [Job] api */ fun <T> Deferred<T>.wrap(): SimpleDeferred<T> = SimpleDeferredImpl(this) private class SimpleDeferredImpl<out T>(private val deferred: Deferred<T>) : SimpleDeferred<T> { override suspend fun await(): T = deferred.await() override val onAwait: SelectClause1<T> get() = deferred.onAwait @ExperimentalCoroutinesApi override fun getCompleted(): T = deferred.getCompleted() @ExperimentalCoroutinesApi override fun getCompletionExceptionOrNull(): Throwable? = deferred.getCompletionExceptionOrNull() }
0
Kotlin
0
0
64889ae99d1f6c8642a58a9c70befad2dbdedd7d
1,453
HealthyCoroutines
Apache License 2.0
android-app/src/main/java/by/iba/sbs/tools/DownloadManager.kt
lev4ik911
309,679,864
false
null
package by.iba.sbs.tools import android.content.Context import android.content.ContextWrapper import android.graphics.Bitmap import android.net.Uri import android.os.Handler import android.os.Message import by.iba.sbs.library.model.Guideline import by.iba.sbs.library.model.Step import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.load.model.LazyHeaders import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import java.io.File import java.io.FileOutputStream import java.util.* class DownloadManager (_context: Context){ private val context: Context init { context = _context } fun createImageFileInInternalStorage(guidelineId: String="", stepId: String = "", remoteImageId: String=""): Uri { var imageFileName = "" if (remoteImageId.isNotEmpty()) imageFileName = remoteImageId else imageFileName = UUID.randomUUID().toString() val cw = ContextWrapper(context) var directory = cw.getDir("imageDir", Context.MODE_PRIVATE) val builder = StringBuilder() builder.append(directory.path) if (guidelineId.isNotEmpty()) { builder.append("/") .append(guidelineId) } if (stepId.isNotEmpty()) { builder.append("/") .append(stepId) } directory = File(builder.toString()).apply { if (!this.exists()) { this.mkdirs(); } } var file = File(String.format("%s/%s.jpg", directory.path, imageFileName)) if (!file.exists()) { file = File.createTempFile( imageFileName, ".jpg", directory ) } return Uri.fromFile(file) } fun downloadImage(url: String, guidelineId: String, stepId: String = "", remoteImageId: String, item: Any, imageHandler: Handler) { val glideUrl = GlideUrl( url, LazyHeaders.Builder().addHeader("Accept", "application/octet-stream;q=0.9, application/json;q=0.1").build()) Glide.with(context) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .load(glideUrl) .listener(object : RequestListener<Bitmap> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean ): Boolean { //TODO("add handler") return false } override fun onResourceReady( resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { val destFile = File(createImageFileInInternalStorage(guidelineId, stepId, remoteImageId).path.orEmpty()) val fos = FileOutputStream(destFile) resource?.compress(Bitmap.CompressFormat.JPEG, 100, fos) when (item) { is Guideline -> item.imagePath = destFile.path is Step -> item.imagePath = destFile.path else -> {} } Message().apply { this.obj = item imageHandler.sendMessage(this) } return true } }) .submit() } }
0
Kotlin
0
0
86e909810e147cf138c0eae4af874c28b52b0c6c
3,973
SBS_JB
Apache License 2.0
app/src/main/java/com/mospolytech/mospolyhelper/domain/schedule/repository/TeacherListRepository.kt
tonykolomeytsev
341,524,793
true
{"Kotlin": 646693}
package com.mospolytech.mospolyhelper.domain.schedule.repository import com.mospolytech.mospolyhelper.data.schedule.local.TeacherListLocalDataSource import com.mospolytech.mospolyhelper.data.schedule.remote.TeacherListRemoteDataSource interface TeacherListRepository { suspend fun getTeacherList(): Map<String, String> }
0
null
0
0
379c9bb22913da1854f536bf33e348a459db48b9
326
mospolyhelper-android
MIT License
src/main/kotlin/net/kankantari/ojima/scores/Token.kt
Nodoka4318
820,824,693
false
{"Kotlin": 40357}
package net.kankantari.ojima.scores class Token { var type: EnumTokenType; var length: Float; constructor(type: EnumTokenType, length: Float) { this.type = type; this.length = length; } }
0
Kotlin
0
0
2cab4530f7e33431999aafaf7ebf5291a018e935
221
Ojima
MIT License
src/main/kotlin/br/com/fabiofiorita/restapi/controller/RespostaController.kt
FabioFiorita
626,425,405
false
null
package br.com.fabiofiorita.restapi.controller import br.com.fabiofiorita.restapi.model.Resposta import br.com.fabiofiorita.restapi.service.RespostaService import io.swagger.v3.oas.annotations.security.SecurityRequirement import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import javax.validation.Valid @RestController @SecurityRequirement(name = "bearerAuth") @RequestMapping("/respostas") class RespostaController( private val respostaService: RespostaService ) { @PostMapping fun salvar(@RequestBody @Valid resposta: Resposta) = respostaService.salvar(resposta) }
0
Kotlin
0
0
78a9c395cf1614164640e5c9e7d08042a3b2347a
771
Kotlin-REST-API
MIT License
native/swift/sir-light-classes/src/org/jetbrains/sir/lightclasses/nodes/SirInitFromKtSymbol.kt
JetBrains
3,432,266
false
{"Kotlin": 78020897, "Java": 6696240, "Swift": 4062767, "C": 2609482, "C++": 1967339, "Objective-C++": 169966, "JavaScript": 135932, "Python": 48402, "Shell": 34800, "TypeScript": 22800, "Lex": 18369, "Groovy": 17400, "Objective-C": 15578, "Batchfile": 11746, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.sir.lightclasses.nodes import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.sir.* import org.jetbrains.kotlin.sir.providers.SirSession import org.jetbrains.kotlin.sir.providers.source.KotlinSource import org.jetbrains.kotlin.sir.providers.utils.withSirAnalyse import org.jetbrains.sir.lightclasses.SirFromKtSymbol import org.jetbrains.sir.lightclasses.extensions.documentation import org.jetbrains.sir.lightclasses.extensions.sirCallableKind internal class SirInitFromKtSymbol( override val ktSymbol: KtConstructorSymbol, override val analysisApiSession: KtAnalysisSession, override val sirSession: SirSession, ) : SirInit(), SirFromKtSymbol { override val origin: SirOrigin override val visibility: SirVisibility = SirVisibility.PUBLIC override val kind: SirCallableKind override var body: SirFunctionBody? = null override val isFailable: Boolean override val parameters: MutableList<SirParameter> = mutableListOf() override val initKind: SirInitializerKind override var documentation: String? override var parent: SirDeclarationParent get() = withSirAnalyse(sirSession, analysisApiSession) { ktSymbol.getSirParent() } set(_) = Unit init { withSirAnalyse(sirSession, analysisApiSession) { origin = KotlinSource(ktSymbol) kind = ktSymbol.sirCallableKind isFailable = false initKind = SirInitializerKind.ORDINARY ktSymbol.valueParameters.mapTo(parameters) { SirParameter( argumentName = it.name.asString(), type = it.returnType.translateType() ) } documentation = ktSymbol.documentation() } } }
176
Kotlin
5601
47,397
a47dcc227952c0474d27cc385021b0c9eed3fb67
2,082
kotlin
Apache License 2.0
android/src/main/java/io/github/ackeecz/extensions/android/FragmentExtensions.kt
AckeeCZ
130,711,681
false
null
package io.github.ackeecz.extensions.android import android.os.Bundle import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.IntRange import androidx.fragment.app.Fragment // Extensions for [Fragment] class /** * Set arguments to fragment and return current instance */ inline fun <reified T : Fragment> T.withArguments(args: Bundle): T { this.arguments = args return this } /** * Set target fragment with request code and return current instance */ fun Fragment.withTargetFragment(fragment: Fragment, reqCode: Int): Fragment { setTargetFragment(fragment, reqCode) return this } /** * Get color from resource with fragment context. */ fun Fragment.color(@ColorRes res: Int) = context!!.color(res) /** * Get color from resource with fragment context and apply [opacity] to it. */ @ColorInt fun Fragment.colorWithOpacity(@ColorRes res: Int, @IntRange(from = 0, to = 100) opacity: Int) = context!!.colorWithOpacity(res, opacity) /** * Open Play Store with the application ID from provided context. Return true if the intent can be * and will be handled, false otherwise. */ fun Fragment.openPlayStore() = requireContext().openPlayStore()
1
Kotlin
0
13
fc56c5c9aba5582f203334a6ab09b198cdc9596c
1,214
kotlin-extensions
Apache License 2.0
app/src/main/java/com/mxalbert/compose/textfield/ui/demo/TextLengthFilter.kt
mxalbert1996
689,564,694
false
{"Kotlin": 43197}
package com.mxalbert.compose.textfield.ui.demo import android.icu.text.BreakIterator import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.mxalbert.compose.textfield.ui.Demo import com.mxalbert.compose.textfield.ui.TextFieldTextStyle import com.mxalbert.compose.textfield.ui.requestFocusOnce @Preview @Composable fun TextLengthFilterDemo() { Demo { var value by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue()) } val badFilter: (TextFieldValue) -> Unit = { if (it.text.length <= 5) { value = it } } val naiveFilter: (TextFieldValue) -> Unit = { value = when { it.text.length <= MaxLength -> it value.text.length == MaxLength -> value else -> it.copy( annotatedString = it.annotatedString.subSequence(0, MaxLength) ) } } val betterFilter: (TextFieldValue) -> Unit = { value = when { it.text.length <= MaxLength -> it value.text.length == MaxLength -> value else -> { // Same as Android's InputFilter.LengthFilter val text = it.annotatedString val end = if (text[MaxLength - 1].isHighSurrogate()) { MaxLength - 1 } else { MaxLength } it.copy(annotatedString = text.subSequence(0, end)) } } } val bestFilter: (TextFieldValue) -> Unit = { value = when { it.text.length <= MaxLength -> it value.text.length == MaxLength -> value else -> { val breakIterator = BreakIterator.getCharacterInstance() breakIterator.setText(it.text) var end = 0 while (true) { val newEnd = breakIterator.next() if (newEnd == BreakIterator.DONE || newEnd > MaxLength) { break } end = newEnd } it.copy(annotatedString = it.annotatedString.subSequence(0, end)) } } } TextField( value = value, onValueChange = bestFilter, textStyle = TextFieldTextStyle, modifier = Modifier .fillMaxWidth() .padding(16.dp) .requestFocusOnce() ) } } private const val MaxLength = 5
0
Kotlin
0
4
52f3a3e14115dffccda5978de6f25300c7efdc82
3,237
DroidKaigi-2023-TextField
MIT License
plugin-enclave-gradle/src/main/kotlin/com/r3/conclave/plugin/enclave/gradle/BuildJarObject.kt
R3Conclave
526,690,075
false
null
package com.r3.conclave.plugin.enclave.gradle import org.gradle.api.GradleException import org.gradle.api.file.RegularFileProperty import org.gradle.api.model.ObjectFactory import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.internal.os.OperatingSystem import javax.inject.Inject open class BuildJarObject @Inject constructor(objects: ObjectFactory) : ConclaveTask() { @get:InputFile val inputLd: RegularFileProperty = objects.fileProperty() @get:InputFile val inputJar: RegularFileProperty = objects.fileProperty() /** * The path of the output object file both determines the working directory for the ld command and the filename to use * for the embedded jar file. */ @get:OutputFile val outputJarObject: RegularFileProperty = objects.fileProperty() override fun action() { if (!OperatingSystem.current().isLinux && !OperatingSystem.current().isWindows && !OperatingSystem.current().isMacOsX) { throw GradleException("At this time you may only build enclaves on a Linux, Windows or macOS host.") } val workingDirectory = outputJarObject.asFile.get().parent val embeddedJarName = outputJarObject.asFile.get().name.removeSuffix(".o") project.copy { spec -> spec.from(inputJar) spec.into(workingDirectory) spec.rename { embeddedJarName } } commandLine( inputLd.get(), "-r", "-b", "binary", "-m", "elf_x86_64", embeddedJarName, "-o", outputJarObject.get().asFile, commandLineConfig = CommandLineConfig(workingDirectory) ) } }
0
C++
8
41
9b49a00bb33a22f311698d7ed8609a189f38d6ae
1,750
conclave-core-sdk
Apache License 2.0
modules/reconciler/src/main/kotlin/org/veupathdb/vdi/lib/reconciler/ReconcilerInstance.kt
VEuPathDB
575,990,672
false
{"Kotlin": 601562, "Java": 211932, "RAML": 63444, "Makefile": 1936, "Dockerfile": 1001, "Shell": 423}
package org.veupathdb.vdi.lib.reconciler import org.apache.logging.log4j.kotlin.logger import org.veupathdb.vdi.lib.common.field.DatasetID import org.veupathdb.vdi.lib.common.field.UserID import org.veupathdb.vdi.lib.common.model.VDIReconcilerTargetRecord import org.veupathdb.vdi.lib.common.model.VDISyncControlRecord import org.veupathdb.vdi.lib.kafka.router.KafkaRouter import org.veupathdb.vdi.lib.s3.datasets.DatasetDirectory import org.veupathdb.vdi.lib.s3.datasets.DatasetManager import vdi.component.metrics.Metrics /** * Component for synchronizing the dataset object store (the source of truth for datasets) with a target database. * * This includes both our internal "cache DB", used to answer questions about user dataset metadata/status and * our application databases in which the contents of datasets are installed. */ class ReconcilerInstance( private val targetDB: ReconcilerTarget, private val datasetManager: DatasetManager, private val kafkaRouter: KafkaRouter, private val deleteDryMode: Boolean = false ) { private var nextTargetDataset: VDIReconcilerTargetRecord? = null val name = targetDB.name fun reconcile() { try { tryReconcile() } catch (e: Exception) { // Don't re-throw error, ensure exception is logged and soldier on for future reconciliation. logger().error("Failure running reconciler for " + targetDB.name, e) Metrics.failedReconciliation.labels(targetDB.name).inc() } } private fun tryReconcile() { logger().info("Beginning reconciliation of ${targetDB.name}") targetDB.streamSortedSyncControlRecords().use { targetDBStream -> val sourceIterator = datasetManager.streamAllDatasets().iterator() val targetIterator = targetDBStream.iterator() nextTargetDataset = if (targetIterator.hasNext()) targetIterator.next() else null // Iterate through datasets in S3. while (sourceIterator.hasNext()) { // Pop the next DatasetDirectory instance from the S3 stream. val sourceDatasetDir = sourceIterator.next() logger().info("Checking dataset ${sourceDatasetDir.ownerID}/${sourceDatasetDir.datasetID} for ${targetDB.name}") // Target stream is exhausted, everything left in source stream is missing from the target database! // Check again if target stream is exhausted, consume source stream if so. if (nextTargetDataset == null) { consumeEntireSourceStream(sourceIterator, sourceDatasetDir) return@use } // Owner ID is included as part of sort, so it must be included when comparing streams. var comparableS3Id = "${sourceDatasetDir.ownerID}/${sourceDatasetDir.datasetID}" var comparableTargetId: String? = nextTargetDataset!!.getComparableID() // If target dataset stream is "ahead" of source stream, delete // the datasets from the target stream until we are aligned // again (or the target stream is consumed). if (comparableS3Id.compareTo(comparableTargetId!!, false) > 0) { // Delete datasets until and advance target iterator until streams are aligned. while (nextTargetDataset != null && comparableS3Id.compareTo(comparableTargetId!!, false) > 0) { logger().info("Attempting to delete dataset with owner $comparableTargetId " + "because $comparableS3Id is lexigraphically greater than $comparableTargetId. Presumably $comparableTargetId is not in MinIO.") tryDeleteDataset(targetDB, nextTargetDataset!!) nextTargetDataset = if (targetIterator.hasNext()) targetIterator.next() else null comparableTargetId = nextTargetDataset?.getComparableID() } } // Check again if target stream is exhausted, consume source stream if so. if (nextTargetDataset == null) { consumeEntireSourceStream(sourceIterator, sourceDatasetDir) return@use } // Owner ID is included as part of sort, so it must be included when comparing streams. comparableS3Id = "${sourceDatasetDir.ownerID}/${sourceDatasetDir.datasetID}" comparableTargetId = nextTargetDataset!!.getComparableID() if (comparableS3Id.compareTo(comparableTargetId, false) < 0) { // Dataset is in source, but not in target. Send an event. Metrics.missingInTarget.labels(targetDB.name).inc() sendSyncIfRelevant(sourceDatasetDir) } else { // If dataset has a delete flag present and the dataset is not marked // as uninstalled from the target, then send a sync event. if (sourceDatasetDir.hasDeleteFlag() && !nextTargetDataset!!.isUninstalled) { sendSyncEvent(nextTargetDataset!!.ownerID, nextTargetDataset!!.datasetID) } // Dataset is in source and target. Check dates to see if sync is needed. else if (isOutOfSync(sourceDatasetDir, nextTargetDataset!!)) { sendSyncIfRelevant(sourceDatasetDir) } // Advance next target dataset pointer, we're done with this one since it's in sync. nextTargetDataset = if (targetIterator.hasNext()) targetIterator.next() else null } } // If nextTargetDataset is not null at this point, then S3 was empty. nextTargetDataset?.also { tryDeleteDataset(targetDB, it) } // Consume target stream, deleting all remaining datasets. while (targetIterator.hasNext()) { tryDeleteDataset(targetDB, targetIterator.next()) } logger().info("Completed reconciliation") } } private fun tryDeleteDataset(targetDB: ReconcilerTarget, record: VDIReconcilerTargetRecord) { logger().info("attempting to delete ${record.ownerID}/${record.datasetID}") try { Metrics.reconcilerDatasetDeleted.labels(targetDB.name).inc() if (!deleteDryMode) { logger().info("Trying to delete dataset ${record.ownerID}/${record.datasetID}") targetDB.deleteDataset(datasetID = record.datasetID, datasetType = record.type) } else { logger().info("Would have deleted dataset ${record.ownerID}/${record.datasetID}") } } catch (e: Exception) { // Swallow exception and alert if unable to delete. Reconciler can safely recover, but the dataset // may need a manual inspection. logger().error("Failed to delete dataset ${record.ownerID}/${record.datasetID} of type ${record.type.name}:${record.type.version} from db ${targetDB.name}", e) } } /** * Returns true if any of our scopes are out of sync. */ private fun isOutOfSync(ds: DatasetDirectory, targetLastUpdated: VDISyncControlRecord): Boolean { val shareOos = targetLastUpdated.sharesUpdated.isBefore(ds.getLatestShareTimestamp(targetLastUpdated.sharesUpdated)) val dataOos = targetLastUpdated.dataUpdated.isBefore(ds.getInstallReadyTimestamp() ?: targetLastUpdated.dataUpdated) val metaOos = targetLastUpdated.metaUpdated.isBefore(ds.getMetaFile().lastModified()) return shareOos || dataOos || metaOos } private fun sendSyncIfRelevant(sourceDatasetDir: DatasetDirectory) { if (targetDB.type == ReconcilerTargetType.Install) { val relevantProjects = sourceDatasetDir.getMetaFile().load()!!.projects if (!relevantProjects.contains(targetDB.name)) { logger().info("Skipping dataset ${sourceDatasetDir.ownerID}/${sourceDatasetDir.datasetID} as it does not target ${targetDB.name}") return } } sendSyncEvent(sourceDatasetDir.ownerID, sourceDatasetDir.datasetID) } private fun sendSyncEvent(ownerID: UserID, datasetID: DatasetID) { logger().info("sending reconciliation event for $ownerID/$datasetID") kafkaRouter.sendReconciliationTrigger(ownerID, datasetID) Metrics.reconcilerDatasetSynced.labels(targetDB.name).inc() } private fun consumeEntireSourceStream( sourceIterator: Iterator<DatasetDirectory>, sourceDatasetDir: DatasetDirectory ) { sendSyncIfRelevant(sourceDatasetDir) while (sourceIterator.hasNext()) { sendSyncIfRelevant(sourceIterator.next()) } } }
26
Kotlin
0
0
0d8fadabb5eacbcdd17ca1305122655ce9d6af63
8,135
vdi-service
Apache License 2.0
app/src/main/java/com/example/recycleview/place/PlacesResponse.kt
sidkiamri
733,158,336
false
{"Kotlin": 113149}
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.recycleview.place import com.google.android.gms.maps.model.LatLng data class PlaceResponse( val geometry: Geometry, val name: String, val vicinity: String, val date :String, val points : Float, val participants :Float, val rating: Float ) { data class Geometry( val location: GeometryLocation ) data class GeometryLocation( val lat: Double, val lng: Double ) } fun PlaceResponse.toPlace(): Place = Place( name = name, latLng = LatLng(geometry.location.lat, geometry.location.lng), address = vicinity, participants = participants, rating = rating, date = date, points = points )
0
Kotlin
0
0
9bf93bd95847eb157aa8d9df6edea0ef9e54c3ca
1,290
SearchAndRecycle-Android
MIT License
app/src/androidTest/java/com/yatik/newsworld/utils/TestConstants.kt
yatiksihag01
603,809,213
false
null
package com.yatik.newsworld.utils import com.yatik.newsworld.models.Article import com.yatik.newsworld.models.Source class TestConstants { companion object { val SAMPLE_ARTICLE_1 = Article(null, "authorName", "contentName", "descriptionName", "2023-02-16T10:30:00Z", Source("123", "NewsWorld"), "titleName", null, "https://fakeurl.com") val SAMPLE_ARTICLE_2 = Article(null, "authorName2", "contentName2", "descriptionName2", "2023-02-16T10:30:00Z", Source("123", "NewsWorld"), "titleName2", null, "https://fakeurl2.com") val EXPECTED_SAMPLE_ARTICLE_1 = Article(1, "authorName", "contentName", "descriptionName", "2023-02-16T10:30:00Z", Source("NewsWorld", "NewsWorld"), "titleName", null, "https://fakeurl.com") val EXPECTED_SAMPLE_ARTICLE_2 = Article(2, "authorName2", "contentName2", "descriptionName2", "2023-02-16T10:30:00Z", Source("NewsWorld", "NewsWorld"), "titleName2", null, "https://fakeurl2.com") } }
0
Kotlin
0
0
3881c91c595b7b2a043814aef87904da54612700
1,103
News-World
Apache License 2.0
src/main/kotlin/org/tjur/simplestatemachine/SimpleStateMachine.kt
tjur-org
363,487,768
false
null
package org.tjur.simplestatemachine import java.util.* import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue import kotlin.collections.HashMap import kotlin.reflect.KClass import kotlin.reflect.full.createInstance open class SimpleStateMachine(private val initialState: KClass<*>) : Runnable { private val messageQueue: BlockingQueue<Message> = LinkedBlockingQueue() private val states: MutableMap <String, State> = HashMap() private val stateStack : Deque<State> = ArrayDeque() private lateinit var currentState: State override fun run() { transition(getState(initialState), StartupMessage()) while (true) { when (val message = messageQueue.take()) { is TransitionMessage -> { transition(getState(message.state), message.message) } is StopMessage -> { break } else -> { val response = process(message, currentState) if (response.clearQueue) messageQueue.clear() response.message?.let { messageQueue.put(it) } } } } stateStack.forEach { it.leave() } } /** * Clears the messages queued up in the state machine. */ fun clearQueue() { messageQueue.removeIf { it !is StopMessage } } /** * Add an already instantiated state to the state machine. */ fun prepareState(state: State) { val name = state::class.qualifiedName ?: throw Exception("Could not get qualified name of $state") if (states.containsKey(name)) throw Exception("$name has already been added.") states[name] = state } /** * Send a Message to be processed by the current state in the state machine (or by any of its parents) * * @param message: Message to be processed */ fun process(message: Message) { messageQueue.put(message) } /** * Stops the state machine, but allowing it to finish what it's currently doing. */ fun stop() { messageQueue.clear() messageQueue.put(StopMessage()) } private fun transition(newState: State, message: Message?) { val newStateStack = getParentStates(newState) newStateStack.push(newState) // check for any potential parent states we have now left behind if (message !is StartupMessage) { stateStack.filter { !newStateStack.contains(it) } .forEach { it.leave() } } // check for any potential parent states we are now entering newStateStack.filter { !stateStack.contains(it) } .reversed() .forEach { enterState(it, message) } // refresh the state stack to reflect our current position stateStack.clear() stateStack.addAll(newStateStack) // enter our current state currentState = newState } private fun enterState(state: State, message: Message?) { val result = state.enter(message) if (result.clearQueue) clearQueue() result.message?.let { messageQueue.put(it) } } private fun getParentStates(state: State): Deque<State> { val parent = state.getParentState() return if (parent == null) { ArrayDeque() } else { val parentState = getState(parent) val deque = getParentStates(parentState) if (deque.contains(parentState)) { throw IllegalStateException("Cyclic parent states for $state") } deque.push(parentState) deque } } private fun getState(kClass: KClass<*>): State { val stateName = kClass.qualifiedName ?: throw Exception("Could not retrieve the qualified name of $kClass.") val state = states[stateName] if (state != null) return state val newState = kClass.createInstance() if (newState !is State) throw IllegalStateException("$stateName does not extend State.") states[stateName] = newState return newState } private fun process(message: Message, state: State): MessageResult { val messageResult = state.process(message) if (messageResult.handled) return messageResult val parent = state.getParentState() ?: return messageResult return process(message, getState(parent)) } }
0
Kotlin
0
0
0ff115a85d3f14a2b8274b719dc70a7dae15dca1
4,534
simplestatemachine
MIT License
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/mpp/publication/MppPublicationCompatibilityIT.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.mpp.publication import org.gradle.api.JavaVersion import org.gradle.util.GradleVersion import org.jetbrains.kotlin.gradle.testbase.* import org.jetbrains.kotlin.gradle.util.cartesianProductOf import org.jetbrains.kotlin.gradle.util.isTeamCityRun import org.jetbrains.kotlin.gradle.util.x import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestMetadata import org.junit.jupiter.api.* import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import java.io.File import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.deleteRecursively import kotlin.io.path.readText import kotlin.io.path.relativeTo import kotlin.io.path.walk @ExtendWith(GradleParameterResolver::class) class MppPublicationCompatibilityIT : KGPBaseTest() { companion object { private val agpVersions = listOf( TestVersions.AGP.MIN_SUPPORTED, TestVersions.AGP.MAX_SUPPORTED, ) private val kotlinVersions = listOf( TestVersions.Kotlin.STABLE_RELEASE, TestVersions.Kotlin.CURRENT ) private val projectVariants = with(ProjectVariant) { listOf( native + jvm, native + android, native + jvm + android, javaOnly, androidOnly, ) } private fun generateScenarios(gradleVersions: List<String>): Set<Scenario> { val projects = cartesianProductOf(gradleVersions, agpVersions, kotlinVersions, projectVariants).map { ScenarioProject( gradleVersion = it[0] as String, agpVersion = it[1] as String, kotlinVersion = it[2] as String, variant = it[3] as ProjectVariant, ) } .filter(Scenario.Project::hasValidVersionCombo) .toSet() val scenarios = (projects x projects) .map { (consumer, producer) -> Scenario(consumer, producer) } .filter(Scenario::hasMasterKmp) // we are not interested in AndroidOnly <-> JavaOnly compatibility .filter(Scenario::isConsumable) .toSet() println("Total scenarios: ${scenarios.size}") println("Total unique publications: ${scenarios.map { it.producer }.toSet().size}") println("Total unique consumer projects: ${scenarios.map { it.consumer }.toSet().size}") return scenarios } private val expectedDataPath = Paths.get( "src", "test", "resources", "testProject", "mppPublicationCompatibility", "expectedData", ) private val Scenario.expectedScenarioDataDir get() = expectedDataPath.resolve("consumer_" + consumer.id).resolve("producer_" + producer.id) private fun Scenario.expectedResolvedConfigurationTestReport(configurationName: String): Path = expectedScenarioDataDir .resolve("$configurationName.txt") private val ProjectVariant.sampleDirectoryName: String get() = when (this) { ProjectVariant.AndroidOnly -> "androidOnly" ProjectVariant.JavaOnly -> "javaOnly" is ProjectVariant.Kmp -> "kmp" } @JvmStatic fun scenarios(specificGradleVersion: GradleVersion?): Iterable<Scenario> { val supportedGradleVersions = listOf( TestVersions.Gradle.MIN_SUPPORTED, TestVersions.Gradle.MAX_SUPPORTED, ) if (specificGradleVersion != null) { if (specificGradleVersion.version !in supportedGradleVersions) return emptyList() println("Generate scenarios for $specificGradleVersion Gradle version") return generateScenarios(listOf(specificGradleVersion.version)) } else { println("Generate scenarios for $supportedGradleVersions Gradle versions") return generateScenarios(supportedGradleVersions) } } @JvmStatic fun rerunScenariosForDebugging(specificGradleVersion: GradleVersion?): Iterable<Scenario> { val rerunIndex = 2 return listOf(scenarios(specificGradleVersion).toList()[rerunIndex]) } @JvmStatic @TempDir lateinit var localRepoDir: Path } // Test data could be regenerated by removing subdirectories in "expectedData" directory in the project dir @DisplayName("test compatibility between published libraries by kotlin multiplatform, java and android") @TestMetadata("mppPublicationCompatibility") @MppGradlePluginTests @ParameterizedTest @Suppress("JUnitMalformedDeclaration") // FIXME: IDEA-320187 @MethodSource("scenarios") /** For debugging use [rerunScenariosForDebugging] */ fun testKmpPublication(scenario: Scenario) { scenario.producer.publish(localRepoDir) scenario.testConsumption(localRepoDir) } @TestMetadata("mppPublicationCompatibility") @MppGradlePluginTests @Test fun checkThereIsNoUnusedTestData() { val autoCleanUp = false // set it to true to automatically clean up unused test data if (isTeamCityRun && autoCleanUp) fail { "Auto cleanup can't be used during TeamCity run" } val existingDataDirs = expectedDataPath.walk().map { it.parent.relativeTo(expectedDataPath) }.toMutableSet() val expectedDataDirs = scenarios(null).map { it.expectedScenarioDataDir.relativeTo(expectedDataPath) }.toSet() val unexpectedDataDirs = existingDataDirs - expectedDataDirs if (unexpectedDataDirs.isEmpty()) return if (autoCleanUp) unexpectedDataDirs.forEach { expectedDataPath.resolve(it).deleteRecursively() } fail { val unexpectedDataDirsString = unexpectedDataDirs.joinToString("\n") { " $it" } "Following data files are registered in $expectedDataPath but aren't used by test ${this::class}:\n" + unexpectedDataDirsString + "\nPlease remove them or update test." } } private fun Scenario.Project.publish(repoDir: Path) { // check if already published if (repoDir.resolve(packageName.replace(".", "/")).resolve(artifactName).toFile().exists()) return val sampleDirectoryName = variant.sampleDirectoryName val scenarioProject = this project( projectName = "mppPublicationCompatibility/sampleProjects/$sampleDirectoryName", gradleVersion = gradleVersion, localRepoDir = repoDir, buildJdk = File(System.getProperty("jdk${JavaVersion.VERSION_17.majorVersion}Home")) ) { prepareProjectForPublication(scenarioProject) val buildOptions = if (hasAndroid) { val androidVersion = scenarioProject.agpVersionString!! defaultBuildOptions.copy(androidVersion = androidVersion) } else { defaultBuildOptions } build("publish", buildOptions = buildOptions) } } private fun Scenario.testConsumption(repoDir: Path) { val consumerDirectory = consumer.variant.sampleDirectoryName project( projectName = "mppPublicationCompatibility/sampleProjects/$consumerDirectory", gradleVersion = consumer.gradleVersion, localRepoDir = repoDir, buildJdk = File(System.getProperty("jdk${JavaVersion.VERSION_17.majorVersion}Home")) ) { prepareConsumerProject(consumer, listOf(producer), repoDir) val buildOptions = if (consumer.hasAndroid) { val androidVersion = consumer.agpVersionString!! defaultBuildOptions.copy(androidVersion = androidVersion) } else { defaultBuildOptions } build("resolveDependencies", buildOptions = buildOptions) fun assertResolvedDependencies(configurationName: String) { val actualReport = projectPath.resolve("resolvedDependenciesReports") .resolve("${configurationName}.txt") .readText() val expectedReportFile = expectedResolvedConfigurationTestReport(configurationName) val actualReportSanitized = actualReport .lineSequence() .filterNot { it.contains("stdlib") } .map { it.replace(TestVersions.Kotlin.CURRENT, "SNAPSHOT") } .joinToString("\n") KotlinTestUtils.assertEqualsToFile(expectedReportFile, actualReportSanitized) } assertAll(consumer.resolvedConfigurationsNames.map { configurationName -> { assertResolvedDependencies(configurationName) } }) } } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
9,310
kotlin
Apache License 2.0
framework/src/main/kotlin/com/github/iipekolict/knest/annotations/properties/Query.kt
IIPEKOLICT
547,946,181
false
null
package com.github.iipekolict.knest.annotations.properties @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.VALUE_PARAMETER) annotation class Query(val name: String = "")
0
Kotlin
0
0
1ad45e476de6972785f97000067a3112ccf1595f
187
knest
MIT License
app/src/main/java/com/mathroule/sample/room/database/entity/Book.kt
mathroule
275,557,783
false
null
package com.mathroule.sample.room.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey import com.mathroule.sample.room.database.entity.User @Entity( tableName = "book", foreignKeys = [ ForeignKey( entity = User::class, parentColumns = ["id"], childColumns = ["user_id"], onDelete = ForeignKey.CASCADE ) ] ) data class Book( @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) val id: Long = 0L, @ColumnInfo(name = "user_id") val userId: Long, @ColumnInfo(name = "title") val title: String )
0
Kotlin
0
0
b895c177e8908608b1c8b91b325d28a8760711a4
675
room-delete-entity-sample
MIT License
app/src/main/java/ru/skillbox/humblr/utils/State.kt
MuratTablyldy
621,417,426
false
null
package ru.skillbox.humblr.utils import kotlinx.coroutines.flow.MutableStateFlow object State { private var state: StateF? = null fun getInstance(): StateF { if (state == null) { state = StateF() } return state!! } class StateF { val expired = MutableStateFlow(false) var error = MutableStateFlow<Throwable?>(null) } }
0
Kotlin
0
0
a89d727ce273e42984cb76ef5b2ea98eca830019
393
Humblr
Apache License 2.0
src/dynamic_programming/problems/Knapsack-01.kt
bddesai
510,888,267
false
{"Kotlin": 96319, "Java": 60624}
package problems import kotlin.math.max fun main() { val profits = intArrayOf(2, 3, 1, 4) val weights = intArrayOf(4, 5, 3, 7) val capacity = 5 println("Ans = ${solveKnapsack(profits, weights, capacity)}") } fun solveKnapsack(profits: IntArray, weights: IntArray, capacity: Int): Int { return knapsackHelper(profits, weights, capacity, 0) } fun knapsackHelper(profits: IntArray, weights: IntArray, capacity: Int, currentIndex: Int): Int { if (capacity <= 0 || currentIndex >= profits.size) return 0 // include var profit1 = 0 if (weights[currentIndex] < capacity) { profit1 = profits[currentIndex] + knapsackHelper(profits, weights, capacity - weights[currentIndex], currentIndex + 1) } // exclude val profit2 = knapsackHelper(profits, weights, capacity, currentIndex + 1) return max(profit1, profit2) }
0
Kotlin
0
0
8d99b9b7c61698119db8e50892a52145ad3ecae0
895
LeetCode-Kotlin
MIT License
app/src/main/java/com/acutecoder/contacts/adapter/OnNumberClickListener.kt
Bhuvaneshw
648,780,492
false
null
package com.acutecoder.contacts.adapter import com.acutecoder.contacts.contact.Contact /** * Created by Bhuvaneshwaran * on 1:24 PM, 6/4/2023 * * @author AcuteCoder */ fun interface OnNumberClickListener { fun onClick(number: String) }
0
Kotlin
0
0
2b2a5363832e5724bcc85b3f18c5e78fda56fc38
248
Contacts
MIT License
kotlin-extensions/src/main/java/com/github/ramonrabello/opencv/android/ktx/MatExtensions.kt
linkedopenknowledge
282,299,556
true
{"Kotlin": 3532}
package com.github.ramonrabello.opencv.android.ktx import android.graphics.Bitmap import org.opencv.android.Utils import org.opencv.core.CvType import org.opencv.core.Mat import org.opencv.core.Size import org.opencv.imgproc.Imgproc /** * Converts [Mat] to gray scale channel. * @param bitmap The [Bitmap] to be converted. */ fun Mat.toGray(bitmap: Bitmap) { Utils.bitmapToMat(bitmap, this) Imgproc.cvtColor(this, this, Imgproc.COLOR_RGB2GRAY) } /** * Applies the Gaussian Blur algorithm using * the provided [Bitmap]. * * @param bitmap The [Bitmap] to be used. * @param kSize the Size of the convolution matrix. * @param sigmaX Offset on axis X. */ inline fun Mat.gaussianBlur(bitmap: Bitmap, kSize: Size = Size(125.toDouble(), 125.toDouble()), sigmaX:Double = 0.toDouble(), block: (Bitmap) -> Unit) { Utils.bitmapToMat(bitmap, this) Imgproc.GaussianBlur(this, this, kSize, sigmaX) return block(this.toBitmap()) } /** * Applies the Canny Edge algorithm in * the provided [Bitmap]. * * @param bitmap The [Bitmap] to be used. * @param threshold1 The initial threshold. * @param threshold2 The final threshold. */ inline fun Mat.canny(bitmap: Bitmap, threshold1: Double = 20.toDouble(), threshold2: Double = 255.toDouble(), block: (Bitmap) -> Unit) { this.toGray(bitmap) Imgproc.Canny(this, this, threshold1, threshold2) return block(this.toBitmap()) } /** * Applies the Canny Edge algorithm in * the provided [Bitmap]. * * @param bitmap The [Bitmap] to be used. * @param thresh The threshold. * @param maxVal Max value for the threshold. * @param type The type of the threshold. */ fun Mat.threshold(bitmap: Bitmap, thresh: Double = 50.toDouble(), maxVal: Double = 255.toDouble(), type:Int = Imgproc.THRESH_BINARY, block: (Bitmap) -> Unit) { this.toGray(bitmap) Imgproc.threshold(this, this, thresh, maxVal, type) return block(this.toBitmap()) } /** * Applies the Adaptive Threshold algorithm in * the provided [Bitmap]. * * @param bitmap The [Bitmap] to be used. * @param maxValue The max value for the threshold. * @param adaptiveMethod The adaptive method to be used. * @param thresholdType The type of the threshold. * @param blockSize The block size to be considered. * @param c The C parameter value for the algorithm. */ fun Mat.adaptiveThreshold(bitmap: Bitmap, maxValue: Double = 255.toDouble(), adaptiveMethod: Int = Imgproc.ADAPTIVE_THRESH_MEAN_C, thresholdType: Int = Imgproc.THRESH_BINARY, blockSize: Int = 11, c: Double = 12.toDouble(), block: (Bitmap) -> Unit) { this.toGray(bitmap) Imgproc.adaptiveThreshold(this, this, maxValue, adaptiveMethod, thresholdType, blockSize, c) return block(this.toBitmap()) } /** * Converts the [Mat] to a [Bitmap]. * * @param config The [Bitmap.Config] to be used. */ fun Mat.toBitmap(config: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap { val bitmap = Bitmap.createBitmap(this.cols(), this.rows(), config) Utils.matToBitmap(this, bitmap) return bitmap } /** * Checks if the [Mat] is in gray scale. */ fun Mat.inGray() = this.type() == CvType.CV_8U
0
null
0
0
4a103a886b4079be1af63cfab4efef7ea112ca7f
3,252
opencv-android-ktx
Apache License 2.0
src/commonMain/kotlin/com/shimmermare/stuffiread/ui/components/layout/PopupContent.kt
Shimmermare
605,765,511
false
null
package com.shimmermare.stuffiread.ui.components.layout import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp /** * Border for popup with border and background. */ @Composable inline fun PopupContent( border: Boolean = true, crossinline content: @Composable () -> Unit ) { Surface( shape = RoundedCornerShape(5.dp), elevation = 12.dp ) { Box( modifier = Modifier .background(MaterialTheme.colors.surface) .let { if (border) it.border(2.dp, MaterialTheme.colors.primary, RoundedCornerShape(5.dp)) else it }, ) { content() } } }
9
Kotlin
0
0
d5ec80f35d8f6aa0bdd9e532350f3e1b8c79605d
988
StuffIRead
MIT License
backend/src/main/kotlin/it/unicam/cs/pawm/routing/AuthenticationRouting.kt
Fedcmm
608,251,161
false
null
package it.unicam.cs.pawm.routing import com.auth0.jwt.interfaces.DecodedJWT import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.date.* import io.ktor.util.pipeline.* import it.unicam.cs.pawm.database.PlayerRefreshService import it.unicam.cs.pawm.database.PlayerService import it.unicam.cs.pawm.model.Player import it.unicam.cs.pawm.model.RefreshToken import it.unicam.cs.pawm.utils.REFRESH_DURATION import it.unicam.cs.pawm.utils.createTokens import it.unicam.cs.pawm.utils.verifyRefresh import kotlinx.serialization.Serializable import java.time.Instant fun Route.authenticationRouting() { route("/player") { post("/signup") { val player = call.receive<Player>() if (PlayerService.accountExists(player.email)) { call.respondText("Account already exists", status = HttpStatusCode.BadRequest) return@post } if (player.name.isBlank() || player.surname.isBlank()) { call.respondText("Invalid information", status = HttpStatusCode.BadRequest) return@post } if (!player.email.matches(Regex("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}\$")) || player.password.isBlank()) { call.respondText("Invalid credentials", status = HttpStatusCode.BadRequest) return@post } PlayerService.add(player) call.respond(HttpStatusCode.Created) } post("/login") { val credentials = call.receive<Credentials>() val id = PlayerService.checkCredentials(credentials.email, credentials.password) if (id < 0) { call.respondText("Invalid credentials", status = HttpStatusCode.Unauthorized) return@post } PlayerRefreshService.delete(id) val tokens = application.createTokens(id, credentials.email) PlayerRefreshService.add(RefreshToken(id, tokens.refreshToken, Instant.now().plusSeconds(REFRESH_DURATION).epochSecond)) call.response.addRefreshCookie(tokens.refreshToken) call.respond(hashMapOf( "id" to id.toString(), "token" to tokens.accessToken )) } post("/logout") { val id = validateRefresh()?.getClaim("id")?.asInt() ?: return@post PlayerRefreshService.delete(id) call.respond(HttpStatusCode.OK) } post("{id}/refresh") { val email = call.receive<String>() // TODO (28/05/23): Maybe remove val oldRefresh = validateRefresh() ?: return@post val id = oldRefresh.getClaim("id").asInt() val tokens = application.createTokens(id, email) PlayerRefreshService.update(id, tokens.refreshToken) call.response.addRefreshCookie(tokens.refreshToken) call.respond(hashMapOf("token" to tokens.accessToken)) } } } @Serializable private data class Credentials(val email: String, val password: String) private fun ApplicationResponse.addRefreshCookie(refresh: String) { cookies.append( Cookie("refresh_token", refresh, expires = GMTDate().plus(REFRESH_DURATION*1000), httpOnly = true) ) } private suspend fun PipelineContext<Unit, ApplicationCall>.validateRefresh(): DecodedJWT? { val cookieToken = call.request.cookies["refresh_token"] ?: run { call.respondText("Refresh token is missing", status = HttpStatusCode.Unauthorized) return null } val oldToken = application.verifyRefresh(cookieToken) ?: run { call.respondText("Invalid refresh token", status = HttpStatusCode.Unauthorized) //PlayerRefreshService.delete(id) return null } val dbToken = PlayerRefreshService.read(oldToken.getClaim("id").asInt()) if (dbToken == null || dbToken.expiration < Instant.now().epochSecond) { call.respondText("Token is expired", status = HttpStatusCode.Unauthorized) PlayerRefreshService.delete(oldToken.getClaim("id").asInt()) return null } return oldToken }
0
Kotlin
0
0
3e9cb621bc1a5250fcc03b9e63657a00aeaca5d9
4,227
ST1121-ProgrammazioneWebMobile
MIT License
app/src/main/java/com/dhirajgupta/currencies/fragment/AmountInputFragment.kt
dhiraj
200,731,659
false
null
package com.dhirajgupta.currencies.fragment import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.core.content.ContextCompat import androidx.core.content.getSystemService import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import com.dhirajgupta.currencies.R import com.dhirajgupta.currencies.viewmodel.CurrencyViewModel import kotlinx.android.synthetic.main.fragment_amount_input.* import timber.log.Timber /** * A fragment that handles the user's input to set the chosen amount that will be converted. * */ class AmountInputFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_amount_input, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val parentActivity = activity if (parentActivity == null) { Timber.e("Activity went away after view got created, not continuing view setup!") return } /** * Use the Activity's [CurrencyViewModel] as the backing ViewModel. */ val viewModel = ViewModelProviders.of(parentActivity).get(CurrencyViewModel::class.java) val currency = viewModel.chosenCurrency.value if (currency == null) { Timber.e("Received null currency as chosen, not continuing view setup!!!") return } //Set the screen title as a visual cue to the user for the action to be done viewModel.currentScreenTitle.postValue(getString(R.string.choose_amount_template, currency.iso_code)) //More visual cue and help text textview_amount_input_description.text = getString(R.string.enter_amount_helptext_template, currency.name, currency.iso_code) edittext_amount.setText(getString(R.string.price_template, viewModel.amount.value!!)) edittext_amount.setOnEditorActionListener { textView, i, keyEvent -> /** * When the user presses the done button on the soft keyboard, we set it on the shared [CurrencyViewModel] * and navigate back to show the updated values. * Note: The inputmode on the [EditText] is set to Numeric to ensure that only numeric values can be entered. */ viewModel.amount.postValue(textView.text.toString().toDouble()) findNavController().popBackStack() return@setOnEditorActionListener false } /** * Automatically raise the keyboard to save the user a tap. */ val input_service = parentActivity.getSystemService(Context.INPUT_METHOD_SERVICE) if (input_service != null) { (input_service as InputMethodManager).toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0) } } }
0
Kotlin
0
0
1bcd92305b959e3f7896ff3aaecd9ffa21469d73
3,168
currencies
MIT License
app/src/main/java/com/example/summary_logger/database/room/CurrentDrawerDao.kt
noti-summary
544,959,036
false
null
package com.example.summary_logger.database.room import androidx.room.* import com.example.summary_logger.model.CurrentDrawer @Dao interface CurrentDrawerDao { @Query("SELECT notificationId FROM current_drawer_table") fun getAll(): List<String> @Query("SELECT DISTINCT packageName FROM current_drawer_table") fun getAllPackages(): List<String> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(currentDrawer: CurrentDrawer) @Query("DELETE FROM current_drawer_table WHERE notificationId = :id") fun deleteById(id: String) @Query("DELETE FROM current_drawer_table WHERE packageName = :pkgName AND groupKey = :group AND sortKey = :sortKey") fun deleteByPackageSortKey(pkgName: String, group: String, sortKey: String) @Query("DELETE FROM current_drawer_table WHERE packageName = :pkgName AND groupKey = :group") fun deleteByPackageGroup(pkgName: String, group: String) @Query("SELECT * FROM current_drawer_table WHERE packageName = :pkgName AND groupKey = :group") fun getByPackageGroup(pkgName:String, group: String): List<CurrentDrawer> @Query("DELETE FROM current_drawer_table") fun deleteAll() }
1
Kotlin
0
1
e6b1ab22836773a201c261330ab02d7f74d5cc3f
1,179
noti-summary-logger
MIT License
shared/core/util/src/commonMain/kotlin/com/thomaskioko/tvmaniac/core/util/helper/DateUtilHelper.kt
c0de-wizard
361,393,353
false
null
package com.thomaskioko.tvmaniac.core.util.helper import com.thomaskioko.tvmaniac.core.util.DateUtil interface DateUtilHelper { fun getTimestampMilliseconds(): Long } internal class DateUtilHelperImpl : DateUtilHelper { override fun getTimestampMilliseconds(): Long = DateUtil.getTimestampMilliseconds() }
3
Kotlin
10
88
e613080658265c2cb8bb184c88d2057fe011e58f
316
tv-maniac
Apache License 2.0
app/src/main/java/com/example/potterguide/webclient/model/ItemLivroResposta.kt
DevLeonardoTissi
557,347,534
false
{"Kotlin": 74998}
package com.example.potterguide.webclient.model import com.example.potterguide.model.Livro import com.example.potterguide.model.VolumeInfo class ItemLivroResposta( private val volumeInfo: VolumeInfo ) { val livro: Livro get() = Livro( titulo = volumeInfo.title?.lowercase()?.capitalize() ?: "", subtitulo = volumeInfo.subtitle ?: "", autores = volumeInfo.authors ?: emptyList(), editora = volumeInfo.publisher ?: "", dataDePublicacao = volumeInfo.publishedDate ?: "", descricao = volumeInfo.description ?: "", numeroDePaginas = volumeInfo.pageCount ?: 0, categorias = volumeInfo.categories, imageLinks = volumeInfo.imageLinks, idioma = volumeInfo.language ?: "" ) }
0
Kotlin
0
2
9ce1b84a45b204967fdf553f6ce1bea7c89b11a0
814
PotterGuide
Apache License 2.0
kalexa-model/src/main/kotlin/com/hp/kalexa/model/directive/ElicitSlotDirective.kt
HPInc
164,478,295
false
null
/* * Copyright 2018 HP Development Company, L.P. * SPDX-License-Identifier: MIT */ package com.hp.kalexa.model.directive import com.fasterxml.jackson.annotation.JsonTypeName import com.hp.kalexa.model.Intent @JsonTypeName("Dialog.ElicitSlot") class ElicitSlotDirective( val updatedIntent: Intent? = null, val slotToElicit: String? = null ) : Directive()
0
Kotlin
1
17
e6674eeb24c255aef1859a62a65b805effdc9676
368
kalexa-sdk
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/RuleFolderTwoTone.kt
karakum-team
387,062,541
false
{"Kotlin": 3058356, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/RuleFolderTwoTone") package mui.icons.material @JsName("default") external val RuleFolderTwoTone: SvgIconComponent
0
Kotlin
5
35
f8b65644caf9131e020de00a02718f005a84b45d
198
mui-kotlin
Apache License 2.0
app/src/main/java/org/openobd2/core/logger/ui/graph/Colors.kt
tzebrowski
326,375,780
false
null
package org.openobd2.core.logger.ui.graph import java.util.* class Colors { private val recycle: Stack<Int> = Stack() private val colors: Stack<Int> = Stack() val color: Int get() { if (colors.size === 0) { while (!recycle.isEmpty()) colors.push(recycle.pop()) Collections.shuffle(colors) } val c: Int = colors.pop() recycle.push(c) return c } init { recycle.addAll( Arrays.asList( -0xbbcca, -0x16e19d, -0x63d850, -0x98c549, -0xc0ae4b, -0xde690d, -0xfc560c, -0xff432c, -0xff6978, -0xb350b0, -0x743cb6, -0x3223c7, -0x14c5, -0x3ef9, -0x6800, -0xa8de, -0x86aab8, -0x616162, -0x9f8275, -0xcccccd ) ) } fun generate(): IntIterator { val colorScheme = mutableListOf<Int>() val randomCollors = Colors() repeat((0 until 30).count()) { colorScheme.add(randomCollors.color) } return colorScheme.toIntArray().iterator() } }
0
Kotlin
0
2
827d9a628cc9fae2616ab437db55edf07b7d0af1
1,108
AlfaDataLogger
Apache License 2.0
app/src/main/java/org/openobd2/core/logger/ui/graph/Colors.kt
tzebrowski
326,375,780
false
null
package org.openobd2.core.logger.ui.graph import java.util.* class Colors { private val recycle: Stack<Int> = Stack() private val colors: Stack<Int> = Stack() val color: Int get() { if (colors.size === 0) { while (!recycle.isEmpty()) colors.push(recycle.pop()) Collections.shuffle(colors) } val c: Int = colors.pop() recycle.push(c) return c } init { recycle.addAll( Arrays.asList( -0xbbcca, -0x16e19d, -0x63d850, -0x98c549, -0xc0ae4b, -0xde690d, -0xfc560c, -0xff432c, -0xff6978, -0xb350b0, -0x743cb6, -0x3223c7, -0x14c5, -0x3ef9, -0x6800, -0xa8de, -0x86aab8, -0x616162, -0x9f8275, -0xcccccd ) ) } fun generate(): IntIterator { val colorScheme = mutableListOf<Int>() val randomCollors = Colors() repeat((0 until 30).count()) { colorScheme.add(randomCollors.color) } return colorScheme.toIntArray().iterator() } }
0
Kotlin
0
2
827d9a628cc9fae2616ab437db55edf07b7d0af1
1,108
AlfaDataLogger
Apache License 2.0
app/src/main/java/com/example/midtermapp/ScoreRepository.kt
vidyakethineni
731,106,205
false
{"Kotlin": 22988}
package com.example.midtermapp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ScoreRepository(private val dao: ScoreDao) { suspend fun getAllScores() = withContext(Dispatchers.IO) {dao.getAll()} val allScoresLD = dao.getAllScores() fun getScoreByUser(userName:String) = dao.get(userName) suspend fun insert(score: Score) { withContext(Dispatchers.IO){ dao.insert(score) } } suspend fun delete(score: Score) { withContext(Dispatchers.IO){ dao.delete(score) } } }
0
Kotlin
0
0
018dbeaf6e18d56bf1defc47a26d3f599db9885d
587
MidtermApp
Apache License 2.0
app/src/main/java/com/robsonribeiroft/chuckjokes/base_presentation/LiveDataXt.kt
robsonribeiroft
528,543,321
false
{"Kotlin": 26161}
package com.robsonribeiroft.chuckjokes.core import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.robsonribeiroft.chuckjokes.base_presentation.UIState import com.robsonribeiroft.chuckjokes.base_presentation.UIState.* fun <T> MutableLiveData<UIState<T>>.setSuccess(data: T) { value = UIState(Status.SUCCESS, data = data) } fun <T> MutableLiveData<UIState<T>>.setError(throwable: Throwable) { value = UIState(Status.ERROR, error = throwable) } fun <T> MutableLiveData<UIState<T>>.setLoading() { value = UIState(Status.LOADING) } fun <T> MutableLiveData<UIState<T>>.setIdle() { value = UIState(Status.IDLE) } fun <T> LiveData<UIState<T>>.onPostValue( lifecycleOwner: LifecycleOwner, loading: () -> Unit, onError: (Throwable) -> Unit, onSuccess: (T) -> Unit ) { observe(lifecycleOwner) { uiState: UIState<T> -> uiState.stateHandler(loading, onError, onSuccess) } }
0
Kotlin
0
0
d2794db2877855e06af462111f5cf723369017fb
989
ChuckJokes
MIT License
player/events/src/test/kotlin/com/tidal/sdk/player/events/util/ActiveMobileNetworkTypeTest.kt
tidal-music
806,866,286
false
{"Kotlin": 1775374, "Shell": 9881, "Python": 7380, "Mustache": 911}
package com.tidal.sdk.player.events.util import android.net.ConnectivityManager import android.net.NetworkInfo import assertk.assertThat import assertk.assertions.isEmpty import assertk.assertions.isEqualTo import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.whenever internal class ActiveMobileNetworkTypeTest { private val connectivityManager = mock<ConnectivityManager>() private val activeMobileNetworkType = ActiveMobileNetworkType(connectivityManager) @AfterEach fun afterEach() = verifyNoMoreInteractions(connectivityManager) @Test fun hasNoActiveNetwork() { whenever(connectivityManager.activeNetworkInfo) doReturn null val actual = activeMobileNetworkType.value verify(connectivityManager).activeNetworkInfo assertThat(actual).isEmpty() } @Test fun hasAnActiveNetwork() { val subtypeName = "subtypeName" val activeNetworkInfo = mock<NetworkInfo> { on { it.subtypeName } doReturn subtypeName } whenever(connectivityManager.activeNetworkInfo) doReturn activeNetworkInfo val actual = activeMobileNetworkType.value verify(connectivityManager).activeNetworkInfo verify(activeNetworkInfo).subtypeName assertThat(actual).isEqualTo(subtypeName) } }
27
Kotlin
0
23
1f654552133ef7794fe9bb7677bc7fc94c713aa3
1,505
tidal-sdk-android
Apache License 2.0
data/src/main/kotlin/com/lukelorusso/data/net/api/ColorApi.kt
lukelorusso
277,556,469
false
{"Kotlin": 177484}
package com.lukelorusso.data.net.api import com.lukelorusso.data.net.RetrofitFactory import com.lukelorusso.data.net.dto.ColorResponseDTO import io.reactivex.rxjava3.core.Single import retrofit2.http.GET import retrofit2.http.Query interface ColorApi { @GET("colorblindness.php") fun getColor( @Query("color_hex") colorHex: String, @Query("lang") language: String, @Query("udid") udid: String, @Query("os") os: String = RetrofitFactory.COLOR_API_OS, @Query("v") version: String = RetrofitFactory.COLOR_API_VERSION ): Single<ColorResponseDTO> }
0
Kotlin
2
4
932fe4a62057ae1cb43e9c249e819a2b3c69b375
600
ColorBlindClickAndroid
Apache License 2.0
app/src/main/java/com/smd/surmaiya/adapters/TopSongsAdapter.kt
AhmadHassan71
786,394,928
false
{"Kotlin": 408430, "Java": 347}
package com.smd.surmaiya.adapters import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.Drawable import android.os.Build import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.FragmentManager import androidx.palette.graphics.Palette import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.smd.surmaiya.Fragments.ArtistPageFragment import com.smd.surmaiya.Fragments.PlaylistSearchFragment import com.smd.surmaiya.HelperClasses.FragmentHelper import com.smd.surmaiya.ManagerClasses.MusicServiceManager import com.smd.surmaiya.ManagerClasses.PlaylistManager import com.smd.surmaiya.R import com.smd.surmaiya.itemClasses.Playlist import com.smd.surmaiya.itemClasses.Song import jp.wasabeef.glide.transformations.BlurTransformation class TopSongsAdapter(private val songs: List<Song>, private val isMonthlyRanking: Boolean, private val playlists: List<Playlist>) : RecyclerView.Adapter<TopSongsAdapter.SongViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SongViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.card_monthly_ranking, parent, false) return SongViewHolder(itemView) } @RequiresApi(Build.VERSION_CODES.P) override fun onBindViewHolder(holder: SongViewHolder, position: Int) { val currentSong = songs[position] if (isMonthlyRanking) { // Load the song image and set the song and artist names for monthly ranking Glide.with(holder.itemView.context) .asBitmap() .load(currentSong.coverArtUrl) .apply(RequestOptions.bitmapTransform(BlurTransformation(5, 1))) // Adjust these values as needed .diskCacheStrategy(DiskCacheStrategy.ALL) .into(object : CustomTarget<Bitmap>() { @RequiresApi(Build.VERSION_CODES.S) override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { holder.songImageView.setImageBitmap(resource) // Generate Palette from the Bitmap Palette.from(resource).generate { palette -> val dominant = palette?.lightVibrantSwatch?.rgb ?: Color.parseColor("#FFFFFF") //get opposite colour val complementaryColour= Color.rgb(255 - Color.red(dominant), 255 - Color.green(dominant), 255 - Color.blue(dominant)) //get compl //light vibrant no //vibrant no //complementary //muted no //lightvibrant yes //light muted //darkmuted holder.songNameTextView.setTextColor(dominant) holder.artistNameTextView.setTextColor(dominant) } } override fun onLoadCleared(placeholder: Drawable?) { // Handle case where the Bitmap load is cleared } }) holder.songNameTextView.text = currentSong.songName holder.artistNameTextView.text = currentSong.artist holder.songImageView.setOnClickListener { MusicServiceManager.broadCastSongSelected(currentSong) } } else { // Load the playlist image and set the playlist name and description for popular playlists Glide.with(holder.itemView.context) .asBitmap() .load(currentSong.coverArtUrl) .apply(RequestOptions.bitmapTransform(BlurTransformation(5, 1))) // Adjust these values as needed .diskCacheStrategy(DiskCacheStrategy.ALL) .into(object : CustomTarget<Bitmap>() { @RequiresApi(Build.VERSION_CODES.S) override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { holder.songImageView.setImageBitmap(resource) // Generate Palette from the Bitmap Palette.from(resource).generate { palette -> val dominant = palette?.lightVibrantSwatch?.rgb ?: Color.parseColor("#FFFFFF") //get opposite colour val complementaryColour= Color.rgb(255 - Color.red(dominant), 255 - Color.green(dominant), 255 - Color.blue(dominant)) //get compl //light vibrant no //vibrant no //complementary //muted no //lightvibrant yes //light muted //darkmuted holder.songNameTextView.setTextColor(dominant) holder.artistNameTextView.setTextColor(dominant) } } override fun onLoadCleared(placeholder: Drawable?) { // Handle case where the Bitmap load is cleared } }) holder.songNameTextView.text = currentSong.songName holder.artistNameTextView.text = currentSong.artist // Set the playlist ID for each item // Use the playlistId as needed //if user clicks on image holder.songImageView.setOnClickListener { PlaylistManager.addPlaylist(playlists[position]) val fragmentManager = (holder.itemView.context as AppCompatActivity).supportFragmentManager fragmentManager.beginTransaction() .replace(R.id.fragment_container, PlaylistSearchFragment()) .addToBackStack(null) .commit() } } } override fun getItemCount() = songs.size inner class SongViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val songImageView: ImageView = itemView.findViewById(R.id.songImageView) val songNameTextView: TextView = itemView.findViewById(R.id.songNameTextView) val artistNameTextView: TextView = itemView.findViewById(R.id.artistNameTextView) } }
0
Kotlin
0
4
53bff924bffca89674c39c8ede66b62fb8318f00
6,996
Surmaiya
MIT License
increase-kotlin-core/src/test/kotlin/com/increase/api/client/IncreaseClientTest.kt
Increase
614,596,742
false
{"Kotlin": 15202562, "Shell": 1257, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. package com.increase.api.client class IncreaseClientTest
0
Kotlin
0
2
7fddd86f07c8ab2da78a786c60ea6a0ef93d099a
113
increase-kotlin
Apache License 2.0
android/src/main/kotlin/com/cloudwebrtc/webrtc/TrackRepository.kt
krida2000
510,302,729
false
null
package com.cloudwebrtc.webrtc import com.cloudwebrtc.webrtc.proxy.MediaStreamTrackProxy import java.lang.ref.WeakReference /** * Repository for all the [MediaStreamTrackProxy]s. * * All created in the `flutter_webrtc` [MediaStreamTrackProxy]s will be stored here under weak * references. So if, a [MediaStreamTrackProxy] is disposed, then it will be `null` here. */ object TrackRepository { /** All [MediaStreamTrackProxy]s created in `flutter_webrtc`. */ private val tracks: HashMap<String, WeakReference<MediaStreamTrackProxy>> = HashMap() /** * Adds a new [MediaStreamTrackProxy]. * * @param track Actual [MediaStreamTrackProxy] which will be stored here. */ fun addTrack(track: MediaStreamTrackProxy) { tracks[track.id()] = WeakReference(track) } /** * Lookups [MediaStreamTrackProxy] with the provided unique ID. * * @param id Unique [MediaStreamTrackProxy] to perform the lookup via. * * @return Found [MediaStreamTrackProxy] with the provided ID, or `null` if the * [MediaStreamTrackProxy] isn't found or was disposed. */ fun getTrack(id: String): MediaStreamTrackProxy? { return tracks[id]?.get() } }
0
Rust
0
0
146467b24dd16a2786c3843f773cd08da68bc83c
1,176
webrtc
MIT License
app/src/main/java/tech/ijkzen/viewtooltip/ViewPagerActivity.kt
ijkzen
293,233,691
false
null
package tech.ijkzen.viewtooltip import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import tech.ijkzen.viewtooltip.databinding.ActivityViewPagerBinding class ViewPagerActivity : AppCompatActivity() { private lateinit var mBinding: ActivityViewPagerBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = ActivityViewPagerBinding.inflate(LayoutInflater.from(this), null, false) setContentView(mBinding.root) mBinding.page.adapter = DemoPageAdapter(this) } }
0
Kotlin
0
0
7e92d8f1f700ecc8adb29cb9f135db9ac07a3aee
611
ViewToolTip
Apache License 2.0
app/src/main/java/com/realllydan/bettertimer/Time.kt
gitryder
327,275,756
false
{"Kotlin": 8453}
package com.realllydan.bettertimer import java.util.* /** * # Time * * `Time` is a Kotlin object that provides a utility method [format] which formats milliseconds as a `String` * * ## Example: * Example formatting 10 minutes in milliseconds as a string: * * > ``val tenMinutesInMilliseconds = 600000L`` * * > ``val time: String = Time.format(tenMinutesInMilliseconds)`` * > ``println(time) // Prints "10:00"`` * */ object Time { /** * A constant representing one second, in milliseconds */ const val MILLIS_ONE_MINUTE = 60000L /** * Uses the provided [millisToFormat] and returns a string formatted * in the usual time format * * @param millisToFormat the time in milliseconds that needs formatting * @return the time in the standard digital clock format, as a formatted string */ @JvmStatic fun format(millisToFormat: Long): String { val minutes = (millisToFormat / 1000 / 60).toInt() val seconds = (millisToFormat / 1000 % 60).toInt() return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds) } }
0
Kotlin
0
4
1ecdbf2e15f5b93e92573a23d970aefe6023aaa8
1,119
better-timer
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/core/adapters/SafeAdapter.kt
LongWen0
474,322,068
true
{"Kotlin": 2822516, "Shell": 2039, "Ruby": 1350}
package io.horizontalsystems.bankwallet.core.adapters import io.horizontalsystems.bankwallet.core.* import io.horizontalsystems.bankwallet.entities.AccountType import io.horizontalsystems.bankwallet.entities.SyncMode import io.horizontalsystems.bankwallet.entities.Wallet import io.horizontalsystems.bankwallet.entities.transactionrecords.TransactionRecord import io.horizontalsystems.bitcoincore.BitcoinCore import io.horizontalsystems.bitcoincore.models.BalanceInfo import io.horizontalsystems.bitcoincore.models.BlockInfo import io.horizontalsystems.bitcoincore.models.TransactionDataSortType import io.horizontalsystems.core.BackgroundManager import io.horizontalsystems.dashkit.models.DashTransactionInfo import io.horizontalsystems.hodler.LockTimeInterval import io.reactivex.Single import com.anwang.safewallet.safekit.SafeKit import java.math.BigDecimal class SafeAdapter( override val kit: SafeKit, syncMode: SyncMode?, backgroundManager: BackgroundManager, wallet: Wallet, testMode: Boolean ) : BitcoinBaseAdapter(kit, syncMode, backgroundManager, wallet, testMode), SafeKit.Listener, ISendSafeAdapter { constructor(wallet: Wallet, syncMode: SyncMode?, testMode: Boolean, backgroundManager: BackgroundManager) : this(createKit(wallet, syncMode, testMode), syncMode, backgroundManager, wallet, testMode) init { kit.listener = this } // // BitcoinBaseAdapter // override val satoshisInBitcoin: BigDecimal = BigDecimal.valueOf(Math.pow(10.0, decimal.toDouble())) // ITransactionsAdapter override val explorerTitle: String = "anwang.com" override fun explorerUrl(transactionHash: String): String? { return if (testMode) null else "https://chain.anwang.com/tx/$transactionHash" } // // DashKit Listener // override fun onBalanceUpdate(balance: BalanceInfo) { balanceUpdatedSubject.onNext(Unit) } override fun onLastBlockInfoUpdate(blockInfo: BlockInfo) { lastBlockUpdatedSubject.onNext(Unit) } override fun onKitStateUpdate(state: BitcoinCore.KitState) { setState(state) } override fun onTransactionsUpdate(inserted: List<DashTransactionInfo>, updated: List<DashTransactionInfo>) { val records = mutableListOf<TransactionRecord>() for (info in inserted) { records.add(transactionRecord(info)) } for (info in updated) { records.add(transactionRecord(info)) } transactionRecordsSubject.onNext(records) } override fun onTransactionsDelete(hashes: List<String>) { // ignored for now } // ISendDashAdapter override fun availableBalance(address: String?): BigDecimal { return availableBalance(feeRate, address, mapOf()) } override fun fee(amount: BigDecimal, address: String?): BigDecimal { return fee(amount, feeRate, address, mapOf()) } override fun validate(address: String) { validate(address, mapOf()) } override fun send(amount: BigDecimal, address: String, logger: AppLogger, lockedTimeInterval: LockTimeInterval? ): Single<Unit> { var unlockedHeight = 0L; if ( lockedTimeInterval != null ){ val lockedMonth = lockedTimeInterval.value(); val step = 86400 * lockedMonth; unlockedHeight = (kit.lastBlockInfo !! .height.toLong()).plus( step ); } return Single.create { emitter -> try { kit.sendSafe(address, (amount * satoshisInBitcoin).toLong(), true, feeRate.toInt(), TransactionDataSortType.Shuffle, mapOf(),unlockedHeight ) emitter.onSuccess(Unit) } catch (ex: Exception) { emitter.onError(ex) } } } companion object { private const val feeRate = 10L private fun getNetworkType(testMode: Boolean) = if (testMode) SafeKit.NetworkType.TestNet else SafeKit.NetworkType.MainNet private fun createKit(wallet: Wallet, syncMode: SyncMode?, testMode: Boolean): SafeKit { val account = wallet.account val accountType = account.type if (accountType is AccountType.Mnemonic) { return SafeKit(context = App.instance, words = accountType.words, passphrase = accountType.passphrase, walletId = account.id, syncMode = getSyncMode(syncMode), networkType = getNetworkType(testMode), confirmationsThreshold = confirmationsThreshold) } throw UnsupportedAccountException() } fun clear(walletId: String, testMode: Boolean) { SafeKit.clear(App.instance, getNetworkType(testMode), walletId) } } }
0
null
0
0
1fca1da9664a35186c40221d2b80f3a3802804d7
4,902
SafeWallet-android
MIT License
composeApp/shared/src/commonMain/kotlin/shared/utils/DecimalFormat.kt
joharei
772,430,932
false
{"Kotlin": 57435, "Swift": 1006}
package shared.utils expect fun Double.format(): String
0
Kotlin
0
0
afba1f62445f6b5a532c754cf16ccb781adb3ade
56
tender
Apache License 2.0
plugins/com.flinty.docsflow.server.core/source/com/flinty/docsflow/server/core/userAccount/rest/LogoutRestHandler.kt
flint80
413,383,841
false
{"Kotlin": 291036, "HTML": 8515, "CSS": 317}
/***************************************************************** * Gridnine AB http://www.gridnine.com * Project: JTasks *****************************************************************/ package com.flinty.docsflow.server.core.userAccount.rest import com.flinty.docsflow.common.core.model.rest.LogoutRequest import com.flinty.docsflow.common.core.model.rest.LogoutResponse import com.flinty.docsflow.server.core.web.DocsFlowAuthFilter import com.gridnine.jasmine.server.core.rest.RestHandler import com.gridnine.jasmine.server.core.rest.RestOperationContext class LogoutRestHandler:RestHandler<LogoutRequest,LogoutResponse> { override fun service(request: LogoutRequest, ctx: RestOperationContext): LogoutResponse { ctx.response.setHeader("Set-Cookie", "${DocsFlowAuthFilter.DOCSFLOW_AUTH_COOKIE}=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT") return LogoutResponse() } }
0
Kotlin
0
0
d64d64bd2f539a6579ee80dc2c89b22b4c644ddc
913
coralina-docs-flow
MIT License
src/main/kotlin/me/luna/trollhack/event/events/render/RenderOverlayEvent.kt
NotMonika
509,752,527
false
{"Kotlin": 2035807, "Java": 168054, "GLSL": 91098}
package me.luna.trollhack.event.events.render import me.luna.trollhack.event.* import net.minecraftforge.client.event.RenderGameOverlayEvent sealed class RenderOverlayEvent(override val event: RenderGameOverlayEvent) : Event, WrappedForgeEvent { val type: RenderGameOverlayEvent.ElementType get() = event.type class Pre(event: RenderGameOverlayEvent.Pre) : RenderOverlayEvent(event), ICancellable, EventPosting by Companion { companion object : EventBus() } class Post(event: RenderGameOverlayEvent.Post) : RenderOverlayEvent(event), ICancellable, EventPosting by Companion { companion object : EventBus() } }
0
Kotlin
0
0
543ac418b69e0c7359cde487e828b4c3d2260241
658
MorisaHack
Do What The F*ck You Want To Public License
app/src/main/java/com/boosters/promise/data/database/UserDataBase.kt
boostcampwm-2022
562,936,971
false
{"Kotlin": 196544}
package com.boosters.promise.data.database import androidx.room.Database import androidx.room.RoomDatabase import com.boosters.promise.data.friend.source.local.FriendEntity import com.boosters.promise.data.friend.source.local.FriendDao @Database(entities = [FriendEntity::class], version = 1) abstract class UserDataBase : RoomDatabase() { abstract fun userDao(): FriendDao }
3
Kotlin
5
23
126598bc7a703001ce699d8e3772386d9ffab86a
383
android03-Promise
MIT License
pod-room/src/main/java/com/github/mahendranv/podroom/dao/EpisodeDao.kt
mahendranv
607,981,900
false
null
package com.github.mahendranv.podroom.dao import android.util.Log import androidx.paging.PagingSource import androidx.room.* import androidx.sqlite.db.SupportSQLiteQuery import com.github.mahendranv.podroom.entity.Episode import com.github.mahendranv.podroom.views.EpisodeDetails import kotlinx.coroutines.flow.Flow @Dao interface EpisodeDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(episode: Episode): Long @Update suspend fun update(episode: Episode) @Transaction suspend fun insertAll(episodes: List<Episode>): Int { var insertions = 0 var updates = 0 episodes.filter { it.streamUrl.trim().isNotEmpty() }.forEach { episode -> val existingEntry = getIDByStream(episode.streamUrl) if (existingEntry == null) { insert(episode) insertions++ } else { Log.d(TAG, "duplicate: [$existingEntry]" + episode.title + " > " + episode.streamUrl) update(episode.copy(id = existingEntry)) updates++ } } Log.d( TAG, "insertAll: [inserts: $insertions, updates: $updates, " + "skipped = ${episodes.size - (insertions + updates)}]" ) return insertions + updates } @Query("SELECT * FROM episodes WHERE channel_id = :channelId ORDER BY pub_date DESC") fun getEpisodesByChannelId(channelId: Long): Flow<List<Episode>> @Query("SELECT * FROM episodes ORDER BY pub_date DESC") fun getAllEpisodes(): Flow<List<Episode>> @Query("SELECT * FROM episodes where id = :id") fun getEpisodeById(id: Long): Episode? // EPISODE details // Workaround: order cannot be provided as argument @RawQuery(observedEntities = [EpisodeDetails::class]) fun getEpisodeDetails(query: SupportSQLiteQuery): PagingSource<Int, EpisodeDetails> /** * Returns pk if the given stream has been already inserted. */ @Query("SELECT id FROM episodes where stream_url = :stream") fun getIDByStream(stream: String): Long? companion object { private const val TAG = "EpisodeDao" } }
4
Kotlin
0
1
bc934d4075c35d21ab7ecf1a1cd042adf1843852
2,201
pod-room
MIT License
app/src/main/java/com/vikaspatidar/shvan/home/PetItem.kt
vikaspatidar
343,876,445
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vikaspatidar.shvan.home import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vikaspatidar.shvan.R import com.vikaspatidar.shvan.model.Gender import com.vikaspatidar.shvan.model.Pet import com.vikaspatidar.shvan.ui.theme.Cyan200 import com.vikaspatidar.shvan.ui.theme.Pink200 @Composable fun PetItem(pet: Pet, onPetSelected: (id: Int) -> Unit) { Box( modifier = Modifier .fillMaxSize() .padding(8.dp) ) { Card( modifier = Modifier.clickable { onPetSelected(pet.id) }, shape = RoundedCornerShape(8.dp), elevation = 2.dp, ) { Column { Image( painter = painterResource(pet.photo), contentDescription = pet.name, contentScale = ContentScale.Crop, modifier = Modifier .padding(0.dp) .height(180.dp) .fillMaxWidth() .clip(shape = RoundedCornerShape(8.dp, 8.dp, 0.dp, 0.dp)), ) Row(verticalAlignment = Alignment.CenterVertically) { Text( text = pet.name, modifier = Modifier.padding(8.dp), style = MaterialTheme.typography.body1, ) Box( modifier = Modifier .fillMaxWidth() .padding(start = 8.dp, end = 8.dp), contentAlignment = Alignment.CenterEnd, ) { val contentDescId: Int val iconId: Int val iconTint: Color when (pet.gender) { Gender.MALE -> { iconTint = Cyan200 iconId = R.drawable.ic_baseline_male_24 contentDescId = R.string.content_desc_male } else -> { iconTint = Pink200 iconId = R.drawable.ic_baseline_female_24 contentDescId = R.string.content_desc_female } } Row(verticalAlignment = Alignment.CenterVertically) { Icon( painter = painterResource(id = iconId), contentDescription = stringResource(contentDescId), modifier = Modifier.padding(8.dp), tint = iconTint ) } } } } } } }
0
Kotlin
0
0
6b537fdb96b6c86fc54acce5756b6d9e64d5e59d
4,220
Shvan
Apache License 2.0
ldfs/src/main/kotlin/com/ldfs/control/domain/service/DirectoryCommandService.kt
space-enthusiast
760,310,461
false
{"Kotlin": 20271, "Dockerfile": 149}
package com.ldfs.control.domain.service import com.ldfs.common.domain.AggregateAssociation import com.ldfs.control.domain.common.toAggregate import com.ldfs.control.domain.common.toEntity import com.ldfs.control.domain.model.aggregate.Directory import com.ldfs.control.domain.repository.DirectoryEntityRepository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.UUID @Service class DirectoryCommandService( private val repository: DirectoryEntityRepository, ) { @Transactional fun create( name: String, parentDirectoryUuid: UUID?, ): Directory { return repository.save( Directory( name = name, parent = parentDirectoryUuid?.let { AggregateAssociation(it) }, ).toEntity(), ).toAggregate() } @Transactional fun save(directory: Directory): Directory { return repository.save(directory.toEntity()).toAggregate() } @Transactional fun saveAll(directories: List<Directory>): List<Directory> { return repository.saveAll(directories.map { it.toEntity() }).map { it.toAggregate() } } @Transactional fun delete(id: UUID) { repository.deleteById(id) } @Transactional fun delete(ids: Set<UUID>) { repository.deleteAllByIdInBatch(ids) } }
0
Kotlin
0
0
82e1edbe795c0ab8d3e2bc79399c2505985905ae
1,461
ldfs
MIT License
src/main/kotlin/at/cpickl/gadsu/service/serialize.kt
christophpickl
56,092,216
false
null
package at.cpickl.gadsu.service //class Serializer(private val bytes: ByteArray) { // fun asString() = Base64.getEncoder().encodeToString(bytes) // fun asFile(target: File) { // asString().saveToFile(target) // } //} // //class Deserializer { // fun <T> byString(deserialized: String) = deserialized.deserialize() as T //} // //fun String.deserialize(): Any { // val data = Base64.getDecoder().decode(this) // val ois = ObjectInputStream(ByteArrayInputStream(data)) // val o = ois.readObject() // ois.close() // return o //} // //fun Any.serialize(): Serializer { // val baos = ByteArrayOutputStream() // val oos = ObjectOutputStream(baos) // oos.writeObject(this) // oos.close() // return Serializer(baos.toByteArray()) //}
43
Kotlin
1
2
f6a84c42e1985bc53d566730ed0552b3ae71d94b
776
gadsu
Apache License 2.0
lib/src/main/java/io/github/staakk/cchart/label/HorizontalLabelRendererImpl.kt
staakk
340,637,391
false
null
package io.github.staakk.cchart.label import android.graphics.Paint import android.graphics.Typeface import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Offset import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import io.github.staakk.cchart.util.Alignment import io.github.staakk.cchart.util.TextAlignment import io.github.staakk.cchart.util.drawText @Composable fun horizontalLabelRenderer( labelsTextSize: TextUnit = 12.sp, labelsTypeface: Typeface = Typeface.DEFAULT, location: Float = 1f, alignment: Alignment = Alignment.BottomCenter, textAlignment: TextAlignment = TextAlignment.Left, labelOffset: Offset = Offset(0f, 12f), labelsProvider: LabelsProvider = IntLabelsProvider, ): HorizontalLabelRenderer { val density = LocalDensity.current val paint = Paint().apply { typeface = labelsTypeface textSize = with(density) { labelsTextSize.toPx() } isAntiAlias = true } return horizontalLabelRenderer( paint, location, alignment, textAlignment, labelOffset, labelsProvider ) } /** * Creates a [HorizontalLabelRenderer]. * * @param paint Paint to draw the labels text with. * @param location Location of the label in percents. * @param alignment The alignment of the label relative to the position at which it should be * rendered. * @param textAlignment The alignment of the label text. * @param labelOffset Offset of the label position relative to the position at which it should be * rendered. * @param labelsProvider Provides the labels text and position for the given range. */ fun horizontalLabelRenderer( paint: Paint, location: Float = 1f, alignment: Alignment = Alignment.BottomCenter, textAlignment: TextAlignment = TextAlignment.Left, labelOffset: Offset = Offset(0f, 12f), labelsProvider: LabelsProvider = IntLabelsProvider ): HorizontalLabelRenderer = HorizontalLabelRenderer { context -> labelsProvider.provide(context.viewport.minX, context.viewport.maxX) .forEach { (text, offset) -> val textWidth = paint.measureText(text) val x = context.toRendererX(offset) - textWidth / 2 if (x > 0 && x + textWidth < size.width) { drawText( text = text, position = Offset( x = context.toRendererX(offset), y = location * size.height ) + labelOffset, alignment = alignment, textAlignment = textAlignment, paint = paint ) } } }
0
Kotlin
1
9
2f5aa3f548a6a4ab55f44ac659ea1aaff5f5d968
2,758
cchart
Apache License 2.0
app/src/main/java/pl/grajek/actions/model/database/AppDatabase.kt
dawids222
169,272,010
false
null
package pl.grajek.actions.model.database import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import android.content.Context import pl.grajek.actions.model.converter.DateConverter import pl.grajek.actions.model.dao.ActionDao import pl.grajek.actions.model.dao.CategoryDao import pl.grajek.actions.model.entity.Action import pl.grajek.actions.model.entity.Category @Database(entities = [Action::class, Category::class], version = 1) @TypeConverters(DateConverter::class) abstract class AppDatabase : RoomDatabase() { abstract fun actionDao(): ActionDao abstract fun categoryDao(): CategoryDao companion object { private var INSTANCE: AppDatabase? = null fun getInstance(context: Context): AppDatabase { if (INSTANCE == null) { synchronized(AppDatabase::class) { INSTANCE = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "app.db" ) .fallbackToDestructiveMigration() .build() } } return INSTANCE!! } fun destroyInstance() { INSTANCE = null } } }
0
Kotlin
0
0
dc8c674b0b171ee68698133bcd023b2e26279612
1,385
Actions
MIT License
app/src/main/java/com/stepstone/apprating/sample/SampleActivity.kt
Gatttest
134,835,469
false
null
package com.stepstone.apprating.sample import android.os.Bundle import android.support.v4.app.FragmentActivity import android.widget.Button import android.widget.Toast import com.stepstone.apprating.AppRatingDialog import com.stepstone.apprating.listener.RatingDialogListener import java.util.* class SampleActivity : FragmentActivity(), RatingDialogListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button1: Button = findViewById(R.id.show_dialog_button1) button1.setOnClickListener { showRatingDialog_example1() } val button2: Button = findViewById(R.id.show_dialog_button2) button2.setOnClickListener { showRatingDialog_example2() } val button3: Button = findViewById(R.id.show_dialog_button3) button3.setOnClickListener { showRatingDialog_example3() } } private fun showRatingDialog_example1() { AppRatingDialog.Builder() .setPositiveButtonText("Submit") .setNegativeButtonText("Cancel") .setNeutralButtonText("Later") .setNoteDescriptions(Arrays.asList("Very Bad", "Not good", "Quite ok", "Very Good", "Excellent !!!")) .setDefaultRating(2) .setTitle("Rate this application") .setDescription("Please select some stars and give your feedback") .setStarColor(R.color.starColor) .setNoteDescriptionTextColor(R.color.noteDescriptionTextColor) .setTitleTextColor(R.color.titleTextColor) .setDescriptionTextColor(R.color.descriptionTextColor) .setCommentTextColor(R.color.commentTextColor) .setCommentBackgroundColor(R.color.colorPrimaryDark) .setWindowAnimation(R.style.MyDialogSlideHorizontalAnimation) .setHint("Please write your comment here ...") .setHintTextColor(R.color.hintTextColor) .create(this@SampleActivity) .show() // this is tst code // this is test 2 // test3333 // test 4444 } private fun showRatingDialog_example2() { AppRatingDialog.Builder() .setPositiveButtonText("Send feedback") .setNumberOfStars(6) .setDefaultRating(4) .setTitle("Rate this application") .setTitleTextColor(R.color.titleTextColor) .setCommentTextColor(R.color.commentTextColor) .setCommentBackgroundColor(R.color.colorPrimaryDark) .setWindowAnimation(R.style.MyDialogFadeAnimation) .setHint("Please write your comment here ...") .setHintTextColor(R.color.hintTextColor) .create(this@SampleActivity) .show() } private fun showRatingDialog_example3() { AppRatingDialog.Builder() .setPositiveButtonText(R.string.send_review) .setNegativeButtonText(R.string.cancel) .setNeutralButtonText(R.string.later) .setNumberOfStars(5) .setDefaultRating(3) .setTitle(R.string.title) .setTitleTextColor(R.color.titleTextColor) .setDescription(R.string.description) .setDefaultComment(R.string.defaultComment) .setDescriptionTextColor(R.color.descriptionTextColor) .setCommentTextColor(R.color.commentTextColor) .setCommentBackgroundColor(R.color.colorPrimaryDark) .setWindowAnimation(R.style.MyDialogSlideVerticalAnimation) .create(this@SampleActivity) .show() } override fun onPositiveButtonClicked(rate: Int, comment: String) { Toast.makeText(this@SampleActivity, "Rate : $rate\nComment : $comment", Toast.LENGTH_LONG).show() } override fun onNegativeButtonClicked() { Toast.makeText(this@SampleActivity, "Negative button clicked", Toast.LENGTH_LONG).show() } override fun onNeutralButtonClicked() { Toast.makeText(this@SampleActivity, "Neutral button clicked", Toast.LENGTH_LONG).show() } }
0
Kotlin
0
0
bec2d6d551d4b70f5afac5bb5d8239465b5ebfe9
4,294
ReviewandRating
Apache License 2.0
shared/src/jsMain/kotlin/com/devscion/classy/getPlatform.kt
zeeshanali-k
679,622,499
false
{"Kotlin": 100741, "Swift": 708, "HTML": 513, "Shell": 228, "Ruby": 101}
package com.devscion.classy actual fun getPlatform(): Int = 3
0
Kotlin
1
24
92772ba4466936bfa393b22f58ced1f0179bfee6
62
Classy
Apache License 2.0
app/src/main/java/com/hulkrent/app/host/photoUpload/Step2ViewModel.kt
Hulk-Cars
772,120,218
false
{"Kotlin": 2511410, "Java": 358761}
package com.hulkrent.app.host.photoUpload import android.content.Intent import android.net.Uri import androidx.databinding.ObservableField import androidx.lifecycle.MutableLiveData import com.google.gson.Gson import com.google.gson.JsonObject import com.hulkrent.app.* import com.hulkrent.app.data.DataManager import com.hulkrent.app.ui.base.BaseViewModel import com.hulkrent.app.util.performOnBackOutOnMain import com.hulkrent.app.util.resource.ResourceProvider import com.hulkrent.app.util.rx.Scheduler import com.hulkrent.app.vo.PhotoList import java.io.File import java.util.* import javax.inject.Inject class Step2ViewModel @Inject constructor( dataManager: DataManager, private val scheduler: Scheduler, val resourceProvider: ResourceProvider ) : BaseViewModel<Step2Navigator>(dataManager, resourceProvider) { init { dataManager.clearHttpCache() } enum class NextScreen { COVER, LISTTITLE, LISTDESC, FINISH, APIUPDATE, UPLOAD } enum class BackScreen { COVER, LISTTITLE, LISTDESC, FINISH, APIUPDATE, UPLOAD } val listID = MutableLiveData<String>() var coverPhoto = MutableLiveData<Int>() val photoList = MutableLiveData<ArrayList<PhotoList>>()//.apply { value = ArrayList() } val step2Result = MutableLiveData<Step2ListDetailsQuery.Results>() val title = ObservableField("") val desc = ObservableField("") var isListActive = false var retryCalled = "" var isStep2 = false var step2Status = MutableLiveData<String>() var loading=MutableLiveData<Boolean>(false) var loading2=MutableLiveData<Boolean>(false) fun setInitialValuesFromIntent(intent: Intent) { try { val initData = intent.getStringExtra("listID") listID.value = initData } catch (e: KotlinNullPointerException) { navigator.showError() } } private fun parseData(results: MutableList<Step2ListDetailsQuery.Result>) { val list = ArrayList<PhotoList>() results.forEachIndexed { _, result -> list.add( PhotoList( UUID.randomUUID().toString(), result.id(), result.name(), result.type(), result.isCover ) ) } photoList.value = list } fun addPhotos(photoPaths: ArrayList<PhotoList>) { val list = photoList.value photoPaths.forEach { list?.add(it) } photoList.value = list } fun addPhoto(photoPaths: String): PhotoList { val referId = UUID.randomUUID().toString() return PhotoList( referId, -1, photoPaths, "", 0, isRetry = false, isLoading = true ) } fun deletephoto(filename: String) { val buildQuery = RemoveListPhotosMutation .builder() .listId(listID.value!!.toInt()) .name(filename) .build() compositeDisposable.add(dataManager.doRemoveListPhotos(buildQuery) .doOnSubscribe { } .doFinally { } .performOnBackOutOnMain(scheduler) .subscribe({ response -> try { val data = response.data()!!.RemoveListPhotos() if (data?.status() == 200) { deletePhotoInList(filename) } else if (data?.status() == 500) { navigator.openSessionExpire("") } else if (data?.status() == 400) { navigator.showToast(resourceProvider.getString(R.string.you_cannot_remove_photos)) } } catch (e: Exception) { e.printStackTrace() } }, { handleException(it) }) ) } private fun deletePhotoInList(filename: String) { val list = photoList.value for (i in 0 until list!!.size) { if (list[i].name == filename) { list.removeAt(i) break } } photoList.value = list } fun getListDetailsStep2() { val buildQuery = Step2ListDetailsQuery .builder() .listId(listID.value!!.toInt()) .listIdInt(listID.value!!.toInt()) .preview(true) .build() compositeDisposable.add(dataManager.doGetStep2ListDetailsQuery(buildQuery) .doOnSubscribe { setIsLoading(true) } .doFinally { setIsLoading(false) } .performOnBackOutOnMain(scheduler) .subscribe({ response -> try { val data = response.data()!!.listingDetails val photoData = response.data()!!.showListPhotos() if (data?.status() == 200) { retryCalled = "" isListActive = true title.set(data.results()!!.title()) desc.set(data.results()!!.description()) coverPhoto.value = data.results()?.coverPhoto() step2Result.value = data?.results() } else if (data?.status() == 500) { navigator.openSessionExpire("") } else { isListActive = false navigator.show404Page() } if (photoData!!.status() == 200) { parseData(photoData.results()!!) } else { photoList.value = ArrayList() } } catch (e: Exception) { e.printStackTrace() } }, { handleException(it) }) ) } fun updateStep2() { val buildQuery = UpdateListingStep2Mutation .builder() .title(title.get()?.trim()) .coverPhoto(coverPhoto.value) .description(desc.get()?.trim()) .id(listID.value!!.toInt()) .build() compositeDisposable.add(dataManager.doUpdateListingStep2(buildQuery) .doOnSubscribe { setIsLoading(true) } .doFinally { setIsLoading(false) } .performOnBackOutOnMain(scheduler) .subscribe({ response -> val data = response.data()?.updateListingStep2() try { if (data?.status() == 200) { retryCalled = "" updateStepDetails() } else if (data?.status() == 500) { navigator.openSessionExpire("") } else { navigator.showSnackbar( resourceProvider.getString(R.string.error), data?.errorMessage()!! ) navigator.navigateToScreen(NextScreen.FINISH) } } catch (e: Exception) { e.printStackTrace() } }, { handleException(it) }) ) } fun updateStepDetails() { val buildQuery = ManageListingStepsMutation .builder() .listId(listID.value.toString()) .currentStep(2) .build() compositeDisposable.add(dataManager.doManageListingSteps(buildQuery) .doFinally { setIsLoading(false) } .performOnBackOutOnMain(scheduler) .subscribe({ response -> val data = response.data()?.ManageListingSteps() try { if (data?.status() == 200) { navigator.navigateToScreen(NextScreen.FINISH) } else if (data?.status() == 500) { navigator.openSessionExpire("") } else { navigator.showError() } } catch (e: Exception) { e.printStackTrace() } }, { handleException(it) }) ) } fun getCoverPhotoId(): Int? { return coverPhoto.value } fun getListAddedStatus(): Boolean { try { if (step2Result.value!!.coverPhoto() == null && step2Result.value!!.title() .isNullOrEmpty() && step2Result.value!!.description().isNullOrEmpty() ) { return true } else { return false } } catch (e: Exception) { } return true } fun setCompleted(bodyAsString: String) { val convertedObject = Gson().fromJson(bodyAsString, JsonObject::class.java) if (convertedObject.get("status").asInt == 200) { val array = convertedObject.get("files").asJsonArray val s = photoList.value array.forEach { val obj = it.asJsonObject val originalname = obj["originalname"].asString val fileName = obj["filename"].asString val id = obj["id"].asString s?.forEach { val file = File(Uri.parse(it.name).path) if (file.name == originalname) { it.isLoading = false it.name = fileName it.id = id.toInt() } } } photoList.value = s } else if (convertedObject.get("status").asInt == 400) { navigator.showSnackbar( resourceProvider.getString(R.string.upload_failed), convertedObject.get("errorMessage").toString() ) } } fun setError(uploadId: String?) { val s = photoList.value s?.forEachIndexed { index, photoList -> if (uploadId == photoList.refId) { photoList.isRetry = true photoList.isLoading = false } } photoList.value = s } fun retryPhotos(uploadId: String?) { val s = photoList.value s?.forEachIndexed { index, photoList -> if (uploadId == photoList.refId) { photoList.isRetry = false photoList.isLoading = true } } photoList.value = s } fun checkFilledData(): Boolean { if (title.get()?.trim().isNullOrEmpty()) { navigator.showSnackbar( resourceProvider.getString(R.string.please_add_a_title_to_your_list), resourceProvider.getString(R.string.add_title) ) } else { if (desc.get()?.trim().isNullOrEmpty()) { navigator.showSnackbar( resourceProvider.getString(R.string.please_add_a_description_to_your_list), resourceProvider.getString(R.string.add_description) ) } else { return true } } return false } fun getStepsSummary() { val buildQuery = ShowListingStepsQuery .builder() .listId(listID.value.toString()) .build() compositeDisposable.add(dataManager.doShowListingSteps(buildQuery) .doOnSubscribe { setIsLoading(true) } .doFinally { setIsLoading(false) } .performOnBackOutOnMain(scheduler) .subscribe({ response -> try { val data = response.data()!!.showListingSteps() if (data!!.status() == 200) { retryCalled = "" step2Status.value = data!!.results()!!.step2()!! } else if (data.status() == 500) { navigator.openSessionExpire("") } else { data.errorMessage()?.let { } } } catch (e: Exception) { e.printStackTrace() } }, { it.printStackTrace() handleException(it) }) ) } }
0
Kotlin
0
0
9886a3455e3d404110a85cdaaf5bbff449390814
12,411
Hulk-Rent-Android
Artistic License 1.0 w/clause 8
app/src/main/java/com/yan/foia/unlogged/ui/fragments/login/LoginFragment.kt
PestClassification
831,577,339
false
{"Kotlin": 16514}
package com.yan.foia.unlogged.ui.fragments.login import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageButton import android.widget.ToggleButton import androidx.constraintlayout.widget.ConstraintLayout import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import com.google.android.material.textfield.TextInputLayout.END_ICON_PASSWORD_TOGGLE import com.yan.foia.R import com.yan.foia.databinding.FragmentLoginBinding import com.yan.foia.logged.LoggedActivity class LoginFragment : Fragment() { private lateinit var backButton: ImageButton private lateinit var eyeButton: ToggleButton private lateinit var eyeButtonClick: ConstraintLayout private lateinit var emailInput: TextInputLayout private lateinit var passwordInput: TextInputLayout private lateinit var emailInputA: TextInputEditText private lateinit var passwordInputB: TextInputEditText private lateinit var loginButton: Button private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val loginViewModel = ViewModelProvider(this)[LoginViewModel::class.java] _binding = FragmentLoginBinding.inflate(layoutInflater, container, false) val root: View = binding.root backButton = binding.loginBackButton backButton.setOnClickListener { _ -> parentFragmentManager.popBackStack() } passwordInput = binding.passwordTextLayout emailInput = binding.emailTextLayout passwordInput.endIconMode = END_ICON_PASSWORD_TOGGLE // eyeButton = binding.eyeButton // eyeButtonClick = binding.eyeButtonClick // eyeButtonClick.setOnClickListener { _ -> // eyeButton.isChecked = !eyeButton.isChecked // } emailInputA = binding.emailTextInput passwordInputB = binding.passwordTextInput loginButton = binding.loginButton loginButton.setOnClickListener { _ -> if(loginViewModel.validateLoginData(emailInputA.text.toString(), passwordInputB.text.toString())) { println(emailInputA.text.toString()) val newActivity = Intent(requireActivity(), LoggedActivity::class.java) startActivity(newActivity) } } return root } }
0
Kotlin
0
0
019df2e3ec1e3d7d26909da99805492a6fdc7197
2,727
Mobile
MIT License
foundation/domain-model/testFixtures/ru/pixnews/domain/model/game/game/SmallandGameFixture.kt
illarionov
305,333,284
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.pixnews.domain.model.game.game import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentSetOf import ru.pixnews.domain.model.company.CompanyFixtures import ru.pixnews.domain.model.company.company.mergeGames import ru.pixnews.domain.model.datasource.DataSourceFixtures import ru.pixnews.domain.model.datasource.igdb import ru.pixnews.domain.model.game.Game import ru.pixnews.domain.model.game.GameFixtures import ru.pixnews.domain.model.game.GameGenreFixtures import ru.pixnews.domain.model.game.GameId import ru.pixnews.domain.model.game.GameLocalizations import ru.pixnews.domain.model.game.GameMode.CoOperative import ru.pixnews.domain.model.game.GameMode.Multiplayer import ru.pixnews.domain.model.game.GameMode.SinglePlayer import ru.pixnews.domain.model.game.GamePlatform.Windows import ru.pixnews.domain.model.game.GameReleaseCategory.MainGame import ru.pixnews.domain.model.game.GameReleaseStatus.EARLY_ACCESS import ru.pixnews.domain.model.game.PlayerPerspective.ThirdPerson import ru.pixnews.domain.model.game.RatingsSummary import ru.pixnews.domain.model.game.adventure import ru.pixnews.domain.model.game.indie import ru.pixnews.domain.model.game.rpg import ru.pixnews.domain.model.links.ExternalLink import ru.pixnews.domain.model.links.ExternalLinkType.DISCORD import ru.pixnews.domain.model.links.ExternalLinkType.EPICGAMES_STORE import ru.pixnews.domain.model.links.ExternalLinkType.OFFICIAL import ru.pixnews.domain.model.links.ExternalLinkType.STEAM import ru.pixnews.domain.model.links.ExternalLinkType.TWITTER import ru.pixnews.domain.model.links.ExternalLinkType.YOUTUBE import ru.pixnews.domain.model.locale.LanguageCode import ru.pixnews.domain.model.locale.Localized import ru.pixnews.domain.model.util.ApproximateDate.ToBeDeterminedYear import ru.pixnews.domain.model.util.CanvasSize import ru.pixnews.domain.model.util.DefaultImageUrl import ru.pixnews.domain.model.util.DefaultVideoUrl import ru.pixnews.domain.model.util.RichText import ru.pixnews.domain.model.util.Url internal val smallandGameId = GameId("smalland") public val GameFixtures.smalland: Game get() = Game( id = smallandGameId, name = Localized( value = "Smalland", language = LanguageCode.ENGLISH, ), summary = Localized( value = RichText( """ | Smalland is a big adventure on a tiny scale! Enjoy multiplayer survival in a vast, hazardous world. | Preparation is key when you're this small, surrounded by massive creatures & at the bottom of the | food chain. Craft weapons & armour, build encampments & explore a strange new land. """.trimMargin(), ), language = LanguageCode.ENGLISH, ), description = Localized(value = RichText(""), language = LanguageCode.ENGLISH), videoUrls = persistentListOf( DefaultVideoUrl("https://www.youtube.com/watch?v=zViO38TNVJY"), ), screenshots = persistentListOf( DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/co3p5t.webp", size = CanvasSize(600U, 800U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmn.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmm.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrml.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmk.webp", size = CanvasSize(2560U, 1440U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmj.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmi.webp", size = CanvasSize(2560U, 1440U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmh.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmg.webp", size = CanvasSize(1600U, 900U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmf.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrme.webp", size = CanvasSize(1920U, 1080U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmd.webp", size = CanvasSize(2560U, 1440U), ), DefaultImageUrl( rawUrl = "https://images.igdb.com/igdb/image/upload/t_original/sccrmc.webp", size = CanvasSize(2560U, 1440U), ), ), developer = CompanyFixtures.mergeGames, publisher = CompanyFixtures.mergeGames, releaseDate = ToBeDeterminedYear(2024, Localized("", LanguageCode.ENGLISH)), releaseStatus = EARLY_ACCESS, genres = persistentSetOf( GameGenreFixtures.adventure, GameGenreFixtures.indie, GameGenreFixtures.rpg, ), tags = persistentSetOf(), ratings = RatingsSummary( gameId = smallandGameId, numberOfVotes = 0U, averageRating = null, distribution = null, ), links = persistentListOf( ExternalLink(OFFICIAL, Url("https://www.mergegames.com/games/smalland")), ExternalLink(STEAM, Url("https://store.steampowered.com/app/768200/SMALLAND")), ExternalLink(EPICGAMES_STORE, Url("https://www.epicgames.com/store/p/smalland")), ExternalLink(TWITTER, Url("https://twitter.com/playsmalland")), ExternalLink(YOUTUBE, Url("https://www.youtube.com/channel/UC8Qkz9-7O3mRu4QUaidgPGg")), ExternalLink(DISCORD, Url("https://discord.gg/smalland")), ), category = MainGame, parentGame = null, series = null, platforms = persistentSetOf(Windows), ageRanking = null, localizations = GameLocalizations( sound = persistentSetOf(), text = persistentSetOf( LanguageCode.ENGLISH, LanguageCode.CHINESE, LanguageCode.SPANISH, LanguageCode.FRENCH, LanguageCode.JAPANESE, LanguageCode.PORTUGUESE, LanguageCode.RUSSIAN, LanguageCode.GERMAN, ), ), gameMode = persistentSetOf(SinglePlayer, CoOperative, Multiplayer), playerPerspectives = persistentSetOf(ThirdPerson), systemRequirements = null, dataSources = DataSourceFixtures.igdb, )
0
Kotlin
0
2
d806ee06019389c78546d946f1c20d096afc7c6e
8,074
Pixnews
Apache License 2.0
src/main/kotlin/com/gcrj/web/bean/XlsProjectBean.kt
Gcrj
149,216,707
false
null
package com.gcrj.web.bean /** * Created by zhangxin on 2018/10/10. */ class XlsProjectBean : ProjectBean() { companion object { const val TYPE_PROJECT = 1 const val TYPE_CUSTOM = 2 fun parseXlsProjectBean(projectBean: ProjectBean): XlsProjectBean { val xlsProjectBean = XlsProjectBean() xlsProjectBean.id = projectBean.id xlsProjectBean.name = projectBean.name xlsProjectBean.create_user = projectBean.create_user xlsProjectBean.subProject = projectBean.subProject xlsProjectBean.type = TYPE_PROJECT return xlsProjectBean } } var title: String? = null var content: String? = null var type = TYPE_CUSTOM }
0
Kotlin
0
0
14883e2e4e38b656a3248ca7062a9890453eaba7
748
ProjectControlWeb
MIT License
SampleApp/app/src/main/java/com/ok/db/TransactionDao.kt
User01ga
455,559,956
false
null
package com.ok.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.ok.db.entity.CategoryWithAmount import com.ok.db.entity.Transaction /** * Created by <NAME>. */ @Dao interface TransactionDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun save(item: Transaction) @Query("SELECT * FROM transactions WHERE category = :category") suspend fun getTransactions(category: String): List<Transaction> @Query("SELECT * FROM transactions") suspend fun getAllTransactions(): List<Transaction> @Query("SELECT SUM(amount) as total, category FROM transactions WHERE incoming = 0 GROUP BY category") suspend fun getExpensesByCategory(): List<CategoryWithAmount> @Query("SELECT SUM(amount) FROM transactions WHERE incoming = 0") suspend fun getTotalExpenses(): Double }
0
Kotlin
0
0
4aa10241877cd31088b0b21325ba42bf11d1f845
899
ChartSampleApp
Apache License 2.0
app/src/main/java/goes/who/whogoes/adapter/AttendeesResponseAdapter.kt
diegolmendonca
102,089,409
false
null
package goes.who.whogoes.adapter /** * Created by <NAME> on 12.09.2017. */ import android.app.Activity import android.graphics.Color import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.squareup.picasso.Picasso import goes.who.whogoes.R import goes.who.whogoes.model.Datum import goes.who.whogoes.model.Declined import goes.who.whogoes.model.Interested class AttendeesResponseAdapter(val act: Activity, var responseList: List<Datum>) : RecyclerView.Adapter<ResponseViewHolder>() { fun setElements(elements: List<Datum>) { responseList = elements } fun getElements(): List<Datum> { return responseList } override fun onBindViewHolder(holder: ResponseViewHolder, position: Int) { val item = responseList[position] holder.title.setTextColor(item.status.color()) val message = when (item.status) { is Interested -> act.getString(R.string.interested) is Declined -> act.getString(R.string.declined) else -> act.getString(R.string.attending) } holder.title.text = message.toUpperCase() holder.body.text = item.name holder.body.setTextColor(Color.BLACK) Picasso.with(act.applicationContext).load(item.picture.data.url).into(holder.image) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResponseViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.response_item, parent, false) return ResponseViewHolder(view, view.findViewById<TextView>(R.id.title), view.findViewById<TextView>(R.id.body), view.findViewById<ImageView>(R.id.profile)) } override fun getItemCount(): Int { return responseList.size } } data class ResponseViewHolder(val view: View, val title: TextView, val body: TextView, val image: ImageView) : RecyclerView.ViewHolder(view)
0
Kotlin
0
2
db738dc2e45b41e386b886be618b3b22ea8d0e80
2,079
whogoes
MIT License
src/main/kotlin/com/ec/aqsoft/arch/exagonal/ddd/order/infrastructure/persistence/repositories/ISprintOderRepository.kt
angelquin1986
438,117,405
false
{"HTML": 18443, "Kotlin": 6842, "JavaScript": 5252, "CSS": 3780}
package com.ec.aqsoft.arch.exagonal.ddd.order.infrastructure.persistence.repositories import com.ec.aqsoft.arch.exagonal.ddd.order.infrastructure.persistence.entities.OrderEntity import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface ISprintOderRepository: CrudRepository<OrderEntity, Int> { }
0
HTML
0
0
678d175589b643053494679b77ae6c3d4cae2e33
372
hexagonal_architecture_java
Apache License 2.0
BadgeMagicModule/src/commonMain/kotlin/org/fossasia/badgemagic/utils/ByteArrayUtils.kt
LoopGlitch26
263,618,871
true
{"Kotlin": 209356, "Swift": 15553, "Shell": 3257, "Ruby": 305}
package org.fossasia.badgemagic.utils object ByteArrayUtils { fun hexStringToByteArray(hexString: String): ByteArray { val length = hexString.length val data = ByteArray(length / 2) for (i in 0 until length step 2) { data[i / 2] = ((getCharacterDigit(hexString[i], 16) shl 4) + getCharacterDigit(hexString[i + 1], 16)).toByte() } return data } private fun getCharacterDigit(hexChar: Char, radix: Int): Int = hexChar.toString().toInt(radix) fun byteArrayToHexString(byteArray: ByteArray): String { val builder = StringBuilder() for (b in byteArray) { builder.append(formatStringToHex(b)) } return builder.toString() } private fun formatStringToHex(byte: Byte): String = (0xFF and byte.toInt()).toString(16).padStart(2, '0') }
0
Kotlin
0
2
cdf3291ce46a9ac16071752912aba845d5178871
851
badge-magic-android
Apache License 2.0
CalculateTip/app/src/test/java/com/fernando/calculatetip/GorjetaTest.kt
0Fernando0
633,567,267
false
null
package com.fernando.calculatetip import com.fernando.calculatetip.ui.gorjeta import org.junit.Assert.assertEquals import org.junit.Test import java.text.NumberFormat class GorjetaTest { @Test fun calcula_20_porcento_noRound(){ val amount = 10.00 val tipPercent = 20.00 val expeckTip = NumberFormat.getCurrencyInstance().format(2.0) val actualTip = gorjeta(amount.toString(),tipPercent.toString(),false) assertEquals(expeckTip,actualTip) } }
0
Kotlin
0
0
c066430e8a8f1c397b4c9e7472982e978c1b2091
497
Portfolio-Android
MIT License
src/main/kotlin/br/com/jiratorio/repository/DynamicFieldConfigRepository.kt
jirareport
126,883,660
false
{"Kotlin": 628412, "Dockerfile": 302}
package br.com.jiratorio.repository import br.com.jiratorio.domain.entity.BoardEntity import br.com.jiratorio.domain.entity.DynamicFieldConfigEntity import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface DynamicFieldConfigRepository : CrudRepository<DynamicFieldConfigEntity, Long> { fun findByBoard(board: BoardEntity): List<DynamicFieldConfigEntity> fun findByBoardIdAndId(boardId: Long, id: Long): DynamicFieldConfigEntity? fun findByIdOrNull(id: Long): DynamicFieldConfigEntity? = findById(id).orElse(null) }
12
Kotlin
12
21
845540e238f47fbd05c1f7f6839152545521c63e
613
jirareport
MIT License
src/main/kotlin/org/hygorm10/bookstore/models/ReviewModel.kt
HygorM10
815,654,114
false
{"Kotlin": 8186}
package org.hygorm10.bookstore.models import com.fasterxml.jackson.annotation.JsonProperty import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.OneToOne import jakarta.persistence.Table import java.util.UUID @Entity @Table(name = "TB_REVIEW") class ReviewModel( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: UUID? = null, @Column(nullable = false) val comment: String, @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @OneToOne @JoinColumn(name = "book_id") val book: BookModel, )
0
Kotlin
0
0
b5bc4f61199388aaaeda88ff8654c1a35e0856d8
741
bookstore-jpa
Apache License 2.0
judokit-android/src/main/java/com/judopay/judokit/android/ui/paymentmethods/adapter/viewholder/SavedCardsFooterViewHolder.kt
Judopay
261,378,339
false
null
package com.judopay.judokit.android.ui.paymentmethods.adapter.viewholder import android.view.View import androidx.recyclerview.widget.RecyclerView import com.judopay.judokit.android.ui.paymentmethods.adapter.BindableRecyclerViewHolder import com.judopay.judokit.android.ui.paymentmethods.adapter.PaymentMethodsAdapterListener import com.judopay.judokit.android.ui.paymentmethods.adapter.model.PaymentMethodItem import com.judopay.judokit.android.ui.paymentmethods.adapter.model.PaymentMethodItemAction import kotlinx.android.synthetic.main.saved_card_footer_item.view.* class SavedCardsFooterViewHolder(view: View) : RecyclerView.ViewHolder(view), BindableRecyclerViewHolder<PaymentMethodItem, PaymentMethodItemAction> { override fun bind(model: PaymentMethodItem, listener: PaymentMethodsAdapterListener?) = with(itemView) { addCardButton.setOnClickListener { listener?.invoke(PaymentMethodItemAction.ADD_CARD, model) } } }
1
Kotlin
3
3
5d595f38039014a26ec079267e475958e4fe1e9c
943
JudoKit-Android
MIT License
zowe-core-for-zowe-sdk/src/jsMain/kotlin/zowe/sdk/core/auth/Login.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
@file:JsModule("@zowe/core-for-zowe-sdk") package zowe.sdk.core.auth import js.promise.Promise import zowe.imperative.rest.session.AbstractSession /** * Class to handle logging onto APIML. */ external class Login { companion object { /** * Perform APIML login to obtain LTPA2 or other token types. */ fun apimlLogin(session: AbstractSession): Promise<String> } }
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
390
kotlin-externals
MIT License
core/src/main/java/com/atech/core/data/network/user/UserModel.kt
aiyu-ayaan
489,575,997
false
null
package com.atech.core.data.network.user import android.os.Parcelable import androidx.annotation.Keep import androidx.room.ColumnInfo import kotlinx.parcelize.Parcelize @Keep @Suppress("") @Parcelize data class UserModel( var uid: String? = null, var name: String? = null, var email: String? = null, var profilePic: String? = null, var syncTime: Long? = System.currentTimeMillis() ) : Parcelable @Keep data class AttendanceUploadModel( @ColumnInfo(name = "subject_name") val subject: String, val total: Int, val present: Int, val teacher: String?, val fromSyllabus: Boolean? = false, val isArchive : Boolean? = false, val isFromOnlineSyllabus: Boolean? = false, val created: Long? = System.currentTimeMillis() )
6
Kotlin
5
13
96f082c8e1fb1eb4aa446afce83f98b7494b4884
770
BIT-App
MIT License
app/src/main/java/com/pet/chat/network/data/send/SendMessage.kt
ViktorMorgachev
438,899,533
false
null
package com.pet.chat.network.data.send import com.google.gson.annotations.SerializedName data class SendMessage( @SerializedName("attachment_id") var attachmentId: Number?, @SerializedName("room_id") var roomId: Number, var text: String, )
0
Kotlin
0
0
14065fa300ece434f4605b56938e7c80a4dde4f4
261
ChatBest
Apache License 2.0
src/main/kotlin/recharts/shape/trapezoid/Props.kt
gm666q
300,695,035
false
null
package recharts.shape.trapezoid import org.w3c.dom.svg.SVGPathElement import recharts.util.types.PresentationAttributes external interface Props : PresentationAttributes<SVGPathElement>, TrapezoidProps
0
Kotlin
1
2
b0efa4c2644d1d6b20bd834a49c745301690440d
205
kotlin-recharts
Apache License 2.0
app/src/main/java/com/teamnexters/android/mealdiary/ui/main/DiaryViewHolder.kt
Jiyoung9310
166,637,099
false
null
package com.teamnexters.android.mealdiary.ui.main import androidx.recyclerview.widget.RecyclerView import com.teamnexters.android.mealdiary.R import com.teamnexters.android.mealdiary.data.model.ListItem import com.teamnexters.android.mealdiary.databinding.ViewDiaryBinding import com.teamnexters.android.mealdiary.util.ImageUtil internal class DiaryViewHolder(private val binding: ViewDiaryBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: ListItem.DiaryItem) { binding.item = item } }
0
Kotlin
0
1
622109f9820cd90121857ca93dff1405b63f0517
519
MealDiary-Android
Apache License 2.0
core/coroutines/src/main/kotlin/app/logdate/core/di/DispatchersModule.kt
WillieCubed
187,304,507
false
{"Kotlin": 458147, "Java": 1084}
package app.logdate.core.di import app.logdate.core.coroutines.AppDispatcher.Default import app.logdate.core.coroutines.AppDispatcher.IO import app.logdate.core.coroutines.Dispatcher import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers @Module @InstallIn(SingletonComponent::class) object DispatchersModule { @Provides @Dispatcher(IO) fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO @Provides @Dispatcher(Default) fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default }
0
Kotlin
0
0
51a51bd8c264aecc9190f67ec1fbb56e37b7e9fc
687
logdate-mobile
MIT License
app/src/main/java/com/personal/tmdb/detail/data/models/EpisodeToAir.kt
Avvami
755,489,313
false
{"Kotlin": 666338}
package com.personal.tmdb.detail.data.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class EpisodeToAir( @Json(name = "air_date") val airDate: String?, @Json(name = "episode_number") val episodeNumber: Int, @Json(name = "episode_type") val episodeType: String?, @Json(name = "id") val id: Int, @Json(name = "name") val name: String?, @Json(name = "overview") val overview: String?, @Json(name = "production_code") val productionCode: String?, @Json(name = "runtime") val runtime: Int?, @Json(name = "season_number") val seasonNumber: Int, @Json(name = "show_id") val showId: Int, @Json(name = "still_path") val stillPath: String?, @Json(name = "vote_average") val voteAverage: Double?, @Json(name = "vote_count") val voteCount: Int? )
0
Kotlin
0
2
de9d96dc4ec271377406e5c794085240a35af69c
908
TMDB
MIT License
JcampConverter/JcampConverter/src/main/java/com/baolan2005/jcampconverter/utils/Utilities.kt
baolanlequang
454,834,872
false
null
package com.baolan2005.jcampconverter.utils public fun String.isNumeric(): Boolean { if (!this.isNullOrEmpty()) { val numsSet = setOf<Char>('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') val thisSet = this.toSet() return numsSet.containsAll(thisSet) } return false } public fun Char.isNumberic(): Boolean { val numsSet = setOf<Char>('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') return numsSet.contains(this) }
0
Kotlin
0
0
1247592104d9c8bb21f1a1b1f581420eadb36287
465
jcamp-converter-android
MIT License
zeta-service/zeta-biz-system/src/main/kotlin/com/zeta/biz/system/service/ISysUserRoleService.kt
xia5800
510,203,856
false
{"Kotlin": 615328, "Lua": 347}
package com.zeta.biz.system.service import com.baomidou.mybatisplus.extension.service.IService import com.zeta.model.system.dto.sysRole.SysRoleDTO import com.zeta.model.system.entity.SysRole import com.zeta.model.system.entity.SysUserRole /** * 用户角色 服务类 * * @author AutoGenerator * @date 2021-12-30 15:24:03 */ interface ISysUserRoleService: IService<SysUserRole> { /** * 根据用户id查询角色 * * @param userId 用户id * @return List<Role> */ fun listByUserId(userId: Long): List<SysRole> /** * 批量根据用户id查询角色 * * @param userIds 用户id集合 * @return List<RoleResult> */ fun listByUserIds(userIds: List<Long>): List<SysRoleDTO> /** * 关联用户角色 * * @param userId 用户id * @param roleIds 角色id列表 * @return 是否成功 */ fun saveUserRole(userId: Long, roleIds: List<Long>?): Boolean /** * 关联用户角色 * * @param userId 用户id * @param roleId 角色id * @return 是否成功 */ fun saveUserRole(userId: Long, roleId: Long): Boolean }
0
Kotlin
0
4
cbfc0ff7f85c8331cf88c1978d908d25f7b554a9
1,033
springboot-kotlin-module
MIT License
app/src/main/java/com/project/laundryappui/menu/notification/NotificationFragment.kt
PramodLakmal
769,692,625
false
{"Kotlin": 21547}
package com.project.laundryappui.menu.notification import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.project.laundryappui.R import com.project.laundryappui.menu.notification.adapter.NotificationAdapter import com.project.laundryappui.menu.notification.model.NotificationModel class NotificationFragment : Fragment() { private var mContext: Context? = null private var recyclerView: RecyclerView? = null private var layoutManager: LinearLayoutManager? = null private var notificationAdapter: NotificationAdapter? = null private var notificationModelList: MutableList<NotificationModel>? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_notification, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setAdapterType(view) setAdapter() } private fun initData() { notificationModelList = ArrayList() (notificationModelList as ArrayList<NotificationModel>).add( NotificationModel( R.drawable.ic_box, "Order No : #73636265", "Order Confirmed" ) ) (notificationModelList as ArrayList<NotificationModel>).add( NotificationModel( R.drawable.ic_box, "Order No : #63231323", "Order Confirmed" ) ) } private fun setAdapterType(view: View) { recyclerView = view.findViewById(R.id.recyclerview_order) layoutManager = LinearLayoutManager(mContext) recyclerView?.setHasFixedSize(true) recyclerView?.setLayoutManager( LinearLayoutManager( mContext, LinearLayoutManager.VERTICAL, false ) ) recyclerView?.isNestedScrollingEnabled = true } private fun setAdapter() { initData() notificationAdapter = NotificationAdapter(notificationModelList) recyclerView!!.setAdapter(notificationAdapter) } override fun onAttach(context: Context) { super.onAttach(context) mContext = context } }
0
Kotlin
0
0
880f3139019cb9cdae0b8e822b853cedd1ab2245
2,582
Laundry_App_UI
Apache License 2.0
app/src/main/java/com/example/arknightsautoclicker/processing/tasks/recruitment/RecruitmentTask.kt
qwerttyuiiop1
684,537,002
false
{"Kotlin": 142059}
package com.example.arknightsautoclicker.processing.tasks.recruitment import com.example.arknightsautoclicker.processing.tasks.Task import com.example.arknightsautoclicker.processing.io.Clicker import com.example.arknightsautoclicker.processing.io.TextRecognizer import com.example.arknightsautoclicker.processing.exe.ResetRunner import com.example.arknightsautoclicker.processing.exe.Instance import com.example.arknightsautoclicker.processing.exe.MyResult open class RecruitmentTask( protected val clicker: Clicker, protected val recognizer: TextRecognizer, protected val analyzer: TagAnalyzer ) : ResetRunner() { override val task = Task.RECRUIT protected val ui = RecruitmentUIBinding(clicker, recognizer) override fun newInstance() = RecruitmentInstance(ui, analyzer) as Instance<String> open class RecruitmentInstance( val ui: RecruitmentUIBinding, val analyzer: TagAnalyzer ): Instance<String>() { val menu = ui.recruitMenu val recruit = ui.recruit val other = ui.other suspend fun inRecruitMenu() = menu.label.matchesLabel(tick) suspend fun inRecruit() = recruit.label.matchesLabel(tick) suspend fun navigateToRecruitMenu() { while (!inRecruitMenu()) { if (inRecruit()) recruit.cancelBtn.click() // can be safely clicked even if not present other.skipBtn.click() awaitTick() } } suspend fun completeRecruits() { navigateToRecruitMenu() for (btn in menu.completeBtns) { join(ClickInst(btn)) navigateToRecruitMenu() } } suspend fun navigateToRecruit(): Boolean { if (inRecruit()) return true navigateToRecruitMenu() for (area in menu.recruitAreas) { if (!area.matchesLabel(tick)) continue var i = 0 while (!inRecruit()) { if (i++ % 5 == 0) area.click() awaitTick() } return true } return false } override suspend fun run(): MyResult<String> { while (true) { awaitTick() if (inRecruitMenu()) completeRecruits() if (!navigateToRecruit()) // no recruit available return MyResult.Success("Recruit completed") join(RecruitPage(ui, analyzer)) awaitTick() navigateToRecruitMenu() } } } }
1
Kotlin
0
1
4c7ca55be02c08d1784bac57b3eff15decd07389
2,686
Arknights-Autoclicker
MIT License
app/src/main/java/com/example/toncontest/data/ton/transactions/CheckAddress.kt
L0mTiCk
625,185,980
false
null
package com.example.toncontest.data.ton.transactions import com.example.toncontest.data.main.send.sendInfo fun checkAddress(): Boolean { //TODO: check address in ton, check if dns if (sendInfo.recipient.length < 48 || sendInfo.recipient.contains(".ton")) { return false } else { return true } }
0
Kotlin
0
0
2115bf7c3bc4558a40d2ab9181b295940848df7b
332
TONContest
MIT License
linea/src/commonMain/kotlin/compose/icons/lineaicons/basic/Home.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineaicons.basic import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.lineaicons.BasicGroup public val BasicGroup.Home: ImageVector get() { if (_home != null) { return _home!! } _home = Builder(name = "Home", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 3.0f) lineToRelative(-30.0f, 30.0f) lineToRelative(9.0f, 0.0f) lineToRelative(0.0f, 30.0f) lineToRelative(12.0f, 0.0f) lineToRelative(0.0f, -16.0f) lineToRelative(16.0f, 0.0f) lineToRelative(0.0f, 16.0f) lineToRelative(12.0f, 0.0f) lineToRelative(0.0f, -30.0f) lineToRelative(11.0f, 0.0f) close() } } .build() return _home!! } private var _home: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
1,710
compose-icons
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Swords.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline 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.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.Swords: ImageVector get() { if (_swords != null) { return _swords!! } _swords = Builder(name = "Swords", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 3.0f) verticalLineToRelative(5.0f) lineToRelative(-11.0f, 9.0f) lineToRelative(-4.0f, 4.0f) lineToRelative(-3.0f, -3.0f) lineToRelative(4.0f, -4.0f) lineToRelative(9.0f, -11.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.0f, 13.0f) lineToRelative(6.0f, 6.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.32f, 17.32f) lineToRelative(3.68f, 3.68f) lineToRelative(3.0f, -3.0f) lineToRelative(-3.365f, -3.365f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.0f, 5.5f) lineToRelative(-2.0f, -2.5f) horizontalLineToRelative(-5.0f) verticalLineToRelative(5.0f) lineToRelative(3.0f, 2.5f) } } .build() return _swords!! } private var _swords: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,053
compose-icon-collections
MIT License
src/main/kotlin/dev/kotx/flylib/command/ConfigElement.kt
TeamKun
353,190,170
false
{"Kotlin": 162659, "Shell": 1295}
/* * Copyright (c) 2021 kotx__ */ package dev.kotx.flylib.command interface ConfigElement<T> { val key: String var value: T? }
0
Kotlin
0
7
89fe7c1560cd9a303b09bec98249fbc39d327d71
138
flylib-reloaded
MIT License
src/main/kotlin/romantointeger/Solution.kt
LuizGC
695,969,536
false
{"Kotlin": 3465}
package romantointeger class Solution { fun romanToInt(s: String): Int { var output = 0 var previous = 0 for (c in s) { val value = when(c) { 'I' -> 1 'V' -> 5 'X' -> 10 'L' -> 50 'C' -> 100 'D' -> 500 'M' -> 1000 else -> 0 } if (previous < value) { output -= previous } else { output += previous } previous = value } return output + previous } }
0
Kotlin
0
0
11f9b671733e587beb15957a344ecd8ece5a2e18
628
kotlin-leet-code-exercises
Apache License 2.0
urbanairship-core/src/main/java/com/urbanairship/contacts/SmsRegistrationOptions.kt
urbanairship
58,972,818
false
{"Kotlin": 3266979, "Java": 2582150, "Python": 10137, "Shell": 589}
/* Copyright Airship and Contributors */ package com.urbanairship.contacts import androidx.core.util.ObjectsCompat import com.urbanairship.json.JsonException import com.urbanairship.json.JsonMap import com.urbanairship.json.JsonSerializable import com.urbanairship.json.JsonValue /** * Sms registration options. */ public class SmsRegistrationOptions internal constructor( /** * Sender ID */ public val senderId: String ) : JsonSerializable { override fun toJsonValue(): JsonValue { return JsonMap.newBuilder().put(SENDER_ID_KEY, senderId).build().toJsonValue() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SmsRegistrationOptions return senderId == other.senderId } override fun hashCode(): Int = ObjectsCompat.hashCode(senderId) override fun toString(): String { return "SmsRegistrationOptions(senderId='$senderId')" } public companion object { private const val SENDER_ID_KEY = "sender_id" /** * Creates default options. * @param senderId The sender Id. * @return The sms options. */ @JvmStatic public fun options(senderId: String): SmsRegistrationOptions { return SmsRegistrationOptions(senderId) } @Throws(JsonException::class) internal fun fromJson(value: JsonValue): SmsRegistrationOptions { val senderId = value.optMap().opt(SENDER_ID_KEY).requireString() return SmsRegistrationOptions(senderId) } } }
2
Kotlin
122
111
21d49c3ffd373e3ba6b51a706a4839ab3713db11
1,650
android-library
Apache License 2.0
Core/src/commonTest/kotlin/io/nacular/doodle/utils/PathTests.kt
nacular
108,631,782
false
{"Kotlin": 2979553}
package io.nacular.doodle.utils import kotlin.js.JsName import kotlin.test.Test import kotlin.test.expect /** * Created by <NAME> on 7/18/20. */ class PathTests { @Test @JsName("topWorks") fun `top works`() { val paths = listOf( listOf(0, 0, 2, 5), listOf(0), listOf() ) paths.forEach { expect(it.firstOrNull()) { Path(it).top } } } @Test @JsName("bottomWorks") fun `bottom works`() { val paths = listOf( listOf(0, 0, 2, 5), listOf(0), listOf() ) paths.forEach { expect(it.lastOrNull()) { Path(it).bottom } } } @Test @JsName("parentWorks") fun `parent works`() { val paths = listOf( listOf(0, 0, 2, 5), listOf(0), listOf() ) paths.forEach { val parent =Path(it).parent if (it.isEmpty()) { expect(null) { parent } } else { expect(Path(it.dropLast(1))) { parent } } } } @Test @JsName("depthWorks") fun `depth works`() { val paths = listOf( listOf(0, 0, 2, 5), listOf(0), listOf() ) paths.forEach { expect(it.size) { Path(it).depth } } } @Test @JsName("overlappingRootWorks") fun `overlapping root works`() { data class Inputs<T>(val first: List<T>, val second: List<T>, val expect: List<T>) val paths = listOf( Inputs(listOf(0, 1), listOf(0, 1, 2, 3, 4, 5), expect = listOf(0, 1)), Inputs(listOf(0, 1, 9, 8), listOf(0, 1, 2, 3, 4, 5), expect = listOf(0, 1)) ) paths.forEach { expect(Path(it.expect)) { Path(it.second).overlappingRoot(Path(it.first )) } expect(Path(it.expect)) { Path(it.first ).overlappingRoot(Path(it.second)) } } } @Test @JsName("nonOverlappingStemWorks") fun `non-overlapping stem works`() { data class Inputs<T>(val first: List<T>, val second: List<T>, val expect: List<T>) val paths = listOf( Inputs(listOf(0, 1), listOf(0, 1, 2, 3, 4, 5), expect = listOf(2, 3, 4, 5)), Inputs(listOf(0, 1, 9, 8), listOf(0, 1, 2, 3, 4, 5), expect = listOf(2, 3, 4, 5)) ) paths.forEach { expect(it.expect) { Path(it.second).nonOverlappingStem(Path(it.first )) } } } @Test @JsName("rootIsAncestorToAll") fun `root is always ancestor`() { val paths = listOf( listOf(0, 0, 2, 5), listOf(0) ) paths.forEach { expect(true) { Path<Int>() ancestorOf Path(it) } } } }
5
Kotlin
19
523
d48ba7fc8c0a8cd0c5bfb24b22286676bc26319e
2,861
doodle
MIT License
java/com/tdi/tmaps/model/MyLocation.kt
DigitalRealm2282
534,740,468
false
{"Kotlin": 372930}
package com.tdi.tmaps.model import androidx.annotation.Keep @Keep class MyLocation { var accuracy: Int = 0 var altitude: Int = 0 var bearing: Int = 0 var bearingAccuracyDegrees: Int = 0 var speed: Int = 0 var speedAccuracyMetersPerSecond: Int = 0 var verticalAccuracyMeters: Int = 0 var isComplete: Boolean = false var isFromMockProvider: Boolean = false var provider: String? = null var time: Long = 0 var elapsedRealtimeNanos: Long = 0 var latitude: Double = 0.toDouble() var longitude: Double = 0.toDouble() }
0
Kotlin
0
0
51df7362986a48dfb1e4b592a56cf8e0e726500f
570
TMaps
MIT License