path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/moegirlviewer/api/account/bean/LoginTokenBean.kt
koharubiyori
449,942,456
false
null
package com.moegirlviewer.api.account.bean data class LoginTokenBean( val batchcomplete: String, val query: Query ) { data class Query( val tokens: Tokens ) { data class Tokens( val logintoken: String ) } }
1
Kotlin
2
16
e09753e76c11932d6f7344302d48f7a214cccf3a
235
Moegirl-plus-native
MIT License
library/src/main/java/renetik/android/core/logging/CSLog.kt
renetik
506,035,450
false
null
package renetik.android.core.logging import android.content.Context import renetik.android.core.extensions.content.toast import renetik.android.core.kotlin.CSUnexpectedException import renetik.android.core.kotlin.primitives.leaveEndOfLength import renetik.android.core.kotlin.then import renetik.android.core.kotlin.toShortString import renetik.android.core.lang.CSEnvironment.isDebug import renetik.android.core.lang.CSStringConstants.NewLine import renetik.android.core.logging.CSLogLevel.Debug import renetik.android.core.logging.CSLogLevel.Error import renetik.android.core.logging.CSLogLevel.Info import renetik.android.core.logging.CSLogLevel.Warn import renetik.android.core.logging.CSLogMessage.Companion.Empty import renetik.android.core.logging.CSLogMessage.Companion.message import renetik.android.core.logging.CSLogMessage.Companion.traceMessage import java.lang.System.currentTimeMillis import java.lang.Thread.currentThread import java.text.DateFormat.getDateTimeInstance object CSLog { var logger: CSLogger = CSPrintLogger() fun init(logger: CSLogger) { this.logger = logger } fun log(level: CSLogLevel) = then { logImpl(level) { message("") } } fun log(level: CSLogLevel, function: () -> CSLogMessage) = then { logImpl(level, function) } fun logDebug() = then { logImpl(Debug) { message() } } fun logDebug(any: Any?) = then { logImpl(Debug) { message(any) } } fun logDebug(function: () -> String) = then { logImpl(Debug) { message(function()) } } fun logDebug(throwable: Throwable, function: (() -> String)? = null) = then { logImpl(Debug) { message(throwable, function?.invoke()) } } fun logDebugTrace(function: (() -> String)? = null) = then { logImpl(Debug) { message(Throwable(), function?.invoke()) } } fun logInfo() = then { logImpl(Info) { message("") } } fun logInfo(any: Any?) = then { logImpl(Info) { message(any) } } fun logInfo(function: () -> String) = then { logImpl(Info) { message(function()) } } fun logInfo(throwable: Throwable, function: (() -> String)? = null) = then { logImpl(Info) { message(throwable, function?.invoke()) } } fun logInfoTrace(any: Any? = null, skip: Int = 0, length: Int = 5) = then { logImpl(Info) { message("$any\n" + Throwable().toShortString(skip, length)) } } fun logInfoTrace(function: () -> String) = then { if (isDebug) logImpl(Info) { traceMessage(function()) } else logImpl(Info) { message(Throwable(), function.invoke()) } } fun logWarn() = then { logImpl(Warn) { message("") } } fun logWarn(any: Any?) = then { logImpl(Warn) { message(any) } } fun logWarn(function: () -> String) = then { logImpl(Warn) { message(function()) } } fun logWarn(throwable: Throwable, function: (() -> String)? = null) = then { logImpl(Warn) { message(throwable, function?.invoke()) } } fun logWarnTrace(function: () -> String) = then { if (isDebug) logImpl(Warn) { traceMessage(function()) } else logImpl(Warn) { message(Throwable(), function.invoke()) } } fun logError() = then { logImpl(Error) { message("") } } fun logError(message: String?) = then { logImpl(Error) { message(message) } } fun logError(function: () -> String) = then { logImpl(Error) { message(function()) } } fun logError(throwable: Throwable?) = then { logImpl(Error) { message(throwable) } } fun logError(throwable: Throwable?, message: String?) = then { logImpl(Error) { message(throwable, message) } } // fun logError(error: Pair<Throwable?, String?>) = // then { logImpl(Error) { message(error.first, error.second) } } fun logErrorTrace(function: () -> String) = then { logImpl(Error) { message(Throwable(), function.invoke()) } } fun Context.logDebugToast() = toast(Debug, logImpl(Debug) { message("") }) fun Context.logDebugStringToast(function: () -> String) = toast(Debug, logImpl(Debug) { CSLogMessage(message = function()) }) fun Context.logDebugToast(function: () -> CSLogMessage) = toast(Debug, logImpl(Debug, function)) fun Context.logInfoToast() = toast(Info, logImpl(Info) { message("") }) fun Context.logInfoToast(value: String) = toast(Info, logImpl(Info) { message(value) }) fun Context.logInfoToast(function: () -> CSLogMessage) = toast(Info, logImpl(Info, function)) fun Context.logWarnToast() = toast(Warn, logImpl(Warn) { message("") }) fun Context.logWarnToast(function: () -> CSLogMessage) = toast(Warn, logImpl(Warn, function)) fun Context.logErrorToast() = toast(Error, logImpl(Error) { message("") }) fun Context.logErrorToast(function: () -> CSLogMessage) = toast(Error, logImpl(Error, function)) private fun logImpl(level: CSLogLevel, message: () -> CSLogMessage = { Empty }): Array<Any?>? { if (logger.isEnabled(level)) message().let { val text = createMessage(it.message) when (level) { Debug -> logger.debug(it.throwable, *text) Info -> logger.info(it.throwable, *text) Warn -> logger.warn(it.throwable, *text) Error -> logger.error(it.throwable, *text) else -> CSUnexpectedException.unexpected() } return text } return null } private fun Context.toast(level: CSLogLevel, text: Array<Any?>?) { if (logger.isEnabled(level)) toast("${text!![2]}".leaveEndOfLength(100).chunked(50) .joinToString { "$it$NewLine" }) } private val timeFormat by lazy { getDateTimeInstance() } fun createMessage(message: Any?) = Array(3) { when (it) { 0 -> timeFormat.format(currentTimeMillis()) 1 -> getTraceLine() else -> message } } private fun getTraceLine(): String { val stackTrace = currentThread().stackTrace val index = stackTrace.indexOfFirst { it.methodName == "logImpl" } + 2 return stackTrace[index].let { element -> "${element.className}$${element.methodName}(${element.fileName}:${element.lineNumber})" } } }
0
null
1
3
aa6a08a94f4faac94a53d2cb6570436e388b0508
6,148
renetik-android-core
MIT License
app/src/main/java/com/leetcode_kotlin/Task/twoSum/TwoSum/ContainmsDublicate/ContainsDublicate.kt
Ashwagandha-coder
568,689,282
false
{"Kotlin": 13356, "Java": 808}
package com.leetcode_kotlin.Task.twoSum.TwoSum.ContainmsDublicate fun containsDuplicate(nums: IntArray): Boolean { var set = mutableSetOf<Int>() for (i in nums) set.add(i) if (set.size == nums.size) return false else return true } fun sol2(nums: IntArray): Boolean { var set = mutableSetOf<Int>() for (num in nums) { if (set.contains(num)) { return true } set.add(num) } return false }
0
Kotlin
0
0
66b4c1a095edc7663214be4de80081904586b794
490
leetcode_kotlin
MIT License
app/src/main/java/com/vivy/app/shared/network/RequestInfo.kt
ShabanKamell
201,554,520
false
null
package com.vivy.app.shared.network import retrofit2.HttpException data class RequestInfo( var inlineHandling: ((HttpException) -> Boolean)? = null, var retryCallback: () -> Unit = {}, var showLoading: Boolean = true ) { fun inlineHandling(inlineHandling: ((HttpException) -> Boolean)?): RequestInfo { this.inlineHandling = inlineHandling return this } fun setRetryCallback(retryCallback: () -> Unit): RequestInfo { this.retryCallback = retryCallback return this } }
1
Kotlin
2
2
e710420c2ec077eea322eae387885ca81faf8338
544
Vivy
Apache License 2.0
wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/OneOfElement.kt
square
12,274,147
false
null
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema.internal.parser import com.squareup.wire.schema.Location import com.squareup.wire.schema.internal.appendDocumentation import com.squareup.wire.schema.internal.appendIndented data class OneOfElement( val name: String, val documentation: String = "", val fields: List<FieldElement> = emptyList(), val groups: List<GroupElement> = emptyList(), val options: List<OptionElement> = emptyList(), val location: Location, ) { fun toSchema() = buildString { appendDocumentation(documentation) append("oneof $name {") if (options.isNotEmpty()) { append('\n') for (option in options) { appendIndented(option.toSchemaDeclaration()) } } if (fields.isNotEmpty()) { append('\n') for (field in fields) { appendIndented(field.toSchema()) } } if (groups.isNotEmpty()) { append('\n') for (group in groups) { appendIndented(group.toSchema()) } } append("}\n") } }
163
null
570
4,244
74715088d7d2ee1fdd6d3e070c8b413eefc7e5bd
1,611
wire
Apache License 2.0
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/settings/ElectrumView.kt
ACINQ
192,964,514
false
null
/* * Copyright 2021 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.settings import android.util.Base64 import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import fr.acinq.lightning.io.TcpSocket import fr.acinq.lightning.utils.Connection import fr.acinq.lightning.utils.ServerAddress import fr.acinq.phoenix.android.* import fr.acinq.phoenix.android.R import fr.acinq.phoenix.android.components.* import fr.acinq.phoenix.android.components.mvi.MVIView import fr.acinq.phoenix.android.utils.* import fr.acinq.phoenix.android.utils.datastore.UserPrefs import fr.acinq.phoenix.controllers.config.ElectrumConfiguration import fr.acinq.phoenix.data.ElectrumConfig import fr.acinq.secp256k1.Hex import io.ktor.util.network.* import kotlinx.coroutines.launch import java.security.MessageDigest import java.security.cert.X509Certificate import java.text.DateFormat import java.text.NumberFormat @Composable fun ElectrumView() { val log = logger("ElectrumView") val nc = navController val context = LocalContext.current val scope = rememberCoroutineScope() val business = LocalBusiness.current val prefElectrumServer = LocalElectrumServer.current var showCustomServerDialog by rememberSaveable { mutableStateOf(false) } val vm = viewModel<ElectrumViewModel>() DefaultScreenLayout { DefaultScreenHeader( onBackClick = { nc.popBackStack() }, title = stringResource(id = R.string.electrum_title), ) Card(internalPadding = PaddingValues(16.dp)) { Text(text = stringResource(R.string.electrum_about)) //, style = MaterialTheme.typography.caption.copy(fontSize = 14.sp)) } MVIView(CF::electrumConfiguration) { model, postIntent -> Card { val config = model.configuration if (showCustomServerDialog) { ElectrumServerDialog( initialAddress = prefElectrumServer, onCheck = vm::checkCertificate, onConfirm = { address -> scope.launch { UserPrefs.saveElectrumServer(context, address) postIntent(ElectrumConfiguration.Intent.UpdateElectrumServer(address)) showCustomServerDialog = false } }, onDismiss = { scope.launch { showCustomServerDialog = false } } ) } // -- connection detail val connection = model.connection SettingInteractive( title = when { connection is Connection.ESTABLISHED -> { stringResource(id = R.string.electrum_connection_connected, "${model.currentServer?.host}:${model.currentServer?.port}") } connection is Connection.ESTABLISHING && config is ElectrumConfig.Random -> { stringResource(id = R.string.electrum_connecting, "${model.currentServer?.host}:${model.currentServer?.port}") } connection is Connection.ESTABLISHING && config is ElectrumConfig.Custom -> { stringResource(id = R.string.electrum_connecting, config.server.host) } connection is Connection.CLOSED && config is ElectrumConfig.Custom -> { stringResource(id = R.string.electrum_connection_closed_with_custom, config.server.host) } else -> { stringResource(id = R.string.electrum_connection_closed_with_random) } }, description = { when (config) { is ElectrumConfig.Custom -> { if (connection is Connection.CLOSED && connection.isBadCertificate()) { Text( text = stringResource(id = R.string.electrum_description_bad_certificate), style = MaterialTheme.typography.subtitle2.copy(color = negativeColor()) ) } else { Text(text = stringResource(id = R.string.electrum_description_custom)) } } else -> Unit } }, icon = R.drawable.ic_server, iconTint = when (connection) { is Connection.ESTABLISHED -> positiveColor() is Connection.ESTABLISHING -> orange else -> negativeColor() }, maxTitleLines = 1 ) { showCustomServerDialog = true } } Card { // block height if (model.blockHeight > 0) { val height = remember { NumberFormat.getInstance().format(model.blockHeight) } Setting(title = stringResource(id = R.string.electrum_block_height_label), description = height) } // fee rate if (model.feeRate > 0) { Setting(title = stringResource(id = R.string.electrum_fee_rate_label), description = stringResource(id = R.string.electrum_fee_rate, model.feeRate.toString())) } // xpub val xpub = remember { business?.walletManager?.getXpub() ?: "" to "" } Setting(title = stringResource(id = R.string.electrum_xpub_label), description = stringResource(id = R.string.electrum_xpub_value, xpub.first, xpub.second)) } } } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun ElectrumServerDialog( initialAddress: ServerAddress?, onCheck: suspend (String, Int) -> ElectrumViewModel.CertificateCheckState, onConfirm: (ServerAddress?) -> Unit, onDismiss: () -> Unit ) { val context = LocalContext.current val scope = rememberCoroutineScope() val keyboardManager = LocalSoftwareKeyboardController.current var useCustomServer by rememberSaveable { mutableStateOf(initialAddress != null) } var address by rememberSaveable { mutableStateOf(initialAddress?.run { "$host:$port" } ?: "") } var addressError by rememberSaveable { mutableStateOf(false) } var connectionCheck by remember { mutableStateOf<ElectrumViewModel.CertificateCheckState>(ElectrumViewModel.CertificateCheckState.Init) } Dialog( onDismiss = onDismiss, buttons = null ) { Column(modifier = Modifier.fillMaxWidth()) { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp) ) { Spacer(Modifier.height(16.dp)) Checkbox( text = stringResource(id = R.string.electrum_dialog_checkbox), checked = useCustomServer, onCheckedChange = { useCustomServer = it if (!it) { connectionCheck = ElectrumViewModel.CertificateCheckState.Init } }, enabled = connectionCheck != ElectrumViewModel.CertificateCheckState.Checking ) TextInput( modifier = Modifier.fillMaxWidth(), text = address, onTextChange = { addressError = false if (address != it) { connectionCheck = ElectrumViewModel.CertificateCheckState.Init } address = it }, label = { Text(stringResource(id = R.string.electrum_dialog_input)) }, enabled = useCustomServer && connectionCheck != ElectrumViewModel.CertificateCheckState.Checking ) if (addressError) { Text(stringResource(id = R.string.electrum_dialog_invalid_input)) } } Spacer(modifier = Modifier.height(24.dp)) when (val check = connectionCheck) { ElectrumViewModel.CertificateCheckState.Init, is ElectrumViewModel.CertificateCheckState.Failure -> { if (check is ElectrumViewModel.CertificateCheckState.Failure) { Text( text = stringResource( R.string.electrum_dialog_cert_failure, when (check.e) { is UnresolvedAddressException -> stringResource(R.string.electrum_dialog_cert_unresolved) else -> check.e.message ?: check.e.javaClass.simpleName } ), modifier = Modifier.padding(horizontal = 24.dp) ) Spacer(Modifier.height(16.dp)) } Row(Modifier.align(Alignment.End)) { Button(onClick = onDismiss, text = stringResource(id = R.string.btn_cancel)) Button( onClick = { keyboardManager?.hide() if (useCustomServer) { if (address.matches("""(.*):*(\d*)""".toRegex())) { val (host, port) = address.trim().run { substringBeforeLast(":") to (substringAfterLast(":").toIntOrNull() ?: 50002) } scope.launch { connectionCheck = ElectrumViewModel.CertificateCheckState.Checking connectionCheck = onCheck(host, port) } } else { addressError = true } } else { onConfirm(null) } }, text = stringResource(id = R.string.electrum_dialog_cert_check_button), ) } } ElectrumViewModel.CertificateCheckState.Checking -> { Row(Modifier.align(Alignment.End)) { ProgressView(text = stringResource(id = R.string.electrum_dialog_cert_checking)) } } is ElectrumViewModel.CertificateCheckState.Valid -> { LaunchedEffect(Unit) { onConfirm(ServerAddress(check.host, check.port, TcpSocket.TLS.TRUSTED_CERTIFICATES)) } } is ElectrumViewModel.CertificateCheckState.Rejected -> { val cert = check.certificate Column( Modifier .background(mutedBgColor()) .padding(horizontal = 24.dp, vertical = 12.dp) ) { TextWithIcon( modifier = Modifier.align(Alignment.CenterHorizontally), icon = R.drawable.ic_alert_triangle, text = stringResource(R.string.electrum_dialog_cert_header), textStyle = MaterialTheme.typography.body2 ) Spacer(Modifier.height(4.dp)) Button( modifier = Modifier.align(Alignment.CenterHorizontally), text = stringResource(id = R.string.electrum_dialog_cert_copy), padding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), space = 8.dp, textStyle = MaterialTheme.typography.body1.copy(fontSize = 12.sp), onClick = { copyToClipboard(context, "-----BEGIN CERTIFICATE-----\n${String(Base64.encode(cert.encoded, Base64.DEFAULT), Charsets.US_ASCII)}-----END CERTIFICATE-----") } ) Spacer(Modifier.height(12.dp)) CertDetail( label = stringResource(id = R.string.electrum_dialog_cert_sha1), value = Hex.encode(MessageDigest.getInstance("SHA-1").digest(cert.encoded)), ) CertDetail( label = stringResource(id = R.string.electrum_dialog_cert_sha256), value = Hex.encode(MessageDigest.getInstance("SHA-256").digest(cert.encoded)), ) if (cert is X509Certificate) { CertDetail( label = stringResource(id = R.string.electrum_dialog_cert_issuer), value = cert.issuerX500Principal.name.substringAfter("CN=").substringBefore(","), ) CertDetail( label = stringResource(id = R.string.electrum_dialog_cert_subject), value = cert.issuerX500Principal.name.substringAfter("CN=").substringBefore(","), ) CertDetail( label = stringResource(id = R.string.electrum_dialog_cert_expiration), value = DateFormat.getDateTimeInstance().format(cert.notAfter), ) } } Row(Modifier.align(Alignment.End)) { Button( text = stringResource(id = R.string.btn_cancel), space = 8.dp, onClick = onDismiss ) Button( text = stringResource(id = R.string.electrum_dialog_cert_accept), icon = R.drawable.ic_check_circle, iconTint = positiveColor(), space = 8.dp, onClick = { onConfirm(ServerAddress(check.host, check.port, TcpSocket.TLS.PINNED_PUBLIC_KEY(Base64.encodeToString(cert.publicKey.encoded, Base64.NO_WRAP)))) }, ) } } } } } } @Composable private fun CertDetail(label: String, value: String) { Text(text = label, style = MaterialTheme.typography.body2) Spacer(modifier = Modifier.height(2.dp)) Text(text = value, style = monoTypo(), maxLines = 1) Spacer(modifier = Modifier.height(4.dp)) }
97
null
96
666
011c8b85f16ea9ad322cbbba2461439c5e2b0aed
16,769
phoenix
Apache License 2.0
src/test/kotlin/no/nav/familie/ef/sak/tilbakekreving/TilbakekrevingControllerTest.kt
navikt
206,805,010
false
null
package no.nav.familie.ef.sak.tilbakekreving import no.nav.familie.ef.sak.OppslagSpringRunnerTest import no.nav.familie.ef.sak.behandling.BehandlingService import no.nav.familie.ef.sak.behandling.domain.Behandling import no.nav.familie.ef.sak.behandling.domain.BehandlingType import no.nav.familie.ef.sak.fagsak.FagsakService import no.nav.familie.ef.sak.tilbakekreving.domain.Tilbakekrevingsvalg.OPPRETT_MED_VARSEL import no.nav.familie.ef.sak.tilbakekreving.domain.Tilbakekrevingsvalg.OPPRETT_UTEN_VARSEL import no.nav.familie.ef.sak.tilbakekreving.dto.TilbakekrevingDto import no.nav.familie.kontrakter.ef.felles.BehandlingÅrsak import no.nav.familie.kontrakter.felles.Ressurs import no.nav.familie.kontrakter.felles.ef.StønadType.OVERGANGSSTØNAD import no.nav.familie.kontrakter.felles.getDataOrThrow import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.web.client.exchange import org.springframework.http.HttpEntity import org.springframework.http.HttpMethod import java.util.UUID internal class TilbakekrevingControllerTest : OppslagSpringRunnerTest() { @Autowired lateinit var behandlingService: BehandlingService @Autowired lateinit var fagsakService: FagsakService @BeforeEach fun setUp() { headers.setBearerAuth(lokalTestToken) } @Test internal fun `Skal lagre siste versjon av tilbakekreving ved to kall`() { val fagsak = fagsakService.hentEllerOpprettFagsakMedBehandlinger("01010172272", OVERGANGSSTØNAD) val behandling = behandlingService.opprettBehandling( BehandlingType.FØRSTEGANGSBEHANDLING, fagsak.id, behandlingsårsak = BehandlingÅrsak.SØKNAD ) lagInitiellTilbakekreving(behandling) val oppdatertTilbakekrevingsDto = TilbakekrevingDto( valg = OPPRETT_MED_VARSEL, varseltekst = "Dette er tekst", begrunnelse = "Nei" ) lagreTilbakekreving(behandling, oppdatertTilbakekrevingsDto) val andreLagredeTilbakekrevingDto = hentTilbakekreving(behandling) assertThat(andreLagredeTilbakekrevingDto.body.getDataOrThrow()).isEqualTo(oppdatertTilbakekrevingsDto) } private fun lagInitiellTilbakekreving(behandling: Behandling) { val initiellTilbakekrevingDto = TilbakekrevingDto( valg = OPPRETT_UTEN_VARSEL, varseltekst = "", begrunnelse = "Ja" ) lagreTilbakekreving(behandling, initiellTilbakekrevingDto) val førsteLagredeTilbakekrevingDto = hentTilbakekreving(behandling) assertThat(førsteLagredeTilbakekrevingDto.body.getDataOrThrow()).isEqualTo(initiellTilbakekrevingDto) } private fun hentTilbakekreving(behandling: Behandling) = restTemplate.exchange<Ressurs<TilbakekrevingDto?>>( localhost("/api/tilbakekreving/${behandling.id}"), HttpMethod.GET, HttpEntity<TilbakekrevingDto>(headers) ) private fun lagreTilbakekreving( behandling: Behandling, forventetTilbakekrevingsDto: TilbakekrevingDto ) { restTemplate.exchange<Ressurs<UUID>>( localhost("/api/tilbakekreving/${behandling.id}"), HttpMethod.POST, HttpEntity(forventetTilbakekrevingsDto, headers) ) } }
8
Kotlin
2
0
d1d8385ead500c4d24739b970940af854fa5fe2c
3,452
familie-ef-sak
MIT License
widgets/src/androidMain/kotlin/dev/icerock/moko/widgets/core/screen/Screen.kt
icerockdev
218,209,603
false
null
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.widgets.screen import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Parcelable import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dev.icerock.moko.graphics.Color import dev.icerock.moko.mvvm.createViewModelFactory import dev.icerock.moko.mvvm.dispatcher.EventsDispatcher import dev.icerock.moko.mvvm.viewmodel.ViewModel import dev.icerock.moko.widgets.utils.ThemeAttrs import dev.icerock.moko.widgets.utils.getIntNullable import java.util.concurrent.Executor import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty actual abstract class Screen<Arg : Args> : Fragment() { private val attachFragmentHooks = mutableListOf<(Fragment) -> Unit>() private val activityResultHooks = mutableMapOf<Int, (result: Int, data: Intent?) -> Unit>() val routeHandlers = mutableMapOf<Int, (Parcelable?) -> Unit>() var requestCode: Int? = null var resultCode: Int? = null var screenId: Int? = null actual open val androidStatusBarColor: Color? = null actual open val isLightStatusBar: Boolean? = null actual inline fun <reified VM : ViewModel, Key : Any> getViewModel( key: Key, crossinline viewModelFactory: () -> VM ): VM { return ViewModelProvider(this, createViewModelFactory { viewModelFactory() }) .get(key.toString(), VM::class.java) } actual fun <T : Any> createEventsDispatcher(): EventsDispatcher<T> { val mainLooper = Looper.getMainLooper() val mainHandler = Handler(mainLooper) val mainExecutor = Executor { mainHandler.post(it) } return EventsDispatcher(mainExecutor) } actual open fun onViewCreated() { } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.run { requestCode = getIntNullable(REQUEST_CODE_KEY) resultCode = getIntNullable(RESULT_CODE_KEY) screenId = getIntNullable(SCREEN_ID_KEY) } onViewCreated() } override fun onResume() { super.onResume() val color = resolveStatusBarColor() setStatusBarColor(color) val lightStatusBar = resolveIsStatusBarLight() setLightStatusBar(lightStatusBar) } private fun resolveStatusBarColor(): Int { if (androidStatusBarColor != null) return androidStatusBarColor!!.argb.toInt() var parent = parentFragment while (parent != null) { if (parent is Screen<*> && parent.androidStatusBarColor != null) { return parent.androidStatusBarColor!!.argb.toInt() } parent = parent.parentFragment } val hostActivity = activity as? HostActivity val appColor = hostActivity?.application?.androidStatusBarColor if (appColor != null) return appColor.argb.toInt() return ThemeAttrs.getPrimaryDarkColor(requireContext()) } private fun resolveIsStatusBarLight(): Boolean { if (isLightStatusBar != null) return isLightStatusBar!! var parent = parentFragment while (parent != null) { if (parent is Screen<*> && parent.isLightStatusBar != null) { return parent.isLightStatusBar!! } parent = parent.parentFragment } val hostActivity = activity as? HostActivity val isLightContent = hostActivity?.application?.isLightStatusBar if (isLightContent != null) return isLightContent return ThemeAttrs.getLightStatusBar(requireContext()) } private fun setStatusBarColor(color: Int) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return requireActivity().window.statusBarColor = color } private fun setLightStatusBar(lightStatusBar: Boolean) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return val view = requireActivity().window.decorView ?: return view.systemUiVisibility = if (lightStatusBar) { view.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { view.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) requestCode?.let { outState.putInt(REQUEST_CODE_KEY, it) } resultCode?.let { outState.putInt(RESULT_CODE_KEY, it) } screenId?.let { outState.putInt(SCREEN_ID_KEY, it) } } override fun onAttachFragment(childFragment: Fragment) { super.onAttachFragment(childFragment) attachFragmentHooks.forEach { it(childFragment) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) activityResultHooks[requestCode]?.let { hook -> hook(resultCode, data) } } fun <T> registerAttachFragmentHook( value: T, hook: (Fragment) -> Unit ): ReadOnlyProperty<Screen<*>, T> { attachFragmentHooks.add(hook) return createConstReadOnlyProperty(value) } fun <T> registerActivityResultHook( requestCode: Int, value: T, hook: (result: Int, data: Intent?) -> Unit ): ReadOnlyProperty<Screen<*>, T> { activityResultHooks[requestCode] = hook return createConstReadOnlyProperty(value) } fun <T> createConstReadOnlyProperty(value: T): ReadOnlyProperty<Screen<*>, T> { return object : ReadOnlyProperty<Screen<*>, T> { override fun getValue(thisRef: Screen<*>, property: KProperty<*>): T { return value } } } private companion object { const val REQUEST_CODE_KEY = "screen:requestCode" const val RESULT_CODE_KEY = "screen:resultCode" const val SCREEN_ID_KEY = "screen:id" } }
40
Kotlin
29
334
63ea65d622f702432a5b5d1f587ba0fb8a81f95e
6,181
moko-widgets
Apache License 2.0
shared/src/commonMain/kotlin/data/repositories/TimerRepository.kt
Appmilla
803,336,812
false
{"Kotlin": 20413, "Swift": 6349}
package data.repositories import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.intPreferencesKey import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import okio.Path.Companion.toPath fun createDataStore(producePath: () -> String): DataStore<Preferences> = PreferenceDataStoreFactory.createWithPath( corruptionHandler = null, migrations = emptyList(), produceFile = { producePath().toPath() }, ) interface TimerRepository { val timerValue: Flow<Int> suspend fun getTimerValue(): Int suspend fun saveTimerValue(value: Int) } class TimerRepositoryImpl(private val dataStore: DataStore<Preferences>) : TimerRepository { private val timerKey = intPreferencesKey("timer_value") override suspend fun getTimerValue(): Int { return dataStore.data.first()[timerKey] ?: 0 } override suspend fun saveTimerValue(value: Int) { dataStore.updateData { preferences -> preferences.toMutablePreferences().apply { this[timerKey] = value } } } override val timerValue: Flow<Int> = dataStore.data.map { preferences -> preferences[timerKey] ?: 0 } }
0
Kotlin
1
4
0c5f7b45bdaaaa0481e4e4f79e95e9447feea1c4
1,408
KMPJetpackDemo
Apache License 2.0
domain/src/main/java/com/ujizin/leafy/domain/usecase/alarm/load/LoadAlarmUseCase.kt
ujizin
442,024,281
false
{"Kotlin": 349427}
package com.ujizin.leafy.domain.usecase.alarm import com.ujizin.leafy.domain.model.Alarm import com.ujizin.leafy.domain.result.Result import kotlinx.coroutines.flow.Flow /** * Load alarm use case. * */ interface LoadAlarm { /** * Load alarm on data source. * * @param id the alarm's id * */ operator fun invoke( id: Long, ): Flow<Result<Alarm>> }
7
Kotlin
1
4
27e28e5984a0fef94d3aa8d7c813ba1851cfd4f3
392
Leafy
Apache License 2.0
rsocket-core/src/commonMain/kotlin/io/rsocket/kotlin/core/RSocketServerBuilder.kt
rsocket
109,894,810
false
null
/* * Copyright 2015-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rsocket.kotlin.core import io.rsocket.kotlin.* import io.rsocket.kotlin.logging.* public class RSocketServerBuilder internal constructor() { @RSocketLoggingApi public var loggerFactory: LoggerFactory = DefaultLoggerFactory public var maxFragmentSize: Int = 0 set(value) { require(value == 0 || value >= 64) { "maxFragmentSize should be zero (no fragmentation) or greater than or equal to 64, but was $value" } field = value } private val interceptors: InterceptorsBuilder = InterceptorsBuilder() public fun interceptors(configure: InterceptorsBuilder.() -> Unit) { interceptors.configure() } @OptIn(RSocketLoggingApi::class) internal fun build(): RSocketServer = RSocketServer(loggerFactory, maxFragmentSize, interceptors.build()) } public fun RSocketServer(configure: RSocketServerBuilder.() -> Unit = {}): RSocketServer { val builder = RSocketServerBuilder() builder.configure() return builder.build() }
27
null
36
515
88e692837137a99de18cfbe69b9a52ac5626a5f9
1,664
rsocket-kotlin
Apache License 2.0
libausbc/src/main/java/com/jiangdg/ausbc/render/effect/EffectZoom.kt
jiangdongguo
105,255,685
false
null
/* * Copyright 2017-2022 Jiangdg * * 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.jiangdg.ausbc.render.effect import android.content.Context import android.opengl.GLES20 import com.jiangdg.ausbc.R import com.jiangdg.ausbc.render.effect.bean.CameraEffect /** Zoom effect * * @author Created by jiangdg on 2022/01/28 */ class EffectZoom(context: Context) : AbstractEffect(context) { private var mTimeStampsHandler = -1 private var mTimeCount = 0 override fun getId(): Int = ID override fun getClassifyId(): Int = CameraEffect.CLASSIFY_ID_ANIMATION override fun init() { mTimeStampsHandler = GLES20.glGetUniformLocation(mProgram, "timeStamps") } override fun beforeDraw() { if (mTimeCount > 65535) { mTimeCount = 0 } GLES20.glUniform1f(mTimeStampsHandler, (++mTimeCount % 9).toFloat()) } override fun getVertexSourceId(): Int = R.raw.effect_zoom_vertex override fun getFragmentSourceId(): Int = R.raw.base_fragment companion object { const val ID = 300 } }
447
null
792
2,323
ebfd9437eb6e23e30f583a0151474b2fa6267fca
1,593
AndroidUSBCamera
Apache License 2.0
instrumented/integration/src/androidTest/kotlin/com/datadog/android/sdk/integration/sessionreplay/textfields/SrTextFieldsMaskUserInputTest.kt
DataDog
219,536,756
false
{"Kotlin": 9121111, "Java": 1179237, "C": 79303, "Shell": 63055, "C++": 32351, "Python": 5556, "CMake": 2000}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.sdk.integration.sessionreplay.images import com.datadog.android.privacy.TrackingConsent import com.datadog.android.sdk.integration.sessionreplay.BaseSessionReplayTest import com.datadog.android.sdk.integration.sessionreplay.SessionReplayImagesActivity import com.datadog.android.sdk.rules.SessionReplayTestRule import com.datadog.android.sdk.utils.SR_PRIVACY_LEVEL import com.datadog.android.sessionreplay.SessionReplayPrivacy import org.junit.Rule import org.junit.Test internal class SrImagesMaskUserInputTest : BaseSessionReplayTest<SessionReplayImagesActivity>() { @get:Rule val rule = SessionReplayTestRule( SessionReplayImagesActivity::class.java, trackingConsent = TrackingConsent.GRANTED, keepRequests = true, intentExtras = mapOf(SR_PRIVACY_LEVEL to SessionReplayPrivacy.MASK_USER_INPUT) ) @Test fun assessRecordedScreenPayload() { runInstrumentationScenario() assessSrPayload(EXPECTED_PAYLOAD_FILE_NAME, rule) } companion object { const val EXPECTED_PAYLOAD_FILE_NAME = "sr_images_mask_user_input_payload.json" } }
60
Kotlin
60
151
d7e640cf6440ab150c2bbfbac261e09b27e258f4
1,400
dd-sdk-android
Apache License 2.0
zoomimage-view/src/main/kotlin/com/github/panpf/zoomimage/view/subsampling/internal/TileDrawHelper.kt
panpf
647,222,866
false
null
/* * Copyright (C) 2023 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.zoomimage.view.subsampling.internal import android.graphics.Canvas import android.graphics.Color import android.graphics.Matrix import android.graphics.Paint import android.graphics.Paint.Style.STROKE import android.graphics.Rect import android.graphics.RectF import android.view.View import androidx.core.graphics.withSave import com.github.panpf.zoomimage.subsampling.AndroidTileBitmap import com.github.panpf.zoomimage.subsampling.ImageInfo import com.github.panpf.zoomimage.subsampling.TileSnapshot import com.github.panpf.zoomimage.subsampling.TileState import com.github.panpf.zoomimage.util.IntSizeCompat import com.github.panpf.zoomimage.util.Logger import com.github.panpf.zoomimage.util.isEmpty import com.github.panpf.zoomimage.view.internal.applyTransform import com.github.panpf.zoomimage.view.subsampling.SubsamplingEngine import com.github.panpf.zoomimage.view.zoom.ZoomableEngine import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.merge import kotlinx.coroutines.launch import kotlin.math.round import kotlin.math.roundToInt class TileDrawHelper( private val logger: Logger, private val view: View, private val zoomableEngine: ZoomableEngine, private val subsamplingEngine: SubsamplingEngine, ) { private val cacheRect1 = Rect() private val cacheRect2 = Rect() private val cacheRect3 = RectF() private val cacheDisplayMatrix: Matrix = Matrix() private val coroutineScope = CoroutineScope(Dispatchers.Main) private var tilePaint: Paint = Paint() private val boundsPaint: Paint by lazy { Paint().apply { style = STROKE strokeWidth = 0.5f * view.resources.displayMetrics.density } } init { coroutineScope.launch { listOf( subsamplingEngine.readyState, subsamplingEngine.foregroundTilesState, subsamplingEngine.backgroundTilesState, subsamplingEngine.showTileBoundsState, ).merge().collect { view.invalidate() } } } fun drawTiles(canvas: Canvas) { val containerSize = zoomableEngine.containerSizeState.value.takeIf { !it.isEmpty() } ?: return val contentSize = zoomableEngine.contentSizeState.value.takeIf { !it.isEmpty() } ?: return val transform = zoomableEngine.transformState.value val imageInfo = subsamplingEngine.imageInfoState.value ?: return val backgroundTiles = subsamplingEngine.backgroundTilesState.value val foregroundTiles = subsamplingEngine.foregroundTilesState.value.takeIf { it.isNotEmpty() } ?: return val imageLoadRect = subsamplingEngine.imageLoadRectState.value.takeIf { !it.isEmpty } ?: return var backgroundCount = 0 var insideLoadCount = 0 var outsideLoadCount = 0 var realDrawCount = 0 canvas.withSave { canvas.concat(cacheDisplayMatrix.applyTransform(transform, containerSize)) backgroundTiles.forEach { tileSnapshot -> if (tileSnapshot.srcRect.overlaps(imageLoadRect)) { if (drawTile(canvas, imageInfo, contentSize, tileSnapshot)) { backgroundCount++ } } } foregroundTiles.forEach { tileSnapshot -> if (tileSnapshot.srcRect.overlaps(imageLoadRect)) { insideLoadCount++ if (drawTile(canvas, imageInfo, contentSize, tileSnapshot)) { realDrawCount++ } if (subsamplingEngine.showTileBoundsState.value) { drawTileBounds(canvas, imageInfo, contentSize, tileSnapshot) } } else { outsideLoadCount++ } } } logger.d { "drawTiles. tiles=${foregroundTiles.size}, " + "insideLoadCount=${insideLoadCount}, " + "outsideLoadCount=${outsideLoadCount}, " + "realDrawCount=${realDrawCount}, " + "backgroundCount=${backgroundCount}. " + "'${subsamplingEngine.imageKey}'" } } private fun drawTile( canvas: Canvas, imageInfo: ImageInfo, contentSize: IntSizeCompat, tileSnapshot: TileSnapshot ): Boolean { val tileBitmap = tileSnapshot.tileBitmap?.takeIf { !it.isRecycled } ?: return false val bitmap = (tileBitmap as AndroidTileBitmap).bitmap?.takeIf { !it.isRecycled } ?: return false val tileDrawSrcRect = cacheRect2.apply { set(0, 0, bitmap.width, bitmap.height) } val widthScale = imageInfo.width / contentSize.width.toFloat() val heightScale = imageInfo.height / contentSize.height.toFloat() val tileDrawDstRect = cacheRect1.apply { set( /* left = */ (tileSnapshot.srcRect.left / widthScale).roundToInt(), /* top = */ (tileSnapshot.srcRect.top / heightScale).roundToInt(), /* right = */ (tileSnapshot.srcRect.right / widthScale).roundToInt(), /* bottom = */ (tileSnapshot.srcRect.bottom / heightScale).roundToInt() ) } tilePaint.alpha = tileSnapshot.alpha canvas.drawBitmap( /* bitmap = */ bitmap, /* src = */ tileDrawSrcRect, /* dst = */ tileDrawDstRect, /* paint = */ tilePaint ) return true } private fun drawTileBounds( canvas: Canvas, imageInfo: ImageInfo, contentSize: IntSizeCompat, tileSnapshot: TileSnapshot ) { val widthScale = imageInfo.width / contentSize.width.toFloat() val heightScale = imageInfo.height / contentSize.height.toFloat() val tileDrawRect = cacheRect3.apply { set( /* left = */ round(tileSnapshot.srcRect.left / widthScale), /* top = */ round(tileSnapshot.srcRect.top / heightScale), /* right = */ round(tileSnapshot.srcRect.right / widthScale), /* bottom = */ round(tileSnapshot.srcRect.bottom / heightScale) ) } val tileBoundsPaint = boundsPaint val bitmapNoRecycled = tileSnapshot.tileBitmap?.isRecycled == false val boundsColor = when { bitmapNoRecycled && tileSnapshot.state == TileState.STATE_LOADED -> Color.GREEN tileSnapshot.state == TileState.STATE_LOADING -> Color.YELLOW tileSnapshot.state == TileState.STATE_NONE -> Color.GRAY else -> Color.RED } tileBoundsPaint.color = boundsColor canvas.drawRect(tileDrawRect, tileBoundsPaint) } }
8
null
7
98
bdc00e862498830df39a205de5d3d490a5f04444
7,551
zoomimage
Apache License 2.0
price/src/main/kotlin/de/richargh/springkotlinhexagonal/properties/PropertyPrinting.kt
Richargh
165,030,359
false
null
package de.richargh.springkotlinhexagonal.properties import java.util.* internal fun printProperties() { val applicationProperties = Properties().apply { load(Thread.currentThread().contextClassLoader.getResourceAsStream("application.properties")) } val devProperties = Properties().apply { load(Thread.currentThread().contextClassLoader.getResourceAsStream("application-dev.properties")) } val key = "price.greeter.person" println("Application.properties has property value: ${applicationProperties.getProperty(key)}") println("Application-dev.properties has property value: ${devProperties.getProperty(key)}") }
0
Kotlin
0
1
f91b0de43d49dc596daeccc8fc0c929e65eb0de9
660
spring-kotlin-hexagonal
MIT License
app/src/main/kotlin/ir/thatsmejavad/backgroundable/screens/settings/SettingsScreen.kt
javadjafari1
642,709,238
false
{"Kotlin": 431381}
package ir.thatsmejavad.backgroundable.screens.settings import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import ir.thatsmejavad.backgroundable.BuildConfig import ir.thatsmejavad.backgroundable.R import ir.thatsmejavad.backgroundable.common.ui.BackgroundableScaffold import ir.thatsmejavad.backgroundable.core.AppScreens import ir.thatsmejavad.backgroundable.core.Constants import ir.thatsmejavad.backgroundable.core.composeMail import ir.thatsmejavad.backgroundable.core.openUrl @Composable fun SettingsScreen( navigateTo: (String) -> Unit, ) { val context = LocalContext.current BackgroundableScaffold( modifier = Modifier /* The padding of the bottomBar, can't use Scaffold to add bottomBar with animation. the bottom of the ui will jump */ .padding(bottom = Constants.NAVIGATION_BAR_HEIGHT), topBar = { CenterAlignedTopAppBar( title = { Text( text = stringResource(R.string.label_setting), style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onSurface ) } ) } ) { Column( Modifier .padding(it) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(16.dp) ) { SettingItem( textId = R.string.label_language, imageId = R.drawable.ic_language, onClick = { navigateTo(AppScreens.Language.route) } ) SettingItem( textId = R.string.label_quality, imageId = R.drawable.ic_high_quality, onClick = { navigateTo(AppScreens.ImageQualitySetting.route) } ) SettingItem( textId = R.string.label_theme, imageId = R.drawable.ic_theme, onClick = { navigateTo(AppScreens.ThemeSetting.route) } ) SettingItem( textId = R.string.label_about_us, imageId = R.drawable.ic_info, onClick = { navigateTo(AppScreens.AboutUs.route) } ) SettingItem( textId = R.string.label_provide_feedback, imageId = R.drawable.ic_star, onClick = { context.openUrl( url = BuildConfig.RATE_URL ) } ) SettingItem( textId = R.string.label_report_a_bug, imageId = R.drawable.ic_feedback, onClick = { context.composeMail( recipientMail = "<EMAIL>" ) } ) Spacer(modifier = Modifier.weight(1f)) Text( modifier = Modifier.align(CenterHorizontally), text = stringResource(R.string.label_version, BuildConfig.VERSION_NAME), style = MaterialTheme.typography.bodyLarge ) } } } @Composable private fun SettingItem( @StringRes textId: Int, @DrawableRes imageId: Int, onClick: () -> Unit, ) { Row( modifier = Modifier .clickable(onClick = onClick) .fillMaxWidth() .padding( horizontal = 24.dp, vertical = 16.dp ), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier.size(32.dp), painter = painterResource(imageId), contentDescription = stringResource(textId), tint = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(modifier = Modifier.width(16.dp)) Text( text = stringResource(textId), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface ) } }
2
Kotlin
2
30
23d62ddbd08b8996319699e505e11a180fcba62e
5,296
Backgroundable
Apache License 2.0
collect_app/src/androidTest/java/org/odk/collect/android/benchmark/SearchBenchmarkTest.kt
getodk
40,213,809
false
{"Java": 3378614, "Kotlin": 2749754, "JavaScript": 2830, "Shell": 2689}
package org.odk.collect.android.benchmark import androidx.test.ext.junit.runners.AndroidJUnit4 import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.blankOrNullString import org.hamcrest.Matchers.not import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith import org.odk.collect.android.benchmark.support.Benchmarker import org.odk.collect.android.benchmark.support.benchmark import org.odk.collect.android.support.TestDependencies import org.odk.collect.android.support.pages.MainMenuPage import org.odk.collect.android.support.rules.CollectTestRule import org.odk.collect.android.support.rules.TestRuleChain.chain import org.odk.collect.android.test.BuildConfig.ENTITIES_FILTER_SEARCH_TEST_PROJECT_URL /** * Benchmarks the performance of search() forms. [ENTITIES_FILTER_SEARCH_TEST_PROJECT_URL] should be * set to a project that contains the "100k Entities Filter search()" form. * * Devices that currently pass: * - Fairphone 3 * */ @RunWith(AndroidJUnit4::class) class SearchBenchmarkTest { private val rule = CollectTestRule(useDemoProject = false) @get:Rule var chain: RuleChain = chain(TestDependencies(true)).around(rule) @Test fun run() { assertThat( "Need to set ENTITIES_FILTER_SEARCH_TEST_PROJECT_URL before running!", ENTITIES_FILTER_SEARCH_TEST_PROJECT_URL, not(blankOrNullString()) ) val benchmarker = Benchmarker() rule.startAtFirstLaunch() .clickManuallyEnterProjectDetails() .inputUrl(ENTITIES_FILTER_SEARCH_TEST_PROJECT_URL) .addProject() .clickGetBlankForm() .clickGetSelected() .clickOK(MainMenuPage()) .clickFillBlankForm() .benchmark("Loading form first time", 20, benchmarker) { it.clickOnForm("100k Entities Filter search()") } .pressBackAndDiscardForm() .clickFillBlankForm() .benchmark("Loading form second time", 2, benchmarker) { it.clickOnForm("100k Entities Filter search()") } .answerQuestion("Which value do you want to filter by?", "1024") .benchmark("Filtering select", 2, benchmarker) { it.swipeToNextQuestion("Filtered select") } benchmarker.assertResults() } }
283
Java
1372
717
63050fdd265c42f3c340f0ada5cdff3c52a883bc
2,433
collect
Apache License 2.0
src/test/kotlin/model/ReferencePositionTest.kt
JSAbrahams
279,637,335
false
null
package model import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.shouldBe import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import main.kotlin.model.ReferencePosition class ReferencePositionTest : FreeSpec({ "a reference position" - { "can be retrieved from a json" { val string = this.javaClass.getResource("/json/reference-position.json").readText() val reference = Json.decodeFromString<ReferencePosition>(string) reference.startProperty.get() shouldBe 612 reference.endProperty.get() shouldBe 585 reference.referenceId shouldBe 660 } "can be written to json" { val keyword = ReferencePosition(referenceId = 860, start = 479, end = 778) val netReferencePosition = Json.decodeFromString<ReferencePosition>(Json.encodeToString(keyword)) netReferencePosition shouldBe keyword } } })
23
Kotlin
1
1
d8c3c22352646972e110b2599a3901b89593d313
1,019
Academic-Journal
MIT License
src/main/kotlin/frc/chargers/wpilibextensions/ratelimit/AngularVelocityRateLimiter.kt
frc-5160-the-chargers
497,722,545
false
{"Kotlin": 438322, "Java": 56704}
package frc.chargers.wpilibextensions.ratelimit import com.batterystaple.kmeasure.quantities.AngularAcceleration import com.batterystaple.kmeasure.quantities.AngularVelocity import com.batterystaple.kmeasure.quantities.Quantity import com.batterystaple.kmeasure.quantities.abs import edu.wpi.first.math.filter.SlewRateLimiter /** * A wrapper over WPILib's [SlewRateLimiter] that rate-limits a [AngularVelocity] input. */ public class AngularVelocityRateLimiter{ private val rateLimiter: SlewRateLimiter private val onlyLimitPositiveAccel: Boolean private var previousInput: AngularVelocity = AngularVelocity(0.0) public constructor(rateLimit: AngularAcceleration, onlyLimitPositiveAccel: Boolean){ rateLimiter = SlewRateLimiter(rateLimit.siValue) this.onlyLimitPositiveAccel = onlyLimitPositiveAccel } public constructor( positiveLimit: AngularAcceleration, negativeLimit: AngularAcceleration, initialValue: AngularAcceleration ){ require(positiveLimit.siValue > 0.0){"Positive Rate Limit must be a positive value."} require(negativeLimit.siValue < 0.0){"Negative Rate Limit must be a negative value."} this.onlyLimitPositiveAccel = false rateLimiter = SlewRateLimiter( positiveLimit.siValue, negativeLimit.siValue, initialValue.siValue ) } public fun calculate(input: AngularVelocity): AngularVelocity = if (onlyLimitPositiveAccel && abs(input) < abs(previousInput)){ previousInput = input rateLimiter.reset(input.siValue) input }else{ previousInput = input Quantity(rateLimiter.calculate(input.siValue)) } public fun reset(value: AngularVelocity): Unit = rateLimiter.reset(value.siValue) }
3
Kotlin
0
2
ef0bca03f00901ffcc5508981089edced59f91aa
1,851
ChargerLib
MIT License
src/main/kotlin/no/nav/dagpenger/soknad/orkestrator/behov/løsere/PermittertFiskeforedlingBehovløser.kt
navikt
758,018,874
false
{"Kotlin": 186367, "HTML": 701, "Dockerfile": 109}
package no.nav.dagpenger.soknad.orkestrator.behov.løsere import no.nav.dagpenger.soknad.orkestrator.behov.Behovløser import no.nav.dagpenger.soknad.orkestrator.behov.BehovløserFactory.Behov.Permittert import no.nav.dagpenger.soknad.orkestrator.behov.Behovmelding import no.nav.dagpenger.soknad.orkestrator.opplysning.asListOf import no.nav.dagpenger.soknad.orkestrator.opplysning.datatyper.ArbeidsforholdSvar import no.nav.dagpenger.soknad.orkestrator.opplysning.datatyper.Sluttårsak import no.nav.dagpenger.soknad.orkestrator.opplysning.db.OpplysningRepository import no.nav.helse.rapids_rivers.RapidsConnection import java.util.UUID class PermittertBehovløser( rapidsConnection: RapidsConnection, opplysningRepository: OpplysningRepository, ) : Behovløser(rapidsConnection, opplysningRepository) { override val behov = Permittert.name override val beskrivendeId = "faktum.arbeidsforhold" override fun løs(behovmelding: Behovmelding) { val svarPåBehov = rettTilDagpengerUnderPermittering(behovmelding.ident, behovmelding.søknadId) publiserLøsning(behovmelding, svarPåBehov) } internal fun rettTilDagpengerUnderPermittering( ident: String, søknadId: UUID, ): Boolean { val arbeidsforholdOpplysning = opplysningRepository.hent(beskrivendeId, ident, søknadId) ?: return false return arbeidsforholdOpplysning.svar.asListOf<ArbeidsforholdSvar>().any { it.sluttårsak == Sluttårsak.PERMITTERT } } }
3
Kotlin
0
0
dfb07db7092c5984706cb6fd98b7bc63e3752186
1,502
dp-soknad-orkestrator
MIT License
sample/src/main/java/com/example/sample/ui/MainViewModel.kt
crow-misia
429,544,850
false
null
package com.example.sample.ui import android.app.Application import android.content.Context import androidx.core.content.edit import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.viewModelScope import com.amazonaws.mobileconnectors.iot.AWSIoTKeystoreHelperExt import com.amazonaws.mobileconnectors.iot.AWSIotKeystoreHelper import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager import com.amazonaws.mobileconnectors.iot.loadPrivateKey import com.amazonaws.mobileconnectors.iot.loadX509Certificate import com.amazonaws.regions.Region import com.amazonaws.services.securitytoken.model.ThingName import com.example.sample.R import io.github.crow_misia.aws.iot.* import io.github.crow_misia.aws.iot.keystore.BasicKeyStoreProvisioningManager import io.github.crow_misia.aws.iot.provisioning.CreateCertificateFromCSRFleetProvisioner import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlinx.serialization.Serializable import timber.log.Timber import java.util.* import java.util.concurrent.atomic.AtomicInteger class MainViewModel(application: Application) : AndroidViewModel(application), DefaultLifecycleObserver { private val sharedPreferences = application.getSharedPreferences("app", Context.MODE_PRIVATE) private val resources = application.resources private val assetManager = application.assets private val provider = AWSIotMqttManagerProvider.create( region = Region.getRegion(resources.getString(R.string.aws_region)), endpoint = AWSIotMqttManager.Endpoint.fromString(resources.getString(R.string.aws_endpoint)), ) private val provisioningManager = BasicKeyStoreProvisioningManager( mqttManagerProvider = provider, provisionerProvider = { CreateCertificateFromCSRFleetProvisioner(it) }, templateName = resources.getString(R.string.aws_template_name), keyStoreProvider = { AWSIoTKeystoreHelperExt.loadKeyStore( certId = "provisioning", certificates = assetManager.loadX509Certificate("certificate.pem"), privateKey = assetManager.loadPrivateKey("private.key"), ) } ) private var thingNameProvider = ThingNameProvider<Unit> { ThingName(sharedPreferences.getString("thingName", null).orEmpty()) } private var shadowClient: AWSIoTMqttShadowClient? = null override fun onCleared() { shadowClient?.disconnect() shadowClient = null provider.allDisconnect() super.onCleared() } private fun createMqttManager(): AWSIotMqttManager { return provider.provide(thingNameProvider.provide(Unit)) } fun onClickProvisioning() { val keystoreName = "iot" val keystorePath = getApplication<Application>().filesDir val keystorePathStr = keystorePath.absolutePath if (AWSIotKeystoreHelper.isKeystorePresent(keystorePathStr, keystoreName)) { Timber.i("Already exists device keystore.") return } val serialNumber = UUID.randomUUID().toString() viewModelScope.launch(context = Dispatchers.IO) { try { provisioningManager.provisioning(mapOf( "SerialNumber" to serialNumber, )).apply { saveCertificateAndPrivateKey( keystorePath = keystorePathStr, keystoreName = keystoreName, ) sharedPreferences.edit { putString("certificateId", certificateId) putString("thingName", thingName) } Timber.i("Registered things.\n%s", this) } } catch (e: Throwable) { Timber.e(e, "Error provisioning.") } } } @OptIn(ExperimentalCoroutinesApi::class) fun onClickSubscribeShadow() { val manager = createMqttManager() val keystoreName = "iot" val keystorePath = getApplication<Application>().filesDir val keystorePathStr = keystorePath.absolutePath val certId = sharedPreferences.getString("certificateId", null) val thingName = sharedPreferences.getString("thingName", null) if (certId.isNullOrBlank() || thingName.isNullOrBlank() || !AWSIotKeystoreHelper.isKeystorePresent(keystorePathStr, keystoreName) ) { return } val keyStore = AWSIotKeystoreHelper.getIotKeystore( certId, keystorePathStr, keystoreName, AWSIotKeystoreHelper.AWS_IOT_INTERNAL_KEYSTORE_PASSWORD ) viewModelScope.launch(Dispatchers.IO) { Timber.i("certId = %s, thingName = %s", certId, thingName) val shadowClient = shadowClient ?: run { manager.asShadowClient(ThingName(thingName)).also { [email protected] = it } } manager.connect(keyStore) // waiting until connected. .filter { it == AWSIotMqttClientStatusCallback.AWSIotMqttClientStatus.Connected } .flatMapConcat { shadowClient.subscribeDocuments<SampleDeviceData>() } .onEach { Timber.i("Received shadow data = %s", it) } .catch { e -> Timber.e(e, "Error subscribe shadow.") } .launchIn(this) } } fun onClickGetShadow() { viewModelScope.launch(Dispatchers.IO) { val shadowClient = shadowClient ?: return@launch try { val data = shadowClient.get<SampleDeviceData>() Timber.i("Get shadow data = %s", data) } catch (e: Throwable) { Timber.e(e, "Error get shadow.") } } } private val counter = AtomicInteger(0) fun onClickUpdateShadow() { viewModelScope.launch(Dispatchers.IO) { val shadowClient = shadowClient ?: return@launch try { val count = counter.incrementAndGet() val data = shadowClient.update(SampleDeviceData(count)) Timber.i("Updated shadow data = %s", data) } catch (e: Throwable) { Timber.e(e, "Error update shadow.") } } } fun onClickDeleteShadow() { viewModelScope.launch(Dispatchers.IO) { val shadowClient = shadowClient ?: return@launch try { shadowClient.delete() Timber.i("Deleted shadow data") } catch (e: Throwable) { Timber.e(e, "Error delete shadow.") } } } @Serializable data class SampleDeviceData( val count: Int?, ) }
0
Kotlin
0
0
bf46c3f734cc7c11bd19889316054e9fbbda02de
7,020
aws-sdk-android-ktx
Apache License 2.0
src/main/kotlin/org/rust/lang/core/macros/RsMacroDataWithHash.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import org.rust.lang.core.macros.errors.ResolveMacroWithoutPsiError import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.RsMacroDefinitionBase import org.rust.lang.core.psi.ext.RsNamedElement import org.rust.lang.core.psi.ext.isProcMacroDef import org.rust.lang.core.psi.ext.procMacroName import org.rust.lang.core.resolve2.DeclMacro2DefInfo import org.rust.lang.core.resolve2.DeclMacroDefInfo import org.rust.lang.core.resolve2.MacroDefInfo import org.rust.lang.core.resolve2.ProcMacroDefInfo import org.rust.stdext.HashCode import org.rust.stdext.RsResult import org.rust.stdext.RsResult.Err import org.rust.stdext.RsResult.Ok class RsMacroDataWithHash<out T : RsMacroData>( val data: T, val bodyHash: HashCode? ) { fun mixHash(call: RsMacroCallDataWithHash): HashCode? { @Suppress("USELESS_CAST") // False-positive val callHash = when (data as RsMacroData) { is RsDeclMacroData -> call.bodyHash is RsProcMacroData -> call.hashWithEnv() is RsBuiltinMacroData -> call.bodyHash } return HashCode.mix(bodyHash ?: return null, callHash ?: return null) } companion object { fun fromPsi(def: RsNamedElement): RsMacroDataWithHash<*>? { return when { def is RsMacroDefinitionBase -> if (def.hasRustcBuiltinMacro) { RsBuiltinMacroData(def.name ?: return null).withHash() } else { RsMacroDataWithHash(RsDeclMacroData(def), def.bodyHash) } def is RsFunction && def.isProcMacroDef -> { val name = def.procMacroName ?: return null val procMacro = def.containingCrate?.procMacroArtifact ?: return null val hash = HashCode.mix(procMacro.hash, HashCode.compute(name)) RsMacroDataWithHash(RsProcMacroData(name, procMacro), hash) } else -> null } } fun fromDefInfo(def: MacroDefInfo): RsResult<RsMacroDataWithHash<*>, ResolveMacroWithoutPsiError> { return when (def) { is DeclMacroDefInfo -> Ok( if (def.hasRustcBuiltinMacro) { RsBuiltinMacroData(def.path.name).withHash() } else { RsMacroDataWithHash(RsDeclMacroData(def.body), def.bodyHash) } ) is DeclMacro2DefInfo -> Ok( if (def.hasRustcBuiltinMacro) { RsBuiltinMacroData(def.path.name).withHash() } else { RsMacroDataWithHash(RsDeclMacroData(def.body), def.bodyHash) } ) is ProcMacroDefInfo -> { val name = def.path.name val procMacroArtifact = def.procMacroArtifact ?: return Err(ResolveMacroWithoutPsiError.NoProcMacroArtifact) val hash = HashCode.mix(procMacroArtifact.hash, HashCode.compute(name)) Ok(RsMacroDataWithHash(RsProcMacroData(name, procMacroArtifact), hash)) } } } } }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
3,395
intellij-rust
MIT License
webauthnkit/src/main/kotlin/webauthnkit/core/data/AuthenticatorAttachment.kt
lyokato
166,183,654
false
null
package webauthnkit.core.data enum class AuthenticatorAttachment( private val rawValue: String ) { Platform("platform"), CrossPlatform("cross-platform"); override fun toString(): String { return rawValue } }
1
null
5
22
7646b8b3f7eb6442832696e34fb7625288d41349
239
WebAuthnKit-Android
MIT License
lib-moshi/src/main/java/net/codefeet/lemmyandroidclient/gen/types/ListRegistrationApplicationsResponse.kt
Flex4Reddit
648,927,752
false
null
package net.codefeet.lemmyandroidclient.gen.types import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlin.collections.List import kotlinx.parcelize.Parcelize @Parcelize @JsonClass(generateAdapter = true) public data class ListRegistrationApplicationsResponse( @Json(name = "registration_applications") public val registrationApplications: List<RegistrationApplicationView>, ) : Parcelable
0
Kotlin
0
0
8028bbf4fc50d7c945d20c7034d6da2de4b7c0ac
449
lemmy-android-client
MIT License
canvas2_lp/src/main/java/com/angcyo/canvas2/laser/pecker/util/LPConstant.kt
angcyo
229,037,684
false
null
package com.angcyo.canvas2.laser.pecker.util import com.angcyo.library.component.hawk.HawkPropertyValue import com.angcyo.library.unit.IRenderUnit import com.angcyo.library.unit.InchRenderUnit import com.angcyo.library.unit.MmRenderUnit import com.angcyo.library.unit.PxRenderUnit /** * 常量 * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2023-3-6 */ object LPConstant { //region ---Canvas--- /**像素单位*/ const val CANVAS_VALUE_UNIT_PIXEL = 1 /**厘米单位*/ const val CANVAS_VALUE_UNIT_MM = 2 /**英寸单位*/ const val CANVAS_VALUE_UNIT_INCH = 3 //endregion ---Canvas--- //region ---Canvas设置项--- /**单温状态, 持久化*/ var CANVAS_VALUE_UNIT: Int by HawkPropertyValue<Any, Int>(2) /**是否开启智能指南, 持久化*/ var CANVAS_SMART_ASSISTANT: Boolean by HawkPropertyValue<Any, Boolean>(true) /**是否开启网格绘制, 持久化*/ var CANVAS_DRAW_GRID: Boolean by HawkPropertyValue<Any, Boolean>(true) /**渲染的单位*/ val renderUnit: IRenderUnit get() = when (CANVAS_VALUE_UNIT) { CANVAS_VALUE_UNIT_PIXEL -> PxRenderUnit() CANVAS_VALUE_UNIT_INCH -> InchRenderUnit() else -> MmRenderUnit() } //endregion ---Canvas设置项--- }
0
Kotlin
4
3
ce8ef6bdd49421a0973367828242ee74bc95b0af
1,205
UICoreEx
MIT License
app/src/main/java/com/example/webexandroid/HomeActivity.kt
wxsd-sales
563,005,023
false
{"Kotlin": 383358}
package com.example.webexandroid import android.content.Intent import android.os.Bundle import android.os.Handler import android.util.Log import android.view.View import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import com.example.webexandroid.auth.LoginActivity import com.example.webexandroid.databinding.ActivityHomeBinding import com.example.webexandroid.utils.Constants import com.example.webexandroid.calling.CallActivity import com.example.webexandroid.search.SearchActivity import com.example.webexandroid.utils.SharedPrefUtils.clearLoginTypePref import com.example.webexandroid.utils.SharedPrefUtils.saveLoginTypePref class HomeActivity : BaseActivity() { lateinit var binding: ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) tag = "HomeActivity" val authenticator = webexViewModel.webex.authenticator webexViewModel.enableBackgroundConnection(webexViewModel.enableBgConnectiontoggle) webexViewModel.setLogLevel(webexViewModel.logFilter) webexViewModel.enableConsoleLogger(webexViewModel.isConsoleLoggerEnabled) /* //Log.d(tag, "Service URls METRICS: ${webexViewModel.getServiceUrl(Phone.ServiceUrlType.METRICS)}" + "\nCLIENT_LOGS: ${webexViewModel.getServiceUrl(Phone.ServiceUrlType.CLIENT_LOGS)}" + "\nKMS: ${webexViewModel.getServiceUrl(Phone.ServiceUrlType.KMS)}")*/ authenticator?.let { saveLoginTypePref(this) } webexViewModel.signOutListenerLiveData.observe(this@HomeActivity, Observer { it?.let { if (it) { clearLoginTypePref(this) finish() } else { binding.progressLayout.visibility = View.GONE } } }) DataBindingUtil.setContentView<ActivityHomeBinding>(this, R.layout.activity_home) .also { binding = it } .apply { ivStartCall.setOnClickListener { startActivity(Intent(this@HomeActivity, SearchActivity::class.java)) } ivWaitingCall.setOnClickListener { startActivity(CallActivity.getIncomingIntent(this@HomeActivity)) } ivLogout.setOnClickListener { progressLayout.visibility = View.VISIBLE webexViewModel.signOut() } } //used some delay because sometimes it gives empty stuff in personDetails Handler().postDelayed(Runnable { }, 1000) webexViewModel.setSpaceObserver() webexViewModel.setMembershipObserver() webexViewModel.setMessageObserver() } override fun onBackPressed() { android.os.Process.killProcess(android.os.Process.myPid()) } override fun onResume() { super.onResume() webexViewModel.setGlobalIncomingListener() } }
0
Kotlin
1
0
ddf63685454955a2afa0eea0bcc81b3e67edc764
3,135
peer-support-demo-app
MIT License
app/src/main/java/com/ogamoga/developerslive/screens/main/PagerAdapter.kt
ogamoga
403,120,927
false
{"Kotlin": 31703}
package com.ogamoga.developerslive.screens.main import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.ogamoga.developerslive.screens.item.ItemFragment class PagerAdapter( fragment: Fragment ) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment = ItemFragment.newInstance(position) }
0
Kotlin
0
0
cfc73aa6fdcbc0009bcf6605ab964b316237a176
429
DevelopersLife
MIT License
modules/dokkatoo-plugin/src/testFixtures/kotlin/kotestStringMatchers.kt
adamko-dev
598,382,061
false
null
package dev.adamko.dokkatoo.utils import io.kotest.assertions.print.print import io.kotest.matchers.MatcherResult import io.kotest.matchers.neverNullMatcher import io.kotest.matchers.should import io.kotest.matchers.shouldNot infix fun String?.shouldContainAll(substrings: Iterable<String>): String? { this should containAll(substrings) return this } infix fun String?.shouldNotContainAll(substrings: Iterable<String>): String? { this shouldNot containAll(substrings) return this } fun String?.shouldContainAll(vararg substrings: String): String? { this should containAll(substrings.asList()) return this } fun String?.shouldNotContainAll(vararg substrings: String): String? { this shouldNot containAll(substrings.asList()) return this } private fun containAll(substrings: Iterable<String>) = neverNullMatcher<String> { value -> MatcherResult( substrings.all { it in value }, { "${value.print().value} should include substrings ${substrings.print().value}" }, { "${value.print().value} should not include substrings ${substrings.print().value}" }) } infix fun String?.shouldContainAnyOf(substrings: Iterable<String>): String? { this should containAnyOf(substrings) return this } infix fun String?.shouldNotContainAnyOf(substrings: Iterable<String>): String? { this shouldNot containAnyOf(substrings) return this } fun String?.shouldContainAnyOf(vararg substrings: String): String? { this should containAnyOf(substrings.asList()) return this } fun String?.shouldNotContainAnyOf(vararg substrings: String): String? { this shouldNot containAnyOf(substrings.asList()) return this } private fun containAnyOf(substrings: Iterable<String>) = neverNullMatcher<String> { value -> MatcherResult( substrings.any { it in value }, { "${value.print().value} should include any of these substrings ${substrings.print().value}" }, { "${value.print().value} should not include any of these substrings ${substrings.print().value}" }) }
671
null
409
9
cfebdcc16620c6972283b4d6c8159cdae61e9b65
2,015
dokkatoo
Apache License 2.0
FluentUI.Demo/src/main/java/com/microsoft/fluentuidemo/demos/PersistentBottomSheetActivity.kt
Anthonysidesapp
454,785,341
false
null
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.fluentuidemo.demos import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.Gravity import android.view.View import android.widget.TextView import com.microsoft.fluentui.bottomsheet.BottomSheetAdapter import com.microsoft.fluentui.bottomsheet.BottomSheetItem import com.microsoft.fluentui.persistentbottomsheet.PersistentBottomSheet import com.microsoft.fluentui.persistentbottomsheet.SheetHorizontalItemAdapter import com.microsoft.fluentui.persistentbottomsheet.SheetItem import com.microsoft.fluentui.snackbar.Snackbar import com.microsoft.fluentuidemo.DemoActivity import com.microsoft.fluentuidemo.R import kotlinx.android.synthetic.main.activity_demo_detail.* import kotlinx.android.synthetic.main.activity_persistent_bottom_sheet.* import kotlinx.android.synthetic.main.demo_persistent_sheet_content.* class PersistentBottomSheetActivity : DemoActivity(), SheetItem.OnClickListener, BottomSheetItem.OnClickListener { override val contentLayoutId: Int get() = R.layout.activity_persistent_bottom_sheet override val contentNeedsScrollableContainer: Boolean get() = false private lateinit var persistentBottomSheetDemo: PersistentBottomSheet private lateinit var defaultPersistentBottomSheet :PersistentBottomSheet private lateinit var currentSheet :PersistentBottomSheet private var isBack:Boolean = false private lateinit var view:TextView private lateinit var mHorizontalSheet:List<SheetItem> private lateinit var mHorizontalSheet2:List<SheetItem> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) persistentBottomSheetDemo = findViewById(R.id.demo_persistent_sheet) defaultPersistentBottomSheet = findViewById(R.id.default_persistent_sheet) PersistentBottomSheet.DefaultContentBuilder(this) .setCustomSheetContent(R.layout.demo_persistent_sheet_content) .buildWith(persistentBottomSheetDemo) mHorizontalSheet = arrayListOf( SheetItem( R.id.bottom_sheet_item_flag, R.drawable.ic_fluent_flag_24_regular, getString(R.string.bottom_sheet_item_flag_title)), SheetItem(R.id.bottom_sheet_item_alarm, dummyBitmap(), getString(R.string.bottom_sheet_item_custom_image)), SheetItem( R.id.persistent_sheet_item_add_view, R.drawable.ic_add_circle_28_fill, getString(R.string.persistent_sheet_item_add_remove_view)), SheetItem( R.id.persistent_sheet_item_change_height_button, R.drawable.ic_vertical_align_center_28_fill, getString(R.string.persistent_sheet_item_change_collapsed_height)), SheetItem( R.id.bottom_sheet_item_reply, R.drawable.ic_fluent_reply_24_regular, getString(R.string.bottom_sheet_item_reply_title)), SheetItem( R.id.bottom_sheet_item_forward, R.drawable.ic_fluent_forward_24_regular, getString(R.string.bottom_sheet_item_forward_title)), SheetItem( R.id.bottom_sheet_item_delete, R.drawable.ic_delete_24_regular, getString(R.string.bottom_sheet_item_delete_title)), SheetItem( R.id.bottom_sheet_item_delete, R.drawable.ic_delete_24_regular, getString(R.string.bottom_sheet_item_delete_title)), SheetItem( R.id.bottom_sheet_item_delete, R.drawable.ic_delete_24_regular, getString(R.string.bottom_sheet_item_delete_title)) ) mHorizontalSheet2 = arrayListOf( SheetItem( R.id.bottom_sheet_item_flag, R.drawable.ic_fluent_flag_24_regular, getString(R.string.bottom_sheet_item_flag_title)), SheetItem( R.id.bottom_sheet_item_reply, R.drawable.ic_fluent_reply_24_regular, getString(R.string.bottom_sheet_item_reply_title)), SheetItem( R.id.bottom_sheet_item_forward, R.drawable.ic_fluent_forward_24_regular, getString(R.string.bottom_sheet_item_forward_title)), SheetItem( R.id.bottom_sheet_item_delete, R.drawable.ic_delete_24_regular, getString(R.string.bottom_sheet_item_delete_title)), SheetItem( R.id.persistent_sheet_item_create_new_folder, R.drawable.ic_create_new_folder_24_filled, getString(R.string.persistent_sheet_item_create_new_folder_title)) ) sheet_horizontal_item_list_1.createHorizontalItemLayout(mHorizontalSheet) sheet_horizontal_item_list_1.sheetItemClickListener = this sheet_horizontal_item_list_1.setTextAppearance(R.style.TextAppearance_FluentUI_ListItemTitle) sheet_horizontal_item_list_2.createHorizontalItemLayout(mHorizontalSheet2) sheet_horizontal_item_list_2.sheetItemClickListener = this sheet_horizontal_item_list_2.setTextAppearance(R.style.TextAppearance_FluentUI_ListItemTitle) val marginBetweenView = resources.getDimension(R.dimen.fluentui_persistent_horizontal_item_right_margin).toInt() val horizontalListAdapter = SheetHorizontalItemAdapter(this, arrayListOf( SheetItem( R.id.persistent_sheet_item_create_new_folder, R.drawable.ic_create_new_folder_24_filled, getString(R.string.persistent_sheet_item_create_new_folder_title)), SheetItem( R.id.persistent_sheet_item_edit, R.drawable.ic_edit_24_filled, getString(R.string.persistent_sheet_item_edit_title)), SheetItem( R.id.persistent_sheet_item_save, R.drawable.ic_save_24_filled, getString(R.string.persistent_sheet_item_save_title)), SheetItem( R.id.persistent_sheet_item_zoom_in, R.drawable.ic_zoom_in_24_filled, getString(R.string.persistent_sheet_item_zoom_in_title)), SheetItem( R.id.persistent_sheet_item_zoom_out, R.drawable.ic_zoom_out_24_filled, getString(R.string.persistent_sheet_item_zoom_out_title)) ),0, marginBetweenView) horizontalListAdapter.mOnSheetItemClickListener = this sheet_horizontal_item_list_3.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) sheet_horizontal_item_list_3.adapter = horizontalListAdapter val verticalListAdapter = BottomSheetAdapter(this, arrayListOf( BottomSheetItem( R.id.bottom_sheet_item_camera, R.drawable.ic_camera_24_regular, getString(R.string.bottom_sheet_item_camera_title), getString(R.string.bottom_sheet_item_camera_subtitle) ), BottomSheetItem( R.id.bottom_sheet_item_gallery, R.drawable.ic_image_library_24_regular, getString(R.string.bottom_sheet_item_gallery_title), getString(R.string.bottom_sheet_item_gallery_subtitle) ), BottomSheetItem( R.id.bottom_sheet_item_videos, R.drawable.ic_video_24_regular, getString(R.string.bottom_sheet_item_videos_title), getString(R.string.bottom_sheet_item_videos_subtitle) ), BottomSheetItem( R.id.bottom_sheet_item_manage, R.drawable.ic_settings_24_regular, getString(R.string.bottom_sheet_item_manage_title), getString(R.string.bottom_sheet_item_manage_subtitle) ) ), 0) verticalListAdapter.onBottomSheetItemClickListener = this sheet_vertical_item_list_1.adapter = verticalListAdapter showDefaultBottomSheet() show_persistent_bottom_sheet_button.setOnClickListener { currentSheet.expand() } collapse_persistent_bottom_sheet_button.setOnClickListener { if(currentSheet.getPeekHeight() == 0) { currentSheet.showPersistentSheet() collapse_persistent_bottom_sheet_button.text = getString(R.string.collapse_persistent_sheet_button) } else { currentSheet.collapsePersistentSheet() collapse_persistent_bottom_sheet_button.text = getString(R.string.show_persistent_sheet_button) } } toggle_bottom_sheet.setOnClickListener { if (defaultPersistentBottomSheet.visibility == View.GONE) { currentSheet = defaultPersistentBottomSheet persistentBottomSheetDemo.visibility = View.GONE } else { currentSheet = persistentBottomSheetDemo defaultPersistentBottomSheet.visibility = View.GONE } currentSheet.visibility = View.VISIBLE } //initially currentSheet = persistentBottomSheetDemo } private fun showDefaultBottomSheet() { defaultPersistentBottomSheet.setItemClickListener(this) PersistentBottomSheet.DefaultContentBuilder(this) .addHorizontalItemList(mHorizontalSheet2) .addDivider() .addHorizontalGridItemList(mHorizontalSheet) .addDivider() .addVerticalItemList(mHorizontalSheet, getString(R.string.fluentui_bottom_sheet_header)) .addVerticalItemList(mHorizontalSheet,getString(R.string.fluentui_bottom_sheet_header)) .buildWith(defaultPersistentBottomSheet) } override fun onSheetItemClick(item: SheetItem){ when(item.id) { R.id.persistent_sheet_item_add_view -> { if(!this::view.isInitialized || view.parent == null) { view = TextView(this) view.text = getString(R.string.new_view) view.height = 200 view.gravity = Gravity.CENTER persistentBottomSheetDemo.addView(view, 1, demo_bottom_sheet) } else { persistentBottomSheetDemo.removeView(view, demo_bottom_sheet) } } R.id.persistent_sheet_item_change_height_button -> { if(isBack) persistentBottomSheetDemo.changePeekHeight(-400) else persistentBottomSheetDemo.changePeekHeight(400) isBack = !isBack } R.id.bottom_sheet_item_flag -> showSnackbar(resources.getString(R.string.bottom_sheet_item_flag_toast)) R.id.bottom_sheet_item_reply -> showSnackbar(resources.getString(R.string.bottom_sheet_item_reply_toast)) R.id.bottom_sheet_item_forward -> showSnackbar(resources.getString(R.string.bottom_sheet_item_forward_toast)) R.id.bottom_sheet_item_delete -> showSnackbar(resources.getString(R.string.bottom_sheet_item_delete_toast)) R.id.persistent_sheet_item_create_new_folder -> showSnackbar(resources.getString(R.string.persistent_sheet_item_create_new_folder_toast)) R.id.persistent_sheet_item_edit -> showSnackbar(resources.getString(R.string.persistent_sheet_item_edit_toast)) R.id.persistent_sheet_item_save -> showSnackbar(resources.getString(R.string.persistent_sheet_item_save_toast)) R.id.persistent_sheet_item_zoom_in -> showSnackbar(resources.getString(R.string.persistent_sheet_item_zoom_in_toast)) R.id.persistent_sheet_item_zoom_out -> showSnackbar(resources.getString(R.string.persistent_sheet_item_zoom_out_toast)) } } override fun onBottomSheetItemClick(item: BottomSheetItem) { when(item.id) { R.id.bottom_sheet_item_camera -> showSnackbar(resources.getString(R.string.bottom_sheet_item_camera_toast)) R.id.bottom_sheet_item_gallery -> showSnackbar(resources.getString(R.string.bottom_sheet_item_gallery_toast)) R.id.bottom_sheet_item_videos -> showSnackbar(resources.getString(R.string.bottom_sheet_item_videos_toast)) R.id.bottom_sheet_item_manage -> showSnackbar(resources.getString(R.string.bottom_sheet_item_manage_toast)) } } private fun showSnackbar(message: String) { Snackbar.make(root_view, message).show() } private fun dummyBitmap(): Bitmap { val option = BitmapFactory.Options() option.outHeight = resources.getDimensionPixelSize(R.dimen.image_size) option.outWidth = resources.getDimensionPixelSize(R.dimen.image_size) return Bitmap.createScaledBitmap(BitmapFactory.decodeResource(resources, R.drawable.avatar_allan_munger), option.outWidth, option.outHeight, false) } }
36
null
65
9
61cbb5799bba74342b342cd98680286a96f27f70
14,454
fluentui-android
MIT License
app/src/main/java/eu/kanade/tachiyomi/ui/source/SourceAdapter.kt
az4521
176,152,541
false
null
package eu.kanade.tachiyomi.ui.browse.source import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.system.getResourceColor /** * Adapter that holds the catalogue cards. * * @param controller instance of [SourceController]. */ class SourceAdapter(val controller: SourceController) : FlexibleAdapter<IFlexible<*>>(null, controller, true) { val cardBackground = controller.activity!!.getResourceColor(R.attr.colorSurface) init { setDisplayHeadersAtStartUp(true) } /** * Listener for browse item clicks. */ val browseClickListener: OnBrowseClickListener = controller /** * Listener for latest item clicks. */ val latestClickListener: OnLatestClickListener = controller /** * Listener which should be called when user clicks browse. * Note: Should only be handled by [SourceController] */ interface OnBrowseClickListener { fun onBrowseClick(position: Int) } /** * Listener which should be called when user clicks latest. * Note: Should only be handled by [SourceController] */ interface OnLatestClickListener { fun onLatestClick(position: Int) } }
22
null
18
471
a72df3df5073300e02054ee75dc990d196cd6db8
1,292
TachiyomiAZ
Apache License 2.0
appcompose/src/main/java/com/developersancho/hb/compose/app/widgets/ProgressIndicator.kt
developersancho
523,126,274
false
{"Kotlin": 182195}
package com.developersancho.component import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.developersancho.jetframework.Delayed object ProgressIndicatorDefaults { val sizeLarge = 32.dp to 2.dp val sizeMedium = 24.dp to 1.5.dp val sizeSmall = 16.dp to 1.dp val size = 48.dp to 4.dp } @Composable fun ProgressIndicatorSmall(modifier: Modifier = Modifier) = ProgressIndicator( modifier, ProgressIndicatorDefaults.sizeSmall.first, ProgressIndicatorDefaults.sizeSmall.second ) @Composable fun ProgressIndicatorMedium(modifier: Modifier = Modifier) = ProgressIndicator( modifier, ProgressIndicatorDefaults.sizeMedium.first, ProgressIndicatorDefaults.sizeMedium.second ) @Composable fun ProgressIndicator(modifier: Modifier = Modifier) = ProgressIndicator( modifier, ProgressIndicatorDefaults.sizeLarge.first, ProgressIndicatorDefaults.sizeLarge.second ) @Composable fun ProgressIndicator( modifier: Modifier = Modifier, size: Dp = ProgressIndicatorDefaults.size.first, strokeWidth: Dp = ProgressIndicatorDefaults.size.second, color: Color = MaterialTheme.colors.secondary, ) { CircularProgressIndicator(modifier.size(size), color, strokeWidth) } private const val FULL_SCREEN_LOADING_DELAY = 100L @Composable fun FullScreenLoading( modifier: Modifier = Modifier, delayMillis: Long = FULL_SCREEN_LOADING_DELAY ) { Delayed(delayMillis = delayMillis) { Box( contentAlignment = Alignment.Center, modifier = when (modifier == Modifier) { true -> Modifier.fillMaxSize() false -> modifier } ) { ProgressIndicator() } } }
3
Kotlin
33
8
3557e85b86699d8c053a9fc370077ef580a8019a
2,206
HB.Case.Android
Apache License 2.0
server/src/main/kotlin/io/github/alessandrojean/tankobon/interfaces/api/rest/dto/SystemStatusDto.kt
alessandrojean
609,405,137
false
null
package io.github.alessandrojean.tankobon.interfaces.api.rest.dto data class SystemStatusDto( val status: SystemStatus, val isDevelopment: Boolean, val isDemo: Boolean, val version: String, ) enum class SystemStatus { OPERATIONAL, PROBLEMS, NO_DATABASE }
0
Kotlin
0
1
cb28b68c0b6f3b1de7f77450122a609295396c28
267
tankobon
MIT License
serverless-simulator/opendc/opendc-core/src/main/kotlin/com/atlarge/opendc/core/failure/FailureDomain.kt
atlarge-research
297,702,102
false
{"Jupyter Notebook": 11330813, "Kotlin": 547073, "Python": 15018, "R": 1048}
/* * MIT License * * Copyright (c) 2020 atlarge-research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opendc.simulator.failures import kotlinx.coroutines.CoroutineScope /** * A logical or physical component in a computing environment which may fail. */ public interface FailureDomain { /** * The lifecycle of the failure domain to which a [FaultInjector] will attach. */ public val scope: CoroutineScope /** * Fail the domain externally. */ public suspend fun fail() /** * Resume the failure domain. */ public suspend fun recover() }
0
Jupyter Notebook
1
2
11c772bcb3fc7a7c2590d6ed6ab979b78cb9fec9
1,644
opendc-serverless
MIT License
android/app/src/main/kotlin/com/babanomania/CleanHabits/SingleHabitWidgetConfigureActivity.kt
clean-apps
287,965,692
false
null
package com.babanomania.CleanHabits import android.app.Activity import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.dart.DartExecutor import io.flutter.plugin.common.MethodChannel import io.flutter.plugins.GeneratedPluginRegistrant import io.flutter.view.FlutterCallbackInformation import io.flutter.view.FlutterMain import java.util.* class SingleHabitWidgetConfigureActivity : Activity(), MethodChannel.Result { private val TAG = this::class.java.simpleName private var isDark:Boolean = false private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID private lateinit var context: Context private var types = arrayOf( "All" ) private lateinit var adapter: ArrayAdapter<String> private var onClickListener = View.OnClickListener { val context = this@SingleHabitWidgetConfigureActivity // It is the responsibility of the configuration activity to update the app widget initializeFlutter() var prefs: SharedPreferences = context.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE); isDark = prefs.getBoolean("flutter.dark-mode", false); var fetchType:String = loadTypePref(context, appWidgetId) SingleHabitWidgetProvider.channel?.invokeMethod("getSingleHabitAppWidgetData", "$appWidgetId#$fetchType", this) // Make sure we pass back the original appWidgetId val resultValue = Intent() resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) setResult(RESULT_OK, resultValue) finish() } public override fun onCreate(icicle: Bundle?) { super.onCreate(icicle) context = applicationContext var fetchType = "All"; SingleHabitWidgetProvider.channel?.invokeMethod("getSingleHabitAppWidgetData", "$appWidgetId#$fetchType#0", this) // Set the result to CANCELED. This will cause the widget host to cancel // out of the widget placement if the user presses the back button. setResult(RESULT_CANCELED) setContentView(R.layout.single_habit_widget_configure) val spinner: Spinner = findViewById<View>(R.id.singleHabitSelection) as Spinner adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.setAdapter(adapter) spinner.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, view: View?, position: Int, id: Long) { saveTypePref(context, appWidgetId, types[position]) } override fun onNothingSelected(p0: AdapterView<*>?) { //deleteTypePref(context, appWidgetId) } }) findViewById<View>(R.id.add_button).setOnClickListener(onClickListener) // Find the widget id from the intent. val intent = intent val extras = intent.extras if (extras != null) { appWidgetId = extras.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) } // If this activity was started with an intent without an app widget ID, finish with an error. if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish() return } } private fun initializeFlutter() { if (SingleHabitWidgetProvider.channel == null) { FlutterMain.startInitialization(context) FlutterMain.ensureInitializationComplete(context, arrayOf()) val handle = WidgetHelper.getRawHandle(context) if (handle == WidgetHelper.NO_HANDLE) { Log.w(TAG, "Couldn't update widget because there is no handle stored!") return } val callbackInfo = FlutterCallbackInformation.lookupCallbackInformation(handle) // You could also use a hard coded value to save you from all // the hassle with SharedPreferences, but alas when running your // app in release mode this would fail. val entryPointFunctionName = callbackInfo.callbackName // Instantiate a FlutterEngine. val engine = FlutterEngine(context.applicationContext) val entryPoint = DartExecutor.DartEntrypoint(FlutterMain.findAppBundlePath(), entryPointFunctionName) engine.dartExecutor.executeDartEntrypoint(entryPoint) // Register Plugins when in background. When there // is already an engine running, this will be ignored (although there will be some // warnings in the log). GeneratedPluginRegistrant.registerWith(engine) SingleHabitWidgetProvider.channel = MethodChannel(engine.dartExecutor.binaryMessenger, WidgetHelper.CHANNEL) } } override fun success(result: Any?) { val args = result as HashMap<*, *> val habits = args["habits"] as List<Map<String, *>> val type = args["type"] as String val isInit = args["init"] as Boolean if( type == "All" ) { for(habit in habits) { val title = habit["title"] as String types += title } adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) val spinner: Spinner = findViewById<View>(R.id.singleHabitSelection) as Spinner spinner.setAdapter(adapter) val selected = loadTypePref(context, appWidgetId) val selectionIndex = types.indexOf(selected) spinner.setSelection( if(selectionIndex < 0 ) 0 else selectionIndex ) adapter.notifyDataSetChanged() if(!isInit){ val id = args["id"] as String val progress = args["progress"] as Map<String, Int> updateSingleHabitWidget(id.toInt(), type, habits, progress, context, isDark) } // } else { val id = args["id"] as String val progress = args["progress"] as Map<String, Int> updateSingleHabitWidget(id.toInt(), type, habits, progress, context, isDark) } } override fun notImplemented() { Log.d(TAG, "notImplemented") } override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) { Log.d(TAG, "onError $errorCode") } } private const val PREFS_NAME = "com.example.cleanhabits.singleHabitWidget.type" private const val PREF_PREFIX_KEY = "singleHabitWidget_" // Write the prefix to the SharedPreferences object for this widget internal fun saveTypePref(context: Context, appWidgetId: Int, text: String) { val prefs = context.getSharedPreferences(PREFS_NAME, 0).edit() prefs.putString(PREF_PREFIX_KEY + appWidgetId, text) prefs.apply() } // Read the prefix from the SharedPreferences object for this widget. // If there is no preference saved, get the default from a resource internal fun loadTypePref(context: Context, appWidgetId: Int): String { val prefs = context.getSharedPreferences(PREFS_NAME, 0) val type = prefs.getString(PREF_PREFIX_KEY + appWidgetId, null) return type ?: "All" } internal fun deleteTypePref(context: Context, appWidgetId: Int) { val prefs = context.getSharedPreferences(PREFS_NAME, 0).edit() prefs.remove(PREF_PREFIX_KEY + appWidgetId) prefs.apply() }
2
Dart
11
19
91b4c604d8714f93bd72735eee88d2c0712108d8
7,943
CleanHabits
Apache License 2.0
runtime/runtime-core/common/src/aws/smithy/kotlin/runtime/net/IpV4Addr.kt
smithy-lang
294,823,838
false
{"Kotlin": 4171610, "Smithy": 122979, "Python": 1215}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.smithy.kotlin.runtime.net /** * An IPv4 address as defined by [RFC 791](https://www.rfc-editor.org/rfc/rfc791) * @param octets The four eight-bit integers that make up this address */ public data class IpV4Addr( override val octets: ByteArray, ) : IpAddr() { /** * Creates a new IPv4 address from four eight-bit octets. The result * represents the IP address `a.b.c.d` */ public constructor(a: UByte, b: UByte, c: UByte, d: UByte) : this(byteArrayOf(a.toByte(), b.toByte(), c.toByte(), d.toByte())) init { require(octets.size == 4) { "Invalid IPv4 repr: $octets; expected 4 bytes" } } public companion object { /** * An IPv4 address with the address pointing to localhost: 127.0.0.1 */ public val LOCALHOST: IpV4Addr = IpV4Addr(127u, 0u, 0u, 1u) /** * An Ipv4 address for the special "unspecified" address (`0.0.0.0`). Also known as * `INADDR_ANY`, see [ip7](https://man7.org/linux/man-pages/man7/ip.7.html) */ public val UNSPECIFIED: IpV4Addr = IpV4Addr(0u, 0u, 0u, 0u) /** * Parse an IPv4 address from a string. Fails with [IllegalArgumentException] when given an invalid IPv4 address */ public fun parse(s: String): IpV4Addr = requireNotNull(s.parseIpv4OrNull()) { "Invalid Ipv4 address: $s" } } /** * Returns true if this is a loopback address (127.0.0.0/8). * Defined by [RFC 1122](https://www.rfc-editor.org/rfc/rfc1122) */ override val isLoopBack: Boolean get() = octets[0] == 127.toByte() /** * Returns true if this is the "any" address (`0.0.0.0`) */ public override val isUnspecified: Boolean get() = this == UNSPECIFIED override val address: String get() = octets.joinToString(separator = ".") { it.toUByte().toString() } override fun toString(): String = address override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as IpV4Addr if (!octets.contentEquals(other.octets)) return false return true } override fun hashCode(): Int = octets.contentHashCode() /** * Convert this IPv4 address to an "IPv4-mapped" IPV6 address as described by * [RFC 4291 Section 2.5.5.2](https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2). * e.g. `fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:a.b.c.d`. * * See [IpV6Addr] documentation for more details. */ public fun toMappedIpv6(): IpV6Addr { val v6Octets = ByteArray(16) v6Octets[10] = 0xff.toByte() v6Octets[11] = 0xff.toByte() v6Octets[12] = octets[0] v6Octets[13] = octets[1] v6Octets[14] = octets[2] v6Octets[15] = octets[3] return IpV6Addr(v6Octets) } }
36
Kotlin
26
82
ad18e2fb043f665df9add82083c17877a23f8610
3,038
smithy-kotlin
Apache License 2.0
src/main/kotlin/br/com/devsrsouza/kotlinbukkitapi/tooling/menu/Declaration.kt
DevSrSouza
278,207,597
false
null
package tech.carcadex.kotlinbukkitkit.tooling.menu data class MenuDeclaration( val displayname: String, val lines: Int, val slots: List<MenuSlotDeclaration> ) data class MenuSlotDeclaration( val line: Int, val slot: Int, val item: String, val isSelected: Boolean = false )
2
null
4
15
5532f33f821cb7daaab4b253c4f0a9c2c8ac3f58
319
KotlinBukkitAPI-Tooling
MIT License
app/src/main/java/com/hover/stax/domain/use_case/financial_tips/TipsUseCase.kt
UseHover
286,494,631
false
{"Kotlin": 1033610, "Java": 88968, "Shell": 274, "Ruby": 235}
/* * Copyright 2022 Stax * * 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.hover.stax.domain.use_case.financial_tips import com.hover.stax.data.tips.FinancialTipsRepository import com.hover.stax.model.FinancialTip import com.hover.stax.model.Resource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class TipsUseCase @Inject constructor( private val financialTipsRepository: FinancialTipsRepository ) { operator fun invoke(): Flow<com.hover.stax.model.Resource<List<com.hover.stax.model.FinancialTip>>> = flow { try { emit(com.hover.stax.model.Resource.Loading()) val financialTips = financialTipsRepository.getTips() emit(com.hover.stax.model.Resource.Success(financialTips)) } catch (e: Exception) { emit(com.hover.stax.model.Resource.Error("Error fetching tips")) } } fun getDismissedTipId(): String? = financialTipsRepository.getDismissedTipId() fun dismissTip(id: String) { financialTipsRepository.dismissTip(id) } }
106
Kotlin
72
79
5b735dc215b63533420fe899c579a42a44f598ea
1,648
Stax
Apache License 2.0
app/src/main/java/com/example/loginsesame/helper/LogAssert.kt
sw21-tug
350,454,499
false
null
package com.example.loginsesame.helper import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.util.regex.Matcher import java.util.regex.Pattern import kotlin.jvm.Throws class LogAssert { private var logText: String? = null private val logs: String private get() { val logcat: Process val log = StringBuilder() try { logcat = Runtime.getRuntime().exec(arrayOf("logcat", "-d")) val br = BufferedReader(InputStreamReader(logcat.inputStream), 4 * 1024) var line: String? val separator = System.getProperty("line.separator") while (br.readLine().also { line = it } != null) { log.append(line) log.append(separator) } } catch (e: Exception) { e.printStackTrace() } return log.toString() } @Throws(Exception::class) fun assertLogsExist(assertPatterns: Array<String>) { logText = logs for (patternString in assertPatterns) { val pattern: Pattern = Pattern.compile(patternString) val matcher: Matcher = pattern.matcher(logText) if (!matcher.find()) { throw Exception("Log [$patternString] is missing") } } } private fun clearLog() { try { val process = ProcessBuilder() .command("logcat", "-c") .redirectErrorStream(true) .start() } catch (e: IOException) { } } init { clearLog() } }
19
null
5
1
684325336e50fad9482073faf56596f70732739f
1,803
Team_17
MIT License
app/src/main/java/com/example/pokedex/network/Pokemon/PokemonStats.kt
RamziJabali
389,429,666
false
{"Kotlin": 35432}
package com.example.pokedex.network.Pokemon import com.google.gson.annotations.SerializedName data class PokemonStats( @SerializedName("base_stat") val pokemonBaseStat: Int, @SerializedName("stat") val pokemonStatType: PokemonStatStype )
0
Kotlin
0
2
59e60563e32feabb07abb1cb22839f0c81a7c37a
256
pokedex-android
Apache License 2.0
src/main/kotin/com/hewking/kotlin/other/OperatorOverloading.kt
hewking
215,742,339
false
null
package main.kotin.com.hewking.kotlin.other /** * @program: kotlinPractice * @description: ${description} * @author: hewking * @create: 2019-10-17 16:46 **/ data class Point(val x: Int,val y: Int) operator fun Point.unaryMinus() = Point(-x,-y) val point = Point(10,20) fun main(){ print(-point) }
0
Kotlin
0
0
7f3d18a87b6c2239d048ea70575933228e23fb19
310
kotlinPractice
Apache License 2.0
features/series/src/main/java/com/chesire/nekome/app/series/list/DialogExtensions.kt
rmwthorne
330,431,997
true
{"Kotlin": 498067, "Ruby": 7559, "JavaScript": 64}
package com.chesire.nekome.app.series.list import androidx.fragment.app.Fragment import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.lifecycle.lifecycleOwner import com.afollestad.materialdialogs.list.listItems import com.afollestad.materialdialogs.list.listItemsMultiChoice import com.chesire.nekome.app.series.SeriesPreferences import com.chesire.nekome.core.R import com.chesire.nekome.core.flags.SortOption import com.chesire.nekome.core.flags.UserSeriesStatus /** * Shows the filter dialog, allowing the user to choose how to filter their series list. */ fun Fragment.showFilterDialog(preferences: SeriesPreferences) { val context = context ?: return val filterOptionMap = UserSeriesStatus.getValueMap(context) MaterialDialog(context).show { title(R.string.filter_dialog_title) listItemsMultiChoice( items = filterOptionMap.values.toList(), initialSelection = preferences.filterPreference.filter { it.value }.keys.toIntArray() ) { _, _, items -> preferences.filterPreference = createFilterMap( filterOptionMap, items.map { it.toString() } ) } negativeButton(R.string.filter_dialog_cancel) positiveButton(R.string.filter_dialog_confirm) lifecycleOwner(viewLifecycleOwner) } } /** * Shows the sort dialog, allowing the user to choose how the series list is sorted. */ fun Fragment.showSortDialog(preferences: SeriesPreferences) { val context = context ?: return val sortOptionMap = SortOption .values() .associate { context.getString(it.stringId) to it.index } MaterialDialog(context).show { title(R.string.sort_dialog_title) listItems(items = sortOptionMap.keys.toList()) { _, _, text -> sortOptionMap[text]?.let { preferences.sortPreference = SortOption.forIndex(it) } } lifecycleOwner(viewLifecycleOwner) } } private fun createFilterMap(allItems: Map<Int, String>, chosenItems: List<String>) = mutableMapOf<Int, Boolean>().apply { allItems.forEach { entry -> this[entry.key] = chosenItems.contains(entry.value) } }
0
null
0
0
c941c4e1fed0ed76ff28948d9d9bfe7fa280117f
2,262
Nekome
Apache License 2.0
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/impl/IrEnumConstructorCallImpl.kt
arrow-kt
109,678,056
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * 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.jetbrains.kotlin.ir.expressions.impl import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.ir.expressions.IrDelegatingConstructorCall import org.jetbrains.kotlin.ir.expressions.typeParametersCount import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrConstructorSymbolImpl import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.visitors.IrElementVisitor class IrDelegatingConstructorCallImpl( startOffset: Int, endOffset: Int, type: IrType, override val symbol: IrConstructorSymbol, override val descriptor: ClassConstructorDescriptor, typeArgumentsCount: Int ) : IrCallWithIndexedArgumentsBase( startOffset, endOffset, type, typeArgumentsCount = typeArgumentsCount, valueArgumentsCount = symbol.descriptor.valueParameters.size ), IrDelegatingConstructorCall { constructor( startOffset: Int, endOffset: Int, type: IrType, symbol: IrConstructorSymbol, descriptor: ClassConstructorDescriptor ) : this(startOffset, endOffset, type, symbol, descriptor, descriptor.typeParametersCount) @Deprecated("Creates unbound symbol") constructor( startOffset: Int, endOffset: Int, type: IrType, descriptor: ClassConstructorDescriptor, typeArgumentsCount: Int ) : this( startOffset, endOffset, type, IrConstructorSymbolImpl(descriptor.original), descriptor, typeArgumentsCount ) override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R { return visitor.visitDelegatingConstructorCall(this, data) } }
125
null
4903
43
d2a24985b602e5f708e199aa58ece652a4b0ea48
2,357
kotlin
Apache License 2.0
core/src/main/java/de/markusressel/kutepreferences/core/preference/action/ActionPreferenceBehavior.kt
markusressel
129,962,741
false
{"Kotlin": 271957, "Shell": 2347, "Makefile": 701}
package de.markusressel.kutepreferences.core.preference.action import de.markusressel.kutepreferences.core.preference.KuteItemBehavior import de.markusressel.kutepreferences.core.preference.category.shimmerLengthMillis import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch open class ActionPreferenceBehavior( val preferenceItem: KuteAction ) : KuteItemBehavior { private val _uiState = MutableStateFlow(UiState()) val uiState = _uiState.asStateFlow() fun onClick() { preferenceItem.onClick?.invoke() } fun onLongClick() { preferenceItem.onLongClick?.invoke() } override fun highlight() { // TODO: figure out how to use the correct coroutine scope GlobalScope.launch { _uiState.update { old -> old.copy(shimmering = true) } delay(shimmerLengthMillis.toLong()) _uiState.update { old -> old.copy(shimmering = false) } } } data class UiState( val shimmering: Boolean = false, ) }
6
Kotlin
0
12
dd5c034d2a6d18a05ed8c75227dd598525cd0916
1,189
KutePreferences
The Unlicense
app/src/main/java/com/example/alertasullana/ui/viewmodel/PerfilViewModel.kt
peteragurto
711,549,330
false
{"Kotlin": 83226}
package com.example.alertasullana.ui.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.alertasullana.data.repository.FirebaseRepository import com.example.alertasullana.data.repository.UsuarioRepository class PerfilViewModel(private val firebaseRepository: FirebaseRepository,//LLamar a Usuario Repository private val usuarioRepository: UsuarioRepository ) : ViewModel() { private val _nombreUsuario = MutableLiveData<String>() private val _correoUsuario = MutableLiveData<String>() private val _urlFotoPerfil = MutableLiveData<String>() //Para navegación private val _navegarARegistro = MutableLiveData<Boolean>() val nombreUsuario: LiveData<String> get() = _nombreUsuario val correoUsuario: LiveData<String> get() = _correoUsuario val urlFotoPerfil: LiveData<String> get() = _urlFotoPerfil val navegarARegistro: LiveData<Boolean> get() = _navegarARegistro init { // Verificar si el usuario ya ha iniciado sesión val currentUser = firebaseRepository.obtenerUsuarioActual() if (currentUser != null) { _nombreUsuario.value = currentUser.displayName _correoUsuario.value = currentUser.email _urlFotoPerfil.value = currentUser.photoUrl?.toString() // Guardar los datos en SharedPreferences usuarioRepository.guardarDatosEnSharedPreferences(currentUser) } } // Método para actualizar los datos del usuario fun actualizarDatosUsuario(nombre: String, correo: String, urlFoto: String) { _nombreUsuario.value = nombre _correoUsuario.value = correo _urlFotoPerfil.value = urlFoto } // Método para cerrar sesión y navegar a la actividad de registro fun cerrarSesionYNavegarARegistro() { firebaseRepository.cerrarSesion() _navegarARegistro.value = true } }
0
Kotlin
0
3
517eeee7f35b6bb3c7a7a5c3b9e53b8ff37263c6
1,968
app-alerta-sullana
MIT License
server/src/main/kotlin/com/studystream/app/server/feature/account/routes/Create.kt
ImpossibleAccuracy
834,219,225
false
{"Kotlin": 158719, "Dockerfile": 625}
package com.studystream.app.server.feature.account.routes import com.studystream.domain.model.Account import com.studystream.domain.security.Permission import com.studystream.domain.repository.AuthRepository import com.studystream.app.server.feature.account.Accounts import com.studystream.app.server.mapper.toDto import com.studystream.app.server.security.requireAccount import com.studystream.app.server.security.requirePermission import com.studystream.app.server.utils.LazyBody import com.studystream.app.server.utils.endpoint import com.studystream.app.server.utils.typeSafePost import com.studystream.shared.payload.dto.AccountDto import com.studystream.shared.payload.request.CreateAccountRequest import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.koin.ktor.ext.get internal fun Routing.installCreateAccountRoute() { authenticate { typeSafePost<Accounts> { val result = createAccount( body = LazyBody { call.receive() }, account = call.requireAccount(), authRepository = call.get(), ) call.respond(result) } } } suspend fun createAccount( body: LazyBody<CreateAccountRequest>, account: Account, authRepository: AuthRepository, ): AccountDto = endpoint { account.requirePermission(Permission.ACCOUNTS_CREATE) authRepository .signUp(body().username, body().password) .getOrThrow() .toDto() }
0
Kotlin
0
0
a34321630eacff596bbcd117a292bd4a52429c49
1,576
study-stream
The Unlicense
ui/galleries/presenter/impl/src/test/kotlin/com/adjectivemonk2/pixels/ui/galleries/presenter/impl/AccountImageUrlGeneratorTest.kt
Sripadmanabans
300,346,280
false
null
package com.adjectivemonk2.pixels.ui.galleries.common.impl import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test internal class AccountImageUrlGeneratorTest { @Test fun `Account thumbnail url generator test`() { val id = "account id" val actual = AccountImageUrlGenerator().thumbnail(id) val expected = """https://imgur.com/user/$id/avatar?maxwidth=290""" assertThat(actual).isEqualTo(expected) } }
11
null
0
2
c925014bad38c7eb659282806289f8f453b78f30
450
Pixels
Apache License 2.0
underwave/src/androidTest/kotlin/com/aallam/underwave/internal/view/ViewManagerTest.kt
Aallam
229,120,653
false
null
package com.aallam.underwave.internal.view import android.os.Handler import com.aallam.underwave.extension.MainCoroutineRule import com.aallam.underwave.extension.runBlocking import com.aallam.underwave.internal.cache.memory.bitmap.BitmapPool import com.aallam.underwave.internal.image.Bitmap import com.aallam.underwave.internal.image.Dimension import com.aallam.underwave.internal.image.ImageView import com.aallam.underwave.internal.image.dimension import com.aallam.underwave.internal.view.impl.ImageViewManager import com.aallam.underwave.load.impl.LoadRequest import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.impl.annotations.RelaxedMockK import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkAll import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import java.lang.ref.WeakReference @RunWith(RobolectricTestRunner::class) @ExperimentalCoroutinesApi internal actual class ViewManagerTest { @get:Rule val coroutineRule = MainCoroutineRule() lateinit var viewManager: ViewManager @RelaxedMockK lateinit var viewMap: HashMap<ImageView, String> @RelaxedMockK lateinit var handler: Handler @RelaxedMockK lateinit var bitmapPool: BitmapPool @RelaxedMockK lateinit var loader: Loader @RelaxedMockK lateinit var imageView: ImageView @Before fun init() { MockKAnnotations.init(this) viewManager = ImageViewManager(viewMap, handler, bitmapPool, loader) mockkStatic("com.aallam.underwave.internal.image.DimensionKt") } @Test actual fun testLoad() = coroutineRule.runBlocking { val loadRequest: LoadRequest = mockk() val bitmap: Bitmap = mockk() val imageViewDimension = Dimension(100, 100) val imageViewRef = WeakReference(imageView) val imageUrl = "URL" every { loadRequest.imageView } returns imageViewRef every { loadRequest.imageUrl } returns imageUrl every { imageView.dimension } returns imageViewDimension every { viewMap[imageView] } returns imageUrl coEvery { loader.scale(bitmap, imageViewDimension, bitmapPool) } returns bitmap viewManager.load(loadRequest, bitmap) coVerify { loader.scale(bitmap, imageViewDimension, bitmapPool) } verify { handler.post(any()) } } @Test actual fun testViewReused() { val imageUrl = "URL" val loadRequest: LoadRequest = mockk() val imageViewRef = WeakReference(imageView) every { viewMap[imageView] } returns imageUrl every { loadRequest.imageView } returns imageViewRef every { loadRequest.imageUrl } returns imageUrl viewManager.isViewReused(loadRequest) verify { viewMap[imageView] } verify { loadRequest.imageView } } @After fun finish() { unmockkAll() } }
0
Kotlin
0
0
0403c4c9cfdfc07a0de9e8e079c5cff00a15e421
3,101
Underwave
Apache License 2.0
kotlin-typescript/src/jsMain/generated/typescript/ForInitializer.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Automatically generated - do not modify! package typescript sealed external interface ForInitializer : Node
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
113
kotlin-wrappers
Apache License 2.0
src/main/kotlin/shell/view/CodeBlockStatisticsView.kt
darthmachina
637,608,931
false
{"Kotlin": 174636, "CSS": 1921, "JavaScript": 301}
package shell.view import MarkdownPostProcessorContext import core.functions.TaskStatisticFunctions.Companion.totalCompleted import core.functions.TaskStatisticViewFunctions.Companion.total import core.functions.TaskStatisticViewFunctions.Companion.totalWeekFive import core.functions.TaskStatisticViewFunctions.Companion.totalWeekFour import core.functions.TaskStatisticViewFunctions.Companion.totalWeekOne import core.functions.TaskStatisticViewFunctions.Companion.totalWeekThree import core.functions.TaskStatisticViewFunctions.Companion.totalWeekTwo import core.store.CompletionStatistics import core.store.HabitStatistics import core.store.UnderlingStore import io.kvision.state.sub import kotlinx.datetime.DayOfWeek import kotlinx.dom.clear import kotlinx.html.div import kotlinx.html.dom.append import kotlinx.html.h3 import mu.KotlinLogging import net.mamoe.yamlkt.Yaml import org.w3c.dom.HTMLElement import shell.view.codeblock.CodeBlockStatisticConfig private val logger = KotlinLogging.logger { } data class StatisticsHolder( val completed: Map<String, CompletionStatistics>, val habits: Map<String, HabitStatistics> ) interface CodeBlockStatisticsView { companion object { fun processCodeBlock(store: UnderlingStore): (source: String, element: HTMLElement, context: MarkdownPostProcessorContext) -> Unit { return { source, element, _ -> val config = Yaml.decodeFromString(CodeBlockStatisticConfig.serializer(), source) element.classList.add("ul-codeblock") store .sub { StatisticsHolder(it.fileStatistics, it.habitStatistics) } .subscribe { stats -> showStatistics(stats.completed, stats.habits, element, config) } } } fun showStatistics( fileStats: Map<String, CompletionStatistics>, habitStats: Map<String, HabitStatistics>, element: HTMLElement, config: CodeBlockStatisticConfig ) { logger.debug { "showStatistics() : $fileStats" } element.clear() if (config.heading.isNotEmpty()) { element.append.div(classes = "ul-codeblock-heading") { +config.heading } } if (config.showWeekly) { element.append.div(classes = "ul-codeblock-stats-weekly") { h3(classes = "ul-codeblock-stats-weekly-header") { +"Weekly Stats" } div(classes = "ul-codeblock-stats-weekly-list") { div(classes = "ul-codeblock-stats-weekly-list-item") { +"Week 1: ${fileStats.totalWeekOne()}" } div(classes = "ul-codeblock-stats-weekly-list-item") { +"Week 2: ${fileStats.totalWeekTwo()}" } div(classes = "ul-codeblock-stats-weekly-list-item") { +"Week 3: ${fileStats.totalWeekThree()}" } div(classes = "ul-codeblock-stats-weekly-list-item") { +"Week 4: ${fileStats.totalWeekFour()}" } div(classes = "ul-codeblock-stats-weekly-list-item") { +"Week 5: ${fileStats.totalWeekFive()}" } } } } if (config.showDayOfWeek) { element.append.div(classes = "ul-codeblock-stats-weekday") { h3(classes = "ul-codeblock-stats-weekday-header") { +"Weekday Stats" } div(classes = "ul-codeblock-stats-weekday-list") { div(classes = "ul-codeblock-stats-weekday-list-item") { +"Monday: ${fileStats.total(DayOfWeek.MONDAY)}"} div(classes = "ul-codeblock-stats-weekday-list-item") { +"Tuesday: ${fileStats.total(DayOfWeek.TUESDAY)}"} div(classes = "ul-codeblock-stats-weekday-list-item") { +"Wednesday: ${fileStats.total(DayOfWeek.WEDNESDAY)}"} div(classes = "ul-codeblock-stats-weekday-list-item") { +"Thursday: ${fileStats.total(DayOfWeek.THURSDAY)}"} div(classes = "ul-codeblock-stats-weekday-list-item") { +"Friday: ${fileStats.total(DayOfWeek.FRIDAY)}"} div(classes = "ul-codeblock-stats-weekday-list-item") { +"Saturday: ${fileStats.total(DayOfWeek.SATURDAY)}"} div(classes = "ul-codeblock-stats-weekday-list-item") { +"Sunday: ${fileStats.total(DayOfWeek.SUNDAY)}"} } } } if (config.showHabits) { showHabitStatistics(habitStats, element, config) } if (config.showTotal) { element.append.div(classes = "ul-codeblock-stats") { +"Total Completed: ${fileStats.totalCompleted()}" } } } fun showHabitStatistics(habitStats: Map<String, HabitStatistics>, element: HTMLElement, config: CodeBlockStatisticConfig) { element.append.div(classes = "ul-codeblock-stats-habits") { h3(classes = "ul-codeblock-stats-habits-header") { +"Habits" } habitStats.forEach { entry -> div(classes = "ul-codeblock-stats-habits-habit") { +"${entry.key} : ${entry.value.streak}" } } } } }}
0
Kotlin
0
1
e0f77b158313707cd5bde0519d9ecba2f2b69c21
5,094
underling-obsidian
MIT License
src/main/java/cn/edu/kmust/flst/web/vo/backstage/website/WebsiteVo.kt
zbeboy
128,647,683
false
{"Maven POM": 1, "Text": 2, "Ignore List": 1, "XML": 115, "Markdown": 1, "Kotlin": 90, "Java": 154, "INI": 3, "YAML": 3, "HTML": 31, "SVG": 1, "CSS": 45, "JavaScript": 300, "SQL": 1}
package cn.edu.kmust.flst.web.vo.backstage.website /** * Created by zbeboy 2018-04-16 . **/ open class WebsiteVo { var address: String? = null var addressEn: String? = null var zipCode: String? = null var phone: String? = null var fax: String? = null }
2
JavaScript
0
0
895b865c6fec882a46f3b47f94e69bbda89724b3
275
FLST
MIT License
krossbow-stomp-core/src/commonTest/kotlin/org/hildan/krossbow/stomp/instrumentation/KrossbowInstrumentationTest.kt
joffrey-bion
190,066,229
false
null
package org.hildan.krossbow.stomp.instrumentation import kotlinx.coroutines.launch import kotlinx.coroutines.test.runBlockingTest import org.hildan.krossbow.stomp.StompErrorFrameReceived import org.hildan.krossbow.stomp.frame.StompCommand import org.hildan.krossbow.stomp.sendText import org.hildan.krossbow.test.KrossbowInstrumentationMock import org.hildan.krossbow.test.connectWithMocks import org.hildan.krossbow.test.simulateErrorFrameReceived import org.hildan.krossbow.test.waitForDisconnectAndSimulateCompletion import org.hildan.krossbow.test.waitForSendAndSimulateCompletion import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class KrossbowInstrumentationTest { @Test fun testInstrumentation_sendAndNormalClosure() = runBlockingTest { val inst = KrossbowInstrumentationMock() launch { val (wsSession, stompSession) = connectWithMocks { instrumentation = inst } launch { wsSession.waitForSendAndSimulateCompletion(StompCommand.SEND) wsSession.waitForDisconnectAndSimulateCompletion() wsSession.expectClose() } stompSession.sendText("/dest", "Some Body") stompSession.disconnect() } val connectFrame = inst.expectOnStompFrameSent() assertEquals(StompCommand.CONNECT, connectFrame.command) inst.expectOnWebsocketFrameReceived() val connectedFrame = inst.expectOnFrameDecoded() assertEquals(StompCommand.CONNECTED, connectedFrame.command) val sendFrame = inst.expectOnStompFrameSent() assertEquals(StompCommand.SEND, sendFrame.command) assertEquals("Some Body", sendFrame.bodyAsText) val disconnectFrame = inst.expectOnStompFrameSent() assertEquals(StompCommand.DISCONNECT, disconnectFrame.command) val closeCause = inst.expectOnWebSocketClosed() assertNull(closeCause, "The web socket should be closed normally") } @Test fun testInstrumentation_webSocketError() = runBlockingTest { val inst = KrossbowInstrumentationMock() launch { val (wsSession, _) = connectWithMocks { instrumentation = inst } wsSession.simulateError("Simulated error") wsSession.expectNoClose() // we don't attempt to close the failed websocket } val connectFrame = inst.expectOnStompFrameSent() assertEquals(StompCommand.CONNECT, connectFrame.command) inst.expectOnWebsocketFrameReceived() val connectedFrame = inst.expectOnFrameDecoded() assertEquals(StompCommand.CONNECTED, connectedFrame.command) val exception = inst.expectOnWebSocketClientError() assertEquals("Simulated error", exception.message) } @Test fun testInstrumentation_stompErrorFrame() = runBlockingTest { val inst = KrossbowInstrumentationMock() launch { val (wsSession, _) = connectWithMocks { instrumentation = inst } wsSession.simulateErrorFrameReceived("Simulated error") wsSession.expectClose() // we should close the websocket on STOMP error } val connectFrame = inst.expectOnStompFrameSent() assertEquals(StompCommand.CONNECT, connectFrame.command) inst.expectOnWebsocketFrameReceived() val connectedFrame = inst.expectOnFrameDecoded() assertEquals(StompCommand.CONNECTED, connectedFrame.command) inst.expectOnWebsocketFrameReceived() val errorFrame = inst.expectOnFrameDecoded() assertEquals(StompCommand.ERROR, errorFrame.command) val closeCause = inst.expectOnWebSocketClosed() assertNotNull(closeCause, "The web socket should be closed with STOMP ERROR as cause") assertEquals("Simulated error", closeCause.message) assertEquals(StompErrorFrameReceived::class, closeCause::class) } }
12
null
7
82
e72a8d8254399e439c454b2d0a689011c297b22e
4,050
krossbow
MIT License
src/main/kotlin/io/github/ydwk/ydwk/evm/handler/handlers/role/GuildRoleUpdateHandler.kt
YDWK
527,250,343
false
null
/* * Copyright 2022 YDWK inc. * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ydwk.ydwk.evm.handler.handlers.role import com.fasterxml.jackson.databind.JsonNode import io.github.ydwk.yde.cache.CacheIds import io.github.ydwk.yde.impl.entities.guild.RoleImpl import io.github.ydwk.ydwk.evm.handler.Handler import io.github.ydwk.ydwk.impl.YDWKImpl class GuildRoleUpdateHandler(ydwk: YDWKImpl, json: JsonNode) : Handler(ydwk, json) { override suspend fun start() { val role = ydwk .getGuildById(json.get("guild_id").asLong()) ?.getRoleById(json.get("role").get("id").asLong()) if (role == null) { ydwk.logger.info("Role not found in cache, creating new role") val roleImpl = RoleImpl(ydwk, json.get("role"), json.get("role").get("id").asLong()) ydwk.cache[roleImpl.id, roleImpl] = CacheIds.ROLE } } }
5
null
1
2
7dd752abeb27614da13f97a962a19a7b4360ea15
1,451
YDWK
Apache License 2.0
src/main/kotlin/fr/zakaoai/coldlibrarybackend/ColdLibraryBackendApplication.kt
zakaoai
344,490,461
false
{"Kotlin": 57777, "Dockerfile": 318}
package fr.zakaoai.coldlibrarybackend import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration import org.springframework.boot.runApplication import org.springframework.cache.annotation.EnableCaching @SpringBootApplication(exclude = [ReactiveSecurityAutoConfiguration::class] ) @EnableCaching class ColdLibraryBackendApplication fun main(args: Array<String>) { runApplication<ColdLibraryBackendApplication>(*args) }
11
Kotlin
0
0
9d6baea25631486bcc00382433b385cea2500cb2
529
cold-library-backend
MIT License
oidc-spec-oauth/src/commonMain/kotlin/OAuth.kt
LSafer
723,829,331
false
{"Kotlin": 203655}
/* * Copyright 2023 cufy.org and meemer.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 net.lsafer.oidc.oauth /** * OAuth Constants. */ object OAuth { /** * Our chosen base path for oauth. (not part of oauth specification) */ const val PATH = "/oauth2" /** * OAuth Endpoint Registry */ object Endpoint { // https://datatracker.ietf.org/doc/html/rfc6749#section-3.1 /** * Our chosen path for oauth authorization endpoint. */ const val AUTHORIZATION = "$PATH/authorize" // https://datatracker.ietf.org/doc/html/rfc6749#section-3.2 /** * Our chosen path for oauth token endpoint. */ const val TOKEN = "$PATH/token" } /** * OAuth Parameters Registry. */ object Param { // Custom; added for convenience const val TENANT_ID = "tenant_id" // https://datatracker.ietf.org/doc/html/rfc6749#section-11.2.2 const val CLIENT_ID = "client_id" const val CLIENT_SECRET = "client_secret" const val RESPONSE_TYPE = "response_type" const val REDIRECT_URI = "redirect_uri" const val SCOPE = "scope" const val STATE = "state" const val CODE = "code" const val ERROR_DESCRIPTION = "error_description" const val ERROR_URI = "error_uri" const val GRANT_TYPE = "grant_type" const val ACCESS_TOKEN = "access_token" const val TOKEN_TYPE = "token_type" const val EXPIRES_IN = "expires_in" const val USERNAME = "username" const val PASSWORD = "password" const val REFRESH_TOKEN = "refresh_token" // https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1 const val ERROR = "error" // https://datatracker.ietf.org/doc/html/rfc6750#section-3 const val REALM = "realm" // https://datatracker.ietf.org/doc/html/rfc7636 /** * REQUIRED. Code challenge. */ const val CODE_CHALLENGE = "code_challenge" /** * OPTIONAL, defaults to "plain" if not present in the request. * Code verifier transformation method is "S256" or "plain". */ const val CODE_CHALLENGE_METHOD = "code_challenge_method" /** * REQUIRED. Code verifier */ const val CODE_VERIFIER = "code_verifier" // https://datatracker.ietf.org/doc/html/rfc8693#section-2.1 /** * OPTIONAL. A URI that indicates the target service or resource where * the client intends to use the requested security token. */ const val RESOURCE = "resource" /** * OPTIONAL. The logical name of the target service where the client intends to * use the requested security token. */ const val AUDIENCE = "audience" /** * OPTIONAL. An identifier for the type of the requested security token. * If the requested type is unspecified, the issued token type is at the * discretion of the authorization server and may be dictated by knowledge * of the requirements of the service or resource indicated by the resource * or audience parameter. */ const val REQUESTED_TOKEN_TYPE = "requested_token_type" /** * REQUIRED. A security token that represents the identity of the party on * behalf of whom the request is being made. Typically, the subject of this * token will be the subject of the security token issued in response to the * request. */ const val SUBJECT_TOKEN = "subject_token" /** * REQUIRED. An identifier, as described in Section 3, that indicates the * type of the security token in the subject_token parameter. */ const val SUBJECT_TOKEN_TYPE = "subject_token_type" /** * OPTIONAL. A security token that represents the identity of the acting party. * Typically, this will be the party that is authorized to use the requested * security token and act on behalf of the subject. */ const val ACTOR_TOKEN = "actor_token" /** * An identifier, as described in Section 3, that indicates the type of the * security token in the actor_token parameter. This is REQUIRED when the actor_token * parameter is present in the request but MUST NOT be included otherwise. */ const val ACTOR_TOKEN_TYPE = "actor_token_type" // https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.1 /** * REQUIRED. An identifier for the representation of the issued security token. */ const val ISSUED_TOKEN_TYPE = "issued_token_type" } /** * OAuth Error Registry. */ object Error { // https://datatracker.ietf.org/doc/html/rfc6749 const val INVALID_REQUEST = "invalid_request" const val UNAUTHORIZED_CLIENT = "unauthorized_client" /** * The resource owner or authorization server denied the request. */ const val ACCESS_DENIED = "access_denied" /** * The authorization server does not support obtaining an * authorization code or access token using this method. */ const val UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type" /** * The requested scope is invalid, unknown, malformed, or * exceeds the scope granted by the resource owner. */ const val INVALID_SCOPE = "invalid_scope" /** * The authorization server encountered an unexpected * condition that prevented it from fulfilling the request. * (This error code is needed because a 500 Internal Server * Error HTTP status code cannot be returned to the client * via an HTTP redirect.) */ const val SERVER_ERROR = "server_error" /** * The authorization server is currently unable to handle * the request due to a temporary overloading or maintenance * of the server. (This error code is needed because a 503 * Service Unavailable HTTP status code cannot be returned * to the client via an HTTP redirect.) */ const val TEMPORARILY_UNAVAILABLE = "temporarily_unavailable" /** * Client authentication failed (e.g., unknown client, no * client authentication included, or unsupported * authentication method). The authorization server MAY * return an HTTP 401 (Unauthorized) status code to indicate * which HTTP authentication schemes are supported. If the * client attempted to authenticate via the "Authorization" * request header field, the authorization server MUST * respond with an HTTP 401 (Unauthorized) status code and * include the "WWW-Authenticate" response header field * matching the authentication scheme used by the client. */ const val INVALID_CLIENT = "invalid_client" /** * The provided authorization grant (e.g., authorization * code, resource owner credentials) or refresh token is * invalid, expired, revoked, does not match the redirection * URI used in the authorization request, or was issued to * another client. */ const val INVALID_GRANT = "invalid_grant" /** * The authorization grant type is not supported by the * authorization server. */ const val UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type" // https://datatracker.ietf.org/doc/html/rfc6750#section-3.1 /** * The access token provided is expired, revoked, malformed, or * invalid for other reasons. The resource SHOULD respond with * the HTTP 401 (Unauthorized) status code. The client MAY * request a new access token and retry the protected resource * request. */ const val INVALID_TOKEN = "invalid_token" /** * The request requires higher privileges than provided by the * access token. The resource server SHOULD respond with the HTTP * 403 (Forbidden) status code and MAY include the "scope" * attribute with the scope necessary to access the protected * resource. */ const val INSUFFICIENT_SCOPE = "insufficient_scope" // https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.2 /** * If the authorization server is unwilling or unable to issue a * token for any target service indicated by the resource or audience * parameters, the invalid_target error code SHOULD be used in the * error response. */ const val INVALID_TARGET = "invalid_target" } /** * OAuth values registry for parameter `response_type` */ object ResponseType { // https://datatracker.ietf.org/doc/html/rfc6749#section-11.3.2 const val CODE = "code" const val TOKEN = "token" } /** * OAuth values registry for parameter `grant_type` */ object GrantType { // https://datatracker.ietf.org/doc/html/rfc6749 const val AUTHORIZATION_CODE = "authorization_code" const val IMPLICIT = "implicit" const val CLIENT_CREDENTIALS = "client_credentials" const val REFRESH_TOKEN = "refresh_token" const val PASSWORD = "password" // https://datatracker.ietf.org/doc/html/rfc8693#section-2.1 const val TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange" } /** * OAuth values registry for parameter `token_type` */ object AccessTokenType { // https://datatracker.ietf.org/doc/html/rfc6749#section-11.1 const val BEARER = "bearer" const val MAC = "mac" } /** * OAuth values registry for parameter `code_challenge_method` */ object CodeChallengeMethod { // https://datatracker.ietf.org/doc/html/rfc7636 /** * code_challenge = code_verifier */ const val PLAIN = "plain" /** * code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) */ const val S256 = "S256" } /** * In token exchange, this a collection of token type identifiers. */ object TokenType { // https://datatracker.ietf.org/doc/html/rfc8693#section-3 /** * Indicates that the token is an OAuth 2.0 access token issued by the given authorization server. */ const val ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token" /** * Indicates that the token is an OAuth 2.0 refresh token issued by the given authorization server. */ const val REFRESH_TOKEN = "urn:ietf:params:oauth:token-type:refresh_token" /** * Indicates that the token is an ID Token as defined in Section 2 of [`OpenID.Core`]. */ const val ID_TOKEN = "urn:ietf:params:oauth:token-type:id_token" /** * Indicates that the token is a base64url-encoded SAML 1.1 [OASIS.saml-core-1.1] assertion. */ const val SAML_1 = "urn:ietf:params:oauth:token-type:saml1" /** * Indicates that the token is a base64url-encoded SAML 2.0 [OASIS.saml-core-2.0-os] assertion. */ const val SAML_2 = "urn:ietf:params:oauth:token-type:saml2" } }
0
Kotlin
0
1
9f8b20446ca6e172af376d8c73066d4f60b7953c
12,144
oidc-spec
Apache License 2.0
abp-demo/abp-demo-sso-server/src/main/kotlin/com/abomb4/abp/UserServiceMain.kt
abomb4
141,275,739
false
{"Maven POM": 8, "Text": 1, "Ignore List": 1, "Markdown": 1, "YAML": 5, "XML": 3, "SQL": 4, "Kotlin": 21, "Java": 3, "HTML": 2}
/* * Copyright 2019 abomb4 * * 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.abomb4.abp.authentication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.ComponentScan import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity /** * * @author yangrl14628 2019-05-14 */ @SpringBootApplication @EnableWebSecurity @ComponentScan("com.abomb4.abp") open class UserServiceMain fun main(args: Array<String>) { runApplication<UserServiceMain>(*args) }
1
Kotlin
0
0
fe0db00b7aab633570212e8a7f83adf69ae1f17b
1,121
ab-platform
Apache License 2.0
app/src/main/java/com/yazag/navigationhomework/ui/home/HomeFragment.kt
oren345
692,884,084
false
{"Kotlin": 10203}
package com.yazag.navigationhomework.ui.home import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.fragment.findNavController import androidx.viewbinding.ViewBinding import com.yazag.navigationhomework.R import com.yazag.navigationhomework.common.viewBinding import com.yazag.navigationhomework.databinding.FragmentHomeBinding class HomeFragment : Fragment(R.layout.fragment_home) { private val binding by viewBinding(FragmentHomeBinding::bind) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with (binding){ btnStart.setOnClickListener { val name = etName.text.toString() val surname = etSurname.text.toString() val empty = (name.isNotEmpty() && surname.isNotEmpty()) if (empty==false){ Toast.makeText(context, R.string.toast, Toast.LENGTH_SHORT).show() } if (empty==true) { val action = HomeFragmentDirections.homeToPersonal(name, surname) findNavController().navigate(action) } } } } }
0
Kotlin
0
0
c63a40b0cc3ced895c76482d800152a07cb2a977
1,353
NavigationHomework
MIT License
presentation/src/main/java/com/doctoror/splittor/presentation/groupsoverview/GroupsOverviewContent.kt
Doctoror
639,914,602
false
null
package com.doctoror.splittor.presentation.groupsoverview import androidx.compose.foundation.Image import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.doctoror.splittor.R import com.doctoror.splittor.platform.compose.AppTheme import com.google.accompanist.systemuicontroller.rememberSystemUiController @OptIn(ExperimentalMaterial3Api::class) @Composable fun GroupsOverviewContent( onAddClick: () -> Unit, onGroupClick: (Long) -> Unit, viewModel: GroupsOverviewViewModel ) { val surfaceColor = AppTheme.colorScheme.surface val systemUiController = rememberSystemUiController() val useDarkIcons = !isSystemInDarkTheme() LaunchedEffect(systemUiController, useDarkIcons) { systemUiController.setSystemBarsColor( color = surfaceColor, darkIcons = useDarkIcons ) } fun shouldShowFab() = viewModel.viewType.value != GroupsOverviewViewModel.ViewType.LOADING AppTheme { Scaffold( floatingActionButton = { if (shouldShowFab()) { FloatingActionButton(onClick = onAddClick) { Image( imageVector = Icons.Filled.Add, contentDescription = stringResource(id = R.string.add_new_group) ) } } }, topBar = { TopAppBar(title = { Text(stringResource(R.string.app_name)) }) } ) { Box( Modifier .fillMaxSize() .padding(it) ) { when (viewModel.viewType.value) { GroupsOverviewViewModel.ViewType.LOADING -> GroupsOverviewContentLoading() GroupsOverviewViewModel.ViewType.EMPTY -> GroupsOverviewContentEmpty(onAddClick) GroupsOverviewViewModel.ViewType.CONTENT -> GroupsOverviewContentLoaded( onGroupClick, viewModel ) } } } } } @Preview @Composable fun GroupsOverviewContentLoadingPreview() { GroupsOverviewContent( onAddClick = {}, onGroupClick = {}, viewModel = GroupsOverviewViewModel().apply { viewType.value = GroupsOverviewViewModel.ViewType.LOADING } ) } @Preview @Composable fun GroupsOverviewContentEmptyPreview() { GroupsOverviewContent( onAddClick = {}, onGroupClick = {}, viewModel = GroupsOverviewViewModel().apply { viewType.value = GroupsOverviewViewModel.ViewType.EMPTY } ) } @Preview @Composable fun GroupsOverviewContentLoadedPreview() { GroupsOverviewContent( onAddClick = {}, onGroupClick = {}, viewModel = GroupsOverviewViewModel().apply { viewType.value = GroupsOverviewViewModel.ViewType.CONTENT groups.add( GroupItemViewModel( amount = "$12.99", allMembersPaid = false, id = 1L, members = "2 members", title = "Lunch" ) ) groups.add( GroupItemViewModel( amount = "$1,000.58", allMembersPaid = false, id = 1L, members = "4 members", title = "Dinner" ) ) groups.add( GroupItemViewModel( amount = "$1,322", allMembersPaid = true, id = 1L, members = "4 members", title = "Some old stuff" ) ) } ) }
0
Kotlin
0
2
f8ae7f4ca61f85b606b51a34c85790702cb2319d
4,524
Android-MVPVM-Architecture-Demo
Apache License 2.0
quartz/src/main/java/com/vitorpamplona/quartz/crypto/Hkdf.kt
vitorpamplona
587,850,619
false
{"Kotlin": 3777160, "Shell": 1488, "Java": 921}
/** * Copyright (c) 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.vitorpamplona.quartz.crypto import java.nio.ByteBuffer import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec class Hkdf(val algorithm: String = "HmacSHA256", val hashLen: Int = 32) { fun extract( key: ByteArray, salt: ByteArray, ): ByteArray { val mac = Mac.getInstance(algorithm) mac.init(SecretKeySpec(salt, algorithm)) return mac.doFinal(key) } fun expand( key: ByteArray, nonce: ByteArray, outputLength: Int, ): ByteArray { check(key.size == hashLen) check(nonce.size == hashLen) val n = if (outputLength % hashLen == 0) outputLength / hashLen else outputLength / hashLen + 1 var hashRound = ByteArray(0) val generatedBytes = ByteBuffer.allocate(Math.multiplyExact(n, hashLen)) val mac = Mac.getInstance(algorithm) mac.init(SecretKeySpec(key, algorithm)) for (roundNum in 1..n) { mac.reset() val t = ByteBuffer.allocate(hashRound.size + nonce.size + 1) t.put(hashRound) t.put(nonce) t.put(roundNum.toByte()) hashRound = mac.doFinal(t.array()) generatedBytes.put(hashRound) } val result = ByteArray(outputLength) generatedBytes.rewind() generatedBytes[result, 0, outputLength] return result } }
5
Kotlin
3
995
0bb39f91b9dddf81dcec63f3d97674f26872fbd0
2,508
amethyst
MIT License
demo-transactions/src/main/kotlin/io/holixon/cqrshexagonaldemo/demoparent/transactions/command/application/port/inbound/customer/CreateCustomerInPort.kt
holixon
747,608,283
false
{"Kotlin": 69299, "Shell": 72}
package io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.inbound.customer import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.common.Name import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.customer.Customer interface CreateCustomerInPort { fun createCustomer(customerName: Name): Customer }
3
Kotlin
0
0
e634c14ca89f3de72f53ae6680c8ca12c539d6a7
384
cqrs-meets-hexagonal
Apache License 2.0
app/src/main/java/com/ajce/hostelmate/nightstudy/inmates/InmatesRequestNightStudyActivity.kt
Jithin-Jude
256,905,231
false
null
package com.ajce.hostelmate.nightstudy.inmates import android.appwidget.AppWidgetManager import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.RemoteViews import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.ajce.hostelmate.R import com.ajce.hostelmate.nightstudy.NightStudy import com.ajce.hostelmate.reportissue.Issue import com.ajce.hostelmate.sickleave.SickLeave import com.google.android.gms.tasks.Task import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import kotlinx.android.synthetic.main.activity_request_sick_leave.* import java.text.SimpleDateFormat import java.util.* /** * Created by JithinJude on 02,May,2020 */ class InmatesRequestNightStudyActivity : AppCompatActivity() { val USER_EMAIL: String = "user_email" var databaseReference: DatabaseReference? = null var personEmail: String? = null var nightStudyReasonForRejection: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_request_night_study) title = getString(R.string.request_nightstudy) //actionbar val actionbar = supportActionBar //set back button actionbar?.setDisplayHomeAsUpEnabled(true) personEmail = intent.extras[USER_EMAIL].toString() databaseReference = FirebaseDatabase.getInstance().getReference("nightstudy") val adapterSpinnerBlock = ArrayAdapter.createFromResource(this, R.array.block_list, android.R.layout.simple_spinner_item) adapterSpinnerBlock.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spBlock.adapter = adapterSpinnerBlock val adapterSpinnerRoom = ArrayAdapter.createFromResource(this, R.array.room_list, android.R.layout.simple_spinner_item) adapterSpinnerRoom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spRoom.adapter = adapterSpinnerRoom btnConfirm.setOnClickListener { addNightStudy() } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } fun addNightStudy() { /* if (nightStudyReasonForRejection == null) { Toast.makeText(this, "Take photo of Issue", Toast.LENGTH_LONG).show() return }*/ val title = etTitle?.text.toString() val block = spBlock.selectedItem.toString() val room = spRoom.selectedItem.toString() val description = etDescription?.text.toString() val reportedBy = personEmail val id = databaseReference?.push()?.key val date = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Date()) val status = "pending" nightStudyReasonForRejection = "" if ("" == title || "" == description) { Toast.makeText(this, "Form fields cannot be empty", Toast.LENGTH_LONG).show() return } val issue = NightStudy(id, title, block, room, description, reportedBy, date, status, nightStudyReasonForRejection) databaseReference?.child(id!!)?.setValue(issue) Toast.makeText(this, "Night Study requested", Toast.LENGTH_LONG).show() finish() } }
0
Kotlin
1
1
da95b289d6767dceec57e07718f0ad283ad1dfc4
3,388
HostelMate_AJCE
MIT License
app/src/main/java/com/midnight/musictest/framwork/repository/mapper/LyricMapperDb.kt
alireza-87
458,341,195
false
{"Kotlin": 89723}
package com.midnight.musictest.framwork.repository.mapper import com.midnight.core.domain.LyricModelCore import com.midnight.musictest.framwork.repository.local.model.LyricModelDb import javax.inject.Inject class LyricMapperDb @Inject constructor(){ fun toCore(data:LyricModelDb?):LyricModelCore?{ data?.let { return LyricModelCore( trackId = it.trackId, lyric = it.lyric ) } return null } }
0
Kotlin
0
1
c3550105a46a1b1cc09db081bcb845c52a56ef5a
481
WhoSings
MIT License
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithSubstringBeforeAfterIntentions.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.substring import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtExpression class ReplaceSubstringWithSubstringAfterInspection : ReplaceSubstringInspection() { override fun inspectionText(element: KtDotQualifiedExpression): String = KotlinBundle.message("inspection.replace.substring.with.substring.after.display.name") override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.substringafter.call") override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { element.replaceWith( "$0.substringAfter($1)", (element.getArgumentExpression(0) as KtDotQualifiedExpression).getArgumentExpression(0) ) } override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean { val arguments = element.callExpression?.valueArguments ?: return false return arguments.size == 1 && isIndexOfCall(arguments[0].getArgumentExpression(), element.receiverExpression) } } class ReplaceSubstringWithSubstringBeforeInspection : ReplaceSubstringInspection() { override fun inspectionText(element: KtDotQualifiedExpression): String = KotlinBundle.message("inspection.replace.substring.with.substring.before.display.name") override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.substringbefore.call") override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) { element.replaceWith( "$0.substringBefore($1)", (element.getArgumentExpression(1) as KtDotQualifiedExpression).getArgumentExpression(0) ) } override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean { val arguments = element.callExpression?.valueArguments ?: return false return arguments.size == 2 && element.isFirstArgumentZero() && isIndexOfCall(arguments[1].getArgumentExpression(), element.receiverExpression) } } private fun KtDotQualifiedExpression.getArgumentExpression(index: Int): KtExpression { return callExpression!!.valueArguments[index].getArgumentExpression()!! }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,636
intellij-community
Apache License 2.0
relateddigital-android/src/main/java/com/relateddigital/relateddigital_android/inapp/spintowin/SpinToWinWebDialogFragment.kt
relateddigital
379,568,070
false
null
package com.relateddigital.relateddigital_google.inapp.slotmachine import android.annotation.SuppressLint import android.os.Build import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.ConsoleMessage import android.webkit.WebChromeClient import android.webkit.WebView import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import com.relateddigital.relateddigital_google.R import com.relateddigital.relateddigital_google.constants.Constants class SlotMachineWebDialogFragment : DialogFragment() { private var webView: WebView? = null private var mResponse: String? = null private var baseUrl: String? = "" private var htmlString: String? = "" private var mIsRotation = false private lateinit var mListener: SlotMachineCompleteInterface private lateinit var mCopyToClipboardInterface: SlotMachineCopyToClipboardInterface private lateinit var mShowCodeInterface: SlotMachineShowCodeInterface fun display(fragmentManagerLoc: FragmentManager?): SlotMachineWebDialogFragment { val ft = fragmentManagerLoc?.beginTransaction() ft?.add(this, TAG) ft?.commitAllowingStateLoss() return this } override fun onStart() { super.onStart() val dialog = dialog if (dialog != null) { val width = ViewGroup.LayoutParams.MATCH_PARENT val height = ViewGroup.LayoutParams.MATCH_PARENT dialog.window!!.setLayout(width, height) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.AppTheme_FullScreenDialog) if (arguments != null) { baseUrl = requireArguments().getString("baseUrl") htmlString = requireArguments().getString("htmlString") mResponse = requireArguments().getString("response") mJavaScriptInterface = SlotMachineJavaScriptInterface(this, mResponse!!) mJavaScriptInterface!!.setJackpotListeners(mListener, mCopyToClipboardInterface, mShowCodeInterface) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) mIsRotation = true } override fun onDestroy() { super.onDestroy() if (!mIsRotation) { if (activity != null) { requireActivity().finish() } } } @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) val view: View = inflater.inflate(R.layout.layout_web_view, container, false) webView = view.findViewById(R.id.webview) webView!!.webChromeClient = webViewClient webView!!.settings.javaScriptEnabled = true webView!!.settings.allowContentAccess = true webView!!.settings.allowFileAccess = true if (Build.VERSION.SDK_INT >= Constants.SDK_MIN_API_VERSION) { webView!!.settings.mediaPlaybackRequiresUserGesture = false } mJavaScriptInterface?.let { webView!!.addJavascriptInterface(it, "Android") } webView!!.loadDataWithBaseURL(baseUrl, htmlString!!, "text/html", "utf-8", "about:blank") webView!!.reload() return view } private val webViewClient: WebChromeClient get() = object : WebChromeClient() { override fun onConsoleMessage(cm: ConsoleMessage): Boolean { Log.d(TAG, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId()) return true } } val javaScriptInterface: SlotMachineJavaScriptInterface? get() = mJavaScriptInterface fun setJackpotListeners( listener: SlotMachineCompleteInterface, copyToClipboardInterface: SlotMachineCopyToClipboardInterface, showCodeInterface: SlotMachineShowCodeInterface ) { mListener = listener mCopyToClipboardInterface = copyToClipboardInterface mShowCodeInterface = showCodeInterface } companion object { const val TAG = "WebViewDialogFragment" // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "response" private const val ARG_PARAM2 = "baseUrl" private const val ARG_PARAM3 = "htmlString" private var mJavaScriptInterface: SlotMachineJavaScriptInterface? = null fun newInstance(baseUrl: String?, htmlString: String?, response: String?): SlotMachineWebDialogFragment { val fragment = SlotMachineWebDialogFragment() val args = Bundle() args.putString(ARG_PARAM1, response) args.putString(ARG_PARAM2, baseUrl) args.putString(ARG_PARAM3, htmlString) mJavaScriptInterface = SlotMachineJavaScriptInterface(fragment, response!!) fragment.arguments = args return fragment } } }
0
null
2
6
ba181b42af58532a51314b1f61a69f479fa11516
5,244
relateddigital-android
Amazon Digital Services License
libraries/tools/src/main/kotlin/com/ave/vastgui/tools/utils/permission/PermissionRegister.kt
SakurajimaMaii
353,212,367
false
{"Kotlin": 1119175, "Java": 31062}
/* * Copyright 2022 VastGui <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ave.vastgui.tools.utils.permission import android.app.Activity import android.app.Application import android.os.Bundle import android.text.TextUtils import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts import com.ave.vastgui.core.extension.defaultLogTag import com.ave.vastgui.tools.config.ToolsConfig import com.ave.vastgui.tools.utils.DateUtils // Author: <NAME> // Email: <EMAIL> // Date: 2023/4/6 /** * Obtain the corresponding [PermissionLauncher] from * [PermissionRegister.singlePermissionLauncherMap] for permission request. * * @since 0.2.0 */ fun ComponentActivity.singlePermissionLauncher(): PermissionLauncher<String, Boolean>? { val activityKey = intent.getStringExtra(PermissionRegister.KEY_UNIQUE_ACTIVITY) return if (TextUtils.isEmpty(activityKey)) null else PermissionRegister.singlePermissionLauncherMap[activityKey] } /** * Obtain the corresponding [PermissionLauncher] from * [PermissionRegister.multiPermissionLauncherMap] for permission request. * * @since 0.2.0 */ fun ComponentActivity.multiPermissionLauncher(): PermissionLauncher<Array<String>, Map<String, Boolean>>? { val activityKey = intent.getStringExtra(PermissionRegister.KEY_UNIQUE_ACTIVITY) return if (TextUtils.isEmpty(activityKey)) null else PermissionRegister.multiPermissionLauncherMap[activityKey] } /** * [PermissionRegister] is for developers to call the * [requestPermission]/[requestMultiplePermissions] API at any time. It * will save an [PermissionLauncher] object for each Activity when it * is created, so that permission requests can be made through this object. * At the same time, the object will be destroyed when the corresponding * Activity is destroyed. PermissionRegister will be initialized in * [ToolsConfig]. * * @see ToolsConfig * @since 0.2.0 */ class PermissionRegister : Application.ActivityLifecycleCallbacks { companion object { /** * A key pointing to a string consisting of the current Activity name and * timestamp, the key-value is stored in [Activity.getIntent]. * * @since 0.2.0 */ const val KEY_UNIQUE_ACTIVITY = "KEY_UNIQUE_ACTIVITY" /** * Saving the [ActivityResultContracts.RequestPermission] of the activities * or fragments. * * @since 0.2.0 */ val singlePermissionLauncherMap: MutableMap<String, PermissionLauncher<String, Boolean>> = mutableMapOf() /** * Saving the [ActivityResultContracts.RequestMultiplePermissions] of the * activities or fragments. * * @since 0.2.0 */ val multiPermissionLauncherMap: MutableMap<String, PermissionLauncher<Array<String>, Map<String, Boolean>>> = mutableMapOf() } override fun onActivityCreated(activity: Activity, bundle: Bundle?) { if (activity is ComponentActivity) { val activityKey = activity.defaultLogTag() + DateUtils.getCurrentTime(DateUtils.FORMAT_YYYY_MM_DD_HH_MM_SS) val singlePermissionLauncher = PermissionLauncher(activity, ActivityResultContracts.RequestPermission()) val multiPermissionLauncher = PermissionLauncher( activity, ActivityResultContracts.RequestMultiplePermissions() ) activity.intent.putExtra(KEY_UNIQUE_ACTIVITY, activityKey) singlePermissionLauncherMap[activityKey] = singlePermissionLauncher multiPermissionLauncherMap[activityKey] = multiPermissionLauncher } } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) { } override fun onActivityDestroyed(activity: Activity) { if (activity is ComponentActivity) { val activityKey = activity.intent.getStringExtra(KEY_UNIQUE_ACTIVITY) if (!TextUtils.isEmpty(activityKey)) { singlePermissionLauncherMap[activityKey]?.unregister() singlePermissionLauncherMap.remove(activityKey) multiPermissionLauncherMap[activityKey]?.unregister() multiPermissionLauncherMap.remove(activityKey) } } } }
8
Kotlin
6
64
81c5ca59680143d9523c01852d9587a8d926c1c3
5,145
Android-Vast-Extension
Apache License 2.0
feature/quiz/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/quiz/participation/ConnectionStatusUi.kt
ls1intum
537,104,541
false
{"Kotlin": 1958120, "Dockerfile": 1306, "Shell": 1187}
package de.tum.informatics.www1.artemis.native_app.feature.quiz.participation import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Wifi import androidx.compose.material.icons.filled.WifiOff import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.tum.informatics.www1.artemis.native_app.feature.quiz.R @Composable internal fun ConnectionStatusUi(modifier: Modifier, isConnected: Boolean) { Row( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = if (isConnected) Icons.Default.Wifi else Icons.Default.WifiOff, contentDescription = null ) Text( text = stringResource( id = if (isConnected) R.string.quiz_participation_connection_status_connected else R.string.quiz_participation_connection_status_not_connected ), style = MaterialTheme.typography.bodyMedium ) } }
21
Kotlin
0
6
ef1ce4b9f87f09f4271f87ca6912b093bcad11a5
1,432
artemis-android
MIT License
usecases/src/main/kotlin/usecase/usecases/common/File.kt
semicolondsm
418,085,977
false
null
package usecase.usecases.common import io.ktor.http.content.* import java.io.File fun writeFile(requestFile: PartData.FileItem, filePath: String) { val savedFile = File(filePath) val directoryPath = filePath.substring(0, filePath.lastIndexOf("/")) val directory = File(directoryPath) if (!directory.exists()) { directory.mkdir() } requestFile.streamProvider().use { its -> savedFile.outputStream().buffered().use { its.copyTo(it) } } requestFile.dispose() } fun deleteFile(filePath: String) { val file = File(filePath) file.delete() }
1
Kotlin
0
0
f75470363d95ff8ef5044a795b7aa0f7e70bd3a1
585
Leesauce-Server
MIT License
biometric/src/main/java/dev/skomlach/biometric/compat/engine/internal/face/facelock/FacelockOldModule.kt
sergeykomlach
317,847,167
false
null
/* * Copyright (c) 2023 <NAME> aka Salat-Cx65; Original project https://github.com/Salat-Cx65/AdvancedBiometricPromptCompat * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.skomlach.biometric.compat.engine.internal.face.facelock import android.app.admin.DevicePolicyManager import android.content.Context import android.content.pm.PackageManager import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import androidx.core.os.CancellationSignal import dev.skomlach.biometric.compat.AuthenticationFailureReason import dev.skomlach.biometric.compat.BiometricCryptoObject import dev.skomlach.biometric.compat.engine.BiometricInitListener import dev.skomlach.biometric.compat.engine.BiometricMethod import dev.skomlach.biometric.compat.engine.core.Core import dev.skomlach.biometric.compat.engine.core.interfaces.AuthenticationListener import dev.skomlach.biometric.compat.engine.core.interfaces.RestartPredicate import dev.skomlach.biometric.compat.engine.internal.AbstractBiometricModule import dev.skomlach.biometric.compat.utils.LockType.isBiometricWeakEnabled import dev.skomlach.biometric.compat.utils.logging.BiometricLoggerImpl.d import dev.skomlach.biometric.compat.utils.logging.BiometricLoggerImpl.e import dev.skomlach.common.misc.ExecutorHelper import java.lang.ref.WeakReference class FacelockOldModule(private var listener: BiometricInitListener?) : AbstractBiometricModule(BiometricMethod.FACELOCK) { private var faceLockHelper: FaceLockHelper? = null private var facelockProxyListener: ProxyListener? = null private var viewWeakReference = WeakReference<SurfaceView?>(null) override var isManagerAccessible = false init { val faceLockInterface: FaceLockInterface = object : FaceLockInterface { override fun onError(code: Int, msg: String) { d("$name:FaceIdInterface.onError $code $msg") if (facelockProxyListener != null) { facelockProxyListener?.onAuthenticationError(code, msg) } } override fun onAuthorized() { d("$name.FaceIdInterface.onAuthorized") if (facelockProxyListener != null) { facelockProxyListener?.onAuthenticationSucceeded(null) } } override fun onConnected() { d("$name.FaceIdInterface.onConnected") if (facelockProxyListener != null) { facelockProxyListener?.onAuthenticationAcquired(0) } if (listener != null) { isManagerAccessible = true listener?.initFinished(biometricMethod, this@FacelockOldModule) listener = null faceLockHelper?.stopFaceLock() } else { try { d(name + ".authorize: " + viewWeakReference.get()) viewWeakReference.get()?.let { view -> if (view.visibility == View.VISIBLE || view.holder.isCreating) { authCallTimestamp.set(System.currentTimeMillis()) faceLockHelper?.startFaceLockWithUi(view) return } else { view.holder.addCallback(object : SurfaceHolder.Callback { override fun surfaceCreated(p0: SurfaceHolder) { authCallTimestamp.set(System.currentTimeMillis()) faceLockHelper?.startFaceLockWithUi(view) } override fun surfaceChanged( p0: SurfaceHolder, p1: Int, p2: Int, p3: Int ) { } override fun surfaceDestroyed(p0: SurfaceHolder) { } }) view.visibility = View.VISIBLE } } ?: kotlin.run { authCallTimestamp.set(System.currentTimeMillis()) faceLockHelper?.startFaceLockWithUi(null) } } catch (e: Throwable) { e("$name.FaceIdInterface.onConnected", e) } } } override fun onDisconnected() { d("$name.FaceIdInterface.onDisconnected") if (facelockProxyListener != null) { facelockProxyListener?.onAuthenticationError( FaceLockHelper.FACELOCK_CANCELED, FaceLockHelper.getMessage(FaceLockHelper.FACELOCK_CANCELED) ) } if (listener != null) { listener?.initFinished(biometricMethod, this@FacelockOldModule) listener = null faceLockHelper?.stopFaceLock() } } } faceLockHelper = FaceLockHelper(faceLockInterface) if (!isHardwarePresent) { if (listener != null) { listener?.initFinished(biometricMethod, this@FacelockOldModule) listener = null } } else { faceLockHelper?.initFacelock() } } override val isUserAuthCanByUsedWithCrypto: Boolean get() = false fun stopAuth() { faceLockHelper?.stopFaceLock() faceLockHelper?.destroy() } override fun getManagers(): Set<Any> { //No way to detect enrollments return emptySet() } // Retrieve all services that can match the given intent override val isHardwarePresent: Boolean get() { val pm = context.packageManager if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) { return false } val dpm = context.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager? if (dpm?.getCameraDisabled(null) == true) return false // Retrieve all services that can match the given intent return faceLockHelper?.faceUnlockAvailable() == true } override val hasEnrolled: Boolean get() { return isBiometricWeakEnabled("com.android.facelock", context) } @Throws(SecurityException::class) override fun authenticate( biometricCryptoObject: BiometricCryptoObject?, cancellationSignal: CancellationSignal?, listener: AuthenticationListener?, restartPredicate: RestartPredicate? ) { d("$name.authenticate - $biometricMethod; Crypto=$biometricCryptoObject") try { d("$name: Facelock call authorize") cancellationSignal?.setOnCancelListener { stopAuth() } authorize( ProxyListener( biometricCryptoObject, restartPredicate, cancellationSignal, listener ) ) return } catch (e: Throwable) { e(e, "$name: authenticate failed unexpectedly") } listener?.onFailure( AuthenticationFailureReason.UNKNOWN, tag() ) } fun setCallerView(targetView: SurfaceView?) { d("$name.setCallerView: $targetView") viewWeakReference = WeakReference(targetView) } private fun authorize(proxyListener: ProxyListener) { facelockProxyListener = proxyListener faceLockHelper?.stopFaceLock() faceLockHelper?.initFacelock() } inner class ProxyListener( private val biometricCryptoObject: BiometricCryptoObject?, private val restartPredicate: RestartPredicate?, private val cancellationSignal: CancellationSignal?, private val listener: AuthenticationListener? ) { private var errorTs = 0L private val skipTimeout = context.resources.getInteger(android.R.integer.config_shortAnimTime) private var selfCanceled = false fun onAuthenticationError(errMsgId: Int, errString: CharSequence?): Void? { d("$name.onAuthenticationError: $errMsgId-$errString") val tmp = System.currentTimeMillis() if (tmp - errorTs <= skipTimeout) return null errorTs = tmp var failureReason = AuthenticationFailureReason.UNKNOWN when (errMsgId) { FaceLockHelper.FACELOCK_FAILED_ATTEMPT -> failureReason = AuthenticationFailureReason.AUTHENTICATION_FAILED FaceLockHelper.FACELOCK_TIMEOUT -> failureReason = AuthenticationFailureReason.TIMEOUT FaceLockHelper.FACELOCK_NO_FACE_FOUND -> failureReason = AuthenticationFailureReason.HARDWARE_UNAVAILABLE FaceLockHelper.FACELOCK_NOT_SETUP -> failureReason = AuthenticationFailureReason.NO_BIOMETRICS_REGISTERED FaceLockHelper.FACELOCK_CANNT_START, FaceLockHelper.FACELOCK_UNABLE_TO_BIND, FaceLockHelper.FACELOCK_API_NOT_FOUND -> failureReason = AuthenticationFailureReason.HARDWARE_UNAVAILABLE else -> { if (!selfCanceled) { listener?.onFailure(failureReason, tag()) postCancelTask { if (cancellationSignal?.isCanceled == false) { selfCanceled = true listener?.onCanceled(tag()) Core.cancelAuthentication(this@FacelockOldModule) } } } return null } } if (restartCauseTimeout(failureReason)) { selfCanceled = true stopAuth() ExecutorHelper.postDelayed({ authenticate( biometricCryptoObject, cancellationSignal, listener, restartPredicate ) }, skipTimeout.toLong()) } else if (failureReason == AuthenticationFailureReason.TIMEOUT || restartPredicate?.invoke( failureReason ) == true ) { listener?.onFailure(failureReason, tag()) selfCanceled = true stopAuth() ExecutorHelper.postDelayed({ authenticate( biometricCryptoObject, cancellationSignal, listener, restartPredicate ) }, 1000) } else { if (mutableListOf( AuthenticationFailureReason.SENSOR_FAILED, AuthenticationFailureReason.AUTHENTICATION_FAILED ).contains(failureReason) ) { lockout() failureReason = AuthenticationFailureReason.LOCKED_OUT } listener?.onFailure(failureReason, tag()) postCancelTask { if (cancellationSignal?.isCanceled == false) { selfCanceled = true listener?.onCanceled(tag()) Core.cancelAuthentication(this@FacelockOldModule) } } } return null } fun onAuthenticationHelp(helpMsgId: Int, helpString: CharSequence?): Void? { d("$name.onAuthenticationHelp: $helpMsgId-$helpString") return null } fun onAuthenticationSucceeded(result: Any?): Void? { d("$name.onAuthenticationSucceeded $result") val tmp = System.currentTimeMillis() if (tmp - errorTs <= skipTimeout || tmp - authCallTimestamp.get() <= skipTimeout) return null errorTs = tmp listener?.onSuccess( tag(), BiometricCryptoObject( biometricCryptoObject?.signature, biometricCryptoObject?.cipher, biometricCryptoObject?.mac ) ) return null } fun onAuthenticationAcquired(acquireInfo: Int): Void? { d("$name.onAuthenticationAcquired $acquireInfo") return null } fun onAuthenticationFailed(): Void? { d("$name.onAuthenticationFailed") listener?.onFailure(AuthenticationFailureReason.AUTHENTICATION_FAILED, tag()) return null } } }
6
null
19
94
9555725a28227e28079a6dbc5da7c91d8b9634bb
14,049
AdvancedBiometricPromptCompat
Apache License 2.0
idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2014 JetBrains s.r.o. * * 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.jetbrains.jet.plugin.stubs import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.jetbrains.jet.lang.psi.JetFile import org.jetbrains.jet.lang.psi.stubs.elements.JetFileStubBuilder import com.intellij.psi.stubs.StubElement import org.jetbrains.jet.lang.psi.stubs.elements.JetStubElementTypes import org.junit.Assert import org.jetbrains.jet.lang.psi.JetPackageDirective import org.jetbrains.jet.lang.psi.stubs.PsiJetPlaceHolderStub import org.jetbrains.jet.lang.psi.JetImportList import org.jetbrains.jet.lang.psi.JetNamedFunction import org.jetbrains.jet.lang.psi.stubs.PsiJetFunctionStub import org.jetbrains.jet.lang.psi.JetTypeReference import org.jetbrains.jet.lang.psi.stubs.PsiJetClassStub import org.jetbrains.jet.lang.psi.JetClass import org.jetbrains.jet.lang.psi.stubs.PsiJetObjectStub import org.jetbrains.jet.lang.psi.JetObjectDeclaration import org.jetbrains.jet.lang.psi.JetProperty import org.jetbrains.jet.lang.psi.stubs.PsiJetPropertyStub import kotlin.test.assertEquals import org.jetbrains.jet.lang.psi.JetClassBody import org.jetbrains.jet.lang.psi.JetClassInitializer import org.jetbrains.jet.lang.psi.JetClassObject import org.jetbrains.jet.lang.psi.debugText.getDebugText public class DebugTextByStubTest : LightCodeInsightFixtureTestCase() { private fun createFileAndStubTree(text: String): Pair<JetFile, StubElement<*>> { val file = myFixture.configureByText("test.kt", text) as JetFile val stub = JetFileStubBuilder().buildStubTree(file)!! return Pair(file, stub) } private fun createStubTree(text: String) = createFileAndStubTree(text).second fun packageDirective(text: String) { val (file, tree) = createFileAndStubTree(text) val packageDirective = tree.findChildStubByType(JetStubElementTypes.PACKAGE_DIRECTIVE) val psi = JetPackageDirective(packageDirective as PsiJetPlaceHolderStub) Assert.assertEquals(file.getPackageDirective()!!.getText(), psi.getDebugText()) } fun function(text: String) { val (file, tree) = createFileAndStubTree(text) val function = tree.findChildStubByType(JetStubElementTypes.FUNCTION) val psi = JetNamedFunction(function as PsiJetFunctionStub) Assert.assertEquals("STUB: " + file.findChildByClass(javaClass<JetNamedFunction>())!!.getText(), psi.getDebugText()) } fun typeReference(text: String) { val (file, tree) = createFileAndStubTree("fun foo(i: $text)") val function = tree.findChildStubByType(JetStubElementTypes.FUNCTION)!! val parameterList = function.findChildStubByType(JetStubElementTypes.VALUE_PARAMETER_LIST)!! val valueParameter = parameterList.findChildStubByType(JetStubElementTypes.VALUE_PARAMETER)!! val typeReferenceStub = valueParameter.findChildStubByType(JetStubElementTypes.TYPE_REFERENCE) val psiFromStub = JetTypeReference(typeReferenceStub as PsiJetPlaceHolderStub) val typeReferenceByPsi = file.findChildByClass(javaClass<JetNamedFunction>())!!.getValueParameters()[0].getTypeReference() Assert.assertEquals(typeReferenceByPsi!!.getText(), psiFromStub.getDebugText()) } fun clazz(text: String, expectedText: String? = null) { val (file, tree) = createFileAndStubTree(text) val clazz = tree.findChildStubByType(JetStubElementTypes.CLASS)!! val psiFromStub = JetClass(clazz as PsiJetClassStub) val classByPsi = file.findChildByClass(javaClass<JetClass>()) val toCheckAgainst = "STUB: " + (expectedText ?: classByPsi!!.getText()) Assert.assertEquals(toCheckAgainst, psiFromStub.getDebugText()) if (expectedText != null) { Assert.assertNotEquals("Expected text should not be specified", classByPsi.getDebugText(), psiFromStub.getDebugText()) } } fun obj(text: String, expectedText: String? = null) { val (file, tree) = createFileAndStubTree(text) val obj = tree.findChildStubByType(JetStubElementTypes.OBJECT_DECLARATION)!! val psiFromStub = JetObjectDeclaration(obj as PsiJetObjectStub) val objectByPsi = file.findChildByClass(javaClass<JetObjectDeclaration>()) val toCheckAgainst = "STUB: " + (expectedText ?: objectByPsi!!.getText()) Assert.assertEquals(toCheckAgainst, psiFromStub.getDebugText()) } fun property(text: String, expectedText: String? = null) { val (file, tree) = createFileAndStubTree(text) val property = tree.findChildStubByType(JetStubElementTypes.PROPERTY)!! val psiFromStub = JetProperty(property as PsiJetPropertyStub) val propertyByPsi = file.findChildByClass(javaClass<JetProperty>()) val toCheckAgainst = "STUB: " + (expectedText ?: propertyByPsi!!.getText()) Assert.assertEquals(toCheckAgainst, psiFromStub.getDebugText()) } fun importList(text: String) { val (file, tree) = createFileAndStubTree(text) val importList = tree.findChildStubByType(JetStubElementTypes.IMPORT_LIST) val psi = JetImportList(importList as PsiJetPlaceHolderStub) Assert.assertEquals(file.getImportList()!!.getText(), psi.getDebugText()) } fun testPackageDirective() { packageDirective("package a.b.c") packageDirective("") packageDirective("package b") } fun testImportList() { importList("import a\nimport b.c.d") importList("import a.*") importList("import a.c as Alias") } fun testFunction() { function("fun foo()") function("fun <T> foo()") function("fun foo<T>()") function("fun foo<T, G>()") function("fun foo(a: Int, b: String)") function("fun Int.foo()") function("fun foo(): String") function("fun <T> T.foo(b: T): List<T>") function("fun <T, G> f() where T : G") function("fun <T, G> f() where T : G, G : T") function("fun <T, G> f() where class object T : G") function("private final fun f()") } fun testTypeReference() { typeReference("T") typeReference("T<G>") typeReference("T<G, H>") typeReference("T<in G>") typeReference("T<out G>") typeReference("T<*>") typeReference("T<*, in G>") typeReference("T?") typeReference("T<G?>") typeReference("() -> T") typeReference("(G?, H) -> T?") typeReference("L.(G?, H) -> T?") typeReference("L?.(G?, H) -> T?") } fun testClass() { clazz("class A") clazz("open private class A") clazz("public class private A") clazz("class A()") clazz("class A() : B()", expectedText = "class A() : B") clazz("class A() : B<T>") clazz("class A() : B(), C()", expectedText = "class A() : B, C") clazz("class A() : B by g", expectedText = "class A() : B") clazz("class A() : B by g, C(), T", expectedText = "class A() : B, C, T") clazz("class A(i: Int, g: String)") clazz("class A(val i: Int, var g: String)") } fun testObject() { obj("object Foo") obj("public final object Foo") obj("object Foo : A()", expectedText = "object Foo : A") obj("object Foo : A by foo", expectedText = "object Foo : A") obj("object Foo : A, T, C by g, B()", expectedText = "object Foo : A, T, C, B") } fun testProperty() { property("val c: Int") property("var c: Int") property("var : Int") property("private final var c: Int") property("val g") property("val g = 3", expectedText = "val g") property("val g by z", expectedText = "val g") property("val g: Int by z", expectedText = "val g: Int") } fun testClassBody() { val tree = createStubTree("class A {\n {} fun f(): Int val c: Int}") val classBody = tree.findChildStubByType(JetStubElementTypes.CLASS)!!.findChildStubByType(JetStubElementTypes.CLASS_BODY) assertEquals("class body for STUB: class A", JetClassBody(classBody as PsiJetPlaceHolderStub).getDebugText()) } fun testClassInitializer() { val tree = createStubTree("class A {\n {} }") val initializer = tree.findChildStubByType(JetStubElementTypes.CLASS)!!.findChildStubByType(JetStubElementTypes.CLASS_BODY)!! .findChildStubByType(JetStubElementTypes.ANONYMOUS_INITIALIZER) assertEquals("initializer in STUB: class A", JetClassInitializer(initializer as PsiJetPlaceHolderStub).getDebugText()) } fun testClassObject() { val tree = createStubTree("class A { class object {} }") val classObject = tree.findChildStubByType(JetStubElementTypes.CLASS)!!.findChildStubByType(JetStubElementTypes.CLASS_BODY)!! .findChildStubByType(JetStubElementTypes.CLASS_OBJECT) assertEquals("class object in STUB: class A", JetClassObject(classObject as PsiJetPlaceHolderStub).getDebugText()) } fun testPropertyAccessors() { val tree = createStubTree("var c: Int\nget() = 3\nset(i: Int) {}") val propertyStub = tree.findChildStubByType(JetStubElementTypes.PROPERTY)!! val accessors = propertyStub.getChildrenByType(JetStubElementTypes.PROPERTY_ACCESSOR, JetStubElementTypes.PROPERTY_ACCESSOR.getArrayFactory())!! assertEquals("getter for STUB: var c: Int", accessors[0].getDebugText()) assertEquals("setter for STUB: var c: Int", accessors[1].getDebugText()) } fun testEnumEntry() { val tree = createStubTree("enum class Enum { E1 E2: Enum() E3: Enum(1, 2)}") val enumClass = tree.findChildStubByType(JetStubElementTypes.CLASS)!!.findChildStubByType(JetStubElementTypes.CLASS_BODY)!! val entries = enumClass.getChildrenByType(JetStubElementTypes.ENUM_ENTRY, JetStubElementTypes.ENUM_ENTRY.getArrayFactory())!! assertEquals("STUB: enum entry E1", entries[0].getDebugText()) assertEquals("STUB: enum entry E2 : Enum", entries[1].getDebugText()) assertEquals("STUB: enum entry E3 : Enum", entries[2].getDebugText()) } }
191
null
4372
83
4383335168338df9bbbe2a63cb213a68d0858104
10,728
kotlin
Apache License 2.0
app/src/main/kotlin/com/ivanovsky/passnotes/domain/usecases/FindNoteForAutofillUseCase.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.domain.usecases import com.ivanovsky.passnotes.data.entity.Note import com.ivanovsky.passnotes.data.entity.OperationResult import com.ivanovsky.passnotes.domain.DispatcherProvider import com.ivanovsky.passnotes.presentation.autofill.model.AutofillStructure import com.ivanovsky.passnotes.util.UrlUtils import kotlinx.coroutines.withContext class FindNoteForAutofillUseCase( private val getDbUseCase: GetDatabaseUseCase, private val dispatchers: DispatcherProvider ) { suspend fun findNoteForAutofill(structure: AutofillStructure): OperationResult<Note?> = withContext(dispatchers.IO) { if (structure.webDomain.isNullOrEmpty() && structure.applicationId.isNullOrEmpty()) { return@withContext OperationResult.success(null) } val getDbResult = getDbUseCase.getDatabase() if (getDbResult.isFailed) { return@withContext getDbResult.takeError() } val db = getDbResult.obj val domain = structure.webDomain?.let { UrlUtils.extractCleanWebDomain(it) } val applicationId = structure.applicationId // TODO(autofill): to improve search, autofill-properties should be also checked after // noteDao.find() if (applicationId != null) { val findResult = db.noteDao.find(applicationId) if (findResult.isFailed) { return@withContext findResult.takeError() } val notes = findResult.obj if (notes.isNotEmpty()) { return@withContext OperationResult.success(notes.firstOrNull()) } } if (domain != null && domain.isNotEmpty()) { val findResult = db.noteDao.find(domain) if (findResult.isFailed) { return@withContext findResult.takeError() } val notes = findResult.obj if (notes.isNotEmpty()) { return@withContext OperationResult.success(notes.firstOrNull()) } } OperationResult.success(null) } }
4
Kotlin
1
7
dc4abdf847393919f5480129b64240ae0469b74c
2,227
kpassnotes
Apache License 2.0
app/src/main/java/com/example/glossaryapp/fragments/ProductListFragment.kt
adamcreeves
296,684,271
false
{"Kotlin": 88550}
package com.example.glossaryapp.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.android.volley.Request import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.example.glossaryapp.R import com.example.glossaryapp.adapters.AdapterProducts import com.example.glossaryapp.app.Endpoints import com.example.glossaryapp.models.Product import com.example.glossaryapp.models.ProductResults import com.example.glossaryapp.models.SubCategory import com.google.gson.Gson import kotlinx.android.synthetic.main.fragment_product_list.view.* class ProductListFragment : Fragment() { var myList: ArrayList<Product> = ArrayList() lateinit var adapterProducts: AdapterProducts private var subId: Int = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { subId = it.getInt(SubCategory.KEY_TO_SUB_ID) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_product_list, container, false) init(view) return view } private fun init(view: View) { getData() adapterProducts = AdapterProducts(view.context) view.recycler_view.adapter = adapterProducts view.recycler_view.layoutManager = LinearLayoutManager(activity) } private fun getData(){ var request = StringRequest(Request.Method.GET, Endpoints.getProductBySubId(subId),{ var gson = Gson() var productResult = gson.fromJson(it, ProductResults::class.java) myList.addAll(productResult.data) adapterProducts.setData(myList) }, { }) Volley.newRequestQueue(activity).add(request) } companion object { @JvmStatic fun newInstance(subId: Int) = ProductListFragment().apply { arguments = Bundle().apply { putInt(SubCategory.KEY_TO_SUB_ID, subId) } } } }
0
Kotlin
0
0
bdac2e3fbebf36c02d1a120d5aad27c88ce6c6c3
2,375
GroceryApp
MIT License
mobilepayments/src/main/java/com/begateway/mobilepayments/models/network/request/Checkout.kt
begateway
205,831,098
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 67, "Kotlin": 72}
package com.begateway.mobilepayments.models.network.request import com.begateway.mobilepayments.models.network.AdditionalFields import com.google.gson.annotations.SerializedName class Checkout( @SerializedName("version") val version: Double = 2.1, @SerializedName("test") val test: Boolean = false, @SerializedName("transaction_type") val transactionType: TransactionType, @SerializedName("attempts") val attempts: Int? = null, @SerializedName("dynamic_billing_descriptor") val dynamicBillingDescriptor: String? = null, @SerializedName("order") val order: Order, @SerializedName("settings") val settings: Settings, @SerializedName("customer") val customer: Customer? = null, @SerializedName("payment_method") val paymentMethod: PaymentMethod? = null, @SerializedName("travel") val travel: Travel? = null, ) : AdditionalFields() class Order( @SerializedName("amount") val amount: Long, @SerializedName("currency") val currency: String, @SerializedName("description") val description: String, @SerializedName("tracking_id") val trackingId: String? = null, @SerializedName("expired_at") val expiredAt: String? = null, @SerializedName("additional_data") val additionalData: AdditionalData? = null, ) : AdditionalFields() class AdditionalData( @SerializedName("receipt_text") val receiptText: Array<String>? = null, @SerializedName("contract") val contract: Array<Contract>? = null, @SerializedName("avs_cvc_verification") val avsCvcVerification: Array<String>? = null, @SerializedName("card_on_file") val card_on_file: CardOnFile? = null, ) : AdditionalFields() class CardOnFile( @SerializedName("initiator") val initiator: Initiator = Initiator.MERCHANT, @SerializedName("type") val cardOnFileType: CardOnFileType = CardOnFileType.DELAYED_CHARGE, ) : AdditionalFields() class Settings( /** If returnUrl defined, then successUrl and declineUrl could be ignored. Use only with header "X-Api-Version: 2" */ @SerializedName("return_url") val returnUrl: String? = null, @SerializedName("success_url") val successUrl: String? = null, @SerializedName("decline_url") val declineUrl: String? = null, @SerializedName("fail_url") val failUrl: String? = null, @SerializedName("cancel_url") val cancelUrl: String? = null, @SerializedName("notification_url") val notificationUrl: String? = null, @SerializedName("verification_url") val verificationUrl: String? = null, @SerializedName("auto_return") val autoReturn: Int? = null, @SerializedName("button_text") val buttonText: String? = null, @SerializedName("button_next_text") val buttonNextText: String? = null, @SerializedName("language") val language: Language? = null, @SerializedName("customer_fields") val customerFields: CustomerFields? = null, @SerializedName("save_card_toggle") val saveCardPolicy: SaveCardPolicy?, ) : AdditionalFields() class SaveCardPolicy( @SerializedName("customer_contract") val customerContract: Boolean?, ) class CustomerFields( @SerializedName("read_only") val readOnly: Array<ReadOnly>? = null, @SerializedName("visible") val visible: Array<Visible>? = null, ) : AdditionalFields() class Customer( @SerializedName("ip") val ip: String? = null, @SerializedName("email") val email: String? = null, @SerializedName("first_name") val firstName: String? = null, @SerializedName("last_name") val lastName: String? = null, @SerializedName("address") val address: String? = null, @SerializedName("city") val city: String? = null, @SerializedName("state") val state: String? = null, @SerializedName("zip") val zip: String? = null, @SerializedName("phone") val phone: String? = null, @SerializedName("birth_date") val birthDate: String? = null, @SerializedName("country") val country: String? = null, @SerializedName("device_id") val deviceId: String? = null, ) : AdditionalFields() class PaymentMethod( @SerializedName("types") val types: Array<PaymentMethodType>, @SerializedName("erip") val erip: Erip? = null, @SerializedName("credit_card") val creditCard: CreditCard, ) : AdditionalFields() class Erip( @SerializedName("order_id") val orderId: String, @SerializedName("account_number") val accountNumber: String, @SerializedName("service_no") val serviceNo: Int? = null, @SerializedName("service_info") val serviceInfo: Array<String>? = null, ) : AdditionalFields() data class CreditCard( @SerializedName("number") val cardNumber: String? = null, @SerializedName("verification_value") val cvc: String? = null, @SerializedName("holder") val holderName: String? = null, @SerializedName("exp_month") val expMonth: String? = null, @SerializedName("exp_year") val expYear: String? = null, @SerializedName("token") val token: String? = null, @SerializedName("save_card") val isSaveCard: Boolean? = null, ) : AdditionalFields() data class BrowserInfo( @SerializedName("accept_header") val acceptHeader: String, @SerializedName("screen_width") val screenWidth: Int, @SerializedName("screen_height") val screenHeight: Int, @SerializedName("screen_color_depth") val screenColorDepth: Int, @SerializedName("window_width") val windowWidth: Int, @SerializedName("window_height") val windowHeight: Int, @SerializedName("language") val language: String, @SerializedName("java_enabled") val javaEnabled: Boolean, @SerializedName("user_agent") val userAgent: String, @SerializedName("time_zone") val timeZone: Int, @SerializedName("time_zone_name") val timeZoneName: String, ) : AdditionalFields() class Travel( @SerializedName("airline") val airline: Airline, ) : AdditionalFields() class Airline( @SerializedName("agency_code") val agencyCode: String? = null, @SerializedName("agency_name") val agencyName: String? = null, @SerializedName("ticket_number") val ticketNumber: String, @SerializedName("booking_number") val bookingNumber: String? = null, @SerializedName("restricted_ticked_indicator") val restrictedTickedIndicator: RestrictedTickedIndicator? = null, @SerializedName("legs") val legs: Array<Leg>, @SerializedName("passengers") val passengers: Array<Passenger>, ) : AdditionalFields() class Leg( @SerializedName("airline_code") val airlineCode: String, @SerializedName("stop_over_code") val stop_over_code: String? = null, @SerializedName("flight_number") val flightNumber: String, @SerializedName("departure_date_time") val departureDateTime: String, @SerializedName("arrival_date_time") val arrivalDateTime: String, @SerializedName("originating_country") val originatingCountry: String, @SerializedName("originating_city") val originatingCity: String, @SerializedName("originating_airport_code") val originatingAirportCode: String, @SerializedName("destination_country") val destinationCountry: String, @SerializedName("destination_city") val destinationCity: String, @SerializedName("destination_airport_code") val destinationAirportCode: String, @SerializedName("coupon") val coupon: String, @SerializedName("class") val clazz: String, ) : AdditionalFields() class Passenger( @SerializedName("first_name") val firstName: String, @SerializedName("last_name") val lastName: String, ) : AdditionalFields() class Company( @SerializedName("name") val nameCompany: String, @SerializedName("site") val siteCompany: String, @SerializedName("small_logo_url") val logoUrlCompany: String, ) : AdditionalFields()
1
null
3
1
9710bcc3b349cfedda6c2b035cf750a2ede26533
7,592
begateway-android-sdk
MIT License
core/src/main/kotlin/nz/co/jedsimson/lgp/core/environment/RandomHelpers.kt
JedS6391
88,687,241
false
null
package nz.co.jedsimson.lgp.core.environment import kotlin.math.ceil import kotlin.math.ln import kotlin.math.pow import kotlin.random.Random /** * Return a random element from the given list. */ fun <T> Random.choice(list: List<T>): T { val randomMultiplier = this.nextDouble() return list[(randomMultiplier * list.size).toInt()] } /** * Chooses a random integer in the range [min, max] (i.e. min <= x <= max). * * @param min The lower, inclusive bound of the random integer. * @param max The upper, inclusive bound of the random integer. * @return A random integer between min and max inclusive. */ fun Random.randInt(min: Int, max: Int): Int { return this.nextInt(max - min + 1) + min } /** * Chooses k unique random elements from the population given. * * @see <a href="https://hg.python.org/cpython/file/2.7/Lib/random.py#l295">Python random.sample reference</a> */ fun <T> Random.sample(population: List<T>, k: Int): List<T> { val n = population.size val log = { a: Double, b: Double -> (ln(a) / ln(b)) } if (k < 0 || k > n) { throw IllegalArgumentException("Negative sample or sample larger than population given.") } val result = mutableListOf<T>() (0 until k).map { idx -> // Just fill the list with the first element of the population as a placeholder. result.add(idx, population[0]) } var setSize = 21 if (k > 5) { val power = ceil(log((k * 3).toDouble(), 4.0)) setSize += 4.0.pow(power).toInt() } if (n <= setSize) { val pool = population.toMutableList() for (i in (0 until k)) { val j = (this.nextDouble() * (n - i)).toInt() result[i] = pool[j] pool[j] = pool[n - i - 1] } } else { val selected = mutableSetOf<Int>() for (i in (0 until k)) { var j = (this.nextDouble() * n).toInt() while (j in selected) { j = (this.nextDouble() * n).toInt() } selected.add(j) result[i] = population[j] } } return result }
5
Kotlin
4
17
a4f11315b07435fec14c20a186913af8404d247b
2,117
LGP
MIT License
VertxAnnoCore/src/main/kotlin/io/github/johnfg10/vertxanno/annotations/fieldannotations/Disable.kt
johnfg2610
126,643,220
false
{"Kotlin": 13739}
package io.github.johnfg10.vertxanno.annotations.fieldannotations @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION) annotation class Disable()
0
Kotlin
0
0
0f2122151b7851753db4186b6742b8c61a79a845
168
VertxAnnotation
The Unlicense
src/main/kotlin/no/nav/lydia/sykefraversstatistikk/api/FilterverdierDto.kt
navikt
444,072,054
false
null
package no.nav.lydia.sykefraværsstatistikk.api import ia.felles.definisjoner.bransjer.Bransjer import kotlinx.serialization.Serializable import no.nav.lydia.ia.sak.domene.IAProsessStatus import no.nav.lydia.sykefraværsstatistikk.api.geografi.Fylke import no.nav.lydia.sykefraværsstatistikk.api.geografi.Kommune import no.nav.lydia.virksomhet.domene.Næringsgruppe import no.nav.lydia.virksomhet.domene.Sektor @Serializable data class FilterverdierDto( val fylker: List<FylkeOgKommuner>, val naringsgrupper: List<Næringsgruppe> = emptyList(), val bransjeprogram: List<Bransjer> = emptyList(), val sorteringsnokler: List<String> = Sorteringsnøkkel.alleSorteringsNøkler(), val statuser: List<IAProsessStatus> = IAProsessStatus.filtrerbareStatuser(), val filtrerbareEiere: List<EierDTO> = emptyList(), val sektorer: List<SektorDto> = Sektor.entries .map { SektorDto(kode = it.kode, beskrivelse = it.beskrivelse) }, ) enum class SnittFilter { BRANSJE_NÆRING_OVER, BRANSJE_NÆRING_UNDER_ELLER_LIK, } @Serializable data class FylkeOgKommuner (val fylke: Fylke, val kommuner: List<Kommune>) @Serializable data class EierDTO (val navIdent: String, val navn: String) @Serializable data class SektorDto(val kode: String, val beskrivelse: String)
2
null
0
2
4026bea42d89710f23d52baaab4d19d592f247da
1,282
lydia-api
MIT License
source/app/src/main/java/com/apion/apionhome/ui/adapter/HouseAdapter.kt
ApionTech
386,238,144
false
null
package com.apion.apionhome.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import com.apion.apionhome.base.BaseAdapter import com.apion.apionhome.base.BaseViewHolder import com.apion.apionhome.data.model.House import com.apion.apionhome.databinding.ItemHouseBinding class HouseAdapter(private val listener: (House) -> Unit) : BaseAdapter<House, ItemHouseBinding>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): BaseViewHolder<House, ItemHouseBinding> = HouseViewHolder( ItemHouseBinding.inflate( LayoutInflater.from(parent.context), parent, false ), listener ) class HouseViewHolder( private val itemHouseBinding: ItemHouseBinding, listener: (House) -> Unit ) : BaseViewHolder<House, ItemHouseBinding>(itemHouseBinding, listener) { override fun onBind(itemData: House) { super.onBind(itemData) itemHouseBinding.house = itemData } } }
0
Kotlin
1
0
24ddb088ffd985dcd34e3e8deeb5edcc1d717558
1,088
apion_home
Apache License 2.0
src/test/kotlin/no/nav/dagpenger/soknad/orkestrator/behov/BehovløserFactoryTest.kt
navikt
758,018,874
false
{"Kotlin": 253872, "HTML": 1388, "Dockerfile": 109}
package no.nav.dagpenger.soknad.orkestrator.behov import io.kotest.matchers.shouldBe import io.mockk.mockk import no.nav.dagpenger.soknad.orkestrator.opplysning.db.OpplysningRepositoryPostgres import no.nav.helse.rapids_rivers.testsupport.TestRapid import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import kotlin.test.Test class BehovløserFactoryTest { private val testRapid = TestRapid() private val opplysningRepository = mockk<OpplysningRepositoryPostgres>(relaxed = true) private val behovløserFactory = BehovløserFactory(testRapid, opplysningRepository) companion object { @JvmStatic fun behovProvider() = BehovløserFactory.Behov.entries.map { arrayOf(it) } } @ParameterizedTest @MethodSource("behovProvider") fun `Skal returnere riktig behovløser basert på gitt behov`(behov: BehovløserFactory.Behov) { behovløserFactory.behovløserFor(behov).behov shouldBe behov.name } @Test fun `Kan hente ut alle behov`() { behovløserFactory.behov() shouldBe listOf( "ØnskerDagpengerFraDato", "EøsArbeid", "KanJobbeDeltid", "HelseTilAlleTyperJobb", "KanJobbeHvorSomHelst", "VilligTilÅBytteYrke", "Søknadstidspunkt", "JobbetUtenforNorge", "Verneplikt", "Lønnsgaranti", "Permittert", "PermittertFiskeforedling", "Ordinær", "Søknadsdato", "TarUtdanningEllerOpplæring", ) } }
2
Kotlin
0
0
bcb167cb9d0fc04eb299dee4514a798a11b8e097
1,667
dp-soknad-orkestrator
MIT License
src/test/kotlin/io/vlang/ide/codeInsight/ReferenceImporterTest.kt
vlang
754,996,747
false
null
package org.vlang.ide.codeInsight class ReferenceImporterTest : ReferenceImporterTestBase() { fun `test simple`() = doTest( """ module main fn main() { os.read_file('') } """.trimIndent(), """ module main import os fn main() { os.read_file('') } """.trimIndent() ) fun `test with private member`() = doTest( """ module main fn main() { os.f_ok // private member } """.trimIndent(), """ module main import os fn main() { os.f_ok // private member } """.trimIndent() ) fun `test several nested`() = doTest( """ module main fn main() { nested.nested_fn() sub.Sub{} } """.trimIndent(), """ module main import nested import nested.sub fn main() { nested.nested_fn() sub.Sub{} } """.trimIndent() ) fun `test without module name`() = doTest( """ struct Foo {} fn main() { os.read_file('') } """.trimIndent(), """ import os struct Foo {} fn main() { os.read_file('') } """.trimIndent() ) }
5
null
5
33
a0d2cbfa63b995d93aaca3c80676f0c2f9bef117
1,674
intellij-v
MIT License
app/src/main/java/com/review/architecture/todoapp/domain/DeleteTaskUseCase.kt
j-a-s-o-n
571,954,395
false
null
package com.review.architecture.todoapp.domain import com.review.architecture.todoapp.data.source.TasksRepository import com.review.architecture.todoapp.util.wrapEspressoIdlingResource class DeleteTaskUseCase( private val tasksRepository: TasksRepository ) { suspend operator fun invoke(taskId: String) { wrapEspressoIdlingResource { return tasksRepository.deleteTask(taskId) } } }
0
Kotlin
0
0
98733f92665d89d39a0cface3b86cb924a587b09
425
architecture
Apache License 2.0
Parent/app/src/main/kotlin/com/github/midros/istheapp/ui/fragments/social/InteractorSocial.kt
mfa237
156,900,862
false
null
package com.github.midros.istheapp.ui.fragments.social import android.content.Context import androidx.fragment.app.FragmentManager import com.github.midros.istheapp.data.rxFirebase.InterfaceFirebase import com.github.midros.istheapp.ui.activities.base.BaseInteractor import com.github.midros.istheapp.utils.Consts.CHILD_PERMISSION import com.github.midros.istheapp.utils.Consts.CHILD_SOCIAL_MS import com.github.midros.istheapp.utils.Consts.SOCIAL import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject /** * Created by <NAME> on 20/03/18. */ class InteractorSocial<V: InterfaceViewSocial> @Inject constructor(supportFragment: FragmentManager, context: Context, firebase: InterfaceFirebase) : BaseInteractor<V>(supportFragment, context,firebase), InterfaceInteractorSocial<V> { override fun valueEventSocial() { getView()!!.addDisposable(firebase().valueEvent("$SOCIAL/$CHILD_SOCIAL_MS") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (getView()!=null) getView()!!.successResult(it) }, { if (getView()!=null) getView()!!.showError(it.message.toString()) })) } override fun valueEventEnablePermission() { getView()!!.addDisposable(firebase().valueEvent("$SOCIAL/$CHILD_PERMISSION") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { if (getView()!=null) getView()!!.setValuePermission(it) }) } }
2
null
227
6
faab27dae4fbf7cb6b341fdd94f670ecb2308742
1,601
Open-source-android-spyware
Apache License 2.0
core/src/main/kotlin/com/deflatedpickle/rawky/event/EventChangeTool.kt
DeflatedPickle
197,672,095
false
null
/* Copyright (c) 2022 DeflatedPickle under the MIT license */ package com.deflatedpickle.rawky.event import com.deflatedpickle.haruhi.api.event.AbstractEvent import com.deflatedpickle.rawky.api.Tool object EventChangeTool : AbstractEvent<Tool<*>>()
7
Kotlin
6
27
b8859e8f706132574996a5157a99145515aac52e
252
Rawky
MIT License
src/main/kotlin/com/github/nenadjakic/eav/dto/converter/EntityRequestToEntityConverter.kt
nenadjakic
782,709,579
false
{"Kotlin": 148939, "Dockerfile": 366}
package com.github.nenadjakic.eav.dto.converter import com.github.nenadjakic.eav.dto.EntityAddRequest import com.github.nenadjakic.eav.entity.Entity import org.modelmapper.AbstractConverter class EntityRequestToEntityConverter : AbstractConverter<EntityAddRequest, Entity>() { override fun convert(source: EntityAddRequest?): Entity { val destination = Entity() destination.id = null return destination } }
0
Kotlin
0
2
d729c8314a35e529c49548847ab42b4edcf86db2
442
eav-platform
MIT License
src/main/kotlin/tech/alexib/plaid/client/model/TransactionsRefreshResponse.kt
ruffCode
353,222,079
false
null
/* * Copyright 2020 Alexi Bre * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.alexib.plaid.client.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * ItemGetResponse defines the response schema for `/item/get` and `/item/webhook/update` * @param item Metadata about the Item. * @param requestId A unique identifier for the request, which can be used for troubleshooting. This * identifier, like all Plaid identifiers, is case sensitive. */ @Serializable data class ItemGetResponse( @SerialName("item") val item: Item, @SerialName("status") val status: NullableItemStatus? = null, @SerialName("request_id") val requestId: RequestID, @SerialName("access_token") val accessToken: NullableAccessToken? = null )
0
Kotlin
0
0
f937243bdd86fc656097f2154c08e8aa3dad399a
1,317
plaid-kotlin
Apache License 2.0
platform/new-ui-onboarding/src/com/intellij/platform/ide/newUiOnboarding/steps/NavigationBarStep.kt
FWDekker
400,854,910
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.platform.ide.newUiOnboarding.steps import com.intellij.ide.ui.UISettings import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.CheckedDisposable import com.intellij.openapi.wm.WindowManager import com.intellij.platform.ide.newUiOnboarding.NewUiOnboardingBundle import com.intellij.platform.ide.newUiOnboarding.NewUiOnboardingStep import com.intellij.platform.ide.newUiOnboarding.NewUiOnboardingStepData import com.intellij.ui.GotItComponentBuilder import com.intellij.ui.awt.RelativePoint import com.intellij.util.ui.JBPoint import com.intellij.util.ui.JBUI class NavigationBarStep : NewUiOnboardingStep { override suspend fun performStep(project: Project, disposable: CheckedDisposable): NewUiOnboardingStepData? { val statusBar = WindowManager.getInstance().getStatusBar(project).component ?: return null val builder = GotItComponentBuilder(NewUiOnboardingBundle.message("navigation.bar.step.text")) .withHeader(NewUiOnboardingBundle.message("navigation.bar.step.header")) .withMaxWidth(JBUI.scale(300)) // make the text fit in three lines val relativePoint = RelativePoint(statusBar, JBPoint(80, -2)) return NewUiOnboardingStepData(builder, relativePoint, Balloon.Position.above) } override fun isAvailable(): Boolean { val settings = UISettings.getInstance() return settings.showStatusBar && settings.showNavigationBarInBottom } }
1
null
1
1
66271fc05fdfe2b2e530f7edc1b564f38c6dc7b2
1,593
intellij-community
Apache License 2.0
core/src/main/kotlin/sampler/SamplerFactory.kt
numq
683,026,324
false
{"Kotlin": 267900, "C++": 13067, "Java": 4521, "CMake": 2370}
package sampler import factory.SuspendFactory class SamplerFactory : SuspendFactory<SamplerFactory.Parameters, Sampler> { data class Parameters(val sampleRate: Int, val channels: Int) override suspend fun create(parameters: Parameters) = with(parameters) { Sampler.create(sampleRate = sampleRate, channels = channels) } }
0
Kotlin
0
8
ad4491c4bf45f033e094db5c101aac85c4fc206f
344
Klarity
Apache License 2.0
lib/src/main/java/io/ashkay/crashgrabber/api/CrashGrabber.kt
Ash-Kay
678,936,244
false
{"Kotlin": 37783}
package io.ashkay.crashgrabber.api import android.content.Context import android.content.Intent import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.graphics.drawable.Icon import android.os.Build import android.util.Log import androidx.core.content.getSystemService import crashgrabber.R import io.ashkay.crashgrabber.internal.data.entity.CrashLogEntity import io.ashkay.crashgrabber.internal.di.CrashGrabberComponent import io.ashkay.crashgrabber.internal.di.DaggerCrashGrabberComponent import io.ashkay.crashgrabber.internal.ui.screen.main.CrashGrabberMainActivity import io.ashkay.crashgrabber.internal.ui.screen.main.substringOrFull import io.ashkay.crashgrabber.internal.utils.CrashReporterExceptionHandler import io.ashkay.crashgrabber.internal.utils.getDeviceMetaAsJson import java.io.PrintWriter import java.io.StringWriter import kotlinx.coroutines.runBlocking object CrashGrabber { private var instance: CrashGrabberComponent? = null private const val SHORTCUT_ID = "io.ashkay.crashgrabber" fun init(context: Context) { getOrCreate(context) createShortcut(context) } internal fun getOrCreate(context: Context): CrashGrabberComponent { instance?.let { return it } DaggerCrashGrabberComponent.factory().build(context).also { instance -> registerUncaughtExceptionHandler(instance) this.instance = instance return instance } } private fun registerUncaughtExceptionHandler(instance: CrashGrabberComponent) { Thread.setDefaultUncaughtExceptionHandler(CrashReporterExceptionHandler { _, throwable -> runBlocking { val stackTrace = getStackTraceString(throwable) instance.getDao().insertCrashLogEntry( CrashLogEntity( fileName = throwable.stackTrace[0].fileName, //TODO: check if can crash message = throwable.message ?: stackTrace.substringOrFull(50), stacktrace = stackTrace, timestamp = System.currentTimeMillis(), meta = getDeviceMetaAsJson() ) ) } }) } fun clear() { val exceptionHandler = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler(exceptionHandler) } private fun getStackTraceString(tr: Throwable): String { val sw = StringWriter() val pw = PrintWriter(sw) tr.printStackTrace(pw) pw.flush() return sw.toString() } /** * Create a shortcut to launch CrashGrabber UI. * @param context An Android [Context]. */ private fun createShortcut(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) { return } val shortcutManager = context.getSystemService<ShortcutManager>() ?: return if (shortcutManager.dynamicShortcuts.any { it.id == SHORTCUT_ID }) { return } val shortcut = ShortcutInfo.Builder(context, SHORTCUT_ID) .setShortLabel(context.getString(R.string.shortcut_label)) .setLongLabel(context.getString(R.string.shortcut_label)) .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher_crashgrabber)) .setIntent(getLaunchIntent(context).setAction(Intent.ACTION_VIEW)) .build() try { shortcutManager.addDynamicShortcuts(listOf(shortcut)) } catch (e: IllegalArgumentException) { Log.e("CrashGrabber", "ShortcutManager addDynamicShortcuts failed ", e) } catch (e: IllegalStateException) { Log.e("CrashGrabber", "ShortcutManager addDynamicShortcuts failed ", e) } } /** * Get an Intent to launch the CrashGrabber UI directly. * @param context An Android [Context]. * @return An Intent for the main CrashGrabber Activity that can be started with [Context.startActivity]. */ @JvmStatic private fun getLaunchIntent(context: Context): Intent { return Intent(context, CrashGrabberMainActivity::class.java) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } }
0
Kotlin
1
2
6557457455eb46966c8f1cae2f583e72bdc179c1
4,306
CrashGrabber
MIT License
src/main/kotlin/io/offscale/openfoodfacts/client/apis/ReadRequestsApi.kt
SamuelMarks
866,322,014
false
{"Kotlin": 537174}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package io.offscale.openfoodfacts.client.apis import io.ktor.client.* import java.io.IOException import io.offscale.openfoodfacts.client.models.GetProductByBarcode200Response import io.offscale.openfoodfacts.client.infrastructure.ApiClient import io.offscale.openfoodfacts.client.infrastructure.ApiResponse import io.offscale.openfoodfacts.client.infrastructure.ClientException import io.offscale.openfoodfacts.client.infrastructure.ClientError import io.offscale.openfoodfacts.client.infrastructure.ServerException import io.offscale.openfoodfacts.client.infrastructure.ServerError import io.offscale.openfoodfacts.client.infrastructure.MultiValueMap import io.offscale.openfoodfacts.client.infrastructure.PartConfig import io.offscale.openfoodfacts.client.infrastructure.RequestConfig import io.offscale.openfoodfacts.client.infrastructure.RequestMethod import io.offscale.openfoodfacts.client.infrastructure.ResponseType import io.offscale.openfoodfacts.client.infrastructure.Success import io.offscale.openfoodfacts.client.infrastructure.toMultiValue class ReadRequestsApi(basePath: kotlin.String = defaultBasePath, client: HttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { companion object { @JvmStatic val defaultBasePath: String by lazy { System.getProperties().getProperty(ApiClient.baseUrlKey, "https://world.openfoodfacts.org") } } /** * READ Product - Get information for a specific product by barcode (API V3) * Retrieve information for a product with a specific barcode. The fields parameter allows to specify what fields to retrieve. * @param barcode The barcode of the product to be fetched * @param cc 2 letter code of the country of the user. Used for localizing some fields in returned values (e.g. knowledge panels). If not passed, the country may be inferred by the IP address of the request. (optional) * @param lc 2 letter code of the language of the user. Used for localizing some fields in returned values (e.g. knowledge panels). If not passed, the language may be inferred by the Accept-Language header of the request. (optional) * @param tagsLc 2 letter language code to request names of tags in a specific language. For READ requests: if passed, all taxonomized tags of the response will include a &#x60;lc_name&#x60; property with the translation in the requested language, if available. Otherwise, the property value will contain the name in the original language, prefixed by the 2 language code and a colon. (optional) * @param fields Comma separated list of fields requested in the response. Special values: * \&quot;none\&quot;: returns no fields * \&quot;raw\&quot;: returns all fields as stored internally in the database * \&quot;all\&quot;: returns all fields except generated fields that need to be explicitly requested such as \&quot;knowledge_panels\&quot;. Defaults to \&quot;all\&quot; for READ requests. The \&quot;all\&quot; value can also be combined with fields like \&quot;attribute_groups\&quot; and \&quot;knowledge_panels\&quot;.&#39; (optional) * @param knowledgePanelsIncluded When knowledge_panels are requested, you can specify which panels should be in the response. All the others will be excluded. (optional) * @param knowledgePanelsExcluded When knowledge_panels are requested, you can specify which panels to exclude from the response. All the others will be included. If a panel is both excluded and included (with the knowledge_panels_excluded parameter), it will be excluded. (optional) * @return GetProductByBarcode200Response * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getProductByBarcode(barcode: kotlin.String, cc: kotlin.String? = null, lc: kotlin.String? = null, tagsLc: kotlin.String? = null, fields: kotlin.String? = null, knowledgePanelsIncluded: kotlin.String? = null, knowledgePanelsExcluded: kotlin.String? = null) : GetProductByBarcode200Response { val localVarResponse = getProductByBarcodeWithHttpInfo(barcode = barcode, cc = cc, lc = lc, tagsLc = tagsLc, fields = fields, knowledgePanelsIncluded = knowledgePanelsIncluded, knowledgePanelsExcluded = knowledgePanelsExcluded) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetProductByBarcode200Response ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) } } } /** * READ Product - Get information for a specific product by barcode (API V3) * Retrieve information for a product with a specific barcode. The fields parameter allows to specify what fields to retrieve. * @param barcode The barcode of the product to be fetched * @param cc 2 letter code of the country of the user. Used for localizing some fields in returned values (e.g. knowledge panels). If not passed, the country may be inferred by the IP address of the request. (optional) * @param lc 2 letter code of the language of the user. Used for localizing some fields in returned values (e.g. knowledge panels). If not passed, the language may be inferred by the Accept-Language header of the request. (optional) * @param tagsLc 2 letter language code to request names of tags in a specific language. For READ requests: if passed, all taxonomized tags of the response will include a &#x60;lc_name&#x60; property with the translation in the requested language, if available. Otherwise, the property value will contain the name in the original language, prefixed by the 2 language code and a colon. (optional) * @param fields Comma separated list of fields requested in the response. Special values: * \&quot;none\&quot;: returns no fields * \&quot;raw\&quot;: returns all fields as stored internally in the database * \&quot;all\&quot;: returns all fields except generated fields that need to be explicitly requested such as \&quot;knowledge_panels\&quot;. Defaults to \&quot;all\&quot; for READ requests. The \&quot;all\&quot; value can also be combined with fields like \&quot;attribute_groups\&quot; and \&quot;knowledge_panels\&quot;.&#39; (optional) * @param knowledgePanelsIncluded When knowledge_panels are requested, you can specify which panels should be in the response. All the others will be excluded. (optional) * @param knowledgePanelsExcluded When knowledge_panels are requested, you can specify which panels to exclude from the response. All the others will be included. If a panel is both excluded and included (with the knowledge_panels_excluded parameter), it will be excluded. (optional) * @return ApiResponse<GetProductByBarcode200Response?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getProductByBarcodeWithHttpInfo(barcode: kotlin.String, cc: kotlin.String?, lc: kotlin.String?, tagsLc: kotlin.String?, fields: kotlin.String?, knowledgePanelsIncluded: kotlin.String?, knowledgePanelsExcluded: kotlin.String?) : ApiResponse<GetProductByBarcode200Response?> { val localVariableConfig = getProductByBarcodeRequestConfig(barcode = barcode, cc = cc, lc = lc, tagsLc = tagsLc, fields = fields, knowledgePanelsIncluded = knowledgePanelsIncluded, knowledgePanelsExcluded = knowledgePanelsExcluded) return request<Unit, GetProductByBarcode200Response>( localVariableConfig ) } /** * To obtain the request config of the operation getProductByBarcode * * @param barcode The barcode of the product to be fetched * @param cc 2 letter code of the country of the user. Used for localizing some fields in returned values (e.g. knowledge panels). If not passed, the country may be inferred by the IP address of the request. (optional) * @param lc 2 letter code of the language of the user. Used for localizing some fields in returned values (e.g. knowledge panels). If not passed, the language may be inferred by the Accept-Language header of the request. (optional) * @param tagsLc 2 letter language code to request names of tags in a specific language. For READ requests: if passed, all taxonomized tags of the response will include a &#x60;lc_name&#x60; property with the translation in the requested language, if available. Otherwise, the property value will contain the name in the original language, prefixed by the 2 language code and a colon. (optional) * @param fields Comma separated list of fields requested in the response. Special values: * \&quot;none\&quot;: returns no fields * \&quot;raw\&quot;: returns all fields as stored internally in the database * \&quot;all\&quot;: returns all fields except generated fields that need to be explicitly requested such as \&quot;knowledge_panels\&quot;. Defaults to \&quot;all\&quot; for READ requests. The \&quot;all\&quot; value can also be combined with fields like \&quot;attribute_groups\&quot; and \&quot;knowledge_panels\&quot;.&#39; (optional) * @param knowledgePanelsIncluded When knowledge_panels are requested, you can specify which panels should be in the response. All the others will be excluded. (optional) * @param knowledgePanelsExcluded When knowledge_panels are requested, you can specify which panels to exclude from the response. All the others will be included. If a panel is both excluded and included (with the knowledge_panels_excluded parameter), it will be excluded. (optional) * @return RequestConfig */ fun getProductByBarcodeRequestConfig(barcode: kotlin.String, cc: kotlin.String?, lc: kotlin.String?, tagsLc: kotlin.String?, fields: kotlin.String?, knowledgePanelsIncluded: kotlin.String?, knowledgePanelsExcluded: kotlin.String?) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { if (cc != null) { put("cc", listOf(cc.toString())) } if (lc != null) { put("lc", listOf(lc.toString())) } if (tagsLc != null) { put("tags_lc", listOf(tagsLc.toString())) } if (fields != null) { put("fields", listOf(fields.toString())) } if (knowledgePanelsIncluded != null) { put("knowledge_panels_included", listOf(knowledgePanelsIncluded.toString())) } if (knowledgePanelsExcluded != null) { put("knowledge_panels_excluded", listOf(knowledgePanelsExcluded.toString())) } } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/api/v3/product/{barcode}".replace("{"+"barcode"+"}" , barcode), // TODO: encodeURIComponent(barcode.toString())), query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, body = localVariableBody ) } }
0
Kotlin
0
1
0ba56f72b5d3ac32b20083ea70c28ca26c6bbdeb
12,995
openfoodfacts-kotlin-openapi
Apache License 2.0
src/main/kotlin/com/zhaoch23/dialog/CommandSrDialog.kt
sakurarealm
740,696,969
false
{"Kotlin": 9169}
package com.zhaoch23.dialog import org.bukkit.command.CommandSender import taboolib.common.platform.command.CommandBody import taboolib.common.platform.command.CommandHeader import taboolib.common.platform.command.mainCommand import taboolib.common.platform.command.subCommand import taboolib.expansion.createHelper @CommandHeader(name = "srdialog", aliases = ["srd"], permission = "srdialog.command") object CommandSrDialog { @CommandBody val main = mainCommand { createHelper() } @CommandBody() val reload = subCommand { execute<CommandSender> { sender, _, _ -> SrChemDialog.loadConfiguration(SrChemDialog.instance.dataFolder) sender.sendMessage("command-reload") } } }
0
Kotlin
0
0
8b64c6f451149dc629b12a778a694a3ed362970c
750
SrChemDialog
MIT License
compiler-plugin-ksp/src/main/kotlin/com/ing/zkflow/processors/serialization/hierarchy/types/Basic.kt
ing-bank
550,239,957
false
{"Kotlin": 1610321, "Shell": 1609}
package com.ing.zkflow.processors.serialization.hierarchy.types import com.google.devtools.ksp.symbol.KSTypeReference import com.ing.zkflow.processors.serialization.hierarchy.SerializingHierarchy import com.ing.zkflow.serialization.serializer.WrappedFixedLengthKSerializerWithDefault import com.ing.zkflow.tracking.Tracker import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.ksp.toClassName import kotlinx.serialization.KSerializer import kotlin.reflect.KClass internal fun KSTypeReference.asBasic(tracker: Tracker, strategy: KClass<out KSerializer<*>>): SerializingHierarchy { val type = resolve() val serializingObject = TypeSpec.objectBuilder("$tracker") .addModifiers(KModifier.PRIVATE) .superclass( WrappedFixedLengthKSerializerWithDefault::class .asClassName() .parameterizedBy(type.toClassName()) ) .addSuperclassConstructorParameter("%T", strategy) .build() return SerializingHierarchy.OfType(type.toClassName(), emptyList(), serializingObject) }
0
Kotlin
4
9
f6e2524af124c1bdb2480f03bf907f6a44fa3c6c
1,237
zkflow
MIT License
mui-kotlin/src/jsMain/kotlin/mui/material/TableHead.mui.kt
karakum-team
387,062,541
false
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) package mui.base import seskar.js.JsValue import seskar.js.JsVirtual import web.cssom.ClassName @JsVirtual sealed external interface MuiMenuButton { companion object { @JsValue("MuiMenuButton-root") val root: ClassName } }
1
Kotlin
5
35
f8b65644caf9131e020de00a02718f005a84b45d
355
mui-kotlin
Apache License 2.0
app/src/main/java/com/example/fuelrecords/EditActivity.kt
Naillin
751,082,021
false
{"Kotlin": 18474}
package com.example.fuelrecords import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.appcompat.app.AppCompatActivity import androidx.core.widget.doAfterTextChanged import com.example.fuelrecords.databinding.ActivityEditBinding import java.util.Calendar import java.util.Date class EditActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener { private lateinit var bindingEditBinding: ActivityEditBinding var prefSpace: SharedPreferences? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindingEditBinding = ActivityEditBinding.inflate(layoutInflater) setContentView(bindingEditBinding.root) //сжатие активити для клавиатуры //window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) bindingEditBinding.apply { val adapter = ArrayAdapter(this@EditActivity, android.R.layout.simple_spinner_item, resources.getStringArray(R.array.typesOfGasolineList)) spinnerTypeOfGasoline.adapter = adapter spinnerTypeOfGasoline.onItemSelectedListener = this@EditActivity calendarViewRefuelingDate.setOnDateChangeListener { _, year, month, dayOfMonth -> calendarRefeling.set(year, month, dayOfMonth) } } prefSpace = getSharedPreferences(Constance.NAME_SECTOR_SHARED_PREF_FUELRECORD, Context.MODE_PRIVATE) textinputTotalMileageDoAfterTextChanged() } private var numberTypeGas: Int = 0 override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Получите выбранный элемент из адаптера Spinner //val selectedItem = parent?.getItemAtPosition(position).toString() numberTypeGas = position } override fun onNothingSelected(parent: AdapterView<*>?) { TODO("Not yet implemented") } private fun textinputTotalMileageDoAfterTextChanged() = with(bindingEditBinding) { val lastItem = SharedPrefTools(prefSpace, Constance.NAME_OBJECT_SHARED_PREF_FUELRECORD, "").takeData().lastOrNull() val lastTotalMileage = lastItem?.totalMileage textinputTotalMileage.doAfterTextChanged { val difference = Math.round((textinputTotalMileage.text.toString().toDoubleOrNull() ?: 0.0) - (lastTotalMileage ?: 0.0)) / 100.0 val strMileage = if(difference > 0.0) difference.toString() else "" textinputMileage.setText(strMileage) } } val calendarRefeling = Calendar.getInstance() fun buttonAddOnClick(view: View) = with(bindingEditBinding) { val calendarСurrent = Calendar.getInstance(); calendarСurrent.time = Date() //val calendarRefeling = Calendar.getInstance(); calendarRefeling.timeInMillis = calendarViewRefuelingDate.date //Почему то устанавливается дата сегодня val record: FuelRecord = FuelRecord( recordDate = calendarСurrent, refuelingDate = calendarRefeling, litersOfGasoline = textinputLitersOfGasoline.text.toString().toDoubleOrNull() ?: 0.0, cost = textinputCost.text.toString().toDoubleOrNull() ?: 0.0, typeOfGasoline = spinnerTypeOfGasoline.selectedItemPosition, totalMileage = textinputTotalMileage.text.toString().toDoubleOrNull() ?: 0.0, mileage = textinputMileage.text.toString().toDoubleOrNull() ?: 0.0, description = editTextDescription.text.toString() ) val editIntent: Intent = Intent().apply { putExtra(Constance.CODE_EDIT_LAUNCHER, record) } setResult(RESULT_OK, editIntent) finish() } fun buttonCancelOnClick(view: View) { setResult(RESULT_CANCELED) finish() } }
0
Kotlin
0
0
736989f9171e73a37dda08f4000508bed176ad85
3,970
FuelRecords
MIT License
prime-router/src/main/kotlin/config/validation/JsonSchemaValidationService.kt
CDCgov
304,423,150
false
null
package gov.cdc.prime.router.config.validation import gov.cdc.prime.router.common.JacksonMapperUtilities import java.io.File import java.io.InputStream /** * Service used to validate YAML files against a JSON schema */ interface JsonSchemaValidationService { /** * Validate the YAML structure of a file */ fun <T> validateYAMLStructure( configType: ConfigurationType<T>, file: File, ): ConfigurationValidationResult<T> /** * Validate the YAML structure of a string */ fun <T> validateYAMLStructure( configType: ConfigurationType<T>, yamlString: String, ): ConfigurationValidationResult<T> /** * Validate the YAML structure of an input stream */ fun <T> validateYAMLStructure( configType: ConfigurationType<T>, inputStream: InputStream, ): ConfigurationValidationResult<T> } class JsonSchemaValidationServiceImpl : JsonSchemaValidationService { override fun <T> validateYAMLStructure( configType: ConfigurationType<T>, file: File, ): ConfigurationValidationResult<T> { return validateYAMLStructure(configType, file.inputStream()) } override fun <T> validateYAMLStructure( configType: ConfigurationType<T>, yamlString: String, ): ConfigurationValidationResult<T> { return validateYAMLStructure(configType, yamlString.byteInputStream()) } override fun <T> validateYAMLStructure( configType: ConfigurationType<T>, inputStream: InputStream, ): ConfigurationValidationResult<T> { var schemaErrors: List<String> = emptyList() return try { val parsedJson = JacksonMapperUtilities.yamlMapper.readTree(inputStream) val schemaValidation = configType.jsonSchema.validate(parsedJson) schemaErrors = schemaValidation.map { it.message } val parsed = configType.convert(parsedJson) if (schemaErrors.isEmpty()) { ConfigurationValidationSuccess(parsed) } else { ConfigurationValidationFailure(schemaErrors) } } catch (ex: Exception) { ConfigurationValidationFailure(schemaErrors, ex) } } }
1,458
null
39
71
81f5d3c284982ccdb7f24f36fc69fdd8fac2a919
2,255
prime-reportstream
Creative Commons Zero v1.0 Universal
src/main/kotlin/br/com/gamemods/nbtmanipulator/NbtFloat.kt
PowerNukkit
188,149,180
false
{"Git Config": 1, "Gradle Kotlin DSL": 2, "Markdown": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Java": 1, "Kotlin": 35, "YAML": 2, "SCSS": 1}
package br.com.gamemods.nbtmanipulator /** * A tag which wraps a float value. * @property value The wrapped value */ public data class NbtFloat(var value: Float) : NbtTag() { /** * Returns a string representation of the tag's value. * * The returned string is compatible with string constructors of the same type. */ override val stringValue: String get() = value.toString() /** * Parses the string value as a signed float and wraps it. * @param signed Signed value from `1.4e-45` to `3.4028235e+38`. NaN and Infinity are also accepted. * @throws NumberFormatException if the number is not within a valid range or if the string does not contain a valid number. */ @Throws(NumberFormatException::class) public constructor(signed: String): this(signed.toFloat()) /** * Returns a new wrapper with the current value. */ override fun deepCopy(): NbtFloat = copy() }
1
Kotlin
1
9
b63a1bd4a406310097e314ef911650026dd812cb
953
NBT-Manipulator
MIT License
Java-Kotlin/src/main/java/string/_1221/SolutionKt.kt
jamesxuhaozhe
179,408,126
false
{"Java": 350846, "Go": 185307, "Kotlin": 56063, "Shell": 72}
package string._1221 /** * Problem link: https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/ * * Time complexity: O(n) * * Space complexity: O(1) */ class SolutionKt { fun balancedStringSplit(s: String): Int { var result = 0 var num = 0 s.forEachIndexed { _, c -> if (c == 'L') { num++ } else { num-- } if (num == 0) { result++ } } return result } }
1
Java
1
4
ea4c60f8f78b42081430b99e0c766c0513461877
531
LeetCode-Java-Kotlin
MIT License
app/src/main/java/net/yslibrary/monotweety/AppComponent.kt
hele-jeremy
213,795,534
true
{"Kotlin": 231238}
package net.yslibrary.monotweety import com.twitter.sdk.android.core.TwitterSession import dagger.Component import net.yslibrary.monotweety.analytics.Analytics import net.yslibrary.monotweety.base.RefWatcherDelegate import net.yslibrary.monotweety.base.di.AppScope import net.yslibrary.monotweety.base.di.Names import net.yslibrary.monotweety.data.DataModule import net.yslibrary.monotweety.login.domain.IsLoggedIn import net.yslibrary.monotweety.setting.domain.FooterStateManager import net.yslibrary.monotweety.setting.domain.KeepOpenManager import net.yslibrary.monotweety.setting.domain.NotificationEnabledManager import rx.subjects.PublishSubject import javax.inject.Named @AppScope @Component( modules = arrayOf(AppModule::class, DataModule::class) ) interface AppComponent : UserComponent.ComponentProvider { fun inject(app: App) fun isLoggedIn(): IsLoggedIn fun notificationEnabledManager(): NotificationEnabledManager fun keepOpenManager(): KeepOpenManager fun footerStateManager(): FooterStateManager fun refWatcherDelegate(): RefWatcherDelegate fun analytics(): Analytics @Named(Names.FOR_LOGIN) fun loginCompletedSubject(): PublishSubject<TwitterSession> }
0
null
0
0
7a65de7fd72953d66ab9b62ba6e4e3eb274aaefe
1,199
monotweety
Apache License 2.0
Code/core/presentation/designsystem/src/main/java/com/istudio/core/presentation/designsystem/dimen/CustomDimens.kt
devrath
794,443,472
false
{"Kotlin": 73074}
package com.istudio.core.presentation.designsystem.dimen import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.staticCompositionLocalOf import com.istudio.core.presentation.designsystem.dimen.screens.IntroScreenDimen import com.istudio.core.presentation.designsystem.dimen.screens.IntroScreenDimenMedium class CustomDimens( val app: RunTracerDimens, val introScreenDimen: IntroScreenDimen, ) { companion object { internal fun createLiskovDimenCompact(): CustomDimens { return CustomDimens( app = RunTracerDimens(), introScreenDimen = IntroScreenDimen() ) } private fun createLiskovDimenMedium(): CustomDimens { return CustomDimens( app = RunTracerDimensMedium(), introScreenDimen = IntroScreenDimenMedium() ) } private fun createLiskovDimenExpanded(): CustomDimens { return CustomDimens( app = RunTracerDimensExpanded(), introScreenDimen = IntroScreenDimenMedium() ) } fun createCustomDimenByWindowSize(windowClassSize: WindowSizeClass?): CustomDimens { return when (windowClassSize?.widthSizeClass) { WindowWidthSizeClass.Compact -> createLiskovDimenCompact() WindowWidthSizeClass.Medium -> createLiskovDimenMedium() WindowWidthSizeClass.Expanded -> createLiskovDimenExpanded() else -> createLiskovDimenCompact() } } } } internal val LocalCustomDimens = staticCompositionLocalOf { CustomDimens.createLiskovDimenCompact() }
0
Kotlin
0
0
f30231da5264fb16d4c9beab71abe0691ad329a0
1,785
RunTracer
Apache License 2.0
web-regresjonstest/src/main/kotlin/no/nav/su/se/bakover/web/komponenttest/Komponenttest.kt
navikt
227,366,088
false
{"Kotlin": 9172373, "Shell": 4369, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.web.komponenttest import io.ktor.server.application.Application import io.ktor.server.testing.ApplicationTestBuilder import io.ktor.server.testing.testApplication import no.nav.su.se.bakover.client.Clients import no.nav.su.se.bakover.common.infrastructure.config.ApplicationConfig import no.nav.su.se.bakover.dokument.application.DokumentServices import no.nav.su.se.bakover.dokument.application.consumer.DistribuerDokumentHendelserKonsument import no.nav.su.se.bakover.dokument.application.consumer.JournalførDokumentHendelserKonsument import no.nav.su.se.bakover.dokument.infrastructure.database.Dokumentkomponenter import no.nav.su.se.bakover.domain.DatabaseRepos import no.nav.su.se.bakover.test.applicationConfig import no.nav.su.se.bakover.test.fixedClock import no.nav.su.se.bakover.test.persistence.dbMetricsStub import no.nav.su.se.bakover.test.persistence.withMigratedDb import no.nav.su.se.bakover.test.satsFactoryTest import no.nav.su.se.bakover.web.Consumers import no.nav.su.se.bakover.web.SharedRegressionTestData import no.nav.su.se.bakover.web.TestClientsBuilder import no.nav.su.se.bakover.web.mapRåttKravgrunnlagPåSakHendelse import no.nav.su.se.bakover.web.services.AccessCheckProxy import no.nav.su.se.bakover.web.services.ServiceBuilder import no.nav.su.se.bakover.web.services.Services import no.nav.su.se.bakover.web.susebakover import org.mockito.kotlin.mock import satser.domain.supplerendestønad.SatsFactoryForSupplerendeStønad import tilbakekreving.presentation.Tilbakekrevingskomponenter import vilkår.formue.domain.FormuegrenserFactory import økonomi.infrastructure.kvittering.consumer.UtbetalingKvitteringConsumer import java.time.Clock import java.time.LocalDate import javax.sql.DataSource class AppComponents private constructor( val clock: Clock, val applicationConfig: ApplicationConfig, val databaseRepos: DatabaseRepos, val clients: Clients, val services: Services, val tilbakekrevingskomponenter: Tilbakekrevingskomponenter, val dokumentHendelseKomponenter: Dokumentkomponenter, val accessCheckProxy: AccessCheckProxy, val consumers: Consumers, ) { companion object { fun instance( clock: Clock, applicationConfig: ApplicationConfig, dataSource: DataSource, repoBuilder: (dataSource: DataSource, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad) -> DatabaseRepos, clientBuilder: (databaseRepos: DatabaseRepos, clock: Clock) -> Clients, serviceBuilder: (databaseRepos: DatabaseRepos, clients: Clients, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad) -> Services, tilbakekrevingskomponenterBuilder: (databaseRepos: DatabaseRepos, services: Services) -> Tilbakekrevingskomponenter, dokumentKomponenterBuilder: (databaseRepos: DatabaseRepos, services: Services, clients: Clients) -> Dokumentkomponenter, ): AppComponents { val databaseRepos = repoBuilder(dataSource, clock, satsFactoryTest) val clients = clientBuilder(databaseRepos, clock) val services: Services = serviceBuilder(databaseRepos, clients, clock, satsFactoryTest) val accessCheckProxy = AccessCheckProxy( personRepo = databaseRepos.person, services = services, ) val consumers = Consumers( utbetalingKvitteringConsumer = UtbetalingKvitteringConsumer( utbetalingService = services.utbetaling, ferdigstillVedtakService = services.ferdigstillVedtak, clock = clock, ), ) val tilbakekrevingskomponenter = tilbakekrevingskomponenterBuilder(databaseRepos, services) val dokumenterKomponenter = dokumentKomponenterBuilder(databaseRepos, services, clients) return AppComponents( clock = clock, applicationConfig = applicationConfig, databaseRepos = databaseRepos, clients = clients, services = services, accessCheckProxy = accessCheckProxy, consumers = consumers, tilbakekrevingskomponenter = tilbakekrevingskomponenter, dokumentHendelseKomponenter = dokumenterKomponenter, ) } } } internal fun withKomptestApplication( clock: Clock = fixedClock, applicationConfig: ApplicationConfig = applicationConfig(), repoBuilder: (dataSource: DataSource, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad) -> DatabaseRepos = { dataSource, klokke, satsFactory -> SharedRegressionTestData.databaseRepos( dataSource = dataSource, clock = klokke, satsFactory = satsFactory, ) }, clientsBuilder: (databaseRepos: DatabaseRepos, clock: Clock) -> Clients = { databaseRepos, klokke -> TestClientsBuilder( clock = klokke, databaseRepos = databaseRepos, ).build(applicationConfig) }, serviceBuilder: (databaseRepos: DatabaseRepos, clients: Clients, clock: Clock, satsFactory: SatsFactoryForSupplerendeStønad) -> Services = { databaseRepos, clients, klokke, satsFactory -> run { val satsFactoryIDag = satsFactory.gjeldende(LocalDate.now(klokke)) val formuegrenserFactoryIDag = FormuegrenserFactory.createFromGrunnbeløp( grunnbeløpFactory = satsFactoryIDag.grunnbeløpFactory, tidligsteTilgjengeligeMåned = satsFactoryIDag.tidligsteTilgjengeligeMåned, ) ServiceBuilder.build( databaseRepos = databaseRepos, clients = clients, behandlingMetrics = mock(), søknadMetrics = mock(), clock = klokke, satsFactory = satsFactoryIDag, formuegrenserFactory = formuegrenserFactoryIDag, applicationConfig = applicationConfig, dbMetrics = dbMetricsStub, ) } }, tilbakekrevingskomponenterBuilder: (databaseRepos: DatabaseRepos, services: Services) -> Tilbakekrevingskomponenter = { databaseRepos, services -> Tilbakekrevingskomponenter.create( clock = clock, sessionFactory = databaseRepos.sessionFactory, personService = services.person, hendelsekonsumenterRepo = databaseRepos.hendelsekonsumenterRepo, tilbakekrevingUnderRevurderingService = services.tilbakekrevingUnderRevurderingService, sakService = services.sak, oppgaveService = services.oppgave, oppgaveHendelseRepo = databaseRepos.oppgaveHendelseRepo, mapRåttKravgrunnlagPåSakHendelse = mapRåttKravgrunnlagPåSakHendelse, hendelseRepo = databaseRepos.hendelseRepo, dokumentHendelseRepo = databaseRepos.dokumentHendelseRepo, brevService = services.brev, tilbakekrevingConfig = applicationConfig.oppdrag.tilbakekreving, dbMetrics = dbMetricsStub, ) }, dokumentKomponenterBuilder: (databaseRepos: DatabaseRepos, services: Services, clients: Clients) -> Dokumentkomponenter = { databaseRepos, services, clients -> val repos = no.nav.su.se.bakover.dokument.infrastructure.database.DokumentRepos( clock = clock, sessionFactory = databaseRepos.sessionFactory, hendelseRepo = databaseRepos.hendelseRepo, hendelsekonsumenterRepo = databaseRepos.hendelsekonsumenterRepo, dokumentHendelseRepo = databaseRepos.dokumentHendelseRepo, ) Dokumentkomponenter( repos = repos, services = DokumentServices( clock = clock, sessionFactory = repos.sessionFactory, hendelsekonsumenterRepo = repos.hendelsekonsumenterRepo, sakService = services.sak, dokumentHendelseRepo = repos.dokumentHendelseRepo, journalførBrevClient = clients.journalførClients.brev, dokDistFordeling = clients.dokDistFordeling, journalførtDokumentHendelserKonsument = JournalførDokumentHendelserKonsument( sakService = services.sak, journalførBrevClient = clients.journalførClients.brev, dokumentHendelseRepo = repos.dokumentHendelseRepo, hendelsekonsumenterRepo = repos.hendelsekonsumenterRepo, sessionFactory = repos.sessionFactory, clock = clock, ), distribuerDokumentHendelserKonsument = DistribuerDokumentHendelserKonsument( sakService = services.sak, dokDistFordeling = clients.dokDistFordeling, hendelsekonsumenterRepo = repos.hendelsekonsumenterRepo, dokumentHendelseRepo = repos.dokumentHendelseRepo, sessionFactory = repos.sessionFactory, clock = clock, ), ), ) }, test: ApplicationTestBuilder.(appComponents: AppComponents) -> Unit, ) { withMigratedDb { dataSource -> testApplication( appComponents = AppComponents.instance( clock = clock, dataSource = dataSource, repoBuilder = repoBuilder, clientBuilder = clientsBuilder, serviceBuilder = serviceBuilder, applicationConfig = applicationConfig, tilbakekrevingskomponenterBuilder = tilbakekrevingskomponenterBuilder, dokumentKomponenterBuilder = dokumentKomponenterBuilder, ), test = test, ) } } fun Application.testSusebakover(appComponents: AppComponents) { return susebakover( clock = appComponents.clock, applicationConfig = appComponents.applicationConfig, databaseRepos = appComponents.databaseRepos, clients = appComponents.clients, services = appComponents.services, accessCheckProxy = appComponents.accessCheckProxy, tilbakekrevingskomponenter = { _, _, _, _, _, _, _, _, _, _, _, _, _ -> appComponents.tilbakekrevingskomponenter }, dokumentkomponenter = appComponents.dokumentHendelseKomponenter, consumers = appComponents.consumers, ) } fun testApplication( appComponents: AppComponents, test: ApplicationTestBuilder.(appComponents: AppComponents) -> Unit, ) { testApplication { application { testSusebakover(appComponents) } test(appComponents) } }
7
Kotlin
1
1
f187a366e1b4ec73bf18f4ebc6a68109494f1c1b
10,773
su-se-bakover
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/config/CfnRemediationConfigurationProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 149148378}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.config import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.jvm.JvmName /** * Properties for defining a `CfnRemediationConfiguration`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.config.*; * Object parameters; * CfnRemediationConfigurationProps cfnRemediationConfigurationProps = * CfnRemediationConfigurationProps.builder() * .configRuleName("configRuleName") * .targetId("targetId") * .targetType("targetType") * // the properties below are optional * .automatic(false) * .executionControls(ExecutionControlsProperty.builder() * .ssmControls(SsmControlsProperty.builder() * .concurrentExecutionRatePercentage(123) * .errorPercentage(123) * .build()) * .build()) * .maximumAutomaticAttempts(123) * .parameters(parameters) * .resourceType("resourceType") * .retryAttemptSeconds(123) * .targetVersion("targetVersion") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html) */ public interface CfnRemediationConfigurationProps { /** * The remediation is triggered automatically. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-automatic) */ public fun automatic(): Any? = unwrap(this).getAutomatic() /** * The name of the AWS Config rule. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-configrulename) */ public fun configRuleName(): String /** * An ExecutionControls object. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-executioncontrols) */ public fun executionControls(): Any? = unwrap(this).getExecutionControls() /** * The maximum number of failed attempts for auto-remediation. If you do not select a number, the * default is 5. * * For example, if you specify MaximumAutomaticAttempts as 5 with RetryAttemptSeconds as 50 * seconds, AWS Config will put a RemediationException on your behalf for the failing resource after * the 5th failed attempt within 50 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-maximumautomaticattempts) */ public fun maximumAutomaticAttempts(): Number? = unwrap(this).getMaximumAutomaticAttempts() /** * An object of the RemediationParameterValue. For more information, see * [RemediationParameterValue](https://docs.aws.amazon.com/config/latest/APIReference/API_RemediationParameterValue.html) * . * * * The type is a map of strings to RemediationParameterValue. * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-parameters) */ public fun parameters(): Any? = unwrap(this).getParameters() /** * The type of a resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-resourcetype) */ public fun resourceType(): String? = unwrap(this).getResourceType() /** * Time window to determine whether or not to add a remediation exception to prevent infinite * remediation attempts. * * If `MaximumAutomaticAttempts` remediation attempts have been made under `RetryAttemptSeconds` , * a remediation exception will be added to the resource. If you do not select a number, the default * is 60 seconds. * * For example, if you specify `RetryAttemptSeconds` as 50 seconds and `MaximumAutomaticAttempts` * as 5, AWS Config will run auto-remediations 5 times within 50 seconds before adding a remediation * exception to the resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-retryattemptseconds) */ public fun retryAttemptSeconds(): Number? = unwrap(this).getRetryAttemptSeconds() /** * Target ID is the name of the SSM document. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-targetid) */ public fun targetId(): String /** * The type of the target. * * Target executes remediation. For example, SSM document. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-targettype) */ public fun targetType(): String /** * Version of the target. For example, version of the SSM document. * * * If you make backward incompatible changes to the SSM document, you must call * PutRemediationConfiguration API again to ensure the remediations can run. * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-targetversion) */ public fun targetVersion(): String? = unwrap(this).getTargetVersion() /** * A builder for [CfnRemediationConfigurationProps] */ @CdkDslMarker public interface Builder { /** * @param automatic The remediation is triggered automatically. */ public fun automatic(automatic: Boolean) /** * @param automatic The remediation is triggered automatically. */ public fun automatic(automatic: IResolvable) /** * @param configRuleName The name of the AWS Config rule. */ public fun configRuleName(configRuleName: String) /** * @param executionControls An ExecutionControls object. */ public fun executionControls(executionControls: IResolvable) /** * @param executionControls An ExecutionControls object. */ public fun executionControls(executionControls: CfnRemediationConfiguration.ExecutionControlsProperty) /** * @param executionControls An ExecutionControls object. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("e20cdb25e82ee7bf91f5e29212f08cdf4f58a08a209868dccf0cfd2dca7cd236") public fun executionControls(executionControls: CfnRemediationConfiguration.ExecutionControlsProperty.Builder.() -> Unit) /** * @param maximumAutomaticAttempts The maximum number of failed attempts for auto-remediation. * If you do not select a number, the default is 5. * For example, if you specify MaximumAutomaticAttempts as 5 with RetryAttemptSeconds as 50 * seconds, AWS Config will put a RemediationException on your behalf for the failing resource * after the 5th failed attempt within 50 seconds. */ public fun maximumAutomaticAttempts(maximumAutomaticAttempts: Number) /** * @param parameters An object of the RemediationParameterValue. For more information, see * [RemediationParameterValue](https://docs.aws.amazon.com/config/latest/APIReference/API_RemediationParameterValue.html) * . * * The type is a map of strings to RemediationParameterValue. */ public fun parameters(parameters: Any) /** * @param resourceType The type of a resource. */ public fun resourceType(resourceType: String) /** * @param retryAttemptSeconds Time window to determine whether or not to add a remediation * exception to prevent infinite remediation attempts. * If `MaximumAutomaticAttempts` remediation attempts have been made under `RetryAttemptSeconds` * , a remediation exception will be added to the resource. If you do not select a number, the * default is 60 seconds. * * For example, if you specify `RetryAttemptSeconds` as 50 seconds and * `MaximumAutomaticAttempts` as 5, AWS Config will run auto-remediations 5 times within 50 seconds * before adding a remediation exception to the resource. */ public fun retryAttemptSeconds(retryAttemptSeconds: Number) /** * @param targetId Target ID is the name of the SSM document. */ public fun targetId(targetId: String) /** * @param targetType The type of the target. * Target executes remediation. For example, SSM document. */ public fun targetType(targetType: String) /** * @param targetVersion Version of the target. For example, version of the SSM document. * * If you make backward incompatible changes to the SSM document, you must call * PutRemediationConfiguration API again to ensure the remediations can run. */ public fun targetVersion(targetVersion: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.config.CfnRemediationConfigurationProps.Builder = software.amazon.awscdk.services.config.CfnRemediationConfigurationProps.builder() /** * @param automatic The remediation is triggered automatically. */ override fun automatic(automatic: Boolean) { cdkBuilder.automatic(automatic) } /** * @param automatic The remediation is triggered automatically. */ override fun automatic(automatic: IResolvable) { cdkBuilder.automatic(automatic.let(IResolvable.Companion::unwrap)) } /** * @param configRuleName The name of the AWS Config rule. */ override fun configRuleName(configRuleName: String) { cdkBuilder.configRuleName(configRuleName) } /** * @param executionControls An ExecutionControls object. */ override fun executionControls(executionControls: IResolvable) { cdkBuilder.executionControls(executionControls.let(IResolvable.Companion::unwrap)) } /** * @param executionControls An ExecutionControls object. */ override fun executionControls(executionControls: CfnRemediationConfiguration.ExecutionControlsProperty) { cdkBuilder.executionControls(executionControls.let(CfnRemediationConfiguration.ExecutionControlsProperty.Companion::unwrap)) } /** * @param executionControls An ExecutionControls object. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("e20cdb25e82ee7bf91f5e29212f08cdf4f58a08a209868dccf0cfd2dca7cd236") override fun executionControls(executionControls: CfnRemediationConfiguration.ExecutionControlsProperty.Builder.() -> Unit): Unit = executionControls(CfnRemediationConfiguration.ExecutionControlsProperty(executionControls)) /** * @param maximumAutomaticAttempts The maximum number of failed attempts for auto-remediation. * If you do not select a number, the default is 5. * For example, if you specify MaximumAutomaticAttempts as 5 with RetryAttemptSeconds as 50 * seconds, AWS Config will put a RemediationException on your behalf for the failing resource * after the 5th failed attempt within 50 seconds. */ override fun maximumAutomaticAttempts(maximumAutomaticAttempts: Number) { cdkBuilder.maximumAutomaticAttempts(maximumAutomaticAttempts) } /** * @param parameters An object of the RemediationParameterValue. For more information, see * [RemediationParameterValue](https://docs.aws.amazon.com/config/latest/APIReference/API_RemediationParameterValue.html) * . * * The type is a map of strings to RemediationParameterValue. */ override fun parameters(parameters: Any) { cdkBuilder.parameters(parameters) } /** * @param resourceType The type of a resource. */ override fun resourceType(resourceType: String) { cdkBuilder.resourceType(resourceType) } /** * @param retryAttemptSeconds Time window to determine whether or not to add a remediation * exception to prevent infinite remediation attempts. * If `MaximumAutomaticAttempts` remediation attempts have been made under `RetryAttemptSeconds` * , a remediation exception will be added to the resource. If you do not select a number, the * default is 60 seconds. * * For example, if you specify `RetryAttemptSeconds` as 50 seconds and * `MaximumAutomaticAttempts` as 5, AWS Config will run auto-remediations 5 times within 50 seconds * before adding a remediation exception to the resource. */ override fun retryAttemptSeconds(retryAttemptSeconds: Number) { cdkBuilder.retryAttemptSeconds(retryAttemptSeconds) } /** * @param targetId Target ID is the name of the SSM document. */ override fun targetId(targetId: String) { cdkBuilder.targetId(targetId) } /** * @param targetType The type of the target. * Target executes remediation. For example, SSM document. */ override fun targetType(targetType: String) { cdkBuilder.targetType(targetType) } /** * @param targetVersion Version of the target. For example, version of the SSM document. * * If you make backward incompatible changes to the SSM document, you must call * PutRemediationConfiguration API again to ensure the remediations can run. */ override fun targetVersion(targetVersion: String) { cdkBuilder.targetVersion(targetVersion) } public fun build(): software.amazon.awscdk.services.config.CfnRemediationConfigurationProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.config.CfnRemediationConfigurationProps, ) : CdkObject(cdkObject), CfnRemediationConfigurationProps { /** * The remediation is triggered automatically. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-automatic) */ override fun automatic(): Any? = unwrap(this).getAutomatic() /** * The name of the AWS Config rule. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-configrulename) */ override fun configRuleName(): String = unwrap(this).getConfigRuleName() /** * An ExecutionControls object. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-executioncontrols) */ override fun executionControls(): Any? = unwrap(this).getExecutionControls() /** * The maximum number of failed attempts for auto-remediation. If you do not select a number, * the default is 5. * * For example, if you specify MaximumAutomaticAttempts as 5 with RetryAttemptSeconds as 50 * seconds, AWS Config will put a RemediationException on your behalf for the failing resource * after the 5th failed attempt within 50 seconds. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-maximumautomaticattempts) */ override fun maximumAutomaticAttempts(): Number? = unwrap(this).getMaximumAutomaticAttempts() /** * An object of the RemediationParameterValue. For more information, see * [RemediationParameterValue](https://docs.aws.amazon.com/config/latest/APIReference/API_RemediationParameterValue.html) * . * * * The type is a map of strings to RemediationParameterValue. * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-parameters) */ override fun parameters(): Any? = unwrap(this).getParameters() /** * The type of a resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-resourcetype) */ override fun resourceType(): String? = unwrap(this).getResourceType() /** * Time window to determine whether or not to add a remediation exception to prevent infinite * remediation attempts. * * If `MaximumAutomaticAttempts` remediation attempts have been made under `RetryAttemptSeconds` * , a remediation exception will be added to the resource. If you do not select a number, the * default is 60 seconds. * * For example, if you specify `RetryAttemptSeconds` as 50 seconds and * `MaximumAutomaticAttempts` as 5, AWS Config will run auto-remediations 5 times within 50 seconds * before adding a remediation exception to the resource. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-retryattemptseconds) */ override fun retryAttemptSeconds(): Number? = unwrap(this).getRetryAttemptSeconds() /** * Target ID is the name of the SSM document. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-targetid) */ override fun targetId(): String = unwrap(this).getTargetId() /** * The type of the target. * * Target executes remediation. For example, SSM document. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-targettype) */ override fun targetType(): String = unwrap(this).getTargetType() /** * Version of the target. For example, version of the SSM document. * * * If you make backward incompatible changes to the SSM document, you must call * PutRemediationConfiguration API again to ensure the remediations can run. * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-remediationconfiguration.html#cfn-config-remediationconfiguration-targetversion) */ override fun targetVersion(): String? = unwrap(this).getTargetVersion() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CfnRemediationConfigurationProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.config.CfnRemediationConfigurationProps): CfnRemediationConfigurationProps = CdkObjectWrappers.wrap(cdkObject) as? CfnRemediationConfigurationProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CfnRemediationConfigurationProps): software.amazon.awscdk.services.config.CfnRemediationConfigurationProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.config.CfnRemediationConfigurationProps } }
4
Kotlin
0
4
db2b3a364f5e74d8f80490e7850da7f1e7f1e7d0
20,023
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/example/mcard/domain/viewModels/basic/other/SettingsViewModel.kt
Ilyandr
548,715,167
false
null
package com.example.mcard.domain.viewModels.basic.other import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.mcard.R import com.example.mcard.domain.models.basic.other.SettingsModel import com.example.mcard.repository.di.AppComponent import com.example.mcard.repository.features.SupportLiveData.default import com.example.mcard.repository.features.SupportLiveData.set import com.example.mcard.repository.features.optionally.DataCorrectness.checkCorrectLogin import com.example.mcard.repository.features.optionally.DataCorrectness.checkCorrectPassword import com.example.mcard.repository.features.rest.firebase.AdditionAuthFirebase import com.example.mcard.repository.features.storage.preferences.UserPreferences import com.example.mcard.repository.source.architecture.viewModels.LiveViewModel import com.example.mcard.repository.source.usage.EntranceUsageSource import javax.inject.Inject internal class SettingsViewModel( appComponent: AppComponent, ) : LiveViewModel<SettingsModel>(), EntranceUsageSource { @Inject lateinit var additionAuthFirebase: AdditionAuthFirebase @Inject override lateinit var userPreferences: UserPreferences private val mutableLiveDataState = MutableLiveData<SettingsModel>() .default( SettingsModel.DefaultState ) override val liveDataState: LiveData<SettingsModel> = this.mutableLiveDataState init { appComponent inject this } override fun actionСompleted() { this.mutableLiveDataState.set( SettingsModel.DefaultState ) } fun changeLogin( oldData: String?, newData: String?, ) { if (oldData.checkCorrectLogin() && newData.checkCorrectLogin() ) { launchWaitingState() additionAuthFirebase.changeLogin( oldData!!, newData!!, ::sendMessage ) } else sendMessage( R.string.msgWarningInputData ) } private infix fun sendMessage(messageId: Int) = this.mutableLiveDataState.set( SettingsModel.MessageState( messageId ) ) private fun launchWaitingState() = this.mutableLiveDataState.set( SettingsModel.WaitingState ) fun changePassword( oldData: String?, newData: String?, ) { if (oldData.checkCorrectPassword() && newData.checkCorrectPassword() ) { launchWaitingState() additionAuthFirebase.changePassword( oldData!!, newData!!, ::sendMessage ) } else sendMessage( R.string.msgWarningInputData ) } fun deleteAccount() { launchWaitingState() additionAuthFirebase.removeAccount( faultAction = ::sendMessage ) { mutableLiveDataState.set( SettingsModel.DeleteAccountState ) } } fun clearCache() = mutableLiveDataState.set( SettingsModel.RemoveCacheState ) override fun registrationOfInteraction(lifecycleOwner: LifecycleOwner) {} }
0
Kotlin
0
1
a5287fc7b7488994f9cfd840cd8c92f11607ef8d
3,303
MCard-indicative
MIT License
examples/src/test/kotlin/examples/onnx/cv/OnnxEfficientNetTestSuite.kt
JetBrains
249,948,572
false
null
/* * Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package examples.onnx.cv import examples.Basic import examples.onnx.cv.custom.efficientnet.* import org.jetbrains.kotlinx.dl.api.inference.onnx.ONNXModels import org.junit.jupiter.api.Test class OnnxEfficientNetTestSuite { @Test fun efficientNetB0PredictionTest() { efficientNetB0Prediction() } @Test fun efficientNetB0AdditionalTrainingTest() { efficientNetB0AdditionalTraining() } @Test fun efficientNetB0EasyPredictionTest() { efficientNetB0EasyPrediction() } @Test fun efficientNetB1PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB1(), resizeTo = Pair(240, 240)) } @Test fun efficientNetB1AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB1(noTop = true), resizeTo = Pair(240, 240)) } @Test fun efficientNetB2PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB2(), resizeTo = Pair(260, 260)) } @Test fun efficientNetB2AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB2(noTop = true), resizeTo = Pair(260, 260)) } @Test fun efficientNetB3PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB3(), resizeTo = Pair(300, 300)) } @Test fun efficientNetB3AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB3(noTop = true), resizeTo = Pair(300, 300)) } @Test fun efficientNetB4PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB4(), resizeTo = Pair(380, 380)) } @Test fun efficientNetB4AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB4(noTop = true), resizeTo = Pair(380, 380)) } @Test fun efficientNetB5PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB5(), resizeTo = Pair(456, 456)) } @Test fun efficientNetB5AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB5(noTop = true), resizeTo = Pair(456, 456)) } @Test fun efficientNetB6PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB6(), resizeTo = Pair(528, 528)) } @Test fun efficientNetB6AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB6(noTop = true), resizeTo = Pair(528, 528)) } @Test fun efficientNetB7PredictionTest() { runONNXImageRecognitionPrediction(ONNXModels.CV.EfficientNetB7(), resizeTo = Pair(600, 600)) } @Test fun efficientNetB7AdditionalTrainingTest() { runONNXAdditionalTraining(ONNXModels.CV.EfficientNetB7(noTop = true), resizeTo = Pair(600, 600)) } @Test fun efficientNetB7EasyPredictionTest() { efficientNetB7EasyPrediction() } }
71
Kotlin
69
727
033c0e3a959a7083ff97fad6ac4907d5dbc65bd1
3,162
KotlinDL
Apache License 2.0
app/src/main/java/com/example/project_music/adapters/base_adapters/BaseAdapterCallBack.kt
Ikrom27
671,861,023
false
null
package com.example.project_music.adapters.base_adapters import android.view.View interface BaseAdapterCallBack<T> { fun onItemClick(model: T, view: View) fun onLongClick(model: T, view: View) }
0
Kotlin
0
0
b8bc250f274a5ac64f7d2e393fc1c8be848bada1
205
MusicClub
MIT License