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
service/src/test/java/fr/nihilus/music/service/actions/DeleteActionTest.kt
ismailghedamsi
322,889,723
true
{"Kotlin": 987508, "Prolog": 57}
/* * Copyright 2019 Thibault Seisel * * 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 fr.nihilus.music.service.actions import android.Manifest import android.os.Bundle import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import fr.nihilus.music.core.media.CustomActions import fr.nihilus.music.core.media.MediaId import fr.nihilus.music.core.media.MediaId.Builder.CATEGORY_ALL import fr.nihilus.music.core.media.MediaId.Builder.CATEGORY_MOST_RATED import fr.nihilus.music.core.media.MediaId.Builder.CATEGORY_RECENTLY_ADDED import fr.nihilus.music.core.media.MediaId.Builder.TYPE_ALBUMS import fr.nihilus.music.core.media.MediaId.Builder.TYPE_ARTISTS import fr.nihilus.music.core.media.MediaId.Builder.TYPE_PLAYLISTS import fr.nihilus.music.core.media.MediaId.Builder.TYPE_ROOT import fr.nihilus.music.core.media.MediaId.Builder.TYPE_TRACKS import fr.nihilus.music.core.media.MediaId.Builder.encode import fr.nihilus.music.core.os.PermissionDeniedException import fr.nihilus.music.media.repo.MediaRepository import io.kotlintest.shouldThrow import io.mockk.* import io.mockk.impl.annotations.MockK import kotlinx.coroutines.test.runBlockingTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.truth.os.BundleSubject.assertThat as assertThatBundle @RunWith(AndroidJUnit4::class) internal class DeleteActionTest { @MockK private lateinit var repository: MediaRepository @Before fun setUp() = MockKAnnotations.init(this) @Test fun whenReadingName_thenReturnActionDeleteMediaConstant() { val action = DeleteAction(repository) assertThat(action.name).isEqualTo(CustomActions.ACTION_DELETE_MEDIA) } @Test fun givenNoParameters_whenExecuting_thenFailWithMissingParameter() = runBlockingTest { val action = DeleteAction(repository) val failure = shouldThrow<ActionFailure> { action.execute(Bundle.EMPTY) } assertThat(failure.errorCode).isEqualTo(CustomActions.ERROR_CODE_PARAMETER) assertThat(failure.errorMessage).contains(CustomActions.EXTRA_MEDIA_IDS) } private suspend fun assertUnsupported(mediaId: MediaId) { val action = DeleteAction(repository) val failure = shouldThrow<ActionFailure> { action.execute(Bundle(1).apply { putStringArray(CustomActions.EXTRA_MEDIA_IDS, arrayOf(mediaId.encoded)) }) } assertThat(failure.errorCode).isEqualTo(CustomActions.ERROR_CODE_UNSUPPORTED_MEDIA_ID) } @Test fun givenDeniedPermissionAndTracks_whenExecuting_thenFailWithDeniedPermission() = runBlockingTest { coEvery { repository.deleteTracks(any()) } throws PermissionDeniedException(Manifest.permission.WRITE_EXTERNAL_STORAGE) val action = DeleteAction(repository) val failure = shouldThrow<ActionFailure> { action.execute(Bundle(1).apply { putStringArray(CustomActions.EXTRA_MEDIA_IDS, arrayOf( encode(TYPE_TRACKS, CATEGORY_ALL, 42) )) }) } assertThat(failure.errorCode).isEqualTo(CustomActions.ERROR_CODE_PERMISSION_DENIED) assertThat(failure.errorMessage).isEqualTo(Manifest.permission.WRITE_EXTERNAL_STORAGE) } @Test fun givenInvalidMediaIds_whenExecuting_thenFailWithUnsupportedParameter() = runBlockingTest { assertUnsupported(MediaId(TYPE_ROOT)) assertUnsupported(MediaId(TYPE_TRACKS)) assertUnsupported(MediaId(TYPE_ALBUMS)) assertUnsupported(MediaId(TYPE_ARTISTS)) assertUnsupported(MediaId(TYPE_PLAYLISTS)) assertUnsupported(MediaId(TYPE_TRACKS, CATEGORY_ALL)) assertUnsupported(MediaId(TYPE_ALBUMS, "54")) assertUnsupported(MediaId(TYPE_ARTISTS, "13")) assertUnsupported(MediaId(TYPE_TRACKS, CATEGORY_MOST_RATED)) assertUnsupported(MediaId(TYPE_TRACKS, CATEGORY_RECENTLY_ADDED)) } @Test fun givenExistingTrackMediaIds_whenExecuting_thenDeleteThoseTracks() = runBlockingTest { val deletedMediaIds = arrayOf( encode(TYPE_TRACKS, CATEGORY_ALL, 16L), encode(TYPE_TRACKS, CATEGORY_ALL, 42L) ) coEvery { repository.deleteTracks(any()) } returns 2 val action = DeleteAction(repository) action.execute(Bundle(1).apply { putStringArray(CustomActions.EXTRA_MEDIA_IDS, deletedMediaIds) }) coVerify { repository.deleteTracks(longArrayOf(16L, 42L)) } } @Test fun givenExistingPlaylistIds_whenExecuting_thenDeleteThosePlaylists() = runBlockingTest { coEvery { repository.deletePlaylist(any()) } just Runs val deletedMediaIds = arrayOf( encode(TYPE_PLAYLISTS, "1"), encode(TYPE_PLAYLISTS, "2") ) val action = DeleteAction(repository) action.execute(Bundle(1).apply { putStringArray(CustomActions.EXTRA_MEDIA_IDS, deletedMediaIds) }) coVerifyAll { repository.deletePlaylist(1L) repository.deletePlaylist(2L) } } @Test fun givenExistingTrackIds_whenExecuting_thenReturnTheNumberOfDeletedTracks() = runBlockingTest { val deletedMediaIds = arrayOf( encode(TYPE_TRACKS, CATEGORY_ALL, 16L), encode(TYPE_TRACKS, CATEGORY_ALL, 42L) ) coEvery { repository.deleteTracks(any()) } returns 2 val action = DeleteAction(repository) val result = action.execute(Bundle(1).apply { putStringArray(CustomActions.EXTRA_MEDIA_IDS, deletedMediaIds) }) assertThat(result).isNotNull() assertThatBundle(result).integer(CustomActions.RESULT_TRACK_COUNT).isEqualTo(2) } }
0
null
0
0
6ae2682be14bb1914ec1ffd3ba07db8b3f1f81c3
6,342
android-odeon
Apache License 2.0
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/visitors/PackageCountVisitor.kt
anna-yn
98,596,998
true
{"Kotlin": 355738, "Groovy": 1433, "Java": 163}
package io.gitlab.arturbosch.detekt.core.visitors import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.core.NUMBER_OF_PACKAGES_KEY import org.jetbrains.kotlin.psi.KtFile class PackageCountVisitor : DetektVisitor() { private val packageNames: MutableSet<String> = HashSet<String>() override fun visitKtFile(file: KtFile) { packageNames.add(file.packageFqNameByTree.toString()) file.putUserData(NUMBER_OF_PACKAGES_KEY, packageNames.size) } }
0
Kotlin
0
0
bcc691883e3c287efafb780534d1bc89ba3ef625
486
detekt
Apache License 2.0
library/src/main/java/io/appwrite/services/Storage.kt
abnegate
438,607,298
false
{"Kotlin": 192641}
package io.appwrite.services import android.net.Uri import io.appwrite.Client import io.appwrite.models.* import io.appwrite.exceptions.AppwriteException import okhttp3.Cookie import okhttp3.Response import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import java.io.File class Storage(client: Client) : Service(client) { /** * List Files * * Get a list of all the user files. You can use the query params to filter * your results. On admin mode, this endpoint will return a list of all of the * project's files. [Learn more about different API modes](/docs/admin). * * @param search Search term to filter your list results. Max length: 256 chars. * @param limit Results limit value. By default will return maximum 25 results. Maximum of 100 results allowed per request. * @param offset Results offset. The default value is 0. Use this param to manage pagination. * @param cursor ID of the file used as the starting point for the query, excluding the file itself. Should be used for efficient pagination when working with large sets of data. * @param cursorDirection Direction of the cursor. * @param orderType Order result by ASC or DESC order. * @return [io.appwrite.models.FileList] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun listFiles( search: String? = null, limit: Long? = null, offset: Long? = null, cursor: String? = null, cursorDirection: String? = null, orderType: String? = null ): io.appwrite.models.FileList { val path = "/storage/files" val params = mapOf<String, Any?>( "search" to search, "limit" to limit, "offset" to offset, "cursor" to cursor, "cursorDirection" to cursorDirection, "orderType" to orderType ) val headers = mapOf( "content-type" to "application/json" ) val convert: (Map<String, Any>) -> io.appwrite.models.FileList = { io.appwrite.models.FileList.from(map = it) } return client.call( "GET", path, headers, params, responseType = io.appwrite.models.FileList::class.java, convert = convert ) } /** * Create File * * Create a new file. The user who creates the file will automatically be * assigned to read and write access unless he has passed custom values for * read and write arguments. * * @param fileId Unique Id. Choose your own unique ID or pass the string `unique()` to auto generate it. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can&#039;t start with a special char. Max length is 36 chars. * @param file Binary file. * @param read An array of strings with read permissions. By default only the current user is granted with read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions. * @param write An array of strings with write permissions. By default only the current user is granted with write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions. * @return [io.appwrite.models.File] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun createFile( fileId: String, file: File, read: List<Any>? = null, write: List<Any>? = null ): io.appwrite.models.File { val path = "/storage/files" val params = mapOf<String, Any?>( "fileId" to fileId, "file" to file, "read" to read, "write" to write ) val headers = mapOf( "content-type" to "multipart/form-data" ) val convert: (Map<String, Any>) -> io.appwrite.models.File = { io.appwrite.models.File.from(map = it) } return client.call( "POST", path, headers, params, responseType = io.appwrite.models.File::class.java, convert = convert ) } /** * Get File * * Get a file by its unique ID. This endpoint response returns a JSON object * with the file metadata. * * @param fileId File unique ID. * @return [io.appwrite.models.File] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun getFile( fileId: String ): io.appwrite.models.File { val path = "/storage/files/{fileId}".replace("{fileId}", fileId) val params = mapOf<String, Any?>( ) val headers = mapOf( "content-type" to "application/json" ) val convert: (Map<String, Any>) -> io.appwrite.models.File = { io.appwrite.models.File.from(map = it) } return client.call( "GET", path, headers, params, responseType = io.appwrite.models.File::class.java, convert = convert ) } /** * Update File * * Update a file by its unique ID. Only users with write permissions have * access to update this resource. * * @param fileId File unique ID. * @param read An array of strings with read permissions. By default no user is granted with any read permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions. * @param write An array of strings with write permissions. By default no user is granted with any write permissions. [learn more about permissions](/docs/permissions) and get a full list of available permissions. * @return [io.appwrite.models.File] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun updateFile( fileId: String, read: List<Any>, write: List<Any> ): io.appwrite.models.File { val path = "/storage/files/{fileId}".replace("{fileId}", fileId) val params = mapOf<String, Any?>( "read" to read, "write" to write ) val headers = mapOf( "content-type" to "application/json" ) val convert: (Map<String, Any>) -> io.appwrite.models.File = { io.appwrite.models.File.from(map = it) } return client.call( "PUT", path, headers, params, responseType = io.appwrite.models.File::class.java, convert = convert ) } /** * Delete File * * Delete a file by its unique ID. Only users with write permissions have * access to delete this resource. * * @param fileId File unique ID. * @return [Any] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun deleteFile( fileId: String ): Any { val path = "/storage/files/{fileId}".replace("{fileId}", fileId) val params = mapOf<String, Any?>( ) val headers = mapOf( "content-type" to "application/json" ) return client.call( "DELETE", path, headers, params, responseType = Any::class.java, ) } /** * Get File for Download * * Get a file content by its unique ID. The endpoint response return with a * 'Content-Disposition: attachment' header that tells the browser to start * downloading the file to user downloads directory. * * @param fileId File unique ID. * @return [ByteArray] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun getFileDownload( fileId: String ): ByteArray { val path = "/storage/files/{fileId}/download".replace("{fileId}", fileId) val params = mapOf<String, Any?>( "project" to client.config["project"] ) return client.call( "GET", path, params = params, responseType = ByteArray::class.java ) } /** * Get File Preview * * Get a file preview image. Currently, this method supports preview for image * files (jpg, png, and gif), other supported formats, like pdf, docs, slides, * and spreadsheets, will return the file icon image. You can also pass query * string arguments for cutting and resizing your preview image. * * @param fileId File unique ID * @param width Resize preview image width, Pass an integer between 0 to 4000. * @param height Resize preview image height, Pass an integer between 0 to 4000. * @param gravity Image crop gravity. Can be one of center,top-left,top,top-right,left,right,bottom-left,bottom,bottom-right * @param quality Preview image quality. Pass an integer between 0 to 100. Defaults to 100. * @param borderWidth Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0. * @param borderColor Preview image border color. Use a valid HEX color, no # is needed for prefix. * @param borderRadius Preview image border radius in pixels. Pass an integer between 0 to 4000. * @param opacity Preview image opacity. Only works with images having an alpha channel (like png). Pass a number between 0 to 1. * @param rotation Preview image rotation in degrees. Pass an integer between 0 and 360. * @param background Preview image background color. Only works with transparent images (png). Use a valid HEX color, no # is needed for prefix. * @param output Output format type (jpeg, jpg, png, gif and webp). * @return [ByteArray] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun getFilePreview( fileId: String, width: Long? = null, height: Long? = null, gravity: String? = null, quality: Long? = null, borderWidth: Long? = null, borderColor: String? = null, borderRadius: Long? = null, opacity: Double? = null, rotation: Long? = null, background: String? = null, output: String? = null ): ByteArray { val path = "/storage/files/{fileId}/preview".replace("{fileId}", fileId) val params = mapOf<String, Any?>( "width" to width, "height" to height, "gravity" to gravity, "quality" to quality, "borderWidth" to borderWidth, "borderColor" to borderColor, "borderRadius" to borderRadius, "opacity" to opacity, "rotation" to rotation, "background" to background, "output" to output, "project" to client.config["project"] ) return client.call( "GET", path, params = params, responseType = ByteArray::class.java ) } /** * Get File for View * * Get a file content by its unique ID. This endpoint is similar to the * download method but returns with no 'Content-Disposition: attachment' * header. * * @param fileId File unique ID. * @return [ByteArray] */ @JvmOverloads @Throws(AppwriteException::class) suspend fun getFileView( fileId: String ): ByteArray { val path = "/storage/files/{fileId}/view".replace("{fileId}", fileId) val params = mapOf<String, Any?>( "project" to client.config["project"] ) return client.call( "GET", path, params = params, responseType = ByteArray::class.java ) } }
0
Kotlin
0
1
c61b6dcf38fb58b9ba8805e52f6f78737dc8cb90
11,639
appwrite-videoreel
MIT License
androidApp/src/main/java/com/example/oradore/android/Theme.kt
AnleAnja
528,355,714
false
null
package com.example.oradore.android import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import com.example.oradore.color.Color private val DarkColorPalette = darkColors( primary = Color.primary.hex.color, primaryVariant = Color.ternary.hex.color, secondary = Color.secondary.hex.color ) private val LightColorPalette = lightColors( primary = Color.primary.hex.color, primaryVariant = Color.ternary.hex.color, secondary = Color.secondary.hex.color ) @Composable fun OradoreTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, content = content, ) } val String.color get() = androidx.compose.ui.graphics.Color(android.graphics.Color.parseColor(this))
6
Kotlin
0
3
008d80b3482154ecec651dee3fea396777c64e9b
1,068
oradore
MIT License
src/test/kotlin/no/skatteetaten/aurora/clerk/service/PodServiceTest.kt
Skatteetaten
173,108,440
false
null
package no.skatteetaten.aurora.clerk.service import assertk.assertThat import assertk.assertions.isEmpty import assertk.assertions.isEqualTo import com.fkorotkov.kubernetes.metadata import com.fkorotkov.kubernetes.newPod import com.fkorotkov.kubernetes.newPodList import com.fkorotkov.kubernetes.status import io.fabric8.kubernetes.api.model.Pod import java.time.Instant import no.skatteetaten.aurora.clerk.controller.PodItem import org.junit.jupiter.api.Test class PodServiceTest : AbstractOpenShiftServerTest() { val namespace = "jedi-test" val podService = PodService(openShiftClient) @Test fun `fetch a single pod`() { withPods(createPod("yoda")) { assertThat(it.count()).isEqualTo(1) val pod = it.first() assertThat(pod.name).isEqualTo("yoda-1") assertThat(pod.applicationName).isEqualTo("yoda") assertThat(pod.status).isEqualTo("Running") assertThat(pod.startTime).isEqualTo(Instant.EPOCH.toString()) } } @Test fun `should ignore build pods when fetching pods`() { withPods(createPod("yoda", podLabel = mapOf(buildPodLabel to "foo"))) { assertThat(it).isEmpty() } } @Test fun `should ignore deploy pods when fetching pods`() { withPods(createPod("yoda", podLabel = mapOf(deployPodLabel to "foo"))) { assertThat(it).isEmpty() } } fun withPods(vararg pod: Pod, name: String? = null, fn: (List<PodItem>) -> Unit) { val podList = newPodList { items = pod.toList() } openShiftMock { rule { podList.toJsonBody() } } val result = podService.getPodItems(namespace, name) fn(result) } } fun createPod( appName: String, instance: String = "1", podLabel: Map<String, String> = mapOf("app" to appName), podPhase: String = "Running" ): Pod { return newPod { metadata { name = "$appName-$instance" labels = podLabel } status { phase = podPhase startTime = Instant.EPOCH.toString() } } }
0
Kotlin
2
1
47501423881da9c39dcef000f23748ff30153e69
2,188
clerk
Apache License 2.0
src/mobile/android/kt/src/app/src/main/java/org/bigsbyspot/tic_tac_toe/Player.kt
Bigsby
130,376,391
false
{"C#": 26401, "JavaScript": 24544, "Kotlin": 9062, "CSS": 1804, "HTML": 1402, "Python": 946, "Batchfile": 256, "C": 245, "F#": 88, "Shell": 82}
package org.bigsbyspot.tic_tac_toe data class Player(val letter: String, val color: Int) { }
0
C#
0
2
785fea33164e48e294a81c6c34d8cf1a94e853bd
93
tic-tac-toe
The Unlicense
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/typeReference/annotationNotQualifierWithTypeArgs.kt
JetBrains
2,489,216
false
null
// "Create annotation 'A'" "false" // ERROR: Unresolved reference: A package p internal fun foo(): <caret>A<Int, String> = throw Throwable("")
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
143
intellij-community
Apache License 2.0
2015/kt/src/test/kotlin/org/adventofcode/Day13Test.kt
windmaomao
225,344,109
false
{"JavaScript": 538717, "Ruby": 89779, "Kotlin": 58408, "Rust": 21350, "Go": 19106, "TypeScript": 9930, "Haskell": 8908, "Dhall": 3201, "PureScript": 1488, "HTML": 1307, "CSS": 1092}
package org.adventofcode import org.junit.Assert.assertEquals import org.junit.Test class Day13Test { private val d: Day13 = Day13() val lines = parseFile("13") @Test fun day13ExtractSitting() { assertEquals( Triple("Alice", "Bob", -57), d.extractSitting("Alice would lose 57 happiness units by sitting next to Bob.") ) assertEquals( Triple("Alice", "Eric", 71), d.extractSitting("Alice would gain 71 happiness units by sitting next to Eric.") ) } @Test fun day13Part1Example() { assertEquals( 330, d.part1(listOf( "Alice would gain 54 happiness units by sitting next to Bob.", "Alice would lose 79 happiness units by sitting next to Carol.", "Alice would lose 2 happiness units by sitting next to David.", "Bob would gain 83 happiness units by sitting next to Alice.", "Bob would lose 7 happiness units by sitting next to Carol.", "Bob would lose 63 happiness units by sitting next to David.", "Carol would lose 62 happiness units by sitting next to Alice.", "Carol would gain 60 happiness units by sitting next to Bob.", "Carol would gain 55 happiness units by sitting next to David.", "David would gain 46 happiness units by sitting next to Alice.", "David would lose 7 happiness units by sitting next to Bob.", "David would gain 41 happiness units by sitting next to Carol." )) ) } @Test fun day13Part1() { assertEquals(618, d.part1(lines)) } @Test fun day12Part2() { assertEquals(601, d.part2(lines)) } }
5
JavaScript
0
0
1d64d7fffa6fcfc6825e6aa9322eda76e790700f
1,614
adventofcode
MIT License
app/src/main/java/com/example/trackme/sensor/SensorSubscriber.kt
unitatem
306,978,983
false
null
package com.example.trackme.sensor abstract class SensorSubscriber { abstract fun update(data: AccelerometerMeasure) }
0
Kotlin
0
0
6f82450f5aae391f989a99c198d8cca5d99adf59
124
track_me
MIT License
library/src/test/kotlin/com/cesarferreira/tempo/StringExtensionsTest.kt
cesarferreira
191,353,694
false
null
package com.cesarferreira.tempo import org.junit.Test class StringExtensionsTest { @Test fun toDate() { assertEquals( expected = Tempo.with(year = 1987, month = 6, day = 2, hour = 0, minute = 0, second = 0), actual = "1987-06-02".toDate("yyyy-MM-dd") ) } }
0
Kotlin
4
39
2d3c1ccc86aafea3b8191a805db1d64c1674b400
312
tempo
Apache License 2.0
core/src/main/java/com/kylecorry/andromeda/core/system/Screen.kt
kylecorry31
394,273,851
false
null
package com.kylecorry.andromeda.core.system import android.app.Activity import android.content.Context import android.os.Build import android.view.View import android.view.Window import android.view.WindowManager object Screen { fun setKeepScreenOn(window: Window, keepOn: Boolean) { if (keepOn) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } fun setBrightness(window: Window, brightness: Float) { val layoutParams = window.attributes layoutParams.screenBrightness = brightness.coerceIn(0f, 1f) window.attributes = layoutParams } fun resetBrightness(window: Window) { val layoutParams = window.attributes layoutParams.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE window.attributes = layoutParams } fun setAllowScreenshots(window: Window, allowed: Boolean) { if (allowed) { window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) } else { window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) } } fun heightCm(view: View): Float { return heightIn(view) * 2.54f } fun heightIn(view: View): Float { val dpi = ydpi(view.context) return view.height / dpi } fun widthCm(view: View): Float { return widthIn(view) * 2.54f } fun widthIn(view: View): Float { val dpi = xdpi(view.context) return view.width / dpi } fun dpi(context: Context): Float { return context.resources.displayMetrics.densityDpi.toFloat() } fun ydpi(context: Context): Float { return context.resources.displayMetrics.ydpi } fun xdpi(context: Context): Float { return context.resources.displayMetrics.xdpi } fun density(context: Context): Float { return context.resources.displayMetrics.density } @Suppress("DEPRECATION") fun setShowWhenLocked(activity: Activity, showWhenLocked: Boolean){ when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1 -> { activity.setShowWhenLocked(showWhenLocked) } showWhenLocked -> { activity.window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED) } else -> { activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } } } }
22
Kotlin
0
6
e6541d527e74c8214f640a0b3907cd55fa730212
2,561
andromeda
MIT License
settings-core/src/main/java/com/michaelflisar/settings/core/Extension.kt
MFlisar
256,263,996
false
null
package com.michaelflisar.settings.core import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.res.ColorStateList import android.text.Spannable import android.text.SpannableString import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.core.widget.ImageViewCompat import androidx.fragment.app.Fragment import com.michaelflisar.dialogs.base.MaterialDialogFragment import com.michaelflisar.settings.core.classes.DialogContext import com.michaelflisar.settings.core.classes.SettingsColor import com.michaelflisar.settings.core.classes.SettingsIcon import com.michaelflisar.text.Text fun Text.get() = this.get(SettingsManager.context) fun Int.asSettingsIcon() = SettingsIcon(this) fun Int.asSettingsColor() = SettingsColor.Color(this) fun Int.asSettingsColorRes() = SettingsColor.ColorRes(this) internal fun View.enableRecursively(enabled: Boolean) { isEnabled = enabled if (this is ViewGroup) { for (i in 0 until childCount) { getChildAt(i).enableRecursively(enabled) } } } internal fun View.animateVisibility(target: Int) { animate().cancel() val targetValue = if (target == View.VISIBLE) 1f else 0f if (alpha == targetValue) { visibility = target return } animate() .alpha(alpha) .setListener(object: AnimatorListenerAdapter() { override fun onAnimationEnd(p0: Animator?) { visibility = target } }) .start() } internal fun ImageView.tint(color: Int, tintingEnabled: Boolean = true) { val csl = if (tintingEnabled) ColorStateList.valueOf(color) else null ImageViewCompat.setImageTintList(this, csl) } internal fun View.setSelectableBackground(borderless: Boolean, enabled: Boolean) { if (enabled) { with(TypedValue()) { context.theme.resolveAttribute(if (borderless) R.attr.selectableItemBackgroundBorderless else R.attr.selectableItemBackground, this, true) setBackgroundResource(resourceId) } } else { background = null } } fun MaterialDialogFragment<*>.show(context: DialogContext) { context.show(this) } val Fragment.parentDialogContext: DialogContext get() = DialogContext.getParentContext(this) internal fun Context.getActivity(): AppCompatActivity? { if (this is ContextWrapper) { return if (this is AppCompatActivity) { this } else { baseContext.getActivity() } } return null }
0
Kotlin
0
2
5fc5264a9b2bfc108aab03e8925244d665c6a9d4
2,877
Settings
Apache License 2.0
app/src/main/java/com/kshitijpatil/elementaryeditor/ui/edit/ExportProgressDialog.kt
Kshitij09
427,469,641
false
null
package com.kshitijpatil.elementaryeditor.ui.edit import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.work.WorkInfo import androidx.work.WorkManager import com.bumptech.glide.Glide import com.kshitijpatil.elementaryeditor.R import com.kshitijpatil.elementaryeditor.databinding.DialogExportProgressBinding import com.kshitijpatil.elementaryeditor.util.viewLifecycleScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.* class ExportProgressDialog( private val editRequestId: UUID, private val saveWorkerId: UUID ) : DialogFragment(R.layout.dialog_export_progress) { private var _binding: DialogExportProgressBinding? = null private val binding get() = _binding!! private val workManager by lazy { WorkManager.getInstance(requireContext()) } private var exportSucceeded = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = DialogExportProgressBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) isCancelable = false updateUiForEditWorkState() updateUiForSaveImageWorkState() binding.btnCancel.setOnClickListener { workManager.cancelWorkById(editRequestId) workManager.cancelWorkById(saveWorkerId) } } private fun updateUiForEditWorkState() { workManager.getWorkInfoByIdLiveData(editRequestId) .observe(viewLifecycleOwner) { workInfo -> binding.ivStatus.isVisible = workInfo.state == WorkInfo.State.FAILED when (workInfo.state) { WorkInfo.State.ENQUEUED, WorkInfo.State.RUNNING -> { binding.txtTitle.text = getString(R.string.progress_processing_image) } WorkInfo.State.SUCCEEDED -> { // wait save to finish before setting up success UI exportSucceeded = true } WorkInfo.State.FAILED -> { binding.txtTitle.text = getString(R.string.error_editing_failed) loadErrorImageView() delayedDismiss() } WorkInfo.State.CANCELLED -> { binding.txtTitle.text = getString(R.string.info_cancelled) delayedDismiss() } WorkInfo.State.BLOCKED -> { // keep showing progress indicator } } } } private fun delayedDismiss() { viewLifecycleScope.launch { delay(400) dismiss() } } private fun updateUiForSaveImageWorkState() { workManager.getWorkInfoByIdLiveData(saveWorkerId) .observe(viewLifecycleOwner) { workInfo -> binding.ivStatus.isVisible = workInfo.state == WorkInfo.State.SUCCEEDED || workInfo.state == WorkInfo.State.FAILED when (workInfo.state) { WorkInfo.State.ENQUEUED, WorkInfo.State.RUNNING -> { binding.txtTitle.text = getString(R.string.progress_saving) } WorkInfo.State.SUCCEEDED -> { if (exportSucceeded) { loadSuccessImageView() binding.txtTitle.text = getString(R.string.info_saved) } else { loadErrorImageView() binding.txtTitle.text = getString(R.string.error_editing_failed) } delayedDismiss() } WorkInfo.State.FAILED -> { binding.txtTitle.text = getString(R.string.error_exporting) loadErrorImageView() delayedDismiss() } WorkInfo.State.CANCELLED -> { binding.txtTitle.text = getString(R.string.info_cancelled) delayedDismiss() } WorkInfo.State.BLOCKED -> { // keep showing progress indicator } } } } private fun loadSuccessImageView() { Glide.with(requireContext()) .load(R.drawable.ic_rounded_check) .into(binding.ivStatus) binding.ivStatus.setColorFilter( ContextCompat.getColor( requireContext(), android.R.color.holo_green_dark ) ) } private fun loadErrorImageView() { Glide.with(requireContext()) .load(R.drawable.ic_filled_rounded_cancel) .into(binding.ivStatus) binding.ivStatus.setColorFilter( ContextCompat.getColor( requireContext(), android.R.color.holo_red_dark ) ) } override fun onDestroyView() { _binding = null super.onDestroyView() } }
4
Kotlin
0
0
67aa2f2cc0f60e9c64f6b9ad40e5a971f2fbe446
5,593
Elementary-Editor
Apache License 2.0
example/shared/src/commonMain/kotlin/com/splendo/kaluga/example/shared/model/scientific/converters/EnergyConverters.kt
splendo
191,371,940
false
{"Kotlin": 6494822, "Swift": 172024, "Shell": 1514}
/* Copyright 2023 Splendo Consulting B.V. The Netherlands 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.splendo.kaluga.example.shared.model.scientific.converters import com.splendo.kaluga.scientific.DefaultScientificValue import com.splendo.kaluga.scientific.PhysicalQuantity import com.splendo.kaluga.scientific.converter.energy.absorbedBy import com.splendo.kaluga.scientific.converter.energy.div import com.splendo.kaluga.scientific.converter.energy.equivalentDoseBy import com.splendo.kaluga.scientific.converter.energy.times import com.splendo.kaluga.scientific.unit.* val PhysicalQuantity.Energy.converters get() = listOf<QuantityConverter<PhysicalQuantity.Energy, *>>( QuantityConverterWithOperator( "Action from Time", QuantityConverter.WithOperator.Type.Multiplication, PhysicalQuantity.Time, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricAndImperialEnergy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) * DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Amount of Substance from Molar Energy", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.MolarEnergy, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Energy && rightUnit is MolarEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Area from Surface Tension", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.SurfaceTension, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is MetricSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is MetricSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is MetricSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is ImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is UKImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is USCustomarySurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is ImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is UKImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is USCustomarySurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomarySurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is MetricSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialSurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomarySurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is SurfaceTension -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Electric Charge from Voltage", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Voltage, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Abvolt -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Abvolt -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Voltage -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Electric Current from Magnetic Flux", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.MagneticFlux, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Maxwell -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Maxwell -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is MagneticFlux -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Force from Length", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Length, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Centimeter -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Centimeter -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is MetricLength -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is ImperialLength -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is ImperialLength -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialLength -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialLength -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Length -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Heat Capacity from Temperature", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Temperature, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricAndImperialEnergy && rightUnit is MetricAndUKImperialTemperature -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomaryTemperature -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is MetricAndUKImperialTemperature -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is MetricAndUKImperialTemperature -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomaryTemperature -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Temperature -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Ionizing Radiation Absorbed Dose from Weight", QuantityConverter.WithOperator.Type.Custom("absorbed by"), PhysicalQuantity.Weight, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Gram -> { DefaultScientificValue(leftValue, leftUnit) absorbedBy DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Gram -> { DefaultScientificValue(leftValue, leftUnit) absorbedBy DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Weight -> { DefaultScientificValue(leftValue, leftUnit) absorbedBy DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Ionizing Radiation Equivalent Dose from Weight", QuantityConverter.WithOperator.Type.Custom("equivalent dose by"), PhysicalQuantity.Weight, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Gram -> { DefaultScientificValue(leftValue, leftUnit) equivalentDoseBy DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Gram -> { DefaultScientificValue(leftValue, leftUnit) equivalentDoseBy DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Weight -> { DefaultScientificValue(leftValue, leftUnit) equivalentDoseBy DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Length from Force", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Force, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Dyne -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Erg && rightUnit is DyneMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Dyne -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is DyneMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is Poundal -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundForce && rightUnit is PoundForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is PoundForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is OunceForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomaryForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomaryForce -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Force -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Magnetic Flux from Electric Current", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.ElectricCurrent, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Abampere -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Abampere -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Erg && rightUnit is Biot -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Biot -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is ElectricCurrent -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Molar Energy from Amount of Substance", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.AmountOfSubstance, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricAndImperialEnergy && rightUnit is AmountOfSubstance -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is AmountOfSubstance -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is AmountOfSubstance -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is AmountOfSubstance -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Power from Time", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Time, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is WattHour && rightUnit is Hour -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is WattHourMultiple && rightUnit is Hour -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Joule && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is JouleMultiple && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Erg && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is Minute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundForce && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundForce && rightUnit is Minute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is Minute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is Minute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is BritishThermalUnit && rightUnit is Hour -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is BritishThermalUnit && rightUnit is Minute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is BritishThermalUnit && rightUnit is Second -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Time -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Pressure from Volume", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Volume, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is CubicCentimeter -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is CubicCentimeter -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is CubicFoot -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundForce && rightUnit is CubicFoot -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialVolume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialVolume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomaryVolume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialVolume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialVolume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomaryVolume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Volume -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Specific Energy from Weight", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Weight, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricAndImperialEnergy && rightUnit is MetricWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomaryWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is MetricWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomaryWeight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Weight -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Surface Tension from Area", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Area, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is SquareCentimeter -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is SquareCentimeter -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is SquareFoot -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is SquareInch -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is SquareInch -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialArea -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialArea -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Area -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Temperature from Heat Capacity", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.HeatCapacity, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricAndImperialEnergy && rightUnit is MetricAndUKImperialHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is MetricHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomaryHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is MetricHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is MetricAndUKImperialHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomaryHeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is HeatCapacity -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Time from Power", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Power, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is WattHour && rightUnit is Watt -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is WattHour && rightUnit is WattMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is WattHourMultiple && rightUnit is Watt -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is WattHourMultiple && rightUnit is Watt -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is HorsepowerHour && rightUnit is Horsepower -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundForce && rightUnit is FootPoundForcePerMinute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is InchPoundForcePerMinute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is BritishThermalUnit && rightUnit is BritishThermalUnitPerHour -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is BritishThermalUnit && rightUnit is BritishThermalUnitPerMinute -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Power -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Voltage from Electric Charge", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.ElectricCharge, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Abcoulomb -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Abcoulomb -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is ElectricCharge -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Volume from Pressure", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.Pressure, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Barye -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Erg && rightUnit is BaryeMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Barye -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is BaryeMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is FootPoundal && rightUnit is PoundSquareFoot -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchPoundForce && rightUnit is PoundSquareInch -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is InchOunceForce && rightUnit is PoundSquareInch -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialPressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialPressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomaryPressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialPressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialPressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomaryPressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is Pressure -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Weight from Ionizing Radiation Absorbed Dose", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.IonizingRadiationAbsorbedDose, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is Rad -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Erg && rightUnit is RadMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is Rad -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is RadMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is IonizingRadiationAbsorbedDose -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Weight from Ionizing Radiation Equivalent Dose", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.IonizingRadiationEquivalentDose, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is Erg && rightUnit is RoentgenEquivalentMan -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Erg && rightUnit is RoentgenEquivalentManMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is RoentgenEquivalentMan -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ErgMultiple && rightUnit is RoentgenEquivalentManMultiple -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is IonizingRadiationEquivalentDose -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, QuantityConverterWithOperator( "Weight from Specific Energy", QuantityConverter.WithOperator.Type.Division, PhysicalQuantity.SpecificEnergy, ) { (leftValue, leftUnit), (rightValue, rightUnit) -> when { leftUnit is MetricAndImperialEnergy && rightUnit is MetricSpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is ImperialSpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is UKImperialSpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricAndImperialEnergy && rightUnit is USCustomarySpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is MetricEnergy && rightUnit is MetricSpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is ImperialSpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is UKImperialSpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is ImperialEnergy && rightUnit is USCustomarySpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } leftUnit is Energy && rightUnit is SpecificEnergy -> { DefaultScientificValue(leftValue, leftUnit) / DefaultScientificValue(rightValue, rightUnit) } else -> throw RuntimeException("Unexpected units: $leftUnit, $rightUnit") } }, )
87
Kotlin
7
315
4094d5625a4cacb851b313d4e96bce6faac1c81f
43,436
kaluga
Apache License 2.0
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findFunctionUsages/functionUsedInPlainText.0.kt
ingokegel
72,937,917
true
null
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction // OPTIONS: textOccurrences // PSI_ELEMENT_AS_TITLE: "fun foo(Int, String): Unit" package test class Foo { fun <caret>foo(i: Int, s: String) { } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
216
intellij-community
Apache License 2.0
kommons-time/src/commonMain/kotlin/com/bkahlert/kommons/time/time.kt
bkahlert
323,048,013
false
{"Kotlin": 1649529, "JavaScript": 540}
package com.bkahlert.kommons.time import kotlinx.datetime.Clock import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.FixedOffsetTimeZone import kotlinx.datetime.Instant import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.UtcOffset import kotlinx.datetime.daysUntil import kotlinx.datetime.plus import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.todayIn import kotlin.time.Duration import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.DurationUnit.DAYS import kotlin.time.DurationUnit.HOURS import kotlin.time.DurationUnit.MINUTES import kotlin.time.DurationUnit.SECONDS /** * Returns a [Clock] with its [Clock.now] * using the specified [now]. */ public operator fun Clock.Companion.invoke(now: () -> Instant): Clock = object : Clock { override fun now(): Instant = now() } /** The current date and time. */ public val Now: Instant get() = Clock.System.now() /** The current date. */ public val Today: LocalDate get() = Clock.System.todayIn(TimeZone.currentSystemDefault()) /** The current date but 1 day in the past. */ public val Yesterday: LocalDate get() = Today - 1.days /** The current date but 1 day in the future. */ public val Tomorrow: LocalDate get() = Today + 1.days /** The passed seconds since 1970-01-01T00:00:00Z. */ public val Timestamp: Long get() = Now.toEpochMilliseconds() /** Returns this [Instant] formatted as a local date (e.g. May 15, 1984). */ public expect fun Instant.toLocalDateString(): String /** Returns a copy of this [LocalDate] with the whole days of the specified [duration] added. */ public operator fun LocalDate.plus(duration: Duration): LocalDate = plus(duration.inWholeDays, DateTimeUnit.DAY) /** Returns a copy of this [LocalDate] with the whole days of the specified [duration] subtracted. */ public operator fun LocalDate.minus(duration: Duration): LocalDate = plus(-duration) /** Returns the [Duration] between this and the specified [other]. */ public operator fun LocalDate.minus(other: LocalDate): Duration = other.daysUntil(this).days /** Returns this [LocalDate] formatted as a local date (e.g. May 15, 1984). */ public expect fun LocalDate.toLocalDateString(): String /** The hour of the month according to universal time. */ public val Instant.utcHours: Int get() = toLocalDateTime(FixedOffsetTimeZone(UtcOffset.ZERO)).hour /** The minutes of the month according to universal time. */ public val Instant.utcMinutes: Int get() = toLocalDateTime(FixedOffsetTimeZone(UtcOffset.ZERO)).minute private fun Duration.describeMoment(moment: String, descriptive: Boolean): String = when { isPositive() -> if (descriptive) "in $moment" else moment isNegative() -> if (descriptive) "$moment ago" else "-$moment" else -> moment } /** * Attempts to describe this duration like a human being would do, * for example "5m ago" instead of "367.232723s". * * Set [descriptive] to `false` to turn off the use of "ago" and "in". */ public fun Duration.toMomentString(descriptive: Boolean = true): String { val diff = this val absDiff = diff.absoluteValue return when { absDiff < .5.seconds -> "now" absDiff < 1.minutes -> describeMoment(absDiff.toString(SECONDS), descriptive) absDiff < 1.hours -> describeMoment(absDiff.toString(MINUTES), descriptive) absDiff < 6.hours -> describeMoment(buildString { val durationInHours = absDiff.inWholeHours.hours append(durationInHours.toString(HOURS)) append(" ") append((absDiff - durationInHours).toString(MINUTES)) }.removeSuffix(" 0m"), descriptive) absDiff < 23.5.hours -> describeMoment(absDiff.toString(HOURS), descriptive) absDiff < 1.days -> describeMoment("1d", descriptive) absDiff < 6.days -> describeMoment(buildString { val durationInDays = absDiff.inWholeDays.days append(durationInDays.toString(DAYS)) append(" ") append((absDiff - durationInDays).toString(HOURS)) }.removeSuffix(" 0h"), descriptive) absDiff < 30.days -> describeMoment(absDiff.toString(DAYS), descriptive) else -> (Now + diff).toLocalDateString() } } /** * Attempts to describe this date like a human being would do, * for example "28 days ago" instead of "2021-22-23T24-25-26Z". * * Set [descriptive] to `false` to turn off the use of "ago" and "in". */ public fun Instant.toMomentString(descriptive: Boolean = true): String { val diff = this - Now return diff.toMomentString(descriptive) } /** * Attempts to describe this date like a human being would do, * for example "28 days ago" instead of "2021-22-23". * * Set [descriptive] to `false` to turn off the use of "ago" and "in". */ public fun LocalDate.toMomentString(descriptive: Boolean = true): String { val diff = this - Today return when (diff.inWholeDays) { -1L -> "yesterday" 0L -> "today" +1L -> "tomorrow" else -> diff.toMomentString(descriptive) } }
5
Kotlin
0
18
747cb51cf6e6b729d574396a4938eabafbdac1fe
5,185
kommons
MIT License
app/src/main/java/com/vimal/margh/util/Utils.kt
vimalcvs
796,155,728
false
{"Kotlin": 42410}
@file:Suppress("DEPRECATION") package com.vimal.margh.util import android.app.DownloadManager import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Environment import android.provider.MediaStore import android.util.Log import android.widget.Toast 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.request.RequestListener import com.bumptech.glide.request.target.Target import java.io.ByteArrayOutputStream object Utils { fun getErrors(e: Exception?) { println("TAG :: " + Log.getStackTraceString(e)) } fun shareImage(context: Context, imageUrl: String?) { Glide.with(context) .asBitmap() .load(imageUrl) .diskCacheStrategy(DiskCacheStrategy.ALL) .listener(object : RequestListener<Bitmap> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Bitmap>, isFirstResource: Boolean ): Boolean { Toast.makeText(context, "Failed to load image for sharing", Toast.LENGTH_SHORT) .show() return false } override fun onResourceReady( resource: Bitmap, model: Any, target: Target<Bitmap>, dataSource: DataSource, isFirstResource: Boolean ): Boolean { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType("image/*") val bytes = ByteArrayOutputStream() resource.compress(Bitmap.CompressFormat.JPEG, 100, bytes) val path = MediaStore.Images.Media.insertImage( context.contentResolver, resource, "Image", null ) val uri = Uri.parse(path) shareIntent.putExtra(Intent.EXTRA_STREAM, uri) context.startActivity(Intent.createChooser(shareIntent, "Share Image")) return false } }) .submit() } fun downloadImage(context: Context, url: String?) { val request = DownloadManager.Request(Uri.parse(url)) request.setTitle("Image Download") request.setDescription("Downloading image...") request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image.jpg") val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager downloadManager.enqueue(request) } fun shareApp(context: Context) { val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType("text/plain") val shareBody = "Check out this awesome app!" + "https://play.google.com/store/apps/details?id=" + context.packageName val shareSubject = "Share App" shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject) shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody) context.startActivity(Intent.createChooser(shareIntent, "Share using")) } fun contactApp(context: Context) { val message = "Hello, this is a direct message from my app!" val uri = Uri.parse("smsto:" + "+918882683887") val intent = Intent(Intent.ACTION_SENDTO, uri) intent.putExtra(Intent.EXTRA_TEXT, message) intent.setPackage("com.whatsapp") context.startActivity(Intent.createChooser(intent, "")) } }
0
Kotlin
0
0
2990033c1cae7494ab4398c7093d1c8f0869c06d
3,964
Retrofit-Room-Multiplatform-KMP-Favorite-List
MIT License
apps/etterlatte-brev-api/src/main/kotlin/no/nav/etterlatte/brev/notat/PdfGeneratorKlient.kt
navikt
417,041,535
false
{"Kotlin": 6191088, "TypeScript": 1564281, "Handlebars": 27578, "Shell": 12214, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556}
package no.nav.etterlatte.brev.notat import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType import io.ktor.http.contentType import no.nav.etterlatte.brev.model.Slate import no.nav.etterlatte.libs.common.logging.CORRELATION_ID import no.nav.etterlatte.libs.common.logging.getCorrelationId import org.slf4j.LoggerFactory /** * Klient mot ey-pdfgen * Brukes i tilfeller hvor vi skal generere PDF-er som ikke er et brev. * Dette fordi Brevbakeren er veldig låst til "brev-format", derav navnet. * * @see: <a href="https://github.com/navikt/pensjon-etterlatte-felles/tree/main/apps/ey-pdfgen">ey-pdfgen</a> * * @see: <a href="https://github.com/navikt/pensjonsbrev">Pensjonsbrev - Brevbaker</a> **/ class PdfGeneratorKlient( private val klient: HttpClient, private val apiUrl: String, ) { private val logger = LoggerFactory.getLogger(this::class.java) suspend fun genererPdf(request: PdfGenRequest): ByteArray { logger.info("Genererer PDF med ey-pdfgen") return klient .post("$apiUrl/notat/tom_mal") { header(CORRELATION_ID, getCorrelationId()) contentType(ContentType.Application.Json) setBody(request) }.body() } } data class PdfGenRequest( val tittel: String, val payload: Slate, )
9
Kotlin
0
6
bfc4d2a6577eb204d0859288a180fa873a75a370
1,461
pensjon-etterlatte-saksbehandling
MIT License
sharedPaywall/src/commonMain/kotlin/apps/amo/paywall/extensions/ImageRes.kt
amomama
754,027,977
false
{"Kotlin": 149946, "Swift": 2049}
package apps.amo.paywall.extensions import androidx.compose.runtime.Composable import apps.amo.paywall.theme.LocalImageRes import org.jetbrains.compose.resources.DrawableResource import org.jetbrains.compose.resources.ExperimentalResourceApi @Composable @OptIn(ExperimentalResourceApi::class) fun String.getResId(): DrawableResource = when (this) { "background_image" -> LocalImageRes.current.backgroundImage "checkbox" -> LocalImageRes.current.checkbox "arrow_right" -> LocalImageRes.current.arrowRight "close" -> LocalImageRes.current.close else -> error("Unsupported image name: $this") }
0
Kotlin
0
0
4ab93a7aac020d6b07438305571a547a88a7bce4
614
AmoPaywallBuilder
Apache License 2.0
common/network-common/src/main/kotlin/com/sotti/watch/network/common/TmdbInterceptor.kt
Sottti
196,598,437
false
null
package com.sotti.watch.network.common import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.Request class TmdbInterceptor : Interceptor { private val apiKeyQueryParamName = "api_key" private val apiKeyQueryParamValue = "<KEY>" override fun intercept(chain: Interceptor.Chain) = chain.request().let { originalRequest -> chain.proceed( originalRequest .newBuilder() .url(addApiKeyQuery(originalRequest)) .build() ) } private fun addApiKeyQuery(request: Request): HttpUrl = request .url .newBuilder() .addQueryParameter(apiKeyQueryParamName, apiKeyQueryParamValue) .build() }
13
Kotlin
2
5
a26b41ff69d6ee1b13300d2fc454d6fbfbe5a360
777
Watch
MIT License
app/src/main/java/com/geekymusketeers/uncrack/presentation/intro/model/OnBoardingItem.kt
uncrack-vault
569,328,395
false
{"Kotlin": 306752, "Java": 23299}
package com.geekymusketeers.uncrack.presentation.intro.model import com.geekymusketeers.uncrack.R data class OnBoardingItem( val title: String, val text: String, val image: Int ) { companion object { // TODO: Need to fix the strings fun onboardingScreenItems() = listOf( OnBoardingItem( "Control your security", "Subtext", R.drawable.logo_uncrack ), OnBoardingItem( "Everything in a single click", "Subtext", R.drawable.logo_uncrack ), OnBoardingItem( "Safe & Secure with us", "Subtext", R.drawable.logo_uncrack ), ) } }
13
Kotlin
3
28
27fc9744a616b1fff17d346ff468691b1cc51189
784
android
MIT License
sdk-base/src/main/java/com/mapbox/maps/interactions/standard/generated/StandardBuildingsStateKey.kt
mapbox
330,365,289
false
{"Kotlin": 3982759, "Java": 98572, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2413, "CMake": 1201, "EJS": 1194}
// This file is generated. package com.mapbox.maps.interactions.standard.generated import com.mapbox.maps.MapboxDelicateApi import com.mapbox.maps.MapboxExperimental import com.mapbox.maps.interactions.FeatureStateKey /** * State keys for [StandardBuildingsState] that should be used in `removeFeatureState`. */ @MapboxExperimental class StandardBuildingsStateKey private constructor( key: String ) : FeatureStateKey<StandardBuildingsState>(key) { /** * Static states. */ companion object { /** * State key standing for "highlight" feature state. */ val HIGHLIGHT: StandardBuildingsStateKey = StandardBuildingsStateKey("highlight") /** * State key standing for "select" feature state. */ val SELECT: StandardBuildingsStateKey = StandardBuildingsStateKey("select") /** * Create custom [StandardBuildingsStateKey] from given [key]. * * Should not be used in most of the cases as this makes sense only when [StandardBuildingsState] * state was constructed with custom state keys / values. */ @MapboxDelicateApi fun create(key: String): StandardBuildingsStateKey = StandardBuildingsStateKey(key) } }
181
Kotlin
131
472
2700dcaf18e70d23a19fc35b479bff6a2d490475
1,191
mapbox-maps-android
Apache License 2.0
src/commonMain/kotlin/com/github/adriantodt/lin/bytecode/insn/BinarySubtractOperationInsn.kt
adriantodt
280,314,655
false
null
package com.github.adriantodt.lin.bytecode.insn import com.github.adriantodt.lin.bytecode.utils.writeU24 import okio.Buffer public object BinarySubtractOperationInsn : Insn() { override fun serializeTo(buffer: Buffer) { buffer.writeByte(Opcode.PARAMETERLESS.ordinal).writeU24(ParameterlessCode.BINARY_SUBTRACT.ordinal) } }
17
Kotlin
0
7
63f833f1522a07e7ef1f59b4714cd76e3b96b4a1
341
Lin
MIT License
app/src/main/kotlin/net/tlalka/fiszki/domain/services/StorageService.kt
jtlalka
52,197,843
false
null
package net.tlalka.fiszki.domain.services import net.tlalka.fiszki.core.annotations.SessionScope import net.tlalka.fiszki.model.helpers.StorageHelper import net.tlalka.fiszki.model.types.LanguageType import net.tlalka.fiszki.model.types.StorageType import javax.inject.Inject @SessionScope class StorageService @Inject constructor() { @Inject lateinit var storageHelper: StorageHelper var isWelcomeView: Boolean get() = storageHelper.getBoolean(StorageType.WELCOME_VIEW, true) set(visible) = storageHelper.setBoolean(StorageType.WELCOME_VIEW, visible) val language: LanguageType get() = storageHelper.getEnum(StorageType.LANGUAGE, DEFAULT_LANGUAGE) val translation: LanguageType get() = storageHelper.getEnum(StorageType.TRANSLATION, DEFAULT_TRANSLATION) fun set(storageType: StorageType, languageType: LanguageType) { storageHelper.setEnum(storageType, languageType) } companion object { private val DEFAULT_LANGUAGE = LanguageType.EN private val DEFAULT_TRANSLATION = LanguageType.PL } }
0
Kotlin
0
2
7e7c2aba5d9a1634a5b295319ec1bb5a4b5a7aa0
1,090
fiszki
MIT License
kotlin/simple-hexagonal/domain/src/main/kotlin/com/example/domain/advertisement/AdvertisementId.kt
Gummybearr
461,541,289
false
null
package com.example.domain.advertisement import com.example.domain.DistributedId data class AdvertisementId(val id: Long) { constructor() : this(DistributedId.nextId()) }
0
Kotlin
3
19
e627e0ac9b03aa38ad388b55603e87b44bbaeec0
177
random-kata
MIT License
ui-base/src/main/java/pl/kamilszustak/read/ui/base/binding/ViewDataBindingAdapter.kt
swistak7171
289,985,013
false
null
package pl.kamilszustak.read.ui.base.binding import android.view.View import androidx.databinding.BindingAdapter import pl.kamilszustak.read.ui.base.util.setGone import pl.kamilszustak.read.ui.base.util.setVisible object ViewDataBindingAdapter { private const val VISIBLE_IF_NOT_NULL_ATTRIBUTE: String = "visibleIfNotNull" private const val GONE_IF_NULL_OR_BLANK_ATTRIBUTE: String = "goneIfNullOrBlank" private const val VISIBLE_IF_ATTRIBUTE: String = "visibleIf" @BindingAdapter(VISIBLE_IF_NOT_NULL_ATTRIBUTE) @JvmStatic fun View.setVisibleIfNotNull(value: Any?) { if (value != null) { setVisible() } else { setGone() } } @BindingAdapter(GONE_IF_NULL_OR_BLANK_ATTRIBUTE) @JvmStatic fun View.setGoneIfNullOrBlank(value: String?) { if (value.isNullOrBlank()) { setGone() } else { setVisible() } } @BindingAdapter(VISIBLE_IF_ATTRIBUTE) @JvmStatic fun View.setVisibleIf(isVisible: Boolean?) { visibility = if (isVisible == true) { View.VISIBLE } else { View.GONE } } }
2
Kotlin
0
1
70d7be58042410bdb969035413b726126426e3d3
1,174
read
Apache License 2.0
shared/src/commonMain/kotlin/com/seiko/greenqrscanner/data/db/adapter/JsonColumnAdapter.kt
qdsfdhvh
650,389,325
false
{"Kotlin": 266749, "Ruby": 1100, "Swift": 628, "Shell": 228}
package com.seiko.greenqrscanner.data.db.adapter import app.cash.sqldelight.ColumnAdapter import com.seiko.greenqrscanner.util.decodeJson import com.seiko.greenqrscanner.util.encodeJson import kotlinx.serialization.KSerializer internal class JsonColumnAdapter<T : Any>( private val serializer: KSerializer<T> ) : ColumnAdapter<T, String> { override fun decode(databaseValue: String) = databaseValue.decodeJson(serializer) override fun encode(value: T) = value.encodeJson(serializer) }
12
Kotlin
0
3
65be33474fa91c635bd7236144b00231a404b0e2
500
green-qrscanner
Apache License 2.0
app/src/test/java/com/gojekgithub/trending/ui/model/MainViewModelTest.kt
anukalp
302,643,538
false
{"Kotlin": 100738}
package com.gojekgithub.trending.ui.model import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.gojekgithub.trending.CoroutinesTestRule import com.gojekgithub.trending.R import com.gojekgithub.trending.constants.FilterResponse import com.gojekgithub.trending.constants.NetworkResponse import com.gojekgithub.trending.constants.Status import com.gojekgithub.trending.data.model.GitRepositoryModel import com.gojekgithub.trending.data.repo.TrendingRepository import com.gojekgithub.trending.util.getOrAwaitValue import com.gojekgithub.trending.utils.NetworkHelper import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.runBlockingTest import org.hamcrest.CoreMatchers import org.hamcrest.MatcherAssert import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito import java.io.InputStreamReader class MainViewModelTest { private val trendingRepository = Mockito.mock(TrendingRepository::class.java) private val networkHelper = Mockito.mock(NetworkHelper::class.java) private lateinit var mainViewModel: MainViewModel private val gson = Gson() @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @ExperimentalCoroutinesApi @get:Rule val coroutinesTestRule = CoroutinesTestRule() @Test @Ignore("Network caching not required now") fun `test verify error state network disconnected`() = coroutinesTestRule.testDispatcher.runBlockingTest { Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(false) mainViewModel = MainViewModel(trendingRepository) val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat( resource!!.status, CoreMatchers.`is`(Status.Error) ) MatcherAssert.assertThat(resource.data, CoreMatchers.nullValue()) Mockito.verify(trendingRepository, Mockito.times(0)).getRepositories() } @Test fun `test verify loading state`() = coroutinesTestRule.testDispatcher.runBlockingTest { val reader: InputStreamReader = javaClass.classLoader.getResourceAsStream("api-response/repos-git.json").reader() val result: List<GitRepositoryModel> = gson.fromJson( reader, object : TypeToken<List<GitRepositoryModel?>?>() {}.type ) Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) val myFlow = flow { delay(2000) emit(NetworkResponse.Success(result)) } Mockito.`when`(trendingRepository.getRepositories()).thenReturn(myFlow) mainViewModel = MainViewModel(trendingRepository) val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource!!.status, CoreMatchers.`is`(Status.Loading)) MatcherAssert.assertThat(resource.data, CoreMatchers.nullValue()) myFlow.collect { val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource!!.status, CoreMatchers.`is`(Status.Success)) MatcherAssert.assertThat(resource.data, CoreMatchers.`is`(result)) Mockito.verify(trendingRepository, Mockito.times(1)).getRepositories() } } @Test fun `test verify network success`() = coroutinesTestRule.testDispatcher.runBlockingTest { val reader: InputStreamReader = javaClass.classLoader.getResourceAsStream("api-response/repos-git.json").reader() val result: List<GitRepositoryModel> = gson.fromJson( reader, object : TypeToken<List<GitRepositoryModel?>?>() {}.type ) Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) Mockito.`when`(trendingRepository.getRepositories()).thenReturn(flow { emit(NetworkResponse.Success(result)) }) mainViewModel = MainViewModel(trendingRepository) val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource!!.status, CoreMatchers.`is`(Status.Success)) MatcherAssert.assertThat(resource.data, CoreMatchers.`is`(result)) Mockito.verify(trendingRepository, Mockito.times(1)).getRepositories() } @Test fun `test verify network success and null body`() = coroutinesTestRule.testDispatcher.runBlockingTest { Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) Mockito.`when`(trendingRepository.getRepositories()).thenReturn(flow { emit(NetworkResponse.Success(null)) }) mainViewModel = MainViewModel(trendingRepository) val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource!!.status, CoreMatchers.`is`(Status.Success)) MatcherAssert.assertThat(resource.data, CoreMatchers.nullValue()) Mockito.verify(trendingRepository, Mockito.times(1)).getRepositories() } @Test fun `test verify repo throws exception`() = coroutinesTestRule.testDispatcher.runBlockingTest { Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) Mockito.`when`(trendingRepository.getRepositories()).thenReturn(flow { throw Exception("Error in repo!") }) mainViewModel = MainViewModel(trendingRepository) val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource!!.status, CoreMatchers.`is`(Status.Error)) MatcherAssert.assertThat(resource.data, CoreMatchers.nullValue()) MatcherAssert.assertThat( resource.message, CoreMatchers.`is`("java.lang.Exception: Error in repo!") ) Mockito.verify(trendingRepository, Mockito.times(1)).getRepositories() } @Test fun `test verify network error response`() = coroutinesTestRule.testDispatcher.runBlockingTest { Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) Mockito.`when`(trendingRepository.getRepositories()).thenReturn(flow { emit(NetworkResponse.Error(Exception("400 bad request"))) }) mainViewModel = MainViewModel(trendingRepository) val resource = mainViewModel.repos.value MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource!!.status, CoreMatchers.`is`(Status.Error)) MatcherAssert.assertThat(resource.data, CoreMatchers.nullValue()) MatcherAssert.assertThat( resource.message, CoreMatchers.`is`("java.lang.Exception: 400 bad request") ) Mockito.verify(trendingRepository, Mockito.times(1)).getRepositories() } @Test fun `test verify sort when not success`() = coroutinesTestRule.testDispatcher.runBlockingTest { Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) val testFlow = flow { emit(NetworkResponse.Error(Exception("400 bad request"))) } Mockito.`when`(trendingRepository.getRepositories()).thenReturn(testFlow) mainViewModel = MainViewModel(trendingRepository) testFlow.collect { mainViewModel.sortData(R.id.action_name) Mockito.verify(trendingRepository, Mockito.never()).filterRepos(anyInt(), any()) } } @Test fun `test verify sort when success`() = coroutinesTestRule.testDispatcher.runBlockingTest { val reader: InputStreamReader = javaClass.classLoader.getResourceAsStream("api-response/repos-git.json").reader() val result: List<GitRepositoryModel> = gson.fromJson( reader, object : TypeToken<List<GitRepositoryModel?>?>() {}.type ) Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true) val testFlow = flow { emit(NetworkResponse.Success(result)) } Mockito.`when`(trendingRepository.getRepositories()).thenReturn(testFlow) mainViewModel = MainViewModel(trendingRepository) val data = arrayListOf<GitRepositoryModel>() data.addAll(result) data.sortByDescending { repoModel -> repoModel.stars } Mockito.`when`( trendingRepository.filterRepos( R.id.action_name, mainViewModel.repos.value!!.data ) ).thenReturn( flow { emit(FilterResponse.Success(data)) }) mainViewModel.sortData(R.id.action_name) Mockito.verify(trendingRepository, Mockito.times(1)).filterRepos(anyInt(), any()) val resource = mainViewModel.repos.getOrAwaitValue() MatcherAssert.assertThat(mainViewModel.repos, CoreMatchers.notNullValue()) MatcherAssert.assertThat(resource.status, CoreMatchers.`is`(Status.Success)) MatcherAssert.assertThat(resource.data, CoreMatchers.`is`(data)) } }
0
Kotlin
0
0
93de746bdeb186d083e5a0dfc017d4f9400557dd
9,670
GojekGithubSample
MIT License
sample/src/main/kotlin/dev/inkremental/sample/YogaActivity.kt
inkremental
205,363,267
true
null
package dev.inkremental.sample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.facebook.soloader.SoLoader import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaFlexDirection import dev.inkremental.dsl.android.Size.MATCH import dev.inkremental.dsl.android.Size.WRAP import dev.inkremental.dsl.android.size import dev.inkremental.dsl.android.text import dev.inkremental.dsl.android.widget.* import dev.inkremental.dsl.yoga.yogaLayout import dev.inkremental.renderableContentView class YogaActivity : AppCompatActivity() { var reversed = false var flexWeight = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) SoLoader.init(this, false) renderableContentView { yogaLayout { size(MATCH, MATCH) flexDirection(if (reversed) YogaFlexDirection.COLUMN_REVERSE else YogaFlexDirection.COLUMN) yogaLayout { size(MATCH, 50.sizeDp) backgroundResource(R.drawable.children_background) flexDirection(YogaFlexDirection.ROW) alignItems(YogaAlign.CENTER) imageView { size(50.sizeDp, 50.sizeDp) imageResource(R.mipmap.ic_launcher) flex(1f) } textView { size(WRAP, WRAP) text(R.string.child_1_text) flex(flexWeight.toFloat()) } } yogaLayout { size(MATCH, 50.sizeDp) backgroundResource(R.drawable.children_background) flexDirection(YogaFlexDirection.ROW_REVERSE) alignItems(YogaAlign.FLEX_START) imageView { size(50.sizeDp, 50.sizeDp) imageResource(R.mipmap.ic_launcher) flex(0f) } textView { size(WRAP, WRAP) text(R.string.child_2_text) flex(1f) } } yogaLayout { size(MATCH, 50.sizeDp) backgroundResource(R.drawable.children_background) flexDirection(YogaFlexDirection.ROW_REVERSE) alignItems(YogaAlign.FLEX_START) imageView { size(50.sizeDp, 50.sizeDp) imageResource(R.mipmap.ic_launcher) flex(0f) marginRightPercent(30f) } textView { size(WRAP, WRAP) text(R.string.child_3_text) flex(1f) } } button { text("Reverse") onClick { reversed = !reversed flexWeight++ } } } } } }
20
Kotlin
5
58
6e6241a0e9ac80a1edd1f0e100ad6bf0c4f8175e
3,226
inkremental
MIT License
ObjectOrientedParadigm/Exercise-1/Document.kt
Johanx22x
674,064,501
false
{"Kotlin": 19851, "Go": 18444, "F#": 13580, "Prolog": 4760, "Rust": 4512, "Makefile": 822}
class Document(name: String, vararg sheets: Sheet) { private var name: String = name get() = field set(value) { field = value } private var sheets: MutableList<Sheet> = sheets.toMutableList() get() = field set(value) { field = value } fun draw() { println("Document: $name") for (sheet in sheets) { sheet.draw() } } fun addSheet(sheet: Sheet) { sheets.add(sheet) } }
0
Kotlin
0
1
17ef99cfb4e12803a15615f235bfd3d0961ec373
470
ProgrammingLanguages
MIT License
bro/src/main/java/me/xx2bab/bro/core/util/Constants.kt
2BAB
125,506,500
false
null
package me.xx2bab.bro.core.util object Constants { const val KEY_DEFAULT_PAGE_TYPE = "default_page_type" const val KEY_DEFAULT_PAGE_TARGET = "default_page_target" const val DEFAULT_PAGE_UNKNOWN_ERROR = 0x23330 const val DEFAULT_PAGE_NOT_FOUND = 0x23333 const val DEFAULT_PAGE_PERMISSION_DENIED = 0x23334 const val DEFAULT_PAGE_NOT_NEW_INSTANCE_METHOD = 0x23335 }
9
Kotlin
0
9
4df07b25d728959d3ec5e65a4f9d5e78f0c5e271
387
Bro
Apache License 2.0
app/src/main/java/com/example/cupcake/ui/SummaryScreen.kt
0da39bc82
782,730,344
false
{"Kotlin": 55054}
package com.example.cupcake.ui import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import com.example.cupcake.R import com.example.cupcake.ui.components.FormattedPriceLabel import com.example.cupcake.ui.theme.SubTheme import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.* import com.example.cupcake.data.DefaultOrderRepository import com.example.cupcake.data.OrderDatabase /** * This composable expects [orderViewModel] that represents the order view model, * [onCancelButtonClicked] lambda that triggers canceling the order, and passes the final * order to [onSendButtonClicked] lambda. */ @Composable fun OrderSummaryScreen( orderViewModel: OrderViewModel, onCancelButtonClicked: () -> Unit, onSendButtonClicked: (String, String, Uri?, String) -> Unit, // Add order summary parameter modifier: Modifier = Modifier ) { val resources = LocalContext.current.resources val orderUiState by orderViewModel.uiState.collectAsState() val orderSummary = buildString { appendLine("Sandwich Type: ${orderViewModel.sandwichType.value}") appendLine("Bread Type: ${orderViewModel.breadType.value}") appendLine("Toppings:") orderViewModel.toppings.forEach { appendLine("- $it") } } val newOrder = stringResource(R.string.new_sub_order) var selectedImageUri by remember { mutableStateOf<Uri?>(null) } val imagePickerLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? -> uri?.let { selectedImageUri = it // Once the image is selected, invoke the sharing functionality onSendButtonClicked(newOrder, orderSummary, selectedImageUri, orderSummary) // Pass order summary } } Column( modifier = modifier, verticalArrangement = Arrangement.SpaceBetween, ) { Column( modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)), ) { Text("Order Summary", fontWeight = FontWeight.Bold, ) Text(orderSummary) Divider(thickness = dimensionResource(R.dimen.thickness_divider)) FormattedPriceLabel( subtotal = orderUiState.price, modifier = Modifier.align(Alignment.End) ) Text( text = "Total Price: $${orderViewModel.totalPrice.value}", modifier = Modifier.align(Alignment.End) ) } Row( modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)) ) { Column( verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { Button( modifier = Modifier.fillMaxWidth(), onClick = { // Launch the image picker imagePickerLauncher.launch("image/*") } ) { Text(stringResource(R.string.send)) } OutlinedButton( modifier = Modifier.fillMaxWidth(), onClick = onCancelButtonClicked ) { Text(stringResource(R.string.cancel)) } } } } } @Preview @Composable fun OrderSummaryPreview() { val context = LocalContext.current val orderDao = OrderDatabase.getDatabase(context).orderDao() val orderRepository = DefaultOrderRepository(orderDao) SubTheme { OrderSummaryScreen( orderViewModel = OrderViewModel(orderRepository), onCancelButtonClicked = {}, // Modify the lambda to accept the Uri? parameter and order summary onSendButtonClicked = { _, _, _, _ -> }, modifier = Modifier.fillMaxHeight() ) } }
0
Kotlin
0
0
eba86c8d80ec1b8b2a31d82361fba39df1df77b2
5,011
Kotlin-SubShop
Apache License 2.0
sudovirtualcards/src/test/java/com/sudoplatform/sudovirtualcards/SudoVirtualCardsProvisionVirtualCardTest.kt
sudoplatform
287,155,437
false
{"Kotlin": 1055433}
/* * Copyright © 2024 <NAME>, Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ package com.sudoplatform.sudovirtualcards import android.content.Context import com.amplifyframework.api.ApiCategory import com.amplifyframework.api.graphql.GraphQLOperation import com.amplifyframework.api.graphql.GraphQLResponse import com.amplifyframework.core.Consumer import com.sudoplatform.sudokeymanager.KeyManagerInterface import com.sudoplatform.sudouser.PublicKey import com.sudoplatform.sudouser.SudoUserClient import com.sudoplatform.sudouser.amplify.GraphQLClient import com.sudoplatform.sudovirtualcards.graphql.ProvisionVirtualCardMutation import com.sudoplatform.sudovirtualcards.graphql.type.ProvisioningState import com.sudoplatform.sudovirtualcards.keys.PublicKeyService import com.sudoplatform.sudovirtualcards.keys.PublicKeyWithKeyRingId import com.sudoplatform.sudovirtualcards.types.ProvisionalVirtualCard import com.sudoplatform.sudovirtualcards.types.inputs.ProvisionVirtualCardInput import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.kotlintest.shouldThrow import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.json.JSONObject import org.junit.After import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.never import org.mockito.kotlin.any import org.mockito.kotlin.argThat import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.doThrow import org.mockito.kotlin.mock import org.mockito.kotlin.stub import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions import org.mockito.kotlin.whenever /** * Test the correct operation of [SudoVirtualCardsClient.provisionVirtualCard] * using mocks and spies. */ class SudoVirtualCardsProvisionVirtualCardTest : BaseTests() { private val input by before { ProvisionVirtualCardInput( "clientRefId", listOf("ownershipProof"), "fundingSourceId", "cardHolder", "alias", null, "addressLine1", "addressLine2", "city", "state", "postalCode", "country", "currency", ) } private val cardProvisionResponse by before { JSONObject( """ { 'cardProvision': { '__typename': 'CardProvision', 'id':'id', 'owner': 'owner', 'version': 1, 'createdAtEpochMs': 1.0, 'updatedAtEpochMs': 1.0, 'clientRefId': 'clientRefId', 'provisioningState': '${ProvisioningState.PROVISIONING}', 'card': [], } } """.trimIndent(), ) } private val mockContext by before { mock<Context>() } private val mockUserClient by before { mock<SudoUserClient>().stub { on { getSubject() } doReturn "subject" } } private val mockApiCategory by before { mock<ApiCategory>().stub { on { mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ) } doAnswer { val mockOperation: GraphQLOperation<String> = mock() @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(cardProvisionResponse.toString(), null), ) mockOperation } } } private val mockKeyManager by before { mock<KeyManagerInterface>().stub { on { getPassword(anyString()) } doReturn ByteArray(42) on { getPublicKeyData(anyString()) } doReturn ByteArray(42) on { getPrivateKeyData(anyString()) } doReturn ByteArray(42) } } private val currentKey = PublicKey( keyId = "keyId", publicKey = "publicKey".toByteArray(), ) private val currentKeyWithKeyRingId = PublicKeyWithKeyRingId( publicKey = currentKey, keyRingId = "keyRingId", ) private val mockPublicKeyService by before { mock<PublicKeyService>().stub { onBlocking { getCurrentKey() } doReturn currentKey onBlocking { getCurrentRegisteredKey() } doReturn currentKeyWithKeyRingId } } private val client by before { SudoVirtualCardsClient.builder() .setContext(mockContext) .setSudoUserClient(mockUserClient) .setGraphQLClient(GraphQLClient(mockApiCategory)) .setKeyManager(mockKeyManager) .setLogger(mock()) .setPublicKeyService(mockPublicKeyService) .build() } @After fun fini() { verifyNoMoreInteractions( mockContext, mockUserClient, mockKeyManager, mockPublicKeyService, mockApiCategory, ) } @Test fun `provisionVirtualCard() should return results when no error present`() = runBlocking<Unit> { val deferredResult = async(Dispatchers.IO) { client.provisionVirtualCard(input) } deferredResult.start() delay(100L) val result = deferredResult.await() result shouldNotBe null with(result) { id shouldBe "id" clientRefId shouldBe "clientRefId" owner shouldBe "owner" version shouldBe 1 provisioningState shouldBe ProvisionalVirtualCard.ProvisioningState.PROVISIONING card shouldBe null createdAt shouldNotBe null updatedAt shouldNotBe null } verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when registered public key retrieval fails`() = runBlocking<Unit> { mockPublicKeyService.stub { onBlocking { getCurrentRegisteredKey() } doThrow PublicKeyService.PublicKeyServiceException.KeyCreateException() } shouldThrow<SudoVirtualCardsClient.VirtualCardException.PublicKeyException> { client.provisionVirtualCard(input) } verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory, never()).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when card mutation response is null`() = runBlocking<Unit> { val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, null), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.ProvisionFailedException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has an identity verification not verified error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "IdentityVerificationNotVerifiedError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.IdentityVerificationException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has an identity verification insufficient error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "IdentityVerificationInsufficientError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.IdentityVerificationInsufficientException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has a funding source not found error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "FundingSourceNotFoundError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.FundingSourceNotFoundException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has a funding source not active error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "FundingSourceNotActiveError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.FundingSourceNotActiveException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has a velocity exceeded error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "VelocityExceededError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.VelocityExceededException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has an entitlement exceeded error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "EntitlementExceededError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.EntitlementExceededException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has an unsupported currency error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "UnsupportedCurrencyError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.UnsupportedCurrencyException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has an invalid token error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "InvalidTokenError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.ProvisionFailedException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when response has an account locked error`() = runBlocking<Unit> { val errors = listOf( GraphQLResponse.Error( "mock", null, null, mapOf("errorType" to "AccountLockedError"), ), ) val mockOperation: GraphQLOperation<String> = mock() whenever( mockApiCategory.mutate<String>( argThat { this.query.equals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT) }, any(), any(), ), ).thenAnswer { @Suppress("UNCHECKED_CAST") (it.arguments[1] as Consumer<GraphQLResponse<String>>).accept( GraphQLResponse(null, errors), ) mockOperation } val deferredResult = async(Dispatchers.IO) { shouldThrow<SudoVirtualCardsClient.VirtualCardException.AccountLockedException> { client.provisionVirtualCard(input) } } deferredResult.start() delay(100L) deferredResult.await() verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should not block coroutine cancellation exception`() = runBlocking<Unit> { mockPublicKeyService.stub { onBlocking { getCurrentRegisteredKey() } doThrow CancellationException("mock") } shouldThrow<CancellationException> { client.provisionVirtualCard(input) } verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory, never()).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } @Test fun `provisionVirtualCard() should throw when key registration fails`() = runBlocking<Unit> { mockPublicKeyService.stub { onBlocking { getCurrentRegisteredKey() } doThrow PublicKeyService.PublicKeyServiceException.KeyCreateException("mock") } shouldThrow<SudoVirtualCardsClient.VirtualCardException.PublicKeyException> { client.provisionVirtualCard(input) } verify(mockPublicKeyService).getCurrentRegisteredKey() verify(mockApiCategory, never()).mutate<String>( org.mockito.kotlin.check { assertEquals(ProvisionVirtualCardMutation.OPERATION_DOCUMENT, it.query) }, any(), any(), ) } }
0
Kotlin
0
0
8e15044222a7b853234fe6994994d5969f6be0da
23,280
sudo-virtual-cards-android
Apache License 2.0
cloudsdk/src/test/java/io/particle/android/sdk/cloud/ParticleCloudTest.kt
particle-iot
34,549,566
false
null
package io.particle.android.sdk.cloud import android.content.Intent import com.google.gson.Gson import com.squareup.okhttp.HttpUrl import com.squareup.okhttp.mockwebserver.MockResponse import com.squareup.okhttp.mockwebserver.MockWebServer import com.squareup.okhttp.mockwebserver.RecordedRequest import io.particle.android.sdk.cloud.ApiFactory.OauthBasicAuthCredentialsProvider import io.particle.android.sdk.cloud.ApiFactory.TokenGetterDelegate import io.particle.android.sdk.cloud.Responses.ClaimCodeResponse import io.particle.android.sdk.persistance.AppDataStorage import io.particle.android.sdk.persistance.SensitiveDataStorage import io.particle.android.sdk.utils.Broadcaster import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import retrofit.RestAdapter.LogLevel import java.util.* import java.util.concurrent.Executors private const val FAKE_API_PORT = 8080 private val FAKE_API_URL = HttpUrl.parse("http://localhost:$FAKE_API_PORT") class ParticleCloudTest { lateinit var cloud: ParticleCloud lateinit var mockServer: MockWebServer private lateinit var mainApi: ApiDefs.CloudApi @Before fun setUp() { initCloud() } @After fun teardown() { // close the socket, stop the listening thread mockServer.shutdown() } private fun initCloud() { // start the mock webserver mockServer = MockWebServer() mockServer.start(FAKE_API_PORT) // build up a few dependency fakes SDKGlobals.appDataStorage = FakeAppDataStorage() SDKGlobals.sensitiveDataStorage = FakeSensitiveDataStorage() val tokenDelegate = TokenGetterDelegate { "d34db33fd34db33fd34db33fd34db33fd34db33f" } val credsProvider = object : OauthBasicAuthCredentialsProvider { override fun getClientSecret(): String = "I_AM_A_CLIENT_SECRET" override fun getClientId(): String = "I_AM_A_CLIENT_ID" } // use actual ApiFactory to build other dependencies val factory = ApiFactory(FAKE_API_URL, LogLevel.FULL, tokenDelegate, credsProvider) mainApi = factory.buildNewCloudApi() // build the cloud itself cloud = ParticleCloud( FAKE_API_URL, mainApi, factory.buildNewIdentityApi(), SDKGlobals.appDataStorage!!, FakeBroadcaster(), Gson(), Executors.newSingleThreadExecutor() ) } @Test fun test_generateClaimCode_HappyPath() { val (claimCode, request, claimCodeResponse) = setUpClaimCodeTest() assertEquals(claimCode, claimCodeResponse.claimCode) assertEquals("blank=okhttp_appeasement", request.body.readUtf8()) } @Test fun test_generateClaimCodeWithProductId_HappyPath() { val productId = 42 val (claimCode, request, claimCodeResponse) = setUpClaimCodeTest(productId) assertEquals(claimCode, claimCodeResponse.claimCode) assertEquals("blank=okhttp_appeasement", request.body.readUtf8()) // verify that we are using the product ID URL assertEquals("/v1/products/$productId/device_claims", request.path) } private fun setUpClaimCodeTest(productId: Int? = null): Triple<String, RecordedRequest, ClaimCodeResponse> { val claimCode = "fed14c9c3b04058562b193c992f37b18604ca0e8" val deviceId1 = "fa80c4a898849e1bb35ada62" val deviceId2 = "afada5fe1b4fa16e9f499416" val mockedResponse = enqueueNew200ResponseWithBody( """ { claim_code: "$claimCode", device_ids: [ "$deviceId1", "$deviceId2" ] }""" ) // set the response mockServer.enqueue(mockedResponse) // make the API call val claimCodeResponse = if (productId == null) { cloud.generateClaimCode() } else { cloud.generateClaimCode(productId) } // grab the request that was given to the mock server val request = mockServer.takeRequest() return Triple(claimCode, request, claimCodeResponse) } @Test fun test_getDevices_PopulatedDeviceListHappyPath() { val device0 = ParticleDevice( mainApi, cloud, DEVICE_STATE_0 ) val device1 = ParticleDevice( mainApi, cloud, DEVICE_STATE_1 ) enqueueNew200ResponseWithBody(DEVICE_LIST_JSON) val devices = cloud.getDevices() assertEquals(devices[0], device0) assertEquals(devices[1], device1) } @Test fun test_getDevice_SingleDeviceHappyPath() { val device1 = ParticleDevice(mainApi, cloud, DEVICE_STATE_1_FULL) enqueueNew200ResponseWithBody(DEVICE_1_FULL_JSON) val deviceFromCloud = cloud.getDevice(device1.id) assertEquals(device1, deviceFromCloud) } private fun enqueueNew200ResponseWithBody(body: String): MockResponse { val mockedResponse = MockResponse() mockedResponse.setResponseCode(200) mockedResponse.setBody(body.trimIndent()) mockServer.enqueue(mockedResponse) return mockedResponse } } class FakeAppDataStorage : AppDataStorage { override val userHasClaimedDevices: Boolean get() = TODO("not implemented") var saveUserHasClaimedDevicesWasCalled = false override fun saveUserHasClaimedDevices(value: Boolean) { saveUserHasClaimedDevicesWasCalled = true } override fun resetUserHasClaimedDevices() { TODO("not implemented") } } class FakeBroadcaster : Broadcaster { override fun sendBroadcast(intent: Intent) { println("Broadcasting intent (content not shown Because Android Reasons)") } } class FakeSensitiveDataStorage : SensitiveDataStorage { var _user: String? = null override val user: String? get() = _user var _password: String? = null override val password: String? get() = _password var _token: String? = null override val token: String? get() = _token var _refreshToken: String? = null override val refreshToken: String? get() = _refreshToken var _tokenExpirationDate: Date? = null override val tokenExpirationDate: Date? get() = _tokenExpirationDate var _hasEverHadStoredUsername: Boolean = false override val hasEverHadStoredUsername: Boolean get() = _hasEverHadStoredUsername override fun saveUser(user: String?) { _user = user } override fun resetUser() { _user = null } override fun savePassword(password: String?) { _password = password } override fun resetPassword() { _password = null } override fun saveToken(token: String?) { _token = token } override fun resetToken() { _token = null } override fun resetRefreshToken() { _refreshToken = null } override fun saveRefreshToken(token: String?) { _refreshToken = token } override fun saveTokenExpirationDate(expirationDate: Date) { _tokenExpirationDate = expirationDate } override fun resetTokenExpirationDate() { _tokenExpirationDate = null } override fun saveHasEverHadStoredUsername(value: Boolean) { _hasEverHadStoredUsername = value } }
34
null
38
38
bda215376a916b39b16c091977132e29e616b8e5
7,461
particle-android
Apache License 2.0
aws-globalaccelerator-endpointgroup/src/test/kotlin/software/amazon/globalaccelerator/endpointgroup/ReadHandlerTest.kt
DJ-C
271,874,034
true
{"Kotlin": 174746}
package software.amazon.globalaccelerator.endpointgroup import com.amazonaws.AmazonWebServiceResult import com.amazonaws.ResponseMetadata import com.amazonaws.services.globalaccelerator.model.* import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy import software.amazon.cloudformation.proxy.HandlerErrorCode import software.amazon.cloudformation.proxy.Logger import software.amazon.cloudformation.proxy.OperationStatus import software.amazon.cloudformation.proxy.ResourceHandlerRequest import java.util.ArrayList import org.mockito.ArgumentMatchers import org.mockito.Mockito.mock import org.mockito.Mockito.doReturn import org.mockito.Mockito.doThrow import java.util.function.Function @ExtendWith(MockitoExtension::class) class ReadHandlerTest { @Mock private var proxy: AmazonWebServicesClientProxy? = null @Mock private var logger: Logger? = null private val portOverrides = listOf(PortOverride(80, 8080)) @BeforeEach fun setup() { proxy = mock(AmazonWebServicesClientProxy::class.java) logger = mock(Logger::class.java) } private fun createTestResourceModel(): ResourceModel { val endpointConfigurations = ArrayList<EndpointConfiguration>() endpointConfigurations.add(EndpointConfiguration.builder().endpointId("EPID1").build()) endpointConfigurations.add(EndpointConfiguration.builder().endpointId("EPID2").build()) return ResourceModel.builder() .endpointGroupArn("ENDPOINTGROUP_ARN") .endpointGroupRegion("us-west-2") .listenerArn("LISTENER_ARN") .healthCheckPort(10) .thresholdCount(100) .endpointConfigurations(endpointConfigurations) .healthCheckPath("/Health") .trafficDialPercentage(100.0) .healthCheckIntervalSeconds(10) .healthCheckProtocol("TCP") .listenerArn("arn:aws:globalaccelerator::474880776455:accelerator/abcd1234/listener/12341234") .portOverrides(portOverrides) .build() } private fun createEndpointDescription(): List<EndpointDescription> { val array = ArrayList<EndpointDescription>() array.add(EndpointDescription() .withClientIPPreservationEnabled(true) .withHealthState("HS1") .withEndpointId("ID1") .withWeight(100) .withHealthReason("Reason1")) array.add(EndpointDescription() .withClientIPPreservationEnabled(false) .withHealthState("HS2") .withEndpointId("ID2") .withWeight(100) .withHealthReason("Reason2")) return array } @Test fun handleRequest_returnsMappedEndpointGroup() { val model = createTestResourceModel() val returnedPortOverrides = com.amazonaws.services.globalaccelerator.model.PortOverride().withListenerPort(80).withEndpointPort(8080) val describeEndpointGroupResult = DescribeEndpointGroupResult() .withEndpointGroup(EndpointGroup() .withEndpointGroupArn("ENDPOINTGROUP_ARN") .withEndpointGroupRegion("us-west-2") .withTrafficDialPercentage(50.0f) .withEndpointDescriptions(createEndpointDescription()) .withPortOverrides(returnedPortOverrides)) doReturn(describeEndpointGroupResult).`when`(proxy!!).injectCredentialsAndInvoke(ArgumentMatchers.any(DescribeEndpointGroupRequest::class.java), ArgumentMatchers.any<Function<DescribeEndpointGroupRequest, AmazonWebServiceResult<ResponseMetadata>>>()) val request = ResourceHandlerRequest.builder<ResourceModel>().desiredResourceState(model).build() val response = ReadHandler().handleRequest(proxy!!, request, null, logger!!) Assertions.assertNotNull(response) Assertions.assertEquals(response.status, OperationStatus.SUCCESS) Assertions.assertNotNull(response.resourceModel) Assertions.assertNull(response.callbackContext) Assertions.assertEquals(response.resourceModel.endpointGroupArn, "ENDPOINTGROUP_ARN") Assertions.assertEquals(response.resourceModel.endpointGroupRegion, "us-west-2") Assertions.assertEquals(response.resourceModel.portOverrides.size, 1) Assertions.assertEquals(response.resourceModel.portOverrides[0].listenerPort, portOverrides[0].listenerPort) Assertions.assertEquals(response.resourceModel.portOverrides[0].endpointPort, portOverrides[0].endpointPort) } @Test fun handleRequest_nonExistingEndpointGroup() { val model = createTestResourceModel() doThrow(EndpointGroupNotFoundException("NOT FOUND")).`when`(proxy)!!.injectCredentialsAndInvoke(ArgumentMatchers.any(DescribeEndpointGroupRequest::class.java), ArgumentMatchers.any<Function<DescribeEndpointGroupRequest, AmazonWebServiceResult<ResponseMetadata>>>()) val request = ResourceHandlerRequest.builder<ResourceModel>().desiredResourceState(model).build() val response = ReadHandler().handleRequest(proxy!!, request, null, logger!!) Assertions.assertNotNull(response) Assertions.assertEquals(response.status, OperationStatus.FAILED) Assertions.assertEquals(response.errorCode, HandlerErrorCode.NotFound) Assertions.assertNull(response.resourceModel) } }
0
Kotlin
0
0
28e547deb0a9f246393bd91ee29ea010d9ef2800
5,761
aws-cloudformation-resource-providers-globalaccelerator-1
Apache License 2.0
app/shared/analytics/public/src/commonMain/kotlin/build/wallet/analytics/events/screen/context/PairHardwareEventTrackerScreenIdContext.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.analytics.events.screen.context /** * Context for screens related to pairing a new HW device in the app. * Customers pair a new HW during new account creation as well as during HW recovery. */ enum class PairHardwareEventTrackerScreenIdContext : EventTrackerScreenIdContext { /** Events for pairing new hardware during new account creation */ ACCOUNT_CREATION, /** Events for pairing new hardware during HW recovery */ HW_RECOVERY, }
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
468
bitkey
MIT License
plugins/devkit/devkit-core/src/inspections/IncorrectParentDisposableInspection.kt
hieuprogrammer
284,920,751
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElementVisitor import com.intellij.uast.UastHintedVisitorAdapter.Companion.create import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class IncorrectParentDisposableInspection : DevKitUastInspectionBase(UCallExpression::class.java) { override fun isAllowed(holder: ProblemsHolder): Boolean = DevKitInspectionBase.isAllowedInPluginsOnly(holder) override fun buildInternalVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = create(holder.file.language, object : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { checkCallExpression(node, holder) return true } }, arrayOf(UCallExpression::class.java)) private val sdkLink = "(<a href=\"https://www.jetbrains.org/intellij/sdk/docs/basics/disposers.html#choosing-a-disposable-parent\">Choosing a Disposable Parent</a>)" private fun checkCallExpression(node: UCallExpression, holder: ProblemsHolder) { val psiMethod = node.resolve() ?: return psiMethod.parameters.forEachIndexed { index, parameter -> val parameterType = (parameter.type as? PsiClassType)?.resolve() ?: return@forEachIndexed if (parameterType.qualifiedName != Disposable::class.java.name) return@forEachIndexed val argumentForParameter = node.getArgumentForParameter(index) ?: return@forEachIndexed val argumentSourcePsi = argumentForParameter.sourcePsi ?: return@forEachIndexed val argumentType = (argumentForParameter.getExpressionType() as? PsiClassType)?.resolve() ?: return@forEachIndexed if (argumentType.qualifiedName == Project::class.java.name) { holder.registerProblem(argumentSourcePsi, "<html>Don't use Project as disposable in plugin code $sdkLink</html>") } else if (argumentType.qualifiedName == Application::class.java.name) { holder.registerProblem(argumentSourcePsi, "<html>Don't use Application as disposable in plugin code $sdkLink</html>") } else if (argumentType.qualifiedName == Module::class.java.name) { holder.registerProblem(argumentSourcePsi, "<html>Don't use Module as disposable in plugin code $sdkLink</html>") } } } }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
2,728
intellij-community
Apache License 2.0
app/src/main/java/com/axel_stein/glucose_tracker/core/DatePeriod.kt
AxelStein
320,277,698
false
null
package com.axel_stein.glucose_tracker.core enum class DatePeriod { TODAY, TWO_WEEKS, MONTH, THREE_MONTHS, SIX_MONTHS, YEAR; fun fromInt(value: Int): DatePeriod { return when (value) { 0 -> TODAY 1 -> TWO_WEEKS 2 -> MONTH 3 -> THREE_MONTHS 4 -> SIX_MONTHS 5 -> YEAR else -> throw IllegalArgumentException() } } }
4
Kotlin
0
1
e6ed8ebdaf7d10bbec4ea830448dd9b174ed8c17
446
GlucoseTracker
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/ListItem.kt
Hexworks
94,116,947
false
null
package org.hexworks.zircon.api.component import org.hexworks.zircon.api.behavior.TextOverride /** * A [ListItem] is a non-interactive [Component] that semantically represents * a textual list item. It also contains style information that's consistent with its * purpose and the other semantic elements, like: * - [Paragraph] * - [Header] * - [Label] * - [Icon] */ interface ListItem : Component, TextOverride
42
null
138
738
55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6
420
zircon
Apache License 2.0
src/main/kotlin/com/kokasai/api/http/user/form/list.kt
astralbrim
332,749,834
true
{"Kotlin": 69658}
package com.kokasai.api.http.user.form import com.kokasai.api.http._dsl.onlyUser import com.kokasai.api.http.group.form.getGroupFormListResponse import com.kokasai.flowerkt.route.RouteAction import io.ktor.application.call import io.ktor.response.respond import io.ktor.routing.get import kotlinx.serialization.Serializable import com.kokasai.api.http.group.form.GetListResponse as GetGroupFormListResponse @Serializable data class GetListResponse(val group: Map<String, GetGroupFormListResponse>) val list: RouteAction = { get { onlyUser { user -> call.respond(GetListResponse(user.file.group.associateWith { getGroupFormListResponse(it) })) } } }
0
Kotlin
0
1
012fdf1c1b209e3d4ce9df8c021fe9d9454538fe
688
api.kokasai.com
Apache License 2.0
log4k-slf4j/src/commonMain/kotlin/saschpe/log4k/slf4j/SLF4JLogger.kt
saschpe
221,440,719
false
{"Kotlin": 45740, "Shell": 4224}
package saschpe.log4k.slf4j import saschpe.log4k.Log import saschpe.log4k.Logger /** * Logger that forwards all log statements to SLF4J API on JVM and Android platforms. * * Suitable to replace [saschpe.log4k.ConsoleLogger]: * * ```kotlin * Log.loggers.clear() * Log.loggers += SLF4JLogger() * ``` * * On JVM or Android, SLF4J is used for logging. On JS or Apple platforms, console logging is used internally. */ expect class SLF4JLogger : Logger { override fun print(level: Log.Level, tag: String, message: String?, throwable: Throwable?) }
0
Kotlin
2
17
702b147a149eee3dca396e1d3e551290a6c73058
559
Log4K
Apache License 2.0
src/main/java/com/sdk/platform/share/ShareApiList.kt
gofynd
337,940,340
false
{"Kotlin": 2497895, "Java": 179}
package com.sdk.platform.share import kotlinx.coroutines.Deferred import retrofit2.Response import okhttp3.ResponseBody import retrofit2.http.* import com.sdk.platform.* interface ShareApiList { @POST ("/service/platform/share/v1.0/company/{company_id}/application/{application_id}/links/short-link/") suspend fun createShortLink(@Path("company_id") companyId: String, @Path("application_id") applicationId: String,@Body body: ShortLinkReq) : Response<ShortLinkRes> @GET ("/service/platform/share/v1.0/company/{company_id}/application/{application_id}/links/short-link/") suspend fun getShortLinks(@Path("company_id") companyId: String, @Path("application_id") applicationId: String, @Query("page_no") pageNo: Int?, @Query("page_size") pageSize: Int?, @Query("created_by") createdBy: String?, @Query("active") active: String?, @Query("q") q: String?) : Response<ShortLinkList> @GET ("/service/platform/share/v1.0/company/{company_id}/application/{application_id}/links/short-link/{hash}/") suspend fun getShortLinkByHash(@Path("company_id") companyId: String, @Path("application_id") applicationId: String, @Path("hash") hash: String) : Response<ShortLinkRes> @PATCH ("/service/platform/share/v1.0/company/{company_id}/application/{application_id}/links/short-link/{id}/") suspend fun updateShortLinkById(@Path("company_id") companyId: String, @Path("application_id") applicationId: String, @Path("id") id: String,@Body body: ShortLinkReq) : Response<ShortLinkRes> @GET ("/service/platform/share/v1.0/company/{company_id}/application/{application_id}/links/short-link/click-stats") suspend fun getShortLinkClickStats(@Query("surl_id") surlId: String, @Path("company_id") companyId: String, @Path("application_id") applicationId: String) : Response<ClickStatsResponse> }
0
Kotlin
4
4
1054e3cfc8828b73b302ace4bc6110459126a1ce
1,861
fdk-client-kotlin
MIT License
examples/basic-integration-jetpack-compose/app/src/main/java/com/deuna/compose_demo/screens/VaultSuccessfulScreen.kt
darwinmorocho-deuna
840,494,266
false
{"Kotlin": 59588}
package com.deuna.compose_demo.screens import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.tooling.preview.* import androidx.compose.ui.unit.* import com.deuna.compose_demo.* import com.deuna.maven.shared.Json import com.deuna.maven.shared.toMap import org.json.JSONObject @Composable fun VaultSuccessfulScreen(card: Json) { val navController = LocalNavController.current Scaffold { innerPadding -> Column( modifier = Modifier .fillMaxSize() .padding(innerPadding), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "Card Saved") Box(modifier = Modifier.height(20.dp)) Text(text = "ID: ${card["id"]}") Text(text = "Holder Name: ${card["cardHolder"]}") Text(text = "First Six Digits: ${card["firstSix"]}") Text(text = "Last Four Digits: ${card["lastFour"]}") Box(modifier = Modifier.height(20.dp)) ElevatedButton( onClick = { // pop the current screen navController.popBackStack() }, ) { Text(text = "Go back!") } } } } @Preview @Composable private fun Preview() { Navigator { VaultSuccessfulScreen( card = JSONObject( """ { "id": "4fd0584b-d336-4406-ad63-cc253fd47f14", "verifiedAt": "0001-01-01T00:00:00Z", "verifiedWithTransactionId": "", "firstSix": "424242", "verifiedBy": "", "bankName": "", "storedCard": false, "company": "visa", "expirationDate": "12/30", "cardHolder": "Test User", "userId": "45aa4524-1e98-4f5d-8845-20394f0f37ee", "cardType": "credit_card", "isValid": false, "cardId": "4fd0584b-d336-4406-ad63-cc253fd47f14", "lastFour": "4242", "createdAt": "2024-07-10T17:54:26.970636182Z", "cardHolderDni": "", "deletedAt": null } """.trimIndent() ).toMap() ) } }
0
Kotlin
0
0
aed627548ac68cbf04fcbcf5a88f63c4f865c1d4
2,268
deunasdk
MIT License
src/Day08.kt
haraldsperre
572,671,018
false
null
fun main() { fun isVisible(patch: List<List<Int>>, tree: Pair<Int, Int>): Boolean { val (x, y) = tree if (x == 0 || y == 0 || x == patch.size - 1 || y == patch[x].size - 1) { return true } val treeHeight = patch[x][y] return treeHeight > listOf( patch.subList(0, x).maxOf { it[y] }, patch.subList(x + 1, patch.size).maxOf { it[y] }, patch[x].subList(0, y).max(), patch[x].subList(y + 1, patch.size).max() ).min() } fun getScenicScore(patch: List<List<Int>>, tree: Pair<Int, Int>): Int { val (x, y) = tree val treeHeight = patch[x][y] var score = 1 var tempScore = 0 if (x == 0 || y == 0 || x == patch.size - 1 || y == patch[x].size - 1) { return 0 } for (xi in (0 until x).reversed()) { tempScore++ if (patch[xi][y] >= treeHeight) break } score *= tempScore tempScore = 0 for (xi in (x + 1) until patch.size) { tempScore++ if (patch[xi][y] >= treeHeight) break } score *= tempScore tempScore = 0 for (yi in (0 until y).reversed()) { tempScore++ if (patch[x][yi] >= treeHeight) break } score *= tempScore tempScore = 0 for (yi in (y + 1) until patch[x].size) { tempScore++ if (patch[x][yi] >= treeHeight) break } score *= tempScore return score } fun part1(input: List<List<Int>>): Int { val value = List(input.size) { y -> List(input[y].size) { x -> isVisible(input, x to y) } } return value.sumOf { row -> row.count { it } } } fun part2(input: List<List<Int>>): Int { val value = List(input.size) { y -> List(input[y].size) { x -> getScenicScore(input, x to y) } } return value.maxOf{ it.maxOf{ it } } } // test if implementation meets criteria from the description, like: val testInput = readInputAsIntLists("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInputAsIntLists("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c4224fd73a52a2c9b218556c169c129cf21ea415
2,357
advent-of-code-2022
Apache License 2.0
src/test/kotlin/no/nav/personbruker/internal/periodic/metrics/reporter/metrics/cache/count/NumberOfCachedRecordsTest.kt
navikt
400,413,252
false
null
package no.nav.personbruker.internal.periodic.metrics.reporter.metrics.cache.count import org.amshove.kluent.`should be equal to` import org.junit.jupiter.api.Test internal class NumberOfCachedRecordsTest { @Test fun `Skal summere totalene riktig`() { val cachedRecords = NumberOfCachedRecords(1, 2, 3, 4, 5, 6, 7) cachedRecords.beskjedTotal `should be equal to` 1 + 2 cachedRecords.innboksTotal `should be equal to` 3 + 4 cachedRecords.oppgaveTotal `should be equal to` 5 + 6 cachedRecords.doneTotal `should be equal to` 2 + 4 + 6 + 7 } }
0
Kotlin
0
0
04cefba9314597cbc81585d7e849debc8f0cb58a
597
internal-periodic-metrics-reporter
MIT License
base/src/main/java/com/frogobox/base/BaseViewModel.kt
frogobox
221,978,119
false
{"Kotlin": 246872}
package com.frogobox.base import android.app.Application import androidx.lifecycle.AndroidViewModel import com.frogobox.base.util.SingleLiveEvent /** * Created by Faisal Amir * FrogoBox Inc License * ========================================= * movie * Copyright (C) 16/11/2019. * All rights reserved * ----------------------------------------- * Name : Muhammad Faisal Amir * E-mail : faisalamircs@gmail.com * Github : github.com/amirisback * LinkedIn : linkedin.com/in/faisalamircs * ----------------------------------------- * FrogoBox Software Industries * com.frogobox.base * */ open class BaseViewModel(application: Application) : AndroidViewModel(application) { var eventShowProgress = SingleLiveEvent<Boolean>() var eventIsEmpty = SingleLiveEvent<Boolean>() }
0
Kotlin
2
16
8cb6e3c49650be2dfe586570d44dd76c207a4598
803
kick-start-android-modular
Apache License 2.0
src/main/kotlin/ee/mcdimus/matewp/service/OpSysServiceFactory.kt
mcdimus
23,383,063
false
null
package ee.mcdimus.matewp.service /** * @author Dmitri Maksimov */ object OpSysServiceFactory { private enum class OS { LINUX, WINDOWS } fun get() = when (detectOS()) { OS.LINUX -> LinuxMateService() OS.WINDOWS -> WindowsService() } private fun detectOS() = when (val osName = System.getProperty("os.name")) { "Windows 7" -> OS.WINDOWS "Linux" -> OS.LINUX else -> makeGuess(osName) } private fun makeGuess(osName: String) = when { osName.contains("windows", ignoreCase = true) -> OS.WINDOWS osName.contains("linux", ignoreCase = true) -> OS.LINUX else -> throw IllegalStateException("unsupported operating system: $osName") } }
0
Kotlin
0
1
b4a958b1a003100a7fa22a303cdecdb0bb26529d
688
mate-wp
MIT License
feature/addmeal/src/main/java/com/kanyideveloper/addmeal/di/AddMealModule.kt
JoelKanyi
554,742,212
false
null
/* * Copyright 2022 Joel Kanyi. * * 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.kanyideveloper.addmeal.di import android.content.Context import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.kanyideveloper.addmeal.data.repository.SaveMealRepositoryImpl import com.kanyideveloper.addmeal.data.repository.UploadImageRepositoryImpl import com.kanyideveloper.addmeal.domain.repository.SaveMealRepository import com.kanyideveloper.addmeal.domain.repository.UploadImageRepository import com.kanyideveloper.core_database.MealTimeDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AddMealModule { @Provides @Singleton fun provideUploadImageRepository( storageReference: StorageReference, @ApplicationContext context: Context ): UploadImageRepository { return UploadImageRepositoryImpl( storageReference = storageReference, context = context ) } @Provides @Singleton fun provideSaveMealRepository( mealTimeDatabase: MealTimeDatabase, databaseReference: DatabaseReference, firebaseAuth: FirebaseAuth ): SaveMealRepository { return SaveMealRepositoryImpl( mealTimeDatabase = mealTimeDatabase, databaseReference = databaseReference, firebaseAuth = firebaseAuth ) } @Provides @Singleton fun provideFirebaseStorageReference(): StorageReference { return FirebaseStorage.getInstance().getReference("meal_images") } }
14
null
9
69
040b552070450d2e2b34cd1817eece7145fb2086
2,409
MealTime
Apache License 2.0
app/src/main/java/com/example/coderadar/data/repository/dataSourceImpl/ContestCacheDataSourceImpl.kt
thekuldeep07
430,311,480
false
null
package com.example.coderadar.data.repository.dataSourceImpl import com.example.coderadar.data.model.Contest import com.example.coderadar.data.repository.dataSource.ContestCacheDataSource class ContestCacheDataSourceImpl : ContestCacheDataSource { private var contestList = ArrayList<Contest>() override suspend fun getContestsFromCache(): List<Contest> { return contestList } override suspend fun saveContestsToCache(contests: List<Contest>) { contestList.clear() contestList = ArrayList(contests) } }
0
Kotlin
3
0
028f4624a72c78b84ae1e5df2aa989e1f893ea7c
550
CodeRadar
MIT License
app/src/main/java/com/kotlin/cleanarchitecture/presentation/common/BottomNavigationScreen.kt
hiroshi-homma-origin
287,533,709
false
{"Kotlin": 36592, "Ruby": 4164}
package com.kotlin.cleanarchitecture.presentation.common import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.util.fastForEachIndexed import com.kotlin.cleanarchitecture.state.PokeDelegate.screenNumber import com.kotlin.project.data.model.appScreenList @Composable fun BottomNavigationScreen() { val sNumber by screenNumber.observeAsState() BottomNavigation(modifier = Modifier.padding(0.dp)) { appScreenList.fastForEachIndexed { index, screenName -> if (index < 5) { BottomNavigationItem( icon = { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Icon( imageVector = Icons.Filled.Home, contentDescription = null, ) if (sNumber == index) { Text( text = screenName, style = TextStyle( fontFamily = FontFamily.Monospace, fontSize = 8.sp ), color = Color(0xBBFFFFFF) ) } } }, selected = sNumber == index, onClick = { screenNumber.value = index }, alwaysShowLabel = false ) } } } }
0
Kotlin
1
1
9f155d0b8cc2e0eb86bcdd6eb226fca887c74a1e
2,450
hiroCleanArchitecture
Apache License 2.0
komapper-processor/src/main/kotlin/org/komapper/processor/EmptySymbolProcessor.kt
komapper
349,909,214
false
{"Kotlin": 2802685, "Java": 57131}
package org.komapper.processor import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.symbol.KSAnnotated object EmptySymbolProcessor : SymbolProcessor { override fun process(resolver: Resolver): List<KSAnnotated> = emptyList() }
7
Kotlin
12
294
5830d985f81f0b0d1eb8b91b304411940394876d
320
komapper
Apache License 2.0
idea/testData/inspectionsLocal/redundantSetter/annotation.kt
JakeWharton
99,388,807
true
null
// PROBLEM: none annotation class Inject class Test { var x = 1 @Inject set<caret> }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
97
kotlin
Apache License 2.0
app/src/main/java/com/madreain/aachulk/module/single/SingleViewModel.kt
yujianchengfeng
342,184,458
true
{"Kotlin": 265090}
package com.madreain.aachulk.module.refreshSingle import androidx.lifecycle.MutableLiveData import com.madreain.aachulk.module.api.ApiService import com.madreain.libhulk.em.RequestDisplay import com.madreain.libhulk.mvvm.BaseViewModel /** * @author madreain * @date 2020/3/16. * module: * description: */ class RefreshSingleViewModel : BaseViewModel<ApiService>() { public override fun onStart() { cityList() } var result = MutableLiveData<List<RefreshSingleData>>() private fun cityList() { launchOnlyresult( //调用接口方法 block = { getApiService().getRefreshCityList() }, //重试 reTry = { //调用重试的方法 cityList() }, //成功 success = { //成功回调 result.value = it //通知ui刷新 }, type = RequestDisplay.REPLACE ) } }
0
null
0
0
9de904506fc388f8adea17578ddc03a226ee4530
956
AACHulk
Apache License 2.0
ECommerceApp/app/src/main/java/com/android/ecommerceapp/service/ApiService.kt
oguzhansatilmis
746,560,331
false
{"Kotlin": 22096}
package com.android.ecommerceapp.service import com.android.ecommerceapp.model.Product import kotlinx.coroutines.flow.Flow import okhttp3.ResponseBody import retrofit2.Response import retrofit2.http.GET interface ApiService { @GET("products/categories") suspend fun getAllCategories():Response<List<String>> @GET("products") suspend fun getAllProducts():Response<List<Product>> }
0
Kotlin
0
0
431c209a6fe4d8449507d15e9a692a9162a8eac0
401
E-Commerce-App
MIT License
app/src/main/java/com/muhammedesadcomert/ecommerceapp/ui/home/Home.kt
muhammedesadcomert
438,645,365
false
{"Kotlin": 57506}
package com.muhammedesadcomert.ecommerceapp.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.google.android.material.bottomnavigation.BottomNavigationView import com.muhammedesadcomert.ecommerceapp.R import com.muhammedesadcomert.ecommerceapp.databinding.FragmentHomeBinding import com.muhammedesadcomert.ecommerceapp.ui.product.ProductAdapter import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class Home : Fragment(R.layout.fragment_home) { private lateinit var binding: FragmentHomeBinding private lateinit var productAdapter: ProductAdapter private val viewModel: HomeViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { binding = FragmentHomeBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.findViewById<BottomNavigationView>(R.id.bottom_nav_view)?.visibility = View.VISIBLE initAdapter() viewModel.products.observe(viewLifecycleOwner) { response -> if (response.error != null) { Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show() } else { productAdapter.differ.submitList(response.value) } } } private fun initAdapter() { productAdapter = ProductAdapter { product -> findNavController().navigate(HomeDirections.actionHomeToProductPage(product)) } binding.recyclerView.apply { adapter = productAdapter layoutManager = GridLayoutManager(context, 2) setHasFixedSize(true) } } }
0
Kotlin
1
5
f52c8332ac7e1df790efcbafd80cfbb989a7902d
2,117
eCommerceApp
MIT License
github-workflows-kt/src/test/kotlin/io/github/typesafegithub/workflows/domain/RunnerTypeTest.kt
typesafegithub
439,670,569
false
{"Kotlin": 1853198}
package io.github.typesafegithub.workflows.domain import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FunSpec class RunnerTypeTest : FunSpec({ context("Labelled") { test("should throw on invalid arguments") { shouldThrow<IllegalArgumentException> { RunnerType.Labelled() } shouldThrow<IllegalArgumentException> { RunnerType.Labelled(linkedSetOf()) } } } })
35
Kotlin
23
482
ead70ab267ec1a5d9d6b4b3ed31cdcf7147af590
495
github-workflows-kt
Apache License 2.0
identity/ui/src/main/java/com/thechance/identity/ui/composable/BackButton.kt
Salmon-family
569,890,321
false
{"Kotlin": 837143}
package com.thechance.identity.ui.composable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.LayoutDirection import androidx.core.text.layoutDirection import com.thechance.identity.ui.R import java.util.* @Composable fun BackButton( onClick: () -> Unit, modifier: Modifier = Modifier, isEnabled: Boolean = true ) { Column( modifier = modifier.wrapContentSize(), horizontalAlignment = Alignment.Start ) { IconButton(onClick = onClick, enabled = isEnabled) { Icon( modifier = Modifier.flipWithLanguage(), imageVector = ImageVector.vectorResource(id = R.drawable.ic_back_arrow), contentDescription = null, tint = MaterialTheme.colors.primaryVariant, ) } } } fun Modifier.flipWithLanguage(): Modifier { val isLayoutRtl = Locale.getDefault().layoutDirection == LayoutDirection.Rtl.ordinal return if (isLayoutRtl) this.scale(scaleX = -1f, scaleY = 1f) else this }
11
Kotlin
19
24
7589d73a400c78ecfa94b24d87189b4f5e01de9b
1,487
Clubs
Apache License 2.0
app/src/main/java/com/gaugustini/vort/database/SkillDao.kt
gaugustini
416,395,415
false
null
package com.gaugustini.vort.database import androidx.room.Dao import androidx.room.Query import com.gaugustini.vort.model.Skill /** * The Data Access Object for [Skill]. */ @Dao interface SkillDao { /** * Returns a list of positive [Skill] for blademaster or gunner. */ @Query("SELECT * FROM skill WHERE points >= 10 AND type IN (0, :type)") suspend fun getSkillList(type: Int): List<Skill> }
0
Kotlin
0
0
2f26bb863801caab95733511c6683b527ef33f35
421
vort
MIT License
app/src/main/java/tr/com/gndg/self/domain/model/ImageUri.kt
Cr3bain
840,332,370
false
{"Kotlin": 567278}
package tr.com.gndg.self.domain.model import tr.com.gndg.self.core.dataSource.roomDatabase.entity.ImageUriEntity data class ImageUri( val id: Long?, val uuid: String, val productUUID: String, val imageUri: String? ) fun ImageUri.toImageUriEntity() = ImageUriEntity( uuid = this.uuid, productUUID = this.productUUID, imageUri = this.imageUri )
0
Kotlin
0
0
12e58c3753a642bfd922d9cca44486eef3453e88
373
self
Apache License 2.0
src/main/kotlin/cafe/ferret/kosekata/_Utils.kt
mazziechai
606,690,300
false
null
/* * Copyright (c) 2023 mazziechai */ package cafe.ferret.kosekata import cafe.ferret.kosekata.database.entities.Note import dev.kord.core.Kord import dev.kord.rest.builder.message.modify.MessageModifyBuilder import dev.kord.rest.builder.message.modify.embed import kotlinx.datetime.Instant import java.text.SimpleDateFormat /** * Formats an Instant to a string. */ fun formatTime(instant: Instant): String { val format = SimpleDateFormat("yyyy MMMM dd, HH:mm") return format.format(instant.epochSeconds * 1000L) + " UTC" } /** * An extension to create note embeds easily and consistently. * * @param kord The bot. * @param note The note to display. */ suspend fun MessageModifyBuilder.noteEmbed(kord: Kord, note: Note) { val noteUser = kord.getUser(note.author) val noteMember = noteUser?.asMemberOrNull(note.guild) embed { author { name = if (noteMember?.nickname != null) { "${noteMember.nickname} (${noteUser.tag})" } else { noteUser?.tag ?: "Unknown user" } icon = noteMember?.avatar?.url } title = note.name description = note.content footer { text = buildString { append("#${note._id.toString(16)} ") append("| Created on ${formatTime(note.timeCreated)}") } } } }
0
Kotlin
0
1
96e4c4482173cc8bd4953ea37e9ba1cdb3c83294
1,395
kose-kata
MIT License
prova01/Ex05_Main.kt
JoaoVitor-nks
765,941,398
false
{"Kotlin": 9774}
import java.time.LocalDate //Nome: João Vitor de Assis Martins e Eduardo Batista Barboza //Crie uma classe Tarefa que represente uma tarefa a ser realizada com atributos como título // , descrição, data de vencimento e prioridade. Crie uma classe GerenciadorDeTarefas que gerencie // uma lista de tarefas. Implemente métodos para adicionar, remover, buscar, marcar como concluída // e listar tarefas por data de vencimento. fun main() { val gerenciador = GerenciadorDeTarefas() // Adicionar algumas tarefas gerenciador.adicionarTarefa(Tarefa("fazer yoga", "ir todos os dias", LocalDate.of(2024, 4, 23), 1)) gerenciador.adicionarTarefa(Tarefa("apostar", "Fazer aposta diariamente até falir", LocalDate.of(2024, 5, 1), 3)) gerenciador.adicionarTarefa(Tarefa("trabalhar", "Fazer de tudo para nunca fazer isso", LocalDate.of(2024, 4, 25), 2)) // Marcar uma tarefa como concluída gerenciador.marcarComoConcluida("apostar") // Listar tarefas println("Todas as Tarefas:") println(gerenciador) // Listar tarefas concluídas println("\nTarefas Concluídas:") gerenciador.listarTarefasConcluidas().forEach { println(it) } // Listar tarefas por data de vencimento println("\nTarefas por Data de Vencimento:") gerenciador.listarTarefasPorDataVencimento().forEach { println(it) } // Listar tarefas Concluidas println("\nTarefas concluidas:") gerenciador.listarTarefasConcluidas().forEach { println(it) } // Listar tarefas Não Concluidas println("\nTarefas Não concluidas:") gerenciador.listarTarefasNaoConcluidas().forEach { println(it) } println() gerenciador.removerTarefa(Tarefa("fazer yoga", "ir todos os dias", LocalDate.of(2024, 4, 23), 1)) println("tarefa removida") println() // Listar tarefas println("Todas as Tarefas:") println(gerenciador) }
0
Kotlin
0
0
c6a30b4c8b9118faab660886773601bd477c97cb
1,909
programacao-mobile
MIT License
jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/Prioritize.kt
jitsi
9,657,943
false
null
/* * Copyright @ 2020 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.cc.allocation import org.jitsi.nlj.MediaSourceDesc import org.jitsi.videobridge.SsrcLimitConfig import org.jitsi.videobridge.calculateLastN import org.jitsi.videobridge.jvbLastNSingleton import org.jitsi.videobridge.load_management.ConferenceSizeLastNLimits.Companion.singleton as conferenceSizeLimits fun prioritize( conferenceSources: MutableList<MediaSourceDesc>, selectedSourceNames: List<String> = emptyList() ): List<MediaSourceDesc> { // Bump selected sources to the top of the list. selectedSourceNames.asReversed().forEach { selectedSourceName -> // Note the usage of sourceName!! which is expected to be always defined in the multi-stream mode conferenceSources.find { it.sourceName == selectedSourceName }?.let { selectedSource -> conferenceSources.remove(selectedSource) conferenceSources.add(0, selectedSource) } } return conferenceSources } /** * Return the "effective" constraints for the given media sources, i.e. the constraints adjusted for LastN. */ fun getEffectiveConstraints(sources: List<MediaSourceDesc>, allocationSettings: AllocationSettings): EffectiveConstraintsMap { // FIXME figure out before merge - is using source count instead of endpoints // Add 1 for the receiver endpoint, which is not in the list. val effectiveLastN = effectiveLastN(allocationSettings.lastN, sources.size + 1) // Keep track of the number of sources with non-zero constraints. Once [effectiveLastN] of them have been // added, all other sources have effectiveConstraints 0, because they would never be forwarded by the // algorithm. var sourcesWithNonZeroConstraints = 0 return sources.associateWith { source -> if (sourcesWithNonZeroConstraints >= effectiveLastN) { VideoConstraints.NOTHING } else { allocationSettings.getConstraints(source.sourceName).also { if (!it.isDisabled()) sourcesWithNonZeroConstraints++ } } } } /** * The LastN value adjusted according to the limits configured on the bridge, or [Int.MAX_VALUE] if LastN is disabled. */ private fun effectiveLastN(lastN: Int, conferenceSize: Int): Int { val adjustedLastN = calculateLastN( lastN, jvbLastNSingleton.jvbLastN, conferenceSizeLimits.getLastNLimit(conferenceSize), SsrcLimitConfig.config.maxVideoSsrcs ) return if (adjustedLastN < 0) Int.MAX_VALUE else adjustedLastN }
179
null
951
2,680
0aa0b1f672f1e92d0382f16145888746aa5cc6a2
3,153
jitsi-videobridge
Apache License 2.0
app/src/main/java/me/spica/spicaweather2/view/view_group/AirIntroduceLayout.kt
yangSpica27
720,276,419
false
{"Kotlin": 424276, "Java": 8338}
package me.spica.spicaweather2.view.view_group import android.content.Context import android.view.Gravity import android.view.ViewGroup import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import androidx.core.view.marginTop import me.spica.spicaweather2.R import me.spica.spicaweather2.tools.getStatusBarHeight class AirIntroduceLayout( context: Context, ) : AViewGroup(context) { private val title = AppCompatTextView(context).apply { text = context.getString(R.string.air_introduce_1) layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 12.dp + context.getStatusBarHeight() } gravity = Gravity.CENTER setTextAppearance(R.style.TextAppearance_Material3_HeadlineMedium) } private val subTitle = AppCompatTextView(context).apply { text = context.getString(R.string.air_introduce_2) layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 14.dp } setTextAppearance(R.style.TextAppearance_Material3_BodyMedium) } private val item1 = AirIntroduceItemLayout(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 20.dp } setData( context.getString(R.string.air_level1_introduce_name), context.getString(R.string.air_level1_introduce_title), context.getString(R.string.air_level1_introduce_body), ContextCompat.getColor(context, R.color.material_green_800), ContextCompat.getColor(context, R.color.material_green_100), ) } private val item2 = AirIntroduceItemLayout(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 12.dp } setData( context.getString(R.string.air_level2_introduce_name), context.getString(R.string.air_level2_introduce_title), context.getString(R.string.air_level2_introduce_body), ContextCompat.getColor(context, R.color.material_light_green_800), ContextCompat.getColor(context, R.color.material_light_green_100), ) } private val item3 = AirIntroduceItemLayout(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 12.dp } setData( context.getString(R.string.air_level3_introduce_name), context.getString(R.string.air_level3_introduce_title), context.getString(R.string.air_level3_introduce_body), ContextCompat.getColor(context, R.color.material_yellow_800), ContextCompat.getColor(context, R.color.material_yellow_100), ) } private val item4 = AirIntroduceItemLayout(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 12.dp } setData( context.getString(R.string.air_level4_introduce_name), context.getString(R.string.air_level4_introduce_title), context.getString(R.string.air_level4_introduce_body), ContextCompat.getColor(context, R.color.material_orange_800), ContextCompat.getColor(context, R.color.material_orange_100), ) } private val item5 = AirIntroduceItemLayout(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 12.dp } setData( context.getString(R.string.air_level5_introduce_name), context.getString(R.string.air_level5_introduce_title), context.getString(R.string.air_level5_introduce_body), ContextCompat.getColor(context, R.color.material_pink_800), ContextCompat.getColor(context, R.color.material_pink_100), ) } private val item6 = AirIntroduceItemLayout(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, ).apply { topMargin = 12.dp } setData( context.getString(R.string.air_level6_introduce_name), context.getString(R.string.air_level6_introduce_title), context.getString(R.string.air_level6_introduce_body), ContextCompat.getColor(context, R.color.material_red_800), ContextCompat.getColor(context, R.color.material_red_100), ) } init { setPadding(14.dp, 20.dp, 14.dp, 20.dp) addView(title) addView(subTitle) addView(item1) addView(item2) addView(item3) addView(item4) addView(item5) addView(item6) } override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int, ) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) title.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), title.defaultHeightMeasureSpec(this), ) subTitle.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), subTitle.defaultHeightMeasureSpec(this), ) item1.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), item1.defaultHeightMeasureSpec(this), ) item2.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), item2.defaultHeightMeasureSpec(this), ) item3.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), item3.defaultHeightMeasureSpec(this), ) item4.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), item4.defaultHeightMeasureSpec(this), ) item5.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), item5.defaultHeightMeasureSpec(this), ) item6.measure( (measuredWidth - paddingLeft - paddingRight).toExactlyMeasureSpec(), item6.defaultHeightMeasureSpec(this), ) setMeasuredDimension( measuredWidth, paddingTop + paddingBottom + title.measuredHeightWithMargins + subTitle.measuredHeightWithMargins + item1.measuredHeightWithMargins + item2.measuredHeightWithMargins + item3.measuredHeightWithMargins + item4.measuredHeightWithMargins + item5.measuredHeightWithMargins + item6.measuredHeightWithMargins, ) } override fun onLayout( p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int, ) { title.layout( paddingLeft, paddingTop + title.marginTop, ) subTitle.layout( paddingLeft, title.bottom + subTitle.marginTop, ) item1.layout( paddingLeft, subTitle.bottom + item1.marginTop, ) item2.layout( paddingLeft, item1.bottom + item2.marginTop, ) item3.layout( paddingLeft, item2.bottom + item3.marginTop, ) item4.layout( paddingLeft, item3.bottom + item4.marginTop, ) item5.layout( paddingLeft, item4.bottom + item5.marginTop, ) item6.layout( paddingLeft, item5.bottom + item6.marginTop, ) } }
0
Kotlin
1
9
c820893d93f955cfb5f7228f22af9216c6caa9de
9,093
SpicaWeather2
MIT License
sqllin-dsl/src/commonMain/kotlin/com/ctrip/sqllin/dsl/sql/clause/GroupByClause.kt
ctripcorp
570,015,389
false
{"C": 576161, "Kotlin": 247558, "Shell": 1539}
/* * Copyright (C) 2022 Ctrip.com. * * 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.ctrip.sqllin.dsl.sql.clause import com.ctrip.sqllin.dsl.sql.statement.GroupBySelectStatement import com.ctrip.sqllin.dsl.sql.statement.JoinSelectStatement import com.ctrip.sqllin.dsl.sql.statement.WhereSelectStatement /** * SQL 'GROUP BY' clause by select statement * @author yaqiao */ public class GroupByClause<T> internal constructor(private val columnNames: Iterable<ClauseElement>) : SelectClause<T> { override val clauseStr: String get() = buildString { append(" GROUP BY ") val iterator = columnNames.iterator() require(iterator.hasNext()) { "Please provider at least one 'BaseClauseElement' for 'GROUP BY' clause!!!" } append(iterator.next().valueName) while (iterator.hasNext()) { append(',') append(iterator.next().valueName) } } } public fun <T> GROUP_BY(vararg elements: ClauseElement): GroupByClause<T> = GroupByClause(elements.toList()) public infix fun <T> WhereSelectStatement<T>.GROUP_BY(element: ClauseElement): GroupBySelectStatement<T> = appendToGroupBy(GroupByClause(listOf(element))).also { container changeLastStatement it } public infix fun <T> WhereSelectStatement<T>.GROUP_BY(elements: Iterable<ClauseElement>): GroupBySelectStatement<T> { val statement = appendToGroupBy(GroupByClause(elements)) container changeLastStatement statement return statement } public infix fun <T> JoinSelectStatement<T>.GROUP_BY(element: ClauseElement): GroupBySelectStatement<T> = appendToGroupBy(GroupByClause(listOf(element))).also { container changeLastStatement it } public infix fun <T> JoinSelectStatement<T>.GROUP_BY(elements: Iterable<ClauseElement>): GroupBySelectStatement<T> { val statement = appendToGroupBy(GroupByClause(elements)) container changeLastStatement statement return statement }
2
C
10
217
4872fddad7ad72f5f95e14ad831b3ebb7fc87d47
2,514
SQLlin
Apache License 2.0
kotlin-antd/antd-samples/src/main/kotlin/samples/localeprovider/Basic.kt
xlj44400
248,655,590
true
{"Kotlin": 1516065, "HTML": 1503}
package samples.localeprovider import antd.localeprovider.* import antd.pagination.* import react.* import react.dom.* import styled.* fun RBuilder.basicApp() { div { pagination { attrs { defaultCurrent = 1 total = 50 showSizeChanger = true } } } } fun RBuilder.basic() { styledDiv { css { LocaleProviderStyles.basic } localeProvider { attrs.locale = zhCN basicApp() } } }
0
Kotlin
0
0
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
528
kotlin-js-wrappers
Apache License 2.0
src/main/kotlin/ds/Queue.kt
xmmmmmovo
280,634,710
false
null
/* * Copyright (c) 2020. xmmmmmovo */ package ds /** * 单向队列类 * @author xmmmmmovo * @date 2020/7/28 16:44 * @since version-1.0 */ class Queue<T> : Collection<T> { private var first: Node<T>? = null private var last: Node<T>? = null private var n: Int = 0 constructor() constructor(q: Queue<T>) { for (i in q) { enqueue(i) } } override fun isEmpty(): Boolean = first == null /** * 入队列 * */ fun enqueue(item: T) { val ol = last last = Node( item, null ) if (isEmpty()) { first = last } else { ol?.next = last } n++ } /** * 出队列 * */ fun dequeue(): T { if (isEmpty()) { throw NoSuchElementException("Stack underflow") } return first?.item.also { first = first?.next n-- if (isEmpty()) { last = null } }!! } /** * 查看队列首 * */ fun peek(): T { if (isEmpty()) { throw NoSuchElementException("Stack underflow") } return first?.item!! } override val size: Int get() = n /** * 是否包含[element] * */ override fun contains(element: T): Boolean { return indexOf(element) != -1 } /** * 是否包含所有[elements] * */ override fun containsAll(elements: Collection<T>): Boolean = if (elements.isEmpty()) false else elements.all { contains(it) } /** * 查看[element]的位置 * */ private fun indexOf(element: T): Int { var index = 0 this.forEach { if (it == element) { return index } index++ } return -1 } override fun toString(): String { return StringBuilder().also { this.forEach { item -> it.append("$item ") } }.toString() } override fun iterator(): Iterator<T> { return LinkedIterator(first) } companion object { private data class Node<T>( val item: T, var next: Node<T>? = null ) } private class LinkedIterator<T>( private var current: Node<T>? ) : Iterator<T> { override fun hasNext(): Boolean { return current != null } override fun next(): T { if (!hasNext()) { throw NoSuchElementException() } val item = current?.item current = current?.next return item!! } } }
0
Kotlin
0
0
94da0519cf2b8d8a9b42b4aea09caf50d9732599
2,746
Algorithms4thEditionKotlinSolutions
Apache License 2.0
src/main/kotlin/com/example/demo3/model/Repository.kt
wenvelope
524,697,668
false
{"Kotlin": 16341}
package com.example.demo3.model import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "repository") data class Repository( @Id var uid:String ?=null, @Column var name:String ?=null, @Column var country:String?=null, @Column var area:String?=null, @Column var state:String?=null ){ constructor():this(null,null,null,null,null) }
0
Kotlin
0
0
422afdc84f07844dc4bbad1bc041dc4a41cfe57d
465
SpringBootDemo
MIT License
src/main/kotlin/mixit/ticket/model/TicketService.kt
mixitconf
76,134,720
false
null
package mixit.ticket.model import mixit.ticket.repository.TicketRepository import mixit.util.cache.CacheTemplate import mixit.util.cache.CacheZone import mixit.util.errors.DuplicateException import org.springframework.stereotype.Service import reactor.core.publisher.Mono @Service class TicketService( private val repository: TicketRepository ) : CacheTemplate<CachedTicket>() { override val cacheZone: CacheZone = CacheZone.TICKET override fun findAll(): Mono<List<CachedTicket>> = findAll { repository.findAll().map { ticket -> CachedTicket(ticket) }.collectList() } fun findByNumber(number: String): Mono<CachedTicket> = findAll().flatMap { tickets -> Mono.justOrEmpty(tickets.firstOrNull { it.number == number }) } fun findByEncryptedEmail(encryptedEmail: String): Mono<CachedTicket> = findAll().flatMap { tickets -> Mono.justOrEmpty(tickets.firstOrNull { it.encryptedEmail == encryptedEmail }) } fun findByLogin(login: String?): Mono<CachedTicket> = findAll().flatMap { tickets -> val ticket = tickets.filter { it.login != null }.firstOrNull() { it.login == login } return@flatMap if (ticket == null) Mono.empty() else Mono.just(ticket) } fun save(ticket: Ticket): Mono<CachedTicket> = findByEncryptedEmail(ticket.encryptedEmail) .flatMap { Mono.error<CachedTicket> { DuplicateException("") } } .switchIfEmpty( repository.save(ticket).map { CachedTicket(it) } .doOnSuccess { cache.invalidateAll() } ) fun deleteOne(id: String) = repository.deleteOne(id).doOnSuccess { cache.invalidateAll() } }
12
Kotlin
125
526
cde6cbedac3a6b7dab1978ebf7e18ffe58cde0a1
1,692
mixit
Apache License 2.0
frontend/app/src/main/java/com/example/library_management_system/presentation/navigations/bottomnavbar/NavGraph.kt
aasif21
835,881,037
false
{"Kotlin": 75858, "JavaScript": 8858}
package com.example.library_management_system.presentation.navigations.bottomnavbar import androidx.compose.runtime.Composable import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.example.library_management_system.presentation.UI.bottombar.UiScreen.Create.CreateScreen import com.example.library_management_system.presentation.UI.bottombar.UiScreen.HomeScreen.MyScreen import com.example.library_management_system.presentation.UI.bottombar.UiScreen.Update.UpdateScreen @Composable fun NavGraph(navController: NavHostController) { NavHost( navController = navController, startDestination = BottomScreens.Home.name, ) { composable(route = BottomScreens.Home.name) { MyScreen() } composable(route = BottomScreens.Update.name) { UpdateScreen(navController) } composable(route = BottomScreens.Create.name) { CreateScreen(navController) } } }
0
Kotlin
0
0
aa41f515fe703505ba9a0ecf047241f34f3f08ad
1,086
Library_Management_System
MIT License
geary-core/src/commonMain/kotlin/com/mineinabyss/geary/context/FormatsContext.kt
MineInAbyss
306,093,350
false
null
package com.mineinabyss.geary.context import com.mineinabyss.geary.serialization.GearyFormats public interface FormatsContext { public val formats: GearyFormats }
19
Kotlin
9
23
b4e5b1b5365d600cdd5eda11ae4d4a0c8249165b
169
Geary
MIT License
authinterceptor/src/main/java/com/matt/authinterceptor/HeaderWriter.kt
mattdrzazga
137,091,064
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 17, "Kotlin": 17}
package com.matt.authinterceptor import okhttp3.Request class HeaderWriter(private val repository: TokenStore) { var defaultWithToken = true fun modifyRequest(request: Request): Request.Builder { val token = repository.getToken() val header = repository.getTokenHeader() val builder = request.newBuilder() removeAuthHeaders(builder) if (hasAuthHeader(request)) { return builder.addHeader(header, token) } if (hasNoAuthHeader(request)) { return builder } if (defaultWithToken) { return builder.addHeader(header, token) } return builder } private fun removeAuthHeaders(builder: Request.Builder) { builder.removeHeader(Header.AUTH) builder.removeHeader(Header.NO_AUTH) } private fun hasNoAuthHeader(request: Request): Boolean { return request.headers().values(Header.AT).contains(Header.VALUE_NO_AUTH) } private fun hasAuthHeader(request: Request): Boolean { return request.headers().values(Header.AT).contains(Header.VALUE_AUTH) } }
0
Kotlin
0
1
093d1dad86b9b6e20957a8c46744e9c577bfad07
1,130
AuthInterceptor
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Investment.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.Investment: ImageVector get() { if (_investment != null) { return _investment!! } _investment = Builder(name = "Investment", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(6.75f, 9.0f) horizontalLineToRelative(3.5f) curveToRelative(1.517f, 0.0f, 2.75f, -1.31f, 2.75f, -2.919f) curveToRelative(0.0f, -1.78f, -1.807f, -3.724f, -3.46f, -4.363f) curveToRelative(0.486f, -0.453f, 0.96f, -1.063f, 0.96f, -1.717f) horizontalLineToRelative(-4.0f) curveToRelative(0.0f, 0.654f, 0.474f, 1.264f, 0.96f, 1.717f) curveToRelative(-1.653f, 0.64f, -3.46f, 2.584f, -3.46f, 4.363f) curveToRelative(0.0f, 1.61f, 1.233f, 2.919f, 2.75f, 2.919f) close() moveTo(8.5f, 3.5f) curveToRelative(0.745f, 0.0f, 2.5f, 1.527f, 2.5f, 2.581f) curveToRelative(0.0f, 0.507f, -0.336f, 0.919f, -0.75f, 0.919f) horizontalLineToRelative(-3.5f) curveToRelative(-0.414f, 0.0f, -0.75f, -0.413f, -0.75f, -0.919f) curveToRelative(0.0f, -1.054f, 1.755f, -2.581f, 2.5f, -2.581f) close() moveTo(23.018f, 8.785f) curveToRelative(-0.595f, -0.542f, -1.356f, -0.82f, -2.169f, -0.782f) curveToRelative(-0.804f, 0.037f, -1.545f, 0.386f, -2.085f, 0.981f) lineToRelative(-3.217f, 3.534f) curveToRelative(-0.551f, -0.91f, -1.55f, -1.519f, -2.689f, -1.519f) lineTo(3.0f, 10.999f) curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f) verticalLineToRelative(7.0f) curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f) horizontalLineToRelative(10.448f) lineToRelative(9.787f, -10.984f) curveToRelative(1.094f, -1.226f, 0.996f, -3.123f, -0.218f, -4.23f) close() moveTo(21.743f, 11.684f) lineToRelative(-9.19f, 10.316f) lineTo(3.0f, 22.0f) curveToRelative(-0.551f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f) verticalLineToRelative(-7.0f) curveToRelative(0.0f, -0.552f, 0.449f, -1.0f, 1.0f, -1.0f) horizontalLineToRelative(9.858f) curveToRelative(0.629f, 0.0f, 1.142f, 0.513f, 1.142f, 1.143f) curveToRelative(0.0f, 0.564f, -0.421f, 1.051f, -0.98f, 1.13f) lineToRelative(-5.161f, 0.737f) lineToRelative(0.283f, 1.98f) lineToRelative(5.161f, -0.737f) curveToRelative(1.175f, -0.168f, 2.129f, -0.988f, 2.514f, -2.059f) lineToRelative(4.427f, -4.864f) curveToRelative(0.181f, -0.2f, 0.43f, -0.316f, 0.699f, -0.329f) curveToRelative(0.272f, -0.008f, 0.529f, 0.082f, 0.728f, 0.262f) curveToRelative(0.407f, 0.372f, 0.44f, 1.009f, 0.072f, 1.421f) close() moveTo(15.251f, 4.75f) lineToRelative(-1.414f, -1.414f) lineToRelative(2.75f, -2.75f) curveToRelative(0.779f, -0.78f, 2.049f, -0.78f, 2.828f, 0.0f) lineToRelative(2.752f, 2.752f) lineToRelative(-1.414f, 1.414f) lineToRelative(-1.752f, -1.752f) verticalLineToRelative(3.422f) curveToRelative(-0.644f, 0.279f, -1.231f, 0.682f, -1.716f, 1.216f) lineToRelative(-0.284f, 0.312f) lineTo(17.001f, 3.0f) lineToRelative(-1.75f, 1.75f) close() } } .build() return _investment!! } private var _investment: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,762
icons
MIT License
app/src/main/kotlin/com/mounacheikhna/nearby/ui/venues/VenuesView.kt
chemouna
47,512,499
false
null
package com.mounacheikhna.nearby.ui.venues import android.Manifest import android.annotation.TargetApi import android.content.Context import android.graphics.Color import android.os.Build import android.support.annotation.StringRes import android.support.design.widget.Snackbar import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import butterknife.bindView import com.jakewharton.rxbinding.support.design.widget.RxSnackbar import com.mounacheikhna.nearby.FoursquareApp import com.mounacheikhna.nearby.R import com.mounacheikhna.nearby.ui.BetterViewAnimator import com.mounacheikhna.nearby.ui.DividerItemDecoration import com.squareup.picasso.Picasso import com.tbruyelle.rxpermissions.RxPermissions import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subjects.PublishSubject import javax.inject.Inject class VenuesView : LinearLayout, VenuesScreen { /** * A {@link PublishSubject} to let subscribers know that the user wants to cancel * the current fetch for location */ private var cancelFetchForLocation: PublishSubject<Void> = PublishSubject.create() val venuesList: RecyclerView by bindView(R.id.venues_list) val venuesAnimator: BetterViewAnimator by bindView(R.id.venues_animator) lateinit var venuesAdapter: VenuesAdapter @Inject lateinit var rxPermissions: RxPermissions @Inject lateinit var picasso: Picasso @Inject lateinit var presenter: VenuesPresenter public constructor(context: Context) : super(context) { init(context); } public constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context); } public constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context); } private fun init(context: Context) { LayoutInflater.from(context).inflate(R.layout.nearby_venues_view, this, true) orientation = VERTICAL } override fun onAttachedToWindow() { super.onAttachedToWindow() FoursquareApp.appComponent.inject(this) presenter.onAttach(this) venuesAdapter = VenuesAdapter(picasso) venuesList.adapter = venuesAdapter venuesList.layoutManager = LinearLayoutManager(context) val dividerPaddingStart = resources.getDimension(R.dimen.venue_divider_padding_start) val forRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isRtl() venuesList.addItemDecoration( DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST, dividerPaddingStart, forRtl)) checkLocationPermission() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() //subscriptions.unsubscribe() //unsubscribe from all to avoid leaks presenter.onDetach() } /** * Check for location permissions (granted pre-Marshmallow and asks the use for them * in Marshmallow and up). * */ private fun checkLocationPermission() { presenter.addSubscription(rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION) .subscribe({ granted -> if (granted) { onLocationPermissionsGranted() } else { val message = R.string.error_permission_not_granted showSnackbar(message) } }, { error -> showSnackbar(error.message ?: "error") })) } private fun onLocationPermissionsGranted() { var subscription = presenter.fetchVenuesForLocations() .subscribe( { venueResult -> if (venuesAnimator.getDisplayedChildId() !== R.id.venues_list) { venuesAnimator.setDisplayedChildId(R.id.venues_list) } venuesAdapter.call(venueResult) }, { error -> venuesAnimator.setDisplayedChildId(R.id.venues_error) }, { if (venuesAnimator.getDisplayedChildId() !== R.id.venues_list && venuesAnimator.getDisplayedChildId() !== R.id.venues_error) { //no result venuesAnimator.setDisplayedChildId(R.id.venues_empty) } } ) presenter.addSubscription(subscription) } override fun onNewLocationUpdate() { var snackBar = Snackbar.make(this, R.string.info_location_changed_fetch, Snackbar.LENGTH_LONG) .setActionTextColor(Color.WHITE) .setAction(R.string.cancel, { /* click action is specified in dismiss subscribe method*/ }) var snackBarSubscription = RxSnackbar.dismisses(snackBar) .firstOrDefault(0) .subscribe { eventId -> when (eventId) { Snackbar.Callback.DISMISS_EVENT_ACTION -> { cancelFetchForLocation.onNext(null) //triggers cancel on presenter } else -> { venuesAdapter.clear() } } } presenter.addSubscription(snackBarSubscription) snackBar.show(); } override fun cancelRefreshForLocation(): Observable<Void> { return cancelFetchForLocation } private fun showSnackbar(message: String) { Snackbar.make(this, message, Snackbar.LENGTH_LONG) .setActionTextColor(Color.WHITE) .show() } private fun showSnackbar(@StringRes message: Int) { Snackbar.make(this, message, Snackbar.LENGTH_LONG) .setActionTextColor(Color.WHITE) .show() } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private fun isRtl(): Boolean { return layoutDirection == View.LAYOUT_DIRECTION_RTL } }
3
Kotlin
6
40
08ffa6a851bf07866b34de2961fa9d1fbc9f9413
6,250
Nearby
Apache License 2.0
gsmovies/src/main/java/com/kyawhut/astycast/gsmovie/data/network/response/VideoResponse.kt
kyawhtut-cu
406,324,527
false
null
package com.kyawhut.astycast.gsmovie.data.network.response import androidx.annotation.Keep import androidx.leanback.widget.DiffCallback import com.google.gson.annotations.SerializedName import java.io.Serializable /** * @author kyawhtut * @date 9/29/21 */ @Keep data class VideoResponse( @SerializedName("status") val status: Int, @SerializedName("message") val message: String, @SerializedName("data") val data: List<Data>? ) { @Keep data class Data( @SerializedName("video_id") val videoID: String, @SerializedName("video_title") val videoTitle: String, @SerializedName("video_poster") val videoPoster: String, @SerializedName("video_cover") val videoCover: String, @SerializedName("video_view_count") val videoViewCount: String, @SerializedName("video_episode") val videoEpisode: String ) : Serializable { companion object { val diff = object : DiffCallback<Data>() { override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean { return oldItem.videoID == newItem.videoID } override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean { return oldItem == newItem } } } } }
0
Kotlin
4
3
72d56fa28f5be7526f0a9848491ddd87cca3804d
1,382
atsy-cast
Apache License 2.0
src/main/kotlin/net/darkdevelopers/magmarun/functions/Player.kt
chain3d
192,891,966
false
null
package net.darkdevelopers.magmarun.functions import de.astride.minecraft.servercore.spigot.ServerCoreSpigotPlugin import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.darkdevelopers.darkbedrock.darkness.spigot.functions.schedule import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.plugin.Plugin /* * Created on 30.06.2019 02:10. * @author <NAME> | LartyHD */ fun Player.removeBlock(plugin: Plugin = ServerCoreSpigotPlugin.javaPlugin) { val location = player.location.subtract(0.0, 1.0, 0.0) val type = location.block.type if (type == Material.AIR) return GlobalScope.launch { delay(100) plugin.schedule { location.block.type = Material.AIR //removes the block } } }
0
Kotlin
0
2
03d10d14009d65634f350c04d7b1750db266550c
815
MagmaRun
MIT License
app/src/main/java/cz/bornasp/charging/data/UserPreferencesRepository.kt
bugulin
603,802,191
false
null
package cz.bornasp.charging.data import android.util.Log import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.floatPreferencesKey import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import java.io.IOException private const val TAG = "UserPreferencesRepo" const val DEFAULT_CHARGE_ALARM_TARGET = 1f const val DEFAULT_CHARGE_ALARM_ENABLED = false const val DEFAULT_CHARGE_ALARM_WENT_OFF = true /** * Repository that stores user preferences. */ class UserPreferencesRepository( private val dataStore: DataStore<Preferences> ) { val chargeAlarmTarget: Flow<Float> = dataStore.data .catch { if (it is IOException) { Log.e(TAG, "Error reading preferences.", it) emit(emptyPreferences()) } else { throw it } } .map { preferences -> preferences[CHARGE_ALARM_TARGET] ?: DEFAULT_CHARGE_ALARM_TARGET } val isChargeAlarmEnabled: Flow<Boolean> = dataStore.data .catch { if (it is IOException) { Log.e(TAG, "Error reading preferences.", it) emit(emptyPreferences()) } else { throw it } } .map { preferences -> preferences[CHARGE_ALARM_ENABLED] ?: DEFAULT_CHARGE_ALARM_ENABLED } val chargeAlarmInformation: Flow<ChargeAlarmInformation> = dataStore.data .catch { if (it is IOException) { Log.e(TAG, "Error reading preferences.", it) emit(emptyPreferences()) } else { throw it } } .map { preferences -> ChargeAlarmInformation( isEnabled = preferences[CHARGE_ALARM_ENABLED] ?: DEFAULT_CHARGE_ALARM_ENABLED, targetCharge = preferences[CHARGE_ALARM_TARGET] ?: DEFAULT_CHARGE_ALARM_TARGET, wentOff = preferences[CHARGE_ALARM_WENT_OFF] ?: DEFAULT_CHARGE_ALARM_WENT_OFF ) } suspend fun updateChargeAlarm(isEnabled: Boolean, target: Float?) { dataStore.edit { preferences -> preferences[CHARGE_ALARM_ENABLED] = isEnabled if (target != null) preferences[CHARGE_ALARM_TARGET] = target } } suspend fun setChargeAlarmWentOff(value: Boolean) { dataStore.edit { preferences -> preferences[CHARGE_ALARM_WENT_OFF] = value } } private companion object { val CHARGE_ALARM_ENABLED = booleanPreferencesKey("charge_alarm_enabled") val CHARGE_ALARM_TARGET = floatPreferencesKey("charge_alarm_target") val CHARGE_ALARM_WENT_OFF = booleanPreferencesKey("charge_alarm_rang") } }
0
Kotlin
0
1
cb76e1af0976eb4c9410f413748dfc59e95e511c
3,040
Charging
Apache License 2.0
airbyte-cdk/java/airbyte-cdk/core/src/test/kotlin/io/airbyte/cdk/integrations/base/IntegrationRunnerTest.kt
tim-werner
511,419,970
false
{"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2}
/* * Copyright (c) 2023 Airbyte, Inc., all rights reserved. */ package io.airbyte.cdk.integrations.base import com.fasterxml.jackson.databind.JsonNode import com.google.common.collect.ImmutableMap import com.google.common.collect.Lists import io.airbyte.cdk.integrations.util.ConnectorExceptionUtil import io.airbyte.commons.exceptions.ConfigErrorException import io.airbyte.commons.io.IOs import io.airbyte.commons.json.Jsons import io.airbyte.commons.util.AutoCloseableIterators import io.airbyte.commons.util.MoreIterators import io.airbyte.protocol.models.v0.* import io.airbyte.validation.json.JsonSchemaValidator import io.github.oshai.kotlinlogging.KotlinLogging import java.io.* import java.net.URI import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer import org.apache.commons.lang3.ThreadUtils import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.mock private val LOGGER = KotlinLogging.logger {} internal class IntegrationRunnerTest { private lateinit var cliParser: IntegrationCliParser private lateinit var stdoutConsumer: Consumer<AirbyteMessage> private lateinit var destination: Destination private lateinit var source: Source private lateinit var configPath: Path private lateinit var configuredCatalogPath: Path private lateinit var statePath: Path private lateinit var configDir: Path @BeforeEach @Throws(IOException::class) fun setup() { cliParser = mock() stdoutConsumer = mock() destination = mock() source = mock() configDir = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), "test") configPath = IOs.writeFile(configDir, CONFIG_FILE_NAME, CONFIG_STRING) configuredCatalogPath = IOs.writeFile( configDir, CONFIGURED_CATALOG_FILE_NAME, Jsons.serialize(CONFIGURED_CATALOG) ) statePath = IOs.writeFile(configDir, STATE_FILE_NAME, Jsons.serialize(STATE)) val testName = Thread.currentThread().name ThreadUtils.getAllThreads() .filter { runningThread: Thread -> !runningThread.isDaemon } .forEach { runningThread: Thread -> runningThread.name = testName } } @Test @Throws(Exception::class) fun testSpecSource() { val intConfig = IntegrationConfig.spec() val output = ConnectorSpecification().withDocumentationUrl(URI("https://docs.airbyte.io/")) Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(source.spec()).thenReturn(output) IntegrationRunner(cliParser, stdoutConsumer, null, source).run(ARGS) Mockito.verify(source).spec() Mockito.verify(stdoutConsumer) .accept(AirbyteMessage().withType(AirbyteMessage.Type.SPEC).withSpec(output)) } @Test @Throws(Exception::class) fun testSpecDestination() { val intConfig = IntegrationConfig.spec() val output = ConnectorSpecification().withDocumentationUrl(URI("https://docs.airbyte.io/")) Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(destination.spec()).thenReturn(output) IntegrationRunner(cliParser, stdoutConsumer, destination, null).run(ARGS) Mockito.verify(destination).spec() Mockito.verify(stdoutConsumer) .accept(AirbyteMessage().withType(AirbyteMessage.Type.SPEC).withSpec(output)) } @Test @Throws(Exception::class) fun testCheckSource() { val intConfig = IntegrationConfig.check(configPath) val output = AirbyteConnectionStatus() .withStatus(AirbyteConnectionStatus.Status.FAILED) .withMessage("it failed") Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(source.check(CONFIG)).thenReturn(output) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(source.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) IntegrationRunner(cliParser, stdoutConsumer, null, source, jsonSchemaValidator).run(ARGS) Mockito.verify(source).check(CONFIG) Mockito.verify(stdoutConsumer) .accept( AirbyteMessage() .withType(AirbyteMessage.Type.CONNECTION_STATUS) .withConnectionStatus(output) ) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testCheckDestination() { val intConfig = IntegrationConfig.check(configPath) val output = AirbyteConnectionStatus() .withStatus(AirbyteConnectionStatus.Status.FAILED) .withMessage("it failed") Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(destination.check(CONFIG)).thenReturn(output) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(destination.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) IntegrationRunner(cliParser, stdoutConsumer, destination, null, jsonSchemaValidator) .run(ARGS) Mockito.verify(destination).check(CONFIG) Mockito.verify(stdoutConsumer) .accept( AirbyteMessage() .withType(AirbyteMessage.Type.CONNECTION_STATUS) .withConnectionStatus(output) ) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testDiscover() { val intConfig = IntegrationConfig.discover(configPath) val output = AirbyteCatalog().withStreams(Lists.newArrayList(AirbyteStream().withName("oceans"))) Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(source.discover(CONFIG)).thenReturn(output) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(source.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) IntegrationRunner(cliParser, stdoutConsumer, null, source, jsonSchemaValidator).run(ARGS) Mockito.verify(source).discover(CONFIG) Mockito.verify(stdoutConsumer) .accept(AirbyteMessage().withType(AirbyteMessage.Type.CATALOG).withCatalog(output)) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testRead() { val intConfig = IntegrationConfig.read(configPath, configuredCatalogPath, statePath) val message1 = AirbyteMessage() .withType(AirbyteMessage.Type.RECORD) .withRecord( AirbyteRecordMessage() .withData(Jsons.jsonNode(ImmutableMap.of("names", "byron"))) ) val message2 = AirbyteMessage() .withType(AirbyteMessage.Type.RECORD) .withRecord( AirbyteRecordMessage() .withData(Jsons.jsonNode(ImmutableMap.of("names", "reginald"))) ) Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(source.read(CONFIG, CONFIGURED_CATALOG, STATE)) .thenReturn(AutoCloseableIterators.fromIterator(MoreIterators.of(message1, message2))) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(source.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) IntegrationRunner(cliParser, stdoutConsumer, null, source, jsonSchemaValidator).run(ARGS) // noinspection resource Mockito.verify(source).read(CONFIG, CONFIGURED_CATALOG, STATE) Mockito.verify(stdoutConsumer).accept(message1) Mockito.verify(stdoutConsumer).accept(message2) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testCheckNestedException() { val intConfig = IntegrationConfig.check(configPath) val output = AirbyteConnectionStatus() .withStatus(AirbyteConnectionStatus.Status.FAILED) .withMessage("Invalid configuration") val configErrorException = ConfigErrorException("Invalid configuration") val runtimeException = RuntimeException(RuntimeException(configErrorException)) Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(source.check(CONFIG)).thenThrow(runtimeException) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(source.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) IntegrationRunner(cliParser, stdoutConsumer, null, source, jsonSchemaValidator).run(ARGS) Mockito.verify(source).check(CONFIG) Mockito.verify(stdoutConsumer) .accept( AirbyteMessage() .withType(AirbyteMessage.Type.CONNECTION_STATUS) .withConnectionStatus(output) ) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testCheckRuntimeException() { val intConfig = IntegrationConfig.check(configPath) val output = AirbyteConnectionStatus() .withStatus(AirbyteConnectionStatus.Status.FAILED) .withMessage( String.format( ConnectorExceptionUtil.COMMON_EXCEPTION_MESSAGE_TEMPLATE, "Runtime Error" ) ) val runtimeException = RuntimeException("Runtime Error") Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`(source.check(CONFIG)).thenThrow(runtimeException) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(source.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) IntegrationRunner(cliParser, stdoutConsumer, null, source, jsonSchemaValidator).run(ARGS) Mockito.verify(source).check(CONFIG) Mockito.verify(stdoutConsumer) .accept( AirbyteMessage() .withType(AirbyteMessage.Type.CONNECTION_STATUS) .withConnectionStatus(output) ) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testWrite() { val intConfig = IntegrationConfig.write(configPath, configuredCatalogPath) val consumerMock = Mockito.mock(SerializedAirbyteMessageConsumer::class.java) Mockito.`when`(cliParser.parse(ARGS)).thenReturn(intConfig) Mockito.`when`( destination.getSerializedMessageConsumer(CONFIG, CONFIGURED_CATALOG, stdoutConsumer) ) .thenReturn(consumerMock) val expectedConnSpec = Mockito.mock(ConnectorSpecification::class.java) Mockito.`when`(destination.spec()).thenReturn(expectedConnSpec) Mockito.`when`(expectedConnSpec.connectionSpecification).thenReturn(CONFIG) val jsonSchemaValidator = Mockito.mock(JsonSchemaValidator::class.java) val runner = Mockito.spy( IntegrationRunner(cliParser, stdoutConsumer, destination, null, jsonSchemaValidator) ) runner.run(ARGS) Mockito.verify(destination) .getSerializedMessageConsumer(CONFIG, CONFIGURED_CATALOG, stdoutConsumer) Mockito.verify(jsonSchemaValidator).validate(any(), any()) } @Test @Throws(Exception::class) fun testDestinationConsumerLifecycleSuccess() { val message1 = AirbyteMessage() .withType(AirbyteMessage.Type.RECORD) .withRecord( AirbyteRecordMessage() .withData(Jsons.deserialize("{ \"color\": \"blue\" }")) .withStream(STREAM_NAME) .withEmittedAt(EMITTED_AT) ) val message2 = AirbyteMessage() .withType(AirbyteMessage.Type.RECORD) .withRecord( AirbyteRecordMessage() .withData(Jsons.deserialize("{ \"color\": \"yellow\" }")) .withStream(STREAM_NAME) .withEmittedAt(EMITTED_AT) ) val stateMessage = AirbyteMessage() .withType(AirbyteMessage.Type.STATE) .withState( AirbyteStateMessage().withData(Jsons.deserialize("{ \"checkpoint\": \"1\" }")) ) System.setIn( ByteArrayInputStream( """${Jsons.serialize(message1)} ${Jsons.serialize(message2)} ${Jsons.serialize(stateMessage)}""".toByteArray( StandardCharsets.UTF_8 ) ) ) Mockito.mock<SerializedAirbyteMessageConsumer>(SerializedAirbyteMessageConsumer::class.java) .use { airbyteMessageConsumerMock -> IntegrationRunner.consumeWriteStream(airbyteMessageConsumerMock) val inOrder = Mockito.inOrder(airbyteMessageConsumerMock) inOrder .verify(airbyteMessageConsumerMock) .accept( Jsons.serialize(message1), Jsons.serialize(message1).toByteArray(StandardCharsets.UTF_8).size ) inOrder .verify(airbyteMessageConsumerMock) .accept( Jsons.serialize(message2), Jsons.serialize(message2).toByteArray(StandardCharsets.UTF_8).size ) inOrder .verify(airbyteMessageConsumerMock) .accept( Jsons.serialize(stateMessage), Jsons.serialize(stateMessage).toByteArray(StandardCharsets.UTF_8).size ) } } @Test @Throws(Exception::class) fun testDestinationConsumerLifecycleFailure() { val message1 = AirbyteMessage() .withType(AirbyteMessage.Type.RECORD) .withRecord( AirbyteRecordMessage() .withData(Jsons.deserialize("{ \"color\": \"blue\" }")) .withStream(STREAM_NAME) .withEmittedAt(EMITTED_AT) ) val message2 = AirbyteMessage() .withType(AirbyteMessage.Type.RECORD) .withRecord( AirbyteRecordMessage() .withData(Jsons.deserialize("{ \"color\": \"yellow\" }")) .withStream(STREAM_NAME) .withEmittedAt(EMITTED_AT) ) System.setIn( ByteArrayInputStream( """${Jsons.serialize(message1)} ${Jsons.serialize(message2)}""".toByteArray( StandardCharsets.UTF_8 ) ) ) Mockito.mock<SerializedAirbyteMessageConsumer>(SerializedAirbyteMessageConsumer::class.java) .use { airbyteMessageConsumerMock -> Mockito.doThrow(IOException("error")) .`when`(airbyteMessageConsumerMock) .accept( Jsons.serialize(message1), Jsons.serialize(message1).toByteArray(StandardCharsets.UTF_8).size ) Assertions.assertThrows(IOException::class.java) { IntegrationRunner.consumeWriteStream(airbyteMessageConsumerMock) } val inOrder = Mockito.inOrder(airbyteMessageConsumerMock) inOrder .verify(airbyteMessageConsumerMock) .accept( Jsons.serialize(message1), Jsons.serialize(message1).toByteArray(StandardCharsets.UTF_8).size ) inOrder.verifyNoMoreInteractions() } } @Test fun testInterruptOrphanThread() { val caughtExceptions: MutableList<Exception> = ArrayList() startSleepingThread(caughtExceptions, false) IntegrationRunner.stopOrphanedThreads( { Assertions.fail() }, 3, TimeUnit.SECONDS, 10, TimeUnit.SECONDS ) try { TimeUnit.SECONDS.sleep(15) } catch (e: Exception) { throw RuntimeException(e) } val runningThreads = ThreadUtils.getAllThreads().filter(IntegrationRunner::filterOrphanedThread) // all threads should be interrupted Assertions.assertEquals(listOf<Any>(), runningThreads) Assertions.assertEquals(1, caughtExceptions.size) } @Test fun testNoInterruptOrphanThread() { val caughtExceptions: MutableList<Exception> = ArrayList() val exitCalled = AtomicBoolean(false) startSleepingThread(caughtExceptions, true) IntegrationRunner.stopOrphanedThreads( { exitCalled.set(true) }, 3, TimeUnit.SECONDS, 10, TimeUnit.SECONDS ) try { TimeUnit.SECONDS.sleep(15) } catch (e: Exception) { throw RuntimeException(e) } val runningThreads = ThreadUtils.getAllThreads().filter(IntegrationRunner::filterOrphanedThread) // a thread that refuses to be interrupted should remain Assertions.assertEquals(1, runningThreads.size) Assertions.assertEquals(1, caughtExceptions.size) Assertions.assertTrue(exitCalled.get()) } private fun startSleepingThread( caughtExceptions: MutableList<Exception>, ignoreInterrupt: Boolean ) { val executorService = Executors.newFixedThreadPool(1) { r: Runnable -> // Create a thread that should be identified as orphaned if still running during // shutdown val thread = Thread(r) thread.name = "sleeping-thread" thread.isDaemon = false thread } executorService.submit { for (tries in 0..2) { try { TimeUnit.MINUTES.sleep(5) } catch (e: Exception) { LOGGER.info("Caught Exception", e) caughtExceptions.add(e) if (!ignoreInterrupt) { executorService.shutdownNow() break } } } } } @Test fun testParseConnectorImage() { Assertions.assertEquals("unknown", IntegrationRunner.parseConnectorVersion(null)) Assertions.assertEquals("unknown", IntegrationRunner.parseConnectorVersion("")) Assertions.assertEquals( "1.0.1-alpha", IntegrationRunner.parseConnectorVersion("airbyte/destination-test:1.0.1-alpha") ) Assertions.assertEquals( "dev", IntegrationRunner.parseConnectorVersion("airbyte/destination-test:dev") ) Assertions.assertEquals( "1.0.1-alpha", IntegrationRunner.parseConnectorVersion("destination-test:1.0.1-alpha") ) Assertions.assertEquals( "1.0.1-alpha", IntegrationRunner.parseConnectorVersion(":1.0.1-alpha") ) } @Test fun testConsumptionOfInvalidStateMessage() { val invalidStateMessage = """ { "type" : "STATE", "state" : { "type": "NOT_RECOGNIZED", "global": { "streamStates": { "foo" : "bar" } } } } """.trimIndent() Assertions.assertThrows(IllegalStateException::class.java) { Mockito.mock(AirbyteMessageConsumer::class.java).use { consumer -> Destination.ShimToSerializedAirbyteMessageConsumer.consumeMessage( consumer, invalidStateMessage ) } } } @Test fun testConsumptionOfInvalidNonStateMessage() { val invalidNonStateMessage = """ { "type" : "NOT_RECOGNIZED", "record" : { "namespace": "namespace", "stream": "stream", "emittedAt": 123456789 } } """.trimIndent() Assertions.assertDoesNotThrow { Mockito.mock<AirbyteMessageConsumer>(AirbyteMessageConsumer::class.java).use { consumer -> Destination.ShimToSerializedAirbyteMessageConsumer.consumeMessage( consumer, invalidNonStateMessage ) Mockito.verify(consumer, Mockito.times(0)).accept(any<AirbyteMessage>()) } } } companion object { private const val CONFIG_FILE_NAME = "config.json" private const val CONFIGURED_CATALOG_FILE_NAME = "configured_catalog.json" private const val STATE_FILE_NAME = "state.json" private val ARGS = arrayOf("args") private const val CONFIG_STRING = "{ \"username\": \"airbyte\" }" private val CONFIG: JsonNode = Jsons.deserialize(CONFIG_STRING) private const val STREAM_NAME = "users" private val EMITTED_AT = Instant.now().toEpochMilli() private val TEST_ROOT: Path = Path.of("/tmp/airbyte_tests") private val CATALOG: AirbyteCatalog = AirbyteCatalog().withStreams(Lists.newArrayList(AirbyteStream().withName(STREAM_NAME))) private val CONFIGURED_CATALOG: ConfiguredAirbyteCatalog = CatalogHelpers.toDefaultConfiguredCatalog(CATALOG) private val STATE: JsonNode = Jsons.jsonNode(ImmutableMap.of("checkpoint", "05/08/1945")) } }
1
null
1
1
b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff
24,305
airbyte
MIT License
Source/packages/apps/ThemePicker/src/com/android/customization/module/SysUiStatsLogger.kt
stayboogy
784,959,483
false
{"XML": 12479, "Ignore List": 14, "Markdown": 7, "Text": 104, "Shell": 20, "Makefile": 32, "INI": 11, "Soong": 58, "Java": 9482, "Gradle": 8, "Java Properties": 5, "Batchfile": 3, "Proguard": 2, "Protocol Buffer": 33, "JSON": 83, "Python": 6, "Kotlin": 469, "C++": 24, "XSLT": 1, "HTML": 5, "C": 23, "AIDL": 5, "Git Attributes": 1, "Gradle Kotlin DSL": 2, "YAML": 3}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.customization.module import android.stats.style.StyleEnums import com.android.systemui.shared.system.SysUiStatsLog import com.android.systemui.shared.system.SysUiStatsLog.STYLE_UI_CHANGED /** The builder for [SysUiStatsLog]. */ class SysUiStatsLogger { private var atom = STYLE_UI_CHANGED private var action = StyleEnums.DEFAULT_ACTION private var colorPackageHash = 0 private var fontPackageHash = 0 private var shapePackageHash = 0 private var clockPackageHash = 0 private var launcherGrid = 0 private var wallpaperCategoryHash = 0 private var wallpaperIdHash = 0 private var colorPreference = 0 private var locationPreference = StyleEnums.EFFECT_PREFERENCE_UNSPECIFIED private var datePreference = StyleEnums.DATE_PREFERENCE_UNSPECIFIED private var launchedPreference = StyleEnums.LAUNCHED_PREFERENCE_UNSPECIFIED private var effectPreference = StyleEnums.EFFECT_PREFERENCE_UNSPECIFIED private var effectIdHash = 0 private var lockWallpaperCategoryHash = 0 private var lockWallpaperIdHash = 0 private var firstLaunchDateSinceSetup = 0 private var firstWallpaperApplyDateSinceSetup = 0 private var appLaunchCount = 0 private var colorVariant = 0 private var timeElapsedMillis = 0L private var effectResultCode = -1 fun setAction(action: Int) = apply { this.action = action } fun setColorPackageHash(color_package_hash: Int) = apply { this.colorPackageHash = color_package_hash } fun setFontPackageHash(font_package_hash: Int) = apply { this.fontPackageHash = font_package_hash } fun setShapePackageHash(shape_package_hash: Int) = apply { this.shapePackageHash = shape_package_hash } fun setClockPackageHash(clock_package_hash: Int) = apply { this.clockPackageHash = clock_package_hash } fun setLauncherGrid(launcher_grid: Int) = apply { this.launcherGrid = launcher_grid } fun setWallpaperCategoryHash(wallpaper_category_hash: Int) = apply { this.wallpaperCategoryHash = wallpaper_category_hash } fun setWallpaperIdHash(wallpaper_id_hash: Int) = apply { this.wallpaperIdHash = wallpaper_id_hash } fun setColorPreference(color_preference: Int) = apply { this.colorPreference = color_preference } fun setLocationPreference(location_preference: Int) = apply { this.locationPreference = location_preference } fun setDatePreference(date_preference: Int) = apply { this.datePreference = date_preference } fun setLaunchedPreference(launched_preference: Int) = apply { this.launchedPreference = launched_preference } fun setEffectPreference(effect_preference: Int) = apply { this.effectPreference = effect_preference } fun setEffectIdHash(effect_id_hash: Int) = apply { this.effectIdHash = effect_id_hash } fun setLockWallpaperCategoryHash(lock_wallpaper_category_hash: Int) = apply { this.lockWallpaperCategoryHash = lock_wallpaper_category_hash } fun setLockWallpaperIdHash(lock_wallpaper_id_hash: Int) = apply { this.lockWallpaperIdHash = lock_wallpaper_id_hash } fun setFirstLaunchDateSinceSetup(first_launch_date_since_setup: Int) = apply { this.firstLaunchDateSinceSetup = first_launch_date_since_setup } fun setFirstWallpaperApplyDateSinceSetup(first_wallpaper_apply_date_since_setup: Int) = apply { this.firstWallpaperApplyDateSinceSetup = first_wallpaper_apply_date_since_setup } fun setAppLaunchCount(app_launch_count: Int) = apply { this.appLaunchCount = app_launch_count } fun setColorVariant(color_variant: Int) = apply { this.colorVariant = color_variant } fun setTimeElapsed(time_elapsed_millis: Long) = apply { this.timeElapsedMillis = time_elapsed_millis } fun setEffectResultCode(effect_result_code: Int) = apply { this.effectResultCode = effect_result_code } fun log() { SysUiStatsLog.write( atom, action, colorPackageHash, fontPackageHash, shapePackageHash, clockPackageHash, launcherGrid, wallpaperCategoryHash, wallpaperIdHash, colorPreference, locationPreference, datePreference, launchedPreference, effectPreference, effectIdHash, lockWallpaperCategoryHash, lockWallpaperIdHash, firstLaunchDateSinceSetup, firstWallpaperApplyDateSinceSetup, appLaunchCount, colorVariant, timeElapsedMillis, effectResultCode, ) } }
0
Java
0
0
e6132560c5e2416db150b856bd3f331d80795c4c
5,367
stayboogy_AOSimPle_Pixel-5_Redfin
Apache License 2.0
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/stepik/hyperskill/HyperskillStartupActivity.kt
JetBrains
43,696,115
false
{"Text": 28, "Gradle Kotlin DSL": 6, "Java Properties": 17, "YAML": 9, "Markdown": 10, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Python": 6, "TOML": 1, "INI": 4, "Java": 7, "Kotlin": 1709, "XML": 105, "CSS": 18, "HTML": 45, "JSON": 268, "SVG": 183, "JavaScript": 2, "CODEOWNERS": 1}
package com.jetbrains.edu.learning.stepik.hyperskill import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.jetbrains.edu.learning.EduLogInListener import com.jetbrains.edu.learning.EduUtilsKt.isStudentProject import com.jetbrains.edu.learning.StudyTaskManager import com.jetbrains.edu.learning.isUnitTestMode import com.jetbrains.edu.learning.stepik.hyperskill.api.HyperskillConnector import com.jetbrains.edu.learning.stepik.hyperskill.api.HyperskillSolutionLoader import com.jetbrains.edu.learning.courseFormat.hyperskill.HyperskillCourse import com.jetbrains.edu.learning.stepik.hyperskill.update.HyperskillCourseUpdateChecker import com.jetbrains.edu.learning.submissions.SubmissionsManager import com.jetbrains.edu.learning.taskToolWindow.ui.TaskToolWindowView import com.jetbrains.edu.learning.taskToolWindow.ui.tab.TabType.SUBMISSIONS_TAB import com.jetbrains.edu.learning.yaml.YamlFormatSynchronizer class HyperskillStartupActivity : StartupActivity { override fun runActivity(project: Project) { if (project.isDisposed || !project.isStudentProject() || isUnitTestMode) return val course = StudyTaskManager.getInstance(project).course as? HyperskillCourse ?: return val submissionsManager = SubmissionsManager.getInstance(project) if (!submissionsManager.submissionsSupported()) return submissionsManager.prepareSubmissionsContentWhenLoggedIn { HyperskillSolutionLoader.getInstance(project).loadSolutionsInBackground() } HyperskillConnector.getInstance().setSubmissionTabListener(object : EduLogInListener { override fun userLoggedIn() { if (project.isDisposed) return submissionsManager.prepareSubmissionsContentWhenLoggedIn() } override fun userLoggedOut() { if (project.isDisposed) return TaskToolWindowView.getInstance(project).updateTab(SUBMISSIONS_TAB) } }) synchronizeTopics(project, course) HyperskillCourseUpdateChecker.getInstance(project).check() } companion object { fun synchronizeTopics(project: Project, hyperskillCourse: HyperskillCourse) { ApplicationManager.getApplication().executeOnPooledThread { HyperskillConnector.getInstance().fillTopics(hyperskillCourse, project) YamlFormatSynchronizer.saveRemoteInfo(hyperskillCourse) } } } }
6
Kotlin
48
143
8c8ffb1372f80ed9efd9aa1ad58544141df9698f
2,428
educational-plugin
Apache License 2.0
src/main/kotlin/no/digdir/catalog_comments_service/repository/UserRepository.kt.kt
Informasjonsforvaltning
424,515,262
false
null
package no.digdir.catalog_comments_service.repository import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository import no.digdir.catalog_comments_service.model.UserDBO @Repository interface UserDAO:MongoRepository<UserDBO,String>
5
Kotlin
0
0
abb56085e01c382f329f7acb8b0cde2c5a9bd99c
290
catalog-comments-service
Apache License 2.0
plugins/kotlin/idea/tests/testData/intentions/removeLabeledReturnInLambda/outerLambda.kt
ingokegel
72,937,917
false
null
// WITH_STDLIB // IS_APPLICABLE: FALSE fun foo() { listOf(1,2,3).forEach { listOf(1,2,3).find { return@forEach<caret> } } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
160
intellij-community
Apache License 2.0
src/图片整理/Main.kt
masx200
798,368,501
false
{"Kotlin": 18728}
package com.github.masx200.nowcoder_test.图片整理 import java.util.Scanner fun main(args: Array<String>) { val read = Scanner(System.`in`) while (read.hasNext()) { val a = read.next() val b = a.toCharArray() b.sort() println(b.joinToString("")) } }
0
Kotlin
0
1
312cab559f386d65cbbbabe7d608ab9cda4af768
290
nowcoder-test
Mulan Permissive Software License, Version 2
src/main/kotlin/br/com/presentation/spring/kafka/reprocessor/consumer/KafkaConsumer.kt
hivisonnmoura
251,085,988
false
null
package br.com.presentation.spring.kafka.reprocessor.consumer import org.apache.kafka.common.TopicPartition import org.slf4j.LoggerFactory import org.springframework.kafka.annotation.KafkaListener import org.springframework.kafka.listener.ConsumerSeekAware import org.springframework.kafka.support.KafkaHeaders import org.springframework.messaging.handler.annotation.Header import org.springframework.messaging.handler.annotation.Payload import org.springframework.stereotype.Service import java.time.Instant import java.util.concurrent.TimeUnit @Service class KafkaConsumer : ConsumerSeekAware { private val logger = LoggerFactory.getLogger(javaClass) @KafkaListener( id = "kafkareset-test", topics = ["KafkaRewind"] ) fun consumer(@Payload event: String, @Header(KafkaHeaders.OFFSET) offset: Long) { logger.info("Message consumed: $event and offset $offset") } override fun onPartitionsAssigned(assignments: MutableMap<TopicPartition, Long>?, callback: ConsumerSeekAware.ConsumerSeekCallback?) { val rewindTo = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(30)).toEpochMilli() callback?.seekToTimestamp(assignments?.keys, rewindTo) } }
0
Kotlin
0
0
8e2f7bc9f7d7da92a882c4e1424f05fb8d8acdfe
1,226
spring-kafka-reprocessor
MIT License
feature/nutritionfacts/src/main/java/com/ariefzuhri/gizee/feature/nutritionfacts/data/NutritionFactsRepository.kt
ariefzuhri
388,739,293
false
null
package com.ariefzuhri.gizee.feature.nutritionfacts.data import com.ariefzuhri.gizee.feature.nutritionfacts.domain.repository.INutritionFactsRepository import com.ariefzuhri.gizee.core.common.dto.ApiResponse import com.ariefzuhri.gizee.core.common.dto.NetworkBoundResource import com.ariefzuhri.gizee.core.common.dto.Resource import com.ariefzuhri.gizee.core.database.domain.model.Nutrient import com.ariefzuhri.gizee.core.database.data.source.local.LocalDataSource import com.ariefzuhri.gizee.core.database.data.source.remote.RemoteDataSource import com.ariefzuhri.gizee.core.database.data.source.remote.response.NutrientResponse import com.ariefzuhri.gizee.core.database.util.mapEntitiesToDomain import com.ariefzuhri.gizee.core.database.util.mapResponsesToEntities import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class NutritionFactsRepository( private val remoteDataSource: RemoteDataSource, private val localDataSource: LocalDataSource, ) : INutritionFactsRepository { override fun getNutrients(): Flow<Resource<List<Nutrient>>> { return object : NetworkBoundResource<List<Nutrient>, List<NutrientResponse>>() { override fun loadFromDB(): Flow<List<Nutrient>> { return localDataSource.getNutrients().map { mapEntitiesToDomain(it) } } override fun shouldFetch(data: List<Nutrient>?): Boolean { return data.isNullOrEmpty() } override suspend fun createCall(): Flow<ApiResponse<List<NutrientResponse>>> { return remoteDataSource.getNutrients() } override suspend fun saveCallResult(data: List<NutrientResponse>) { val nutrientEntities = mapResponsesToEntities(data) localDataSource.insertNutrients(nutrientEntities) } }.asFlow() } }
5
Kotlin
2
4
228e830857d6d2622282ef2146891dd7d76b6b03
1,919
Gizee
MIT License
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/components/contact/ContactsListView.kt
ACINQ
192,964,514
false
{"C": 8424033, "Kotlin": 2796821, "Swift": 1884690, "Java": 39996, "HTML": 13403, "Dockerfile": 3585, "CMake": 2276, "CSS": 504}
/* * Copyright 2024 ACINQ SAS * * 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 fr.acinq.phoenix.android.components.contact import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import fr.acinq.phoenix.android.R import fr.acinq.phoenix.android.Screen import fr.acinq.phoenix.android.business import fr.acinq.phoenix.android.components.Button import fr.acinq.phoenix.android.components.Clickable import fr.acinq.phoenix.android.components.ItemCard import fr.acinq.phoenix.android.components.PhoenixIcon import fr.acinq.phoenix.android.components.ProgressView import fr.acinq.phoenix.android.components.TextInput import fr.acinq.phoenix.android.navController import fr.acinq.phoenix.android.utils.mutedTextFieldColors import fr.acinq.phoenix.data.ContactInfo @Composable fun ContactsListView( canEditContact: Boolean, onEditContact: (ContactInfo) -> Unit, isOnSurface: Boolean, ) { val contactsState = if (canEditContact) { business.contactsManager.contactsList.collectAsState(null) } else { business.contactsManager.contactsWithOfferList.collectAsState(null) } contactsState.value?.let { contacts -> var nameFilterInput by remember { mutableStateOf("") } TextInput( text = nameFilterInput, staticLabel = null, leadingIcon = { PhoenixIcon(resourceId = R.drawable.ic_inspect, tint = MaterialTheme.typography.caption.color) }, placeholder = { Text(text = stringResource(id = R.string.contact_search_name)) }, singleLine = true, onTextChange = { nameFilterInput = it }, textFieldColors = mutedTextFieldColors(), modifier = Modifier.padding(horizontal = 12.dp) ) Spacer(modifier = Modifier.height(6.dp)) ContactsList( canEditContact = canEditContact, onEditContact = onEditContact, contacts = if (nameFilterInput.isNotBlank()) { contacts.filter { it.name.contains(nameFilterInput, ignoreCase = true) } } else { contacts }, isOnSurface = isOnSurface ) } ?: ProgressView(text = stringResource(id = R.string.utils_loading_data)) } @Composable private fun ContactsList( canEditContact: Boolean, onEditContact: (ContactInfo) -> Unit, contacts: List<ContactInfo>, isOnSurface: Boolean, ) { val navController = navController val listState = rememberLazyListState() if (contacts.isEmpty()) { Text( text = stringResource(id = R.string.contact_none), modifier = Modifier.fillMaxWidth().padding(16.dp), style = MaterialTheme.typography.caption, textAlign = TextAlign.Center, ) } else { LazyColumn(state = listState) { itemsIndexed(contacts) { index, contact -> val onClick = { contact.mostRelevantOffer?.let { navController.navigate("${Screen.ScanData.route}?input=${it.encode()}") } ?: run { if (canEditContact) { onEditContact(contact) } } } if (isOnSurface) { Clickable( modifier = Modifier.padding(horizontal = 8.dp), onClick = onClick, ) { ContactRow(contact = contact, canEditContact = canEditContact, onEditContact = onEditContact) } } else { ItemCard( index = index, maxItemsCount = contacts.size, onClick = onClick ) { ContactRow(contact = contact, canEditContact = canEditContact, onEditContact = onEditContact) } } } } } } @Composable private fun ContactRow(contact: ContactInfo, canEditContact: Boolean, onEditContact: (ContactInfo) -> Unit) { Row( verticalAlignment = Alignment.CenterVertically, ) { Spacer(modifier = Modifier.width(12.dp)) ContactPhotoView(photoUri = contact.photoUri, name = contact.name, onChange = null, imageSize = 32.dp) Spacer(modifier = Modifier.width(8.dp)) Text( text = contact.name, modifier = Modifier .weight(1f) .padding(vertical = 16.dp), style = MaterialTheme.typography.body1.copy(fontSize = 18.sp) ) if (canEditContact) { Button( icon = R.drawable.ic_edit, onClick = { onEditContact(contact) }, padding = PaddingValues(horizontal = 16.dp, vertical = 16.dp), ) } } }
100
C
96
666
011c8b85f16ea9ad322cbbba2461439c5e2b0aed
6,355
phoenix
Apache License 2.0
device-manager-v2/src/com/android/tools/idea/devicemanagerv2/ActionButtonsPanel.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.devicemanagerv2 import com.android.sdklib.deviceprovisioner.DeviceHandle import com.android.sdklib.deviceprovisioner.DeviceTemplate import com.android.tools.adtui.categorytable.IconButton import com.android.tools.adtui.categorytable.constrainSize import com.intellij.openapi.project.Project import com.intellij.ui.components.JBPanel import com.intellij.util.ui.JBDimension import kotlinx.coroutines.CoroutineScope import javax.swing.BoxLayout internal open class ActionButtonsPanel : JBPanel<ActionButtonsPanel>() { protected fun setUp(vararg buttons: IconButton?) { layout = BoxLayout(this, BoxLayout.X_AXIS) isOpaque = false val size = JBDimension(22, 22) for (button in buttons.filterNotNull()) { button.constrainSize(size) add(button) } } open fun updateState(state: DeviceRowData) {} } internal class DeviceHandleButtonsPanel(val project: Project?, handle: DeviceHandle) : ActionButtonsPanel() { private val overflowButton = OverflowButton() init { val activationAction = handle.activationAction val deactivationAction = handle.deactivationAction when { activationAction != null && deactivationAction != null -> { setUp( StartStopButton(handle, activationAction, deactivationAction, handle.repairDeviceAction), overflowButton ) } project == null -> setUp(overflowButton) else -> setUp(StartStopMirroringButton(handle, project), overflowButton) } } } internal class DeviceTemplateButtonsPanel( coroutineScope: CoroutineScope, deviceTemplate: DeviceTemplate ) : ActionButtonsPanel() { init { setUp(ActivateTemplateButton(coroutineScope, deviceTemplate), OverflowButton()) } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
2,373
android
Apache License 2.0
tools-manage/invocationlab-admin-21/src/main/kotlin/org/javamaster/invocationlab/admin/model/erd/DatatypeBean.kt
jufeng98
191,107,543
false
null
package org.javamaster.invocationlab.admin.model.erd import org.javamaster.invocationlab.admin.annos.AllOpen /** * @author yudong * @date 2023/2/12 */ @AllOpen class DatatypeBean { var name: String? = null var code: String? = null var apply: ApplyBean? = null }
32
null
66
129
0ea2a5644bd08c1b8b2226a8490ab7c37a25a36f
281
java-master
Apache License 2.0
kuksa-sdk/src/test/kotlin/org/eclipse/kuksa/connectivity/databroker/docker/SecureDataBrokerDockerContainer.kt
eclipse-kuksa
687,949,615
false
{"Kotlin": 486057, "Java": 7211, "Shell": 2409}
/* * Copyright (c) 2023 - 2024 Contributors to the Eclipse Foundation * * 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. * * SPDX-License-Identifier: Apache-2.0 * */ package org.eclipse.kuksa.connectivity.databroker.docker import com.github.dockerjava.api.command.CreateContainerResponse import com.github.dockerjava.api.model.AccessMode import com.github.dockerjava.api.model.Bind import com.github.dockerjava.api.model.HostConfig import com.github.dockerjava.api.model.Volume import org.eclipse.kuksa.connectivity.databroker.DATABROKER_CONTAINER_NAME import org.eclipse.kuksa.connectivity.databroker.DATABROKER_PORT import org.eclipse.kuksa.test.TestResourceFile // tls enabled, authentication enabled class SecureDataBrokerDockerContainer( containerName: String = DATABROKER_CONTAINER_NAME, port: Int = DATABROKER_PORT, ) : DataBrokerDockerContainer(containerName, port) { private val authenticationFolder = TestResourceFile("authentication").toString() private val authenticationMount = "/resources/authentication" private val tlsFolder = TestResourceFile("tls").toString() private val tlsMount = "/resources/tls" override val hostConfig: HostConfig = super.hostConfig .withBinds( Bind(tlsFolder, Volume(tlsMount), AccessMode.ro), Bind(authenticationFolder, Volume(authenticationMount), AccessMode.ro), ) @Suppress("ArgumentListWrapping", "ktlint:standard:argument-list-wrapping") // better key-value pair readability override fun createContainer(tag: String): CreateContainerResponse { return dockerClient.createContainerCmd("$repository:$tag") .withName(containerName) .withHostConfig(hostConfig) .withCmd( "--port", "$port", "--tls-cert", "$tlsMount/Server.pem", "--tls-private-key", "$tlsMount/Server.key", "--jwt-public-key", "$authenticationMount/jwt.key.pub", ) .exec() } }
14
Kotlin
1
2
5cbbf9250a10dd94e8f4cdd9e14d6e50e87d0519
2,516
kuksa-android-sdk
Apache License 2.0
src/all/webtoons/src/eu/kanade/tachiyomi/extension/th/webtoons/WebtoonsThai.kt
yshalsager
163,608,699
true
{"Kotlin": 1568796, "Java": 4615, "Shell": 1729}
package eu.kanade.tachiyomi.extension.th.webtoons import eu.kanade.tachiyomi.extension.all.webtoons.WebtoonsDefault import java.text.SimpleDateFormat import java.util.* class WebtoonsThai: WebtoonsDefault("th") { override fun chapterParseDate(date: String): Long { return SimpleDateFormat("d MMM yyyy", Locale("th")).parse(date).time } }
0
Kotlin
0
0
948b756e7f8ca8e7c4742d57696bc606a6e57699
356
tachiyomi-extensions
Apache License 2.0
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/perfetto/MemoryUsageQuery.kt
androidx
256,589,781
false
{"Kotlin": 102794437, "Java": 64412412, "C++": 9138104, "AIDL": 617598, "Python": 310931, "Shell": 189529, "TypeScript": 40586, "HTML": 35176, "Groovy": 27482, "ANTLR": 26700, "Svelte": 20307, "CMake": 18033, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * 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.benchmark.macro.perfetto import androidx.benchmark.macro.MemoryUsageMetric import androidx.benchmark.macro.MemoryUsageMetric.Mode import androidx.benchmark.perfetto.PerfettoTraceProcessor import androidx.benchmark.perfetto.processNameLikePkg import org.intellij.lang.annotations.Language internal object MemoryUsageQuery { // https://perfetto.dev/docs/data-sources/memory-counters @Language("sql") internal fun getQuery(targetPackageName: String, mode: Mode) = when (mode) { Mode.Last -> "SELECT track.name as counter_name, MAX(ts), value " Mode.Max -> "SELECT track.name as counter_name, MAX(value) as value " } + """ FROM counter LEFT JOIN process_counter_track as track on counter.track_id = track.id LEFT JOIN process using (upid) WHERE ${processNameLikePkg(targetPackageName)} AND ( track.name LIKE 'mem.rss%' OR track.name LIKE 'Heap size (KB)' OR track.name LIKE 'GPU Memory' ) GROUP BY counter_name """.trimIndent() fun getMemoryUsageKb( session: PerfettoTraceProcessor.Session, targetPackageName: String, mode: Mode ): Map<MemoryUsageMetric.SubMetric, Int>? { val queryResultIterator = session.query( query = getQuery(targetPackageName = targetPackageName, mode) ) val rows = queryResultIterator.toList() return if (rows.isEmpty()) { null } else { rows.mapNotNull { row -> val counterName = row.string("counter_name") val metric = MemoryUsageMetric.SubMetric.values().firstOrNull { it.counterName == counterName } if (metric == null) { null } else { val measurement = row.double("value") metric to if (metric.alreadyInKb) { measurement.toInt() } else { measurement.toInt() / 1024 } } }.toMap() } } }
28
Kotlin
937
5,108
89ec14e39cf771106a8719337062572717cbad31
2,879
androidx
Apache License 2.0
data/src/main/java/appus/software/githubusers/data/entities/ContributorEntity.kt
appus-studio
180,989,176
false
null
package appus.software.githubusers.data.entities import appus.software.githubusers.domain.model.ContributorModel import appus.software.githubusers.domain.model.UserModel import com.google.gson.annotations.SerializedName /** * Created by bogdan.martynov on 2019-04-24 16:12. top-github-contributors-android */ data class ContributorEntity( @SerializedName("total") val total: Int?, @SerializedName("author") val author: AuthorEntity? ) fun ContributorEntity.toModel(): ContributorModel{ return ContributorModel(total?:0, author?.toModel() ?: UserModel()) }
0
Kotlin
0
1
72b630dbaffe7e2d6c08a81ac48d551f8578b627
583
top-github-contributors-android
Apache License 2.0
src/main/kotlin/com/dood/springboot/springdemo/config/CoroutineConfig.kt
coderdude1
505,686,334
false
null
package com.dood.springboot.springdemo.config import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class CoroutineConfig { //Some Coroutine Scopes to support structure concurrency @Bean fun ioScope(): CoroutineScope = CoroutineScope(Dispatchers.IO) @Bean fun defaultScope(): CoroutineScope = CoroutineScope(Dispatchers.Default) }
0
Kotlin
0
0
088d0692a226dfc34dcc39fc8fb97a100d88f1b0
520
SpringBootKotlin
Apache License 2.0
domain/src/main/java/uoc/cbonache/tfg/route/GetRouteInteractor.kt
cbonacheuoc
109,753,411
true
{"Kotlin": 144808, "Java": 6706}
package uoc.cbonache.tfg.route import uoc.cbonache.tfg.Result import uoc.cbonache.tfg.async.PostExecutionThread import uoc.cbonache.tfg.interactor.Interactor import uoc.cbonache.tfg.model.Step import uoc.cbonache.tfg.repository.RouteRepository import javax.inject.Inject /** * @author cbonache */ class GetRouteInteractor @Inject constructor(postExecutionThread: PostExecutionThread, val repository: RouteRepository) : Interactor<List<Step>, GetRouteInteractor.Parameters>(postExecutionThread) { override fun run(params: Parameters): Result<List<Step>, *> { return repository.getRoute(params.latOrigin,params.lngOrigin,params.destination) } data class Parameters(val latOrigin: Double,val lngOrigin:Double, val destination: String) }
0
Kotlin
0
1
c6c3cdc87eb96aaf179a6442111371aebe0a80dc
809
Transpdroid-Android-App
Apache License 2.0
app/src/main/java/com/kylecorry/trail_sense/shared/lists/ListItem.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.shared.lists import android.graphics.Bitmap import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import com.kylecorry.trail_sense.shared.database.Identifiable data class ListItem( override val id: Long, val title: CharSequence, val subtitle: CharSequence? = null, val singleLineSubtitle: Boolean = false, val icon: ListIcon? = null, val checkbox: ListItemCheckbox? = null, val tags: List<ListItemTag> = emptyList(), val data: List<ListItemData> = emptyList(), val trailingText: CharSequence? = null, val trailingIcon: ListIcon? = null, val trailingIconAction: () -> Unit = {}, val menu: List<ListMenuItem> = emptyList(), val longClickAction: () -> Unit = {}, val action: () -> Unit = {} ) : Identifiable data class ListMenuItem(val text: String, val action: () -> Unit) data class ListItemTag(val text: String, val icon: ListIcon?, @ColorInt val color: Int) data class ListItemData(val text: CharSequence, val icon: ListIcon?) data class ListItemCheckbox(val checked: Boolean, val onClick: () -> Unit) interface ListIcon data class ResourceListIcon(@DrawableRes val id: Int, @ColorInt val tint: Int? = null) : ListIcon data class AsyncBitmapListIcon(val provider: suspend () -> Bitmap) : ListIcon
281
Kotlin
37
396
f42af867337e90b18fb91590246ec72f04021f2e
1,316
Trail-Sense
MIT License
android_kmp/craftd-compose/src/main/java/com/github/codandotv/craftd/compose/builder/CraftDComposeBuilders.kt
CodandoTV
788,958,834
false
{"Kotlin": 53080, "C++": 20938, "CMake": 18713, "Dart": 14923, "Swift": 7869, "HTML": 1836, "C": 1425, "SCSS": 607, "Objective-C": 38}
package com.github.codandotv.craftd.compose.builder import com.github.codandotv.craftd.compose.ui.button.CraftDButtonComposeBuilder import com.github.codandotv.craftd.compose.ui.empty.CraftDEmptyComposeRender import com.github.codandotv.craftd.compose.ui.text.CraftDTextComposeRender class CraftDComposeBuilders { private val listDynamicBuilder = listOf( CraftDButtonComposeBuilder(), CraftDTextComposeRender() ) private val customBuilders = mutableListOf<CraftDComposeBuilder>() fun addBuilderRenders( customDynamicBuilderList: List<CraftDComposeBuilder> ): CraftDComposeBuilders { customBuilders.addAll(customDynamicBuilderList) return this } fun addBuilderRender( dynamicComposeBuilder: CraftDComposeBuilder ): CraftDComposeBuilders { customBuilders.add(dynamicComposeBuilder) return this } fun getBuilder( key: String ): CraftDComposeBuilder = (listDynamicBuilder + customBuilders) .distinctBy { it.key } .find { it.key == key } ?: CraftDEmptyComposeRender() }
1
Kotlin
0
1
e897123e2428adf25929b30b8bef19adce71e940
1,121
CraftD
MIT License
app/src/main/java/com/changrojasalex1168165/simonsays/navigation/NavManager.kt
JellyPork
717,329,885
false
{"Kotlin": 46812}
package com.changrojasalex1168165.simonsays.navigation import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.changrojasalex1168165.simonsays.database.GameViewModel import com.changrojasalex1168165.simonsays.views.MainGameComponent import com.changrojasalex1168165.simonsays.views.MainMenuComponent import com.changrojasalex1168165.simonsays.views.ScoreBoardComponent import com.changrojasalex1168165.simonsays.views.SettingsComponent @Composable fun NavManager(viewModel: GameViewModel, navController: NavHostController) { NavHost(navController = navController, startDestination = "menu") { composable("menu") { MainMenuComponent(navController, viewModel) } composable("game/{option}/{name}", arguments = listOf(navArgument("option"){type = NavType.IntType}, navArgument("name"){type = NavType.StringType} ) ) { backStackEntry -> MainGameComponent(navController,viewModel, backStackEntry.arguments?.getInt("option"), backStackEntry.arguments?.getString("name")) } composable("scoreboards") { ScoreBoardComponent(navController, viewModel) } composable("options") { SettingsComponent() } } }
0
Kotlin
0
0
3bd220f8f9fed60c3d426120ecc409c86630d86f
1,473
SimonSays
Apache License 2.0
src/main/java/com/gazman/db/callbacks/MainThreadCallback.kt
gazman-sdk
62,981,480
false
null
package com.gazman.db.callbacks import android.os.Handler import android.os.Looper /** * Created by <NAME> on 7/9/2016. */ abstract class MainThreadCallback<T> protected constructor() : DataBaseDataCallback<T>(HANDLER) { companion object { val HANDLER = Handler(Looper.getMainLooper()) } }
0
Kotlin
1
4
b0573b64d7f086fbb873dc8bdf1df743c212d5d1
309
SQLite-Assets-Helper
Apache License 2.0
common/src/main/java/com/laposa/common/features/mediaSource/ui/MediaSourceItemContent.kt
laposa
796,639,770
false
{"Kotlin": 274304}
package com.laposa.common.features.mediaSource.ui import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.tv.material3.Card import androidx.tv.material3.Icon import androidx.tv.material3.MaterialTheme @Composable fun MediaSourceItemContent( index: Int, title: String, type: String, icon: Int, onClick: () -> Unit, ) { val focusRequester = FocusRequester() LaunchedEffect(index) { if (index == 0) { focusRequester.requestFocus() } } Column { Card( onClick = onClick, modifier = Modifier .height(90.dp) .width(150.dp) .focusRequester(focusRequester) .testTag("media_source_item_${title}_$type") ) { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Icon( painter = painterResource(id = icon), contentDescription = title, Modifier .size(56.dp) ) Text( type, style = MaterialTheme.typography.titleSmall.copy(color = MaterialTheme.colorScheme.onSurfaceVariant) ) } } } Spacer(Modifier.height(8.dp)) Text( text = title, style = MaterialTheme.typography.bodyMedium, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Start, color = MaterialTheme.colorScheme.onSurfaceVariant ) } }
4
Kotlin
0
2
b0f5964f7e62f8070577465a5199a386f4cdfb19
2,654
media-player
MIT License
src/zh/kanmanhua886/src/eu/kanade/tachiyomi/extension/zh/mkanmanhua886/Kanmanhua886.kt
ZongerZY
287,689,898
true
{"Kotlin": 3948599, "Shell": 1958, "Java": 608}
package eu.kanade.tachiyomi.extension.zh.mkanmanhua886 import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import okhttp3.Request import okhttp3.Response import org.jsoup.Jsoup class Kanmanhua886 : HttpSource() { override val name = "看漫画K886" override val baseUrl = "https://m.k886.net" override val lang = "zh" override val supportsLatest = true private val htmlUrl = "https://www.k886.net" override fun popularMangaRequest(page: Int): Request { return GET("$htmlUrl/index-html-status-0-typeid-0-sort-hot?&page=$page") } override fun popularMangaParse(response: Response): MangasPage = searchMangaParse(response) override fun latestUpdatesRequest(page: Int): Request { return GET("$htmlUrl/index-html-status-0-typeid-0-sort-uptime?&page=$page") } override fun latestUpdatesParse(response: Response): MangasPage = searchMangaParse(response) override fun mangaDetailsRequest(manga: SManga): Request { return GET(manga.url) } override fun mangaDetailsParse(response: Response): SManga = SManga.create().apply { val body = response.body()!!.string() var document = Jsoup.parseBodyFragment(body) title = document.select("div.fl.show-center div.twobleft.center_nr div.box-bd.comic-earn div.box-hd h1").text() thumbnail_url = document.select("div.fl.show-center div.twobleft.center_nr div.box-bd.comic-earn dl.mh-detail dt a img").attr("src") author = document.select("div.fl.show-center div.twobleft.center_nr div.box-bd.comic-earn dl.mh-detail dd p").get(0).select("a[itemprop=author]").text() artist = "Tachiyomi:ZongerZY" status = if (document.select("div.fl.show-center div.twobleft.center_nr div.box-bd.comic-earn dl.mh-detail dd p").get(1).select("a").text().contains("完結")) 2 else 1 genre = document.select("#classdh").text() description = document.select("div.fl.show-center div.twobleft.center_nr div.box-bd.comic-earn div.mh-introduce p").text() } override fun chapterListRequest(manga: SManga): Request { return GET(manga.url) } override fun chapterListParse(response: Response): List<SChapter> { var chapterList = ArrayList<SChapter>() val body = response.body()!!.string() var elements = Jsoup.parseBodyFragment(body).select("#oneCon2 ul.b1").select("li") for (element in elements) { chapterList.add(SChapter.create().apply { name = element.select("a").text().trim() url = element.select("a").attr("href") }) } return chapterList } override fun pageListRequest(chapter: SChapter): Request { return GET(chapter.url) } override fun pageListParse(response: Response): List<Page> { val body = response.body()!!.string() val requestUrl = response.request().url().toString() var elements = Jsoup.parseBodyFragment(body).select("select[name=select1]").select("option") var arrList = ArrayList<Page>(elements.size) for (i in 0 until elements.size) { arrList.add(Page(i, "$requestUrl-p-${elements[i].attr("value")}")) } return arrList } override fun imageUrlRequest(page: Page): Request { return GET(page.url) } override fun imageUrlParse(response: Response): String { val body = response.body()!!.string() return Jsoup.parseBodyFragment(body).select("#ComicPic").attr("src") } override fun searchMangaParse(response: Response): MangasPage { val body = response.body()!!.string() val document = Jsoup.parseBodyFragment(body) var mangasElements = document.select("div.box.across.list div.box-bd ul.liemh.htmls.indliemh li") var mangas = ArrayList<SManga>(mangasElements.size) for (mangaElement in mangasElements) { mangas.add(SManga.create().apply { title = mangaElement.select("a div.tit").text() thumbnail_url = mangaElement.select("a img").attr("src") url = mangaElement.select("a").attr("href") }) } return MangasPage(mangas, mangasElements.size == 30) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { if (query != "") { return GET("$htmlUrl/search-index?searchType=1&q=$query&page=$page") } else { val params = filters.map { if (it is UriPartFilter) { it.toUriPart() } else "" }.filter { it != "" }.joinToString("-") return GET("$htmlUrl/index-html-$params?&page=$page") } } override fun getFilterList() = FilterList( ThemeFilter(), SortFilter(), FinishFilter() ) private class FinishFilter : UriPartFilter("进度", arrayOf( Pair("全部", "status-0"), Pair("连载", "status-1"), Pair("完结", "status-2") )) private class ThemeFilter : UriPartFilter("题材", arrayOf( Pair("全部", "typeid-0"), Pair("萌系", "typeid-1"), Pair("搞笑", "typeid-2"), Pair("格鬥", "typeid-3"), Pair("科幻", "typeid-4"), Pair("劇情", "typeid-5"), Pair("偵探", "typeid-6"), Pair("競技", "typeid-7"), Pair("魔法", "typeid-8"), Pair("神鬼", "typeid-9"), Pair("校園", "typeid-10"), Pair("驚栗", "typeid-11"), Pair("廚藝", "typeid-12"), Pair("偽娘", "typeid-13"), Pair("圖片", "typeid-14"), Pair("冒險", "typeid-15"), Pair("小說", "typeid-16"), Pair("港漫", "typeid-17"), Pair("耽美", "typeid-18"), Pair("經典", "typeid-19"), Pair("歐美", "typeid-20"), Pair("日本", "typeid-21"), Pair("親情", "typeid-22"), Pair("修真", "typeid-25"), Pair("韓漫", "typeid-27"), Pair("真人", "typeid-28"), Pair("English", "typeid-30"), Pair("3D", "typeid-31") )) private class SortFilter : UriPartFilter("排序", arrayOf( Pair("观看次数", "sort-hot"), Pair("更新时间", "sort-uptime"), Pair("增加时间", "sort-pubtime") )) private open class UriPartFilter( displayName: String, val vals: Array<Pair<String, String>>, defaultValue: Int = 0 ) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray(), defaultValue) { open fun toUriPart() = vals[state].second } }
0
Kotlin
1
8
1f40e4d4c4aff4b71fa72ffae03dbcd871e91803
6,812
tachiyomi-extensions
Apache License 2.0
tribune-core/src/main/kotlin/com/sksamuel/tribune/core/collections/lists.kt
sksamuel
10,692,938
false
null
package com.sksamuel.tribune.core.collections import arrow.core.invalidNel import arrow.core.sequence import com.sksamuel.tribune.core.Parser /** * Lifts an existing [Parser] to support lists of the input types supported by * the underlying parser. * * In other words, given a parser from I to A, returns a parser from List<I> to List<A>. * * @return a parser that accepts lists */ fun <I, A, E> Parser<I, A, E>.asList(): Parser<Collection<I>, List<A>, E> { return Parser { input -> input.map { this@asList.parse(it) }.sequence() } } fun <I, A, E> Parser.Companion.list(elementParser: Parser<I, A, E>): Parser<Collection<I>, List<A>, E> = elementParser.asList() /** * Lifts an existing [Parser] to support lists of the input types supported by * the underlying parser. This version of repeated supports upper and lower bounds * on the list size. * * In other words, given a parser, this will return a parser that handles lists of the inputs. * * @param min the minimum number of elements in the list * @param max the maximum number of elements in the list * * @return a parser that accepts lists */ fun <I, A, E> Parser<I, A, E>.asList( min: Int = 0, max: Int = Int.MAX_VALUE, ifInvalidSize: (Int) -> E ): Parser<List<I>, List<A>, E> { return Parser { input -> if ((min..max).contains(input.size)) input.map { this@asList.parse(it) }.sequence() else ifInvalidSize(input.size).invalidNel() } }
0
Kotlin
19
152
0f265805583df39aa5c1e755e86e71221db304b0
1,457
tribune
Apache License 2.0