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
src/test/kotlin/no/nav/omsorgspenger/koronaoverføringer/rivers/GosysKoronaOverføringerTest.kt
navikt
293,469,365
false
{"Kotlin": 599806, "Dockerfile": 208}
package no.nav.omsorgspenger.koronaoverføringer.rivers import no.nav.helse.rapids_rivers.testsupport.TestRapid import no.nav.omsorgspenger.Periode import no.nav.omsorgspenger.personopplysninger.VurderRelasjonerMelding import no.nav.omsorgspenger.registerOverføreKoronaOmsorgsdager import no.nav.omsorgspenger.testutils.DataSourceExtension import no.nav.omsorgspenger.testutils.IdentitetsnummerGenerator import no.nav.omsorgspenger.testutils.TestApplicationContextBuilder import no.nav.omsorgspenger.testutils.cleanAndMigrate import no.nav.omsorgspenger.testutils.sisteMeldingSomJSONObject import no.nav.omsorgspenger.testutils.ventPå import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import javax.sql.DataSource @ExtendWith(DataSourceExtension::class) internal class GosysKoronaOverføringerTest( dataSource: DataSource) { private val applicationContext = TestApplicationContextBuilder( dataSource = dataSource.cleanAndMigrate() ).build() private val rapid = TestRapid().apply { this.registerOverføreKoronaOmsorgsdager(applicationContext) } @BeforeEach fun reset() { rapid.reset() } @Test fun `Annen periode enn støttet blir til Gosys journalføringsoppgaver`() { val fra = IdentitetsnummerGenerator.identitetsnummer() val til = IdentitetsnummerGenerator.identitetsnummer() val barn = koronaBarn() val (id, behovssekvens) = behovssekvensOverføreKoronaOmsorgsdager( fra = fra, til = til, omsorgsdagerÅOverføre = 10, periode = Periode("2020-06-01/2020-12-31"), journalpostIder = listOf("88124"), barn = listOf(barn) ) rapid.sendTestMessage(behovssekvens) rapid.ventPå(1) rapid.sisteMeldingSomJSONObject().assertGosysJournalføringsoppgave( behovssekvensId = id, fra = fra, til = til, barn = barn.identitetsnummer, journalpostId = "88124" ) } @Test fun `Svart at man ikke jobber i Norge blir til Gosys journalføringsoppgaver`() { val fra = IdentitetsnummerGenerator.identitetsnummer() val til = IdentitetsnummerGenerator.identitetsnummer() val barn = koronaBarn() val (id, behovssekvens) = behovssekvensOverføreKoronaOmsorgsdager( fra = fra, til = til, omsorgsdagerÅOverføre = 10, jobberINorge = false, journalpostIder = listOf("88126"), barn = listOf(barn) ) rapid.sendTestMessage(behovssekvens) rapid.ventPå(1) rapid.sisteMeldingSomJSONObject().assertGosysJournalføringsoppgave( behovssekvensId = id, fra = fra, til = til, barn = barn.identitetsnummer, journalpostId = "88126" ) } @Test fun `Ikke funnet vedtak om utvidet rett som gjør at hele overføringen ikke kan gjennomføres blir til Gosys journalføringsoppgaver`() { val fra = IdentitetsnummerGenerator.identitetsnummer() val til = IdentitetsnummerGenerator.identitetsnummer() val barnet = koronaBarn(utvidetRett = true) val (id, behovssekvens) = behovssekvensOverføreKoronaOmsorgsdager( fra = fra, til = til, omsorgsdagerTattUtIÅr = 0, omsorgsdagerÅOverføre = 21, // En dag mer enn man kan overføre uten utvidet rett barn = listOf(barnet), journalpostIder = listOf("88127") ) rapid.sendTestMessage(behovssekvens) rapid.ventPå(1) rapid.mockHentOmsorgspengerSaksnummerOchVurderRelasjoner( fra = fra, til = til, relasjoner = setOf( VurderRelasjonerMelding.Relasjon(identitetsnummer = barnet.identitetsnummer, relasjon = "barn", borSammen = true), VurderRelasjonerMelding.Relasjon(identitetsnummer = til, relasjon = "INGEN", borSammen = true) ) ) rapid.ventPå(2) rapid.sisteMeldingSomJSONObject().assertGosysJournalføringsoppgave( behovssekvensId = id, fra = fra, til = til, barn = barnet.identitetsnummer, journalpostId = "88127", forventetLøsninger = listOf( "HentFordelingGirMeldinger", "HentOverføringGirMeldinger", "HentKoronaOverføringGirMeldinger", "HentUtvidetRettVedtak", "HentOmsorgspengerSaksnummer", "VurderRelasjoner", "OverføreKoronaOmsorgsdagerBehandling", "OverføreKoronaOmsorgsdager" ) ) } }
3
Kotlin
0
2
b9bdc4afefc44430c75eb1cbb46b6720a4837e66
4,804
omsorgspenger-rammemeldinger
MIT License
app/src/main/java/kerala/superhero/app/login/LoginActivity.kt
coronasafe
367,320,621
false
null
package kerala.superhero.app.login import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kerala.superhero.app.R import kerala.superhero.app.data.ResultWrapper import kerala.superhero.app.home.HomeActivity import kerala.superhero.app.network.login import kerala.superhero.app.prefs import kerala.superhero.app.signup.SignUpActivity import kerala.superhero.app.utils.handleGenericError import kerala.superhero.app.utils.handleNetworkError import kerala.superhero.app.utils.isAValidIndianPhoneNumber import kerala.superhero.app.views.ProgressDialog import kotlinx.android.synthetic.main.activity_login.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.anko.alert class LoginActivity : AppCompatActivity(), Login { private var progressDialog: ProgressDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) progressDialog = ProgressDialog(this) loginButton.setOnClickListener { attemptLogin() } loginButtonImage.setOnClickListener { attemptLogin() } signUpLink.setOnClickListener { Intent(this, SignUpActivity::class.java).apply { putExtra("phone", intent.extras?.getString("phone", "")) }.let(::startActivity) finishAffinity() } forgotPasswordLink.setOnClickListener { Intent(this, ResetPasswordActivity::class.java).apply { putExtra("phone", intent.extras?.getString("phone", "")) }.let(::startActivity) finishAffinity() } if (intent.extras?.getString("phone", "").isNullOrEmpty()) { resetPasswordPhoneNumberEditText.isEnabled = true } else { resetPasswordPhoneNumberEditText.isEnabled = false resetPasswordPhoneNumberEditText.setText(intent.extras?.getString("phone", "")) } } override fun onDestroy() { progressDialog?.dismiss() super.onDestroy() } private fun attemptLogin() { if (validate()) { showProgress() invokeLoginAPI() } } private fun showProgress() { progressDialog?.show() } override fun invokeLoginAPI() { GlobalScope.launch { when ( val response = withContext(Dispatchers.Default) { login( resetPasswordPhoneNumberEditText.text.toString().trim(), resetPasswordEditText.text.toString() ) } ) { is ResultWrapper.Success -> navigateToHome(response.value.data.access_token) is ResultWrapper.GenericError -> handleGenericError(response, true) is ResultWrapper.NetworkError -> handleNetworkError() } hideProgress() } } private fun hideProgress() { runOnUiThread { progressDialog?.hide() } } override fun validatePhone(): Boolean { val isValid = resetPasswordPhoneNumberEditText.text.isAValidIndianPhoneNumber() if (!isValid) { showErrorDialog(getString(R.string.incorrect_phone_number)) } return isValid } private fun showErrorDialog(errorMessage: String) { alert { message = errorMessage title = getString(R.string.incorrect_input) positiveButton(R.string.ok) { it.dismiss() } }.show() } override fun validatePassword(): Boolean { val isValid = resetPasswordEditText.text.isNotEmpty() if (!isValid) { showErrorDialog(getString(R.string.please_enter_your_password)) } return isValid } override fun navigateToHome(accessToken: String) { prefs.accessToken = accessToken hideProgress() Intent(this, HomeActivity::class.java).let(::startActivity) finish() } override fun validate(): Boolean { return validatePhone() && validatePassword() } }
0
Kotlin
4
4
6d2a50455b63d43d48486e657419e1fef95d1826
4,333
superhero_app
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateGeospatialCoordinateBoundsPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.quicksight import cloudshift.awscdk.common.CdkDslMarker import kotlin.Number import software.amazon.awscdk.services.quicksight.CfnAnalysis /** * The bound options (north, south, west, east) of the geospatial window options. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.quicksight.*; * GeospatialCoordinateBoundsProperty geospatialCoordinateBoundsProperty = * GeospatialCoordinateBoundsProperty.builder() * .east(123) * .north(123) * .south(123) * .west(123) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-geospatialcoordinatebounds.html) */ @CdkDslMarker public class CfnAnalysisGeospatialCoordinateBoundsPropertyDsl { private val cdkBuilder: CfnAnalysis.GeospatialCoordinateBoundsProperty.Builder = CfnAnalysis.GeospatialCoordinateBoundsProperty.builder() /** @param east The longitude of the east bound of the geospatial coordinate bounds. */ public fun east(east: Number) { cdkBuilder.east(east) } /** @param north The latitude of the north bound of the geospatial coordinate bounds. */ public fun north(north: Number) { cdkBuilder.north(north) } /** @param south The latitude of the south bound of the geospatial coordinate bounds. */ public fun south(south: Number) { cdkBuilder.south(south) } /** @param west The longitude of the west bound of the geospatial coordinate bounds. */ public fun west(west: Number) { cdkBuilder.west(west) } public fun build(): CfnAnalysis.GeospatialCoordinateBoundsProperty = cdkBuilder.build() }
4
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
2,036
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/ca/on/hojat/gamenews/feature_info/presentation/widgets/header/InfoScreenHeader.kt
hojat72elect
574,228,468
false
null
@file:Suppress("LongMethod") package ca.hojat.gamehub.feature_info.presentation.widgets.header import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Dimension import ca.hojat.gamehub.R import ca.hojat.gamehub.common_ui.clickable import ca.hojat.gamehub.common_ui.theme.GameHubTheme import ca.hojat.gamehub.common_ui.theme.lightScrim import ca.hojat.gamehub.common_ui.theme.subtitle3 import ca.hojat.gamehub.common_ui.widgets.GameCover import ca.hojat.gamehub.common_ui.widgets.Info import ca.hojat.gamehub.feature_info.presentation.widgets.header.artworks.Artworks import ca.hojat.gamehub.feature_info.presentation.widgets.header.artworks.InfoScreenArtworkUiModel private const val ConstraintIdArtworks = "artworks" private const val ConstraintIdArtworksScrim = "artworks_scrim" private const val ConstraintIdBackButton = "back_button" private const val ConstraintIdPageIndicator = "page_indicator" private const val ConstraintIdBackdrop = "backdrop" private const val ConstraintIdCoverSpace = "cover_space" private const val ConstraintIdCover = "cover" private const val ConstraintIdLikeButton = "like_button" private const val ConstraintIdFirstTitle = "first_title" private const val ConstraintIdSecondTitle = "second_title" private const val ConstraintIdReleaseDate = "release_date" private const val ConstraintIdDeveloperName = "developer_name" private const val ConstraintIdRating = "rating" private const val ConstraintIdLikeCount = "like_count" private const val ConstraintIdAgeRating = "age_rating" private const val ConstraintIdGameCategory = "game_category" private val CoverSpace = 40.dp private val InfoIconSize = 34.dp @Composable fun InfoScreenHeader( headerInfo: InfoScreenHeaderUiModel, onArtworkClicked: (artworkIndex: Int) -> Unit, onBackButtonClicked: () -> Unit, onCoverClicked: () -> Unit, onLikeButtonClicked: () -> Unit, ) { val artworks = headerInfo.artworks val isPageIndicatorVisible by remember(artworks) { mutableStateOf(artworks.size > 1) } var selectedArtworkPage by rememberSaveable { mutableStateOf(0) } var secondTitleText by rememberSaveable { mutableStateOf("") } val isSecondTitleVisible by remember { derivedStateOf { secondTitleText.isNotEmpty() } } ConstraintLayout( constraintSet = constructExpandedConstraintSet(), modifier = Modifier.fillMaxWidth(), ) { Artworks( artworks = artworks, isScrollingEnabled = true, modifier = Modifier.layoutId(ConstraintIdArtworks), onArtworkChanged = { page -> selectedArtworkPage = page }, onArtworkClicked = if (headerInfo.artworks.any { artWork -> artWork is InfoScreenArtworkUiModel.UrlImage }) onArtworkClicked else null, ) Box( modifier = Modifier .layoutId(ConstraintIdArtworksScrim) .background(Color.Transparent), ) Icon( painter = painterResource(R.drawable.arrow_left), contentDescription = null, modifier = Modifier .layoutId(ConstraintIdBackButton) .statusBarsPadding() .size(56.dp) .clickable( indication = rememberRipple( bounded = false, radius = 18.dp, ), onClick = onBackButtonClicked, ) .padding(GameHubTheme.spaces.spacing_2_5) .background( color = GameHubTheme.colors.lightScrim, shape = CircleShape, ) .padding(GameHubTheme.spaces.spacing_1_5), tint = Color.White, ) if (isPageIndicatorVisible) { Text( text = stringResource( R.string.game_info_header_page_indicator_template, selectedArtworkPage + 1, headerInfo.artworks.size, ), modifier = Modifier .layoutId(ConstraintIdPageIndicator) .statusBarsPadding() .background( color = GameHubTheme.colors.lightScrim, shape = RoundedCornerShape(20.dp), ) .padding( vertical = GameHubTheme.spaces.spacing_1_5, horizontal = GameHubTheme.spaces.spacing_2_0, ), color = Color.White, style = GameHubTheme.typography.subtitle3, ) } Box( modifier = Modifier .layoutId(ConstraintIdBackdrop) .shadow( elevation = GameHubTheme.spaces.spacing_0_5, shape = RectangleShape, clip = false, ) .background( color = GameHubTheme.colors.surface, shape = RectangleShape, ) .clip(RectangleShape), ) Spacer( modifier = Modifier .layoutId(ConstraintIdCoverSpace) .height(CoverSpace), ) GameCover( title = null, imageUrl = headerInfo.coverImageUrl, modifier = Modifier.layoutId(ConstraintIdCover), onCoverClicked = if (headerInfo.hasCoverImageUrl) onCoverClicked else null, ) val state = remember { LikeButtonState() } state.isLiked = headerInfo.isLiked LikeButton( resId = R.raw.like_animation, modifier = Modifier.layoutId(ConstraintIdLikeButton), onClick = onLikeButtonClicked, state = state ) Text( text = headerInfo.title, modifier = Modifier.layoutId(ConstraintIdFirstTitle), color = GameHubTheme.colors.onPrimary, maxLines = 1, onTextLayout = { textLayoutResult -> if (textLayoutResult.hasVisualOverflow) { val firstTitleWidth = textLayoutResult.size.width.toFloat() val firstTitleOffset = Offset(firstTitleWidth, 0f) val firstTitleVisibleTextEndIndex = textLayoutResult.getOffsetForPosition(firstTitleOffset) + 1 secondTitleText = headerInfo.title.substring(firstTitleVisibleTextEndIndex) } }, style = GameHubTheme.typography.h6, ) Box(modifier = Modifier.layoutId(ConstraintIdSecondTitle)) { if (isSecondTitleVisible) { // Remove font padding once https://issuetracker.google.com/issues/171394808 // is implemented (includeFontPadding="false" in XML) Text( text = secondTitleText, color = GameHubTheme.colors.onPrimary, maxLines = 2, overflow = TextOverflow.Ellipsis, style = GameHubTheme.typography.h6, ) } } Text( text = headerInfo.releaseDate, modifier = Modifier.layoutId(ConstraintIdReleaseDate), color = GameHubTheme.colors.onSurface, style = GameHubTheme.typography.subtitle3, ) Box(modifier = Modifier.layoutId(ConstraintIdDeveloperName)) { if (headerInfo.hasDeveloperName) { Text( text = checkNotNull(headerInfo.developerName), color = GameHubTheme.colors.onSurface, style = GameHubTheme.typography.subtitle3, ) } } Info( icon = painterResource(R.drawable.star_circle_outline), title = headerInfo.rating, modifier = Modifier.layoutId(ConstraintIdRating), iconSize = InfoIconSize, titleTextStyle = GameHubTheme.typography.caption, ) Info( icon = painterResource(R.drawable.account_heart_outline), title = headerInfo.likeCount, modifier = Modifier.layoutId(ConstraintIdLikeCount), iconSize = InfoIconSize, titleTextStyle = GameHubTheme.typography.caption, ) Info( icon = painterResource(R.drawable.age_rating_outline), title = headerInfo.ageRating, modifier = Modifier.layoutId(ConstraintIdAgeRating), iconSize = InfoIconSize, titleTextStyle = GameHubTheme.typography.caption, ) Info( icon = painterResource(R.drawable.shape_outline), title = headerInfo.gameCategory, modifier = Modifier.layoutId(ConstraintIdGameCategory), iconSize = InfoIconSize, titleTextStyle = GameHubTheme.typography.caption, ) } } @Composable private fun constructExpandedConstraintSet(): ConstraintSet { val artworksHeight = 240.dp val pageIndicatorMargin = GameHubTheme.spaces.spacing_2_5 val coverSpaceMargin = CoverSpace val coverMarginStart = GameHubTheme.spaces.spacing_3_5 val likeBtnMarginEnd = GameHubTheme.spaces.spacing_2_5 val titleMarginStart = GameHubTheme.spaces.spacing_3_5 val firstTitleMarginEnd = GameHubTheme.spaces.spacing_1_0 val secondTitleMarginEnd = GameHubTheme.spaces.spacing_3_5 val releaseDateMarginTop = GameHubTheme.spaces.spacing_2_5 val releaseDateMarginHorizontal = GameHubTheme.spaces.spacing_3_5 val developerNameMarginHorizontal = GameHubTheme.spaces.spacing_3_5 val bottomBarrierMargin = GameHubTheme.spaces.spacing_5_0 val infoItemMarginBottom = GameHubTheme.spaces.spacing_3_5 return ConstraintSet { val artworks = createRefFor(ConstraintIdArtworks) val artworksScrim = createRefFor(ConstraintIdArtworksScrim) val backButton = createRefFor(ConstraintIdBackButton) val pageIndicator = createRefFor(ConstraintIdPageIndicator) val backdrop = createRefFor(ConstraintIdBackdrop) val coverSpace = createRefFor(ConstraintIdCoverSpace) val cover = createRefFor(ConstraintIdCover) val likeButton = createRefFor(ConstraintIdLikeButton) val firstTitle = createRefFor(ConstraintIdFirstTitle) val secondTitle = createRefFor(ConstraintIdSecondTitle) val releaseDate = createRefFor(ConstraintIdReleaseDate) val developerName = createRefFor(ConstraintIdDeveloperName) val bottomBarrier = createBottomBarrier(cover, developerName, margin = bottomBarrierMargin) val rating = createRefFor(ConstraintIdRating) val likeCount = createRefFor(ConstraintIdLikeCount) val ageRating = createRefFor(ConstraintIdAgeRating) val gameCategory = createRefFor(ConstraintIdGameCategory) constrain(artworks) { width = Dimension.fillToConstraints height = Dimension.value(artworksHeight) top.linkTo(parent.top) centerHorizontallyTo(parent) } constrain(artworksScrim) { width = Dimension.fillToConstraints height = Dimension.fillToConstraints centerVerticallyTo(artworks) centerHorizontallyTo(artworks) } constrain(backButton) { top.linkTo(parent.top) start.linkTo(parent.start) } constrain(pageIndicator) { top.linkTo(parent.top, pageIndicatorMargin) end.linkTo(parent.end, pageIndicatorMargin) } constrain(backdrop) { width = Dimension.fillToConstraints height = Dimension.fillToConstraints top.linkTo(artworks.bottom) bottom.linkTo(parent.bottom) centerHorizontallyTo(parent) } constrain(coverSpace) { start.linkTo(parent.start) bottom.linkTo(artworks.bottom, coverSpaceMargin) } constrain(cover) { top.linkTo(coverSpace.bottom) start.linkTo(parent.start, coverMarginStart) } constrain(likeButton) { top.linkTo(artworks.bottom) bottom.linkTo(artworks.bottom) end.linkTo(parent.end, likeBtnMarginEnd) } constrain(firstTitle) { width = Dimension.fillToConstraints top.linkTo(artworks.bottom, titleMarginStart) start.linkTo(cover.end, titleMarginStart) end.linkTo(likeButton.start, firstTitleMarginEnd) } constrain(secondTitle) { width = Dimension.fillToConstraints top.linkTo(firstTitle.bottom) start.linkTo(cover.end, titleMarginStart) end.linkTo(parent.end, secondTitleMarginEnd) } constrain(releaseDate) { width = Dimension.fillToConstraints top.linkTo(secondTitle.bottom, releaseDateMarginTop) start.linkTo(cover.end, releaseDateMarginHorizontal) end.linkTo(parent.end, releaseDateMarginHorizontal) } constrain(developerName) { width = Dimension.fillToConstraints top.linkTo(releaseDate.bottom) start.linkTo(cover.end, developerNameMarginHorizontal) end.linkTo(parent.end, developerNameMarginHorizontal) } constrain(rating) { width = Dimension.fillToConstraints top.linkTo(bottomBarrier) bottom.linkTo(parent.bottom, infoItemMarginBottom) linkTo(start = parent.start, end = likeCount.start, bias = 0.25f) } constrain(likeCount) { width = Dimension.fillToConstraints top.linkTo(bottomBarrier) bottom.linkTo(parent.bottom, infoItemMarginBottom) linkTo(start = rating.end, end = ageRating.start, bias = 0.25f) } constrain(ageRating) { width = Dimension.fillToConstraints top.linkTo(bottomBarrier) bottom.linkTo(parent.bottom, infoItemMarginBottom) linkTo(start = likeCount.end, end = gameCategory.start, bias = 0.25f) } constrain(gameCategory) { width = Dimension.fillToConstraints top.linkTo(bottomBarrier) bottom.linkTo(parent.bottom, infoItemMarginBottom) linkTo(start = ageRating.end, end = parent.end, bias = 0.25f) } } } @Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun InfoScreenHeaderPreview() { GameHubTheme { InfoScreenHeader( headerInfo = InfoScreenHeaderUiModel( artworks = listOf(InfoScreenArtworkUiModel.DefaultImage), isLiked = true, coverImageUrl = null, title = "<NAME>", releaseDate = "Feb 25, 2022 (in a month)", developerName = "FromSoftware", rating = "N/A", likeCount = "92", ageRating = "N/A", gameCategory = "Main", ), onArtworkClicked = {}, onBackButtonClicked = {}, onCoverClicked = {}, onLikeButtonClicked = {}, ) } }
0
null
8
4
b1c07551e90790ee3d273bc4c0ad3a5f97f71202
17,060
GameHub
MIT License
sms-core/src/main/kotlin/team/msg/sms/domain/region/spi/QueryRegionPort.kt
GSM-MSG
625,717,097
false
{"Kotlin": 529642, "Shell": 1480, "Dockerfile": 288}
package team.msg.sms.domain.region.spi import team.msg.sms.domain.region.model.Region import java.util.* interface QueryRegionPort { fun queryByStudentUuid(uuid: UUID): List<Region> }
7
Kotlin
0
9
b602a6b4c00cba7291f2bdb570868d6e0fc05294
189
SMS-BackEnd
MIT License
analysis/symbol-light-classes/src/org/jetbrains/kotlin/light/classes/symbol/fields/SymbolLightFieldForObject.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.light.classes.symbol.fields import com.intellij.psi.PsiExpression import com.intellij.psi.PsiModifier import com.intellij.psi.PsiModifierList import com.intellij.psi.PsiType import kotlinx.collections.immutable.mutate import org.jetbrains.annotations.NotNull import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.analysis.api.symbols.sourcePsiSafe import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin import org.jetbrains.kotlin.asJava.classes.lazyPub import org.jetbrains.kotlin.light.classes.symbol.annotations.SymbolLightSimpleAnnotation import org.jetbrains.kotlin.light.classes.symbol.annotations.hasDeprecatedAnnotation import org.jetbrains.kotlin.light.classes.symbol.classes.SymbolLightClassForClassLike import org.jetbrains.kotlin.light.classes.symbol.compareSymbolPointers import org.jetbrains.kotlin.light.classes.symbol.isValid import org.jetbrains.kotlin.light.classes.symbol.modifierLists.LazyModifiersBox import org.jetbrains.kotlin.light.classes.symbol.modifierLists.SymbolLightMemberModifierList import org.jetbrains.kotlin.light.classes.symbol.nonExistentType import org.jetbrains.kotlin.light.classes.symbol.withSymbol import org.jetbrains.kotlin.psi.KtObjectDeclaration internal class SymbolLightFieldForObject private constructor( containingClass: SymbolLightClassForClassLike<*>, private val name: String, lightMemberOrigin: LightMemberOrigin?, private val objectSymbolPointer: KtSymbolPointer<KtNamedClassOrObjectSymbol>, override val kotlinOrigin: KtObjectDeclaration?, ) : SymbolLightField(containingClass, lightMemberOrigin) { internal constructor( ktAnalysisSession: KtAnalysisSession, objectSymbol: KtNamedClassOrObjectSymbol, name: String, lightMemberOrigin: LightMemberOrigin?, containingClass: SymbolLightClassForClassLike<*>, ) : this( containingClass = containingClass, name = name, lightMemberOrigin = lightMemberOrigin, kotlinOrigin = objectSymbol.sourcePsiSafe(), objectSymbolPointer = with(ktAnalysisSession) { objectSymbol.createPointer() }, ) private inline fun <T> withObjectDeclarationSymbol(crossinline action: KtAnalysisSession.(KtNamedClassOrObjectSymbol) -> T): T = objectSymbolPointer.withSymbol(ktModule, action) override fun getName(): String = name private val _modifierList: PsiModifierList by lazyPub { SymbolLightMemberModifierList( containingDeclaration = this, initialValue = LazyModifiersBox.MODALITY_MODIFIERS_MAP.mutate { it[PsiModifier.FINAL] = true it[PsiModifier.STATIC] = true }, lazyModifiersComputer = ::computeModifiers, ) { modifierList -> listOf(SymbolLightSimpleAnnotation(NotNull::class.java.name, modifierList)) } } private fun computeModifiers(modifier: String): Map<String, Boolean>? { if (modifier !in LazyModifiersBox.VISIBILITY_MODIFIERS) return null return LazyModifiersBox.computeVisibilityForMember(ktModule, objectSymbolPointer) } private val _isDeprecated: Boolean by lazyPub { withObjectDeclarationSymbol { objectSymbol -> objectSymbol.hasDeprecatedAnnotation() } } override fun isDeprecated(): Boolean = _isDeprecated override fun getModifierList(): PsiModifierList = _modifierList private val _type: PsiType by lazyPub { withObjectDeclarationSymbol { objectSymbol -> objectSymbol.buildSelfClassType().asPsiType(this@SymbolLightFieldForObject) } ?: nonExistentType() } override fun getType(): PsiType = _type override fun getInitializer(): PsiExpression? = null //TODO override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SymbolLightFieldForObject || other.ktModule != ktModule) return false if (kotlinOrigin != null || other.kotlinOrigin != null) { return other.kotlinOrigin == kotlinOrigin } return other.containingClass == containingClass && compareSymbolPointers(other.objectSymbolPointer, objectSymbolPointer) } override fun hashCode(): Int = kotlinOrigin.hashCode() override fun isValid(): Boolean = kotlinOrigin?.isValid ?: objectSymbolPointer.isValid(ktModule) }
7
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
4,783
kotlin
Apache License 2.0
compiler/build-tools/kotlin-build-statistics/src/org/jetbrains/kotlin/build/report/metrics/BuildAttribute.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.build.report.metrics import java.io.Serializable enum class BuildAttributeKind : Serializable { REBUILD_REASON; companion object { const val serialVersionUID = 0L } } enum class BuildAttribute(val kind: BuildAttributeKind, val readableString: String) : Serializable { NO_BUILD_HISTORY(BuildAttributeKind.REBUILD_REASON, "Build history file not found"), NO_ABI_SNAPSHOT(BuildAttributeKind.REBUILD_REASON, "ABI snapshot not found"), CACHE_CORRUPTION(BuildAttributeKind.REBUILD_REASON, "Cache corrupted"), UNKNOWN_CHANGES_IN_GRADLE_INPUTS(BuildAttributeKind.REBUILD_REASON, "Unknown Gradle changes"), JAVA_CHANGE_UNTRACKED_FILE_IS_REMOVED(BuildAttributeKind.REBUILD_REASON, "Untracked Java file is removed"), JAVA_CHANGE_UNEXPECTED_PSI(BuildAttributeKind.REBUILD_REASON, "Java PSI file is expected"), JAVA_CHANGE_UNKNOWN_QUALIFIER(BuildAttributeKind.REBUILD_REASON, "Unknown Java qualifier name"), DEP_CHANGE_REMOVED_ENTRY(BuildAttributeKind.REBUILD_REASON, "Jar file is removed form dependency"), DEP_CHANGE_HISTORY_IS_NOT_FOUND(BuildAttributeKind.REBUILD_REASON, "Dependency history not found"), DEP_CHANGE_HISTORY_CANNOT_BE_READ(BuildAttributeKind.REBUILD_REASON, "Dependency history can not be read"), DEP_CHANGE_HISTORY_NO_KNOWN_BUILDS(BuildAttributeKind.REBUILD_REASON, "Dependency history id not available"), DEP_CHANGE_NON_INCREMENTAL_BUILD_IN_DEP(BuildAttributeKind.REBUILD_REASON, "Non incremental build in history"), IN_PROCESS_EXECUTION(BuildAttributeKind.REBUILD_REASON, "In-process execution"), OUT_OF_PROCESS_EXECUTION(BuildAttributeKind.REBUILD_REASON, "Out of process execution"), IC_IS_NOT_ENABLED(BuildAttributeKind.REBUILD_REASON, "Incremental compilation is not enabled"); companion object { const val serialVersionUID = 0L } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,086
kotlin
Apache License 2.0
apps/samples/src/main/kotlin/io/agora/meeting/example/uicontroller/LecturerLayout.kt
AgoraIO-Usecase
390,732,016
false
null
package io.agora.meeting.example.uicontroller import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.agora.meeting.R import io.agora.meeting.annotation.Example import io.agora.meeting.common.model.Examples import io.agora.meeting.ui.base.KBaseFragment import io.agora.meeting.ui.module.main.render.lecturer.LecturerLayoutUC @Example( index = 12, group = Examples.GROUP_UI_CONTROLLER, nameStrId = R.string.ui_controller_lecturer_layout, tipStrId = R.string.ui_controller_lecturer_layout_tip ) class LecturerLayout : KBaseFragment() { private val lecturerLayoutUC by lazy { createUiController(LecturerLayoutUC::class.java).apply { statsDisplayEnable = true mainRenderId = 1 } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.layout_container, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lecturerLayoutUC.createViewBinding(requireContext(), viewLifecycleOwner, view.findViewById(R.id.container)) lecturerLayoutUC.bindViewModel(this) } }
3
Kotlin
4
6
25739896f4a20e9e0fa01a005dc361b1030192c1
1,318
AgoraMeeting-Android
MIT License
src/main/kotlin/com/terraformation/backend/tracking/model/ObservationPlotModel.kt
terraware
323,722,525
false
{"Kotlin": 3666257, "HTML": 86728, "Python": 44051, "FreeMarker": 16407, "PLpgSQL": 3305, "Makefile": 746, "Dockerfile": 674}
package com.terraformation.backend.tracking.model import com.terraformation.backend.db.default_schema.UserId import com.terraformation.backend.db.tracking.MonitoringPlotId import com.terraformation.backend.db.tracking.ObservationId import com.terraformation.backend.db.tracking.tables.references.OBSERVATION_PLOTS import java.time.Instant import org.jooq.Record data class ObservationPlotModel( val claimedBy: UserId? = null, val claimedTime: Instant? = null, val completedBy: UserId? = null, val completedTime: Instant? = null, val isPermanent: Boolean, val monitoringPlotId: MonitoringPlotId, val notes: String? = null, val observedTime: Instant? = null, val observationId: ObservationId, ) { companion object { fun of(record: Record): ObservationPlotModel { return ObservationPlotModel( claimedBy = record[OBSERVATION_PLOTS.CLAIMED_BY], claimedTime = record[OBSERVATION_PLOTS.CLAIMED_TIME], completedBy = record[OBSERVATION_PLOTS.COMPLETED_BY], completedTime = record[OBSERVATION_PLOTS.COMPLETED_TIME], isPermanent = record[OBSERVATION_PLOTS.IS_PERMANENT]!!, monitoringPlotId = record[OBSERVATION_PLOTS.MONITORING_PLOT_ID]!!, notes = record[OBSERVATION_PLOTS.NOTES], observedTime = record[OBSERVATION_PLOTS.OBSERVED_TIME], observationId = record[OBSERVATION_PLOTS.OBSERVATION_ID]!!, ) } } }
6
Kotlin
1
9
5dcea95423dc6a6960a87fc8ccbdbbdb1e0ea785
1,446
terraware-server
Apache License 2.0
ceria/02/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File; fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input: List<String>) :Int { var validPasswordIndexes = mutableListOf<Int>() input.forEachIndexed { index, line -> val parts = line.split(" ") val minmax = parts.get(0).split("-").map{ it.toInt() } val range = IntRange(minmax.get(0), minmax.get(1)) val countInPasswd = parts.get(2).count{ parts.get(1).dropLast(1).contains(it) } if (range.contains(countInPasswd)) { validPasswordIndexes.add(index) } } return validPasswordIndexes.size } private fun solution2(input: List<String>) :Int { var validPasswordIndexes = mutableListOf<Int>() input.forEachIndexed { index, line -> val parts = line.split(" ") val minmax = parts.get(0).split("-").map{ it.toInt() } val range = IntRange(minmax.get(0), minmax.get(1)) if ((parts.get(2).get(range.start - 1) == parts.get(1).dropLast(1).single()).xor( (parts.get(2).get(range.endInclusive - 1) == parts.get(1).dropLast(1).single())) ) { validPasswordIndexes.add(index) } } return validPasswordIndexes.size }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
1,343
advent-of-code-2020
MIT License
shared/src/commonMain/kotlin/com/erendev/gemini/common/resources/Strings.kt
erenalpaslan
735,675,016
false
{"Kotlin": 127277, "JavaScript": 1780, "Swift": 773, "HTML": 231}
package com.erendev.gemini.common.resources /** * Created by erenalpaslan on 25.05.2023 */ object Strings { const val APP_NAME = "Gemini" const val ChatTitle = "Chat" object Button { const val Continue = "Continue" const val Delete = "Delete" const val Rename = "Rename" const val ViewDetails = "View Details" const val NewChat = "New Chat" const val Save = "Save" } object Onboarding { fun letsDo(action: String): String = "Let's $action" const val CREATE = "create" const val GO = "go" const val DESIGN = "design" const val BRAINSTORM = "brainstorm" const val EXPLORE = "explore" const val CHIT_CHAT = "chit-chat" } object Welcome { const val WELCOME_TITLE = "Welcome to\nGeminiChat" const val WELCOME_DESC = "This app uses Gemini AI, syncs your history in your device and brings latest improvements from Gemini" const val TITLE_ONE = "The Gemini era: enabling a future of innovation" const val DESC_ONE = "This is a significant milestone in the development of AI, and the start of a new era for us at Google as we continue to rapidly innovate and responsibly advance the capabilities of our models." const val TITLE_SECOND = "Next-generation capabilities" const val DESC_SECOND = "Gemini is natively multimodal, pre-trained from the start on different modalities" const val TITLE_THIRD = "Built with responsibility and safety at the core" const val DESC_THIRD = "Building upon Google’s AI Principles and the robust safety policies across google's products, new protections to account for Gemini’s multimodal capabilities" } object ViewDetail { const val ModelInfo = "Model Info" const val DefaultAiModel = "Default (Gemini-Pro)" const val ModelDescription = "Best model for scaling across a wide range of tasks." } object Chat { const val Message = "Message" const val Search = "Search" const val Title = "Title" const val RenameChat = "Rename Chat" } }
0
Kotlin
0
1
219835105a0ac011d42585fb4e5bead2ff721196
2,137
gemini
MIT License
app/src/main/java/com/ave/vastgui/app/network/service/SuspendService.kt
SakurajimaMaii
353,212,367
false
null
/* * 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.app.network.service import com.ave.vastgui.app.network.QRCodeKey import com.ave.vastgui.tools.network.response.ResponseBuilder import retrofit2.http.POST import retrofit2.http.Query // Author: <NAME> // Email: <EMAIL> // Date: 2023/6/7 // Description: // Documentation: // Reference: /** * The service when you use [ResponseBuilder] to request data. */ interface SuspendService { @POST("/login/qr/key") suspend fun generateQRCode(@Query("timestamp") timestamp: String): QRCodeKey }
2
null
4
38
23759b1c4e89b78cc76f2755d397954bb28ed9fc
1,117
Android-Vast-Extension
Apache License 2.0
util/src/test/kotlin/com/lomeone/util/security/authentication/PasswordUtilsTest.kt
lomeone
583,942,276
false
{"Kotlin": 105805, "Smarty": 1861}
package com.lomeone.util.security.authentication import com.lomeone.util.security.authentication.PasswordUtils.checkPasswordValidity import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FreeSpec class PasswordUtilsTest : FreeSpec({ "비밀번호의 형식이 맞는지 검증할 수 있다" - { shouldThrow<IllegalArgumentException> { checkPasswordValidity("") } shouldThrow<IllegalArgumentException> { checkPasswordValidity("<PASSWORD>") } checkPasswordValidity("<PASSWORD>") } })
4
Kotlin
0
0
480a369035240983e71db4144cddd343b46dc1d5
555
lomeone-server
MIT License
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/ui/destinations/agile/components/GaugeWidget.kt
ryanw-mobile
794,752,204
false
{"Kotlin": 1440473, "Ruby": 2466, "Swift": 693}
/* * Copyright (c) 2024. RW MobiMedia UK Limited * * Contributions made by other developers remain the property of their respective authors but are licensed * to RW MobiMedia UK Limited and others under the same licence terms as the main project, as outlined in * the LICENSE file. * * RW MobiMedia UK Limited reserves the exclusive right to distribute this application on app stores. * Reuse of this source code, with or without modifications, requires proper attribution to * RW MobiMedia UK Limited. Commercial distribution of this code or its derivatives without prior written * permission from RW MobiMedia UK Limited is prohibited. * * Please refer to the LICENSE file for the full terms and conditions. */ package com.rwmobi.kunigami.ui.destinations.agile.components import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Density import com.rwmobi.kunigami.ui.components.CommonPreviewSetup import com.rwmobi.kunigami.ui.composehelper.drawHalfCircleArcSegment import com.rwmobi.kunigami.ui.composehelper.drawPlainColorArc import com.rwmobi.kunigami.ui.composehelper.palette.RatePalette import com.rwmobi.kunigami.ui.composehelper.palette.generateGYRHueSpectrum import com.rwmobi.kunigami.ui.composehelper.shouldUseDarkTheme import kunigami.composeapp.generated.resources.Res import kunigami.composeapp.generated.resources.agile_expire import org.jetbrains.compose.resources.stringResource /*** * percentage: can be negative */ @Composable internal fun GaugeWidget( modifier: Modifier, percentage: Float, countDownText: String?, colorPalette: List<Color>, ) { val countDownTextMagicWidth = 480f var textBoundWidth by remember { mutableStateOf(countDownTextMagicWidth) } val fontScale = remember(textBoundWidth) { textBoundWidth / countDownTextMagicWidth } val animatedPercentage by animateFloatAsState( targetValue = percentage, animationSpec = tween(durationMillis = 1_000, easing = FastOutSlowInEasing), ) var breathingColor by remember { mutableStateOf(Color.Transparent) } var isAnimatedPercentageComplete by remember { mutableStateOf(false) } val shouldUseDarkTheme = shouldUseDarkTheme() LaunchedEffect(animatedPercentage) { isAnimatedPercentageComplete = animatedPercentage == percentage } if (isAnimatedPercentageComplete && animatedPercentage <= 0) { val infiniteTransition = rememberInfiniteTransition() val breathingPercentage by infiniteTransition.animateFloat( initialValue = animatedPercentage, targetValue = 0f, animationSpec = infiniteRepeatable( animation = tween(durationMillis = 2_000, easing = LinearEasing), repeatMode = RepeatMode.Reverse, ), ) breathingColor = RatePalette.lookupColorFromPercentage( percentage = breathingPercentage, shouldUseDarkTheme = shouldUseDarkTheme, ) } Box( modifier = modifier .aspectRatio( ratio = 2f, matchHeightConstraintsFirst = true, ) // Ensure the aspect ratio is 2:1 .drawBehind { if (animatedPercentage >= 0) { drawHalfCircleArcSegment( percentage = animatedPercentage, colorPalette = colorPalette, onInnerSpaceMeasured = { width, _ -> textBoundWidth = width }, ) } else { drawPlainColorArc( color = if (isAnimatedPercentageComplete) { breathingColor } else { RatePalette.lookupColorFromPercentage( percentage = animatedPercentage, shouldUseDarkTheme = shouldUseDarkTheme, ) }, onInnerSpaceMeasured = { width, _ -> textBoundWidth = width }, ) } }, contentAlignment = Alignment.BottomCenter, ) { countDownText?.let { CompositionLocalProvider( LocalDensity provides Density( density = 2.625f, fontScale = fontScale, ), ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Bottom, ) { Text( style = MaterialTheme.typography.bodyMedium.copy( lineHeightStyle = LineHeightStyle( alignment = LineHeightStyle.Alignment.Bottom, trim = LineHeightStyle.Trim.Both, ), ), maxLines = 1, textAlign = TextAlign.Center, text = stringResource(resource = Res.string.agile_expire), ) Text( style = MaterialTheme.typography.headlineMedium.copy( lineHeightStyle = LineHeightStyle( alignment = LineHeightStyle.Alignment.Bottom, trim = LineHeightStyle.Trim.Both, ), ), maxLines = 1, textAlign = TextAlign.Center, text = it, ) } } } } } @Preview @Composable private fun Preview() { CommonPreviewSetup { GaugeWidget( modifier = Modifier.aspectRatio(ratio = 2f), colorPalette = generateGYRHueSpectrum(), countDownText = "33:33", percentage = 0.8f, ) } }
16
Kotlin
10
145
7f278204448e9c59ca028e520e9e5aca97fa1e13
7,486
OctoMeter
Creative Commons Attribution 4.0 International
legacy/storage/src/main/java/com/fsck/k9/storage/messages/DatabaseOperations.kt
thunderbird
1,326,671
false
{"Kotlin": 4766001, "Java": 2159946, "Shell": 2768, "AIDL": 1946}
package com.fsck.k9.storage.messages import com.fsck.k9.mailstore.LockableDatabase import com.fsck.k9.mailstore.StorageManager import timber.log.Timber internal class DatabaseOperations( private val lockableDatabase: LockableDatabase, val storageManager: StorageManager, val accountUuid: String ) { fun getSize(): Long { val storageProviderId = lockableDatabase.storageProviderId val attachmentDirectory = storageManager.getAttachmentDirectory(accountUuid, storageProviderId) return lockableDatabase.execute(false) { val attachmentFiles = attachmentDirectory.listFiles() ?: emptyArray() val attachmentsSize = attachmentFiles.asSequence() .filter { file -> file.exists() } .fold(initial = 0L) { accumulatedSize, file -> accumulatedSize + file.length() } val databaseFile = storageManager.getDatabase(accountUuid, storageProviderId) val databaseSize = databaseFile.length() databaseSize + attachmentsSize } } fun compact() { Timber.i("Before compaction size = %d", getSize()) lockableDatabase.execute(false) { database -> database.execSQL("VACUUM") } Timber.i("After compaction size = %d", getSize()) } }
846
Kotlin
5
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
1,343
thunderbird-android
Apache License 2.0
dokilog/src/main/java/com/dokidevs/dokilog/DokiLog.kt
tingyik90
154,005,099
false
null
@file:Suppress("NOTHING_TO_INLINE") package com.dokidevs.dokilog import android.util.Log /** * Main interface for DokiLog. See [LogProfile] to customize logging. */ interface DokiLog { /* companion object */ companion object { private val mutableLogProfiles = mutableListOf<LogProfile>() private var logProfiles = arrayOf<LogProfile>() /** * Add a log profile. This is similar to planting a tree in Timber (by <NAME>). * The profile name must be unique. Newly added profile will overwrite the old profile with the same name. * @param logProfile Customizable [LogProfile] which is identified by its name. */ fun addProfile(logProfile: LogProfile) { synchronized(mutableLogProfiles) { if (mutableLogProfiles.contains(logProfile)) { mutableLogProfiles.remove(logProfile) } mutableLogProfiles.add(logProfile) logProfiles = mutableLogProfiles.toTypedArray() } } /** * Remove a log profile. This is similar to uprooting a tree in Timber (by <NAME>). * @param logProfile Customizable [LogProfile] which is identified by its name. */ fun removeProfile(logProfile: LogProfile) { synchronized(mutableLogProfiles) { mutableLogProfiles.remove(logProfile) logProfiles = mutableLogProfiles.toTypedArray() } } /** * Remove all log profiles. */ fun clearAllProfiles() { synchronized(mutableLogProfiles) { mutableLogProfiles.clear() logProfiles = arrayOf() } } /** * Check if log profiles are present before dispatching the log. * @return true if [logProfiles] is not empty. */ fun hasLogProfiles(): Boolean { synchronized(logProfiles) { return logProfiles.isNotEmpty() } } /** * Actual execution method to loop through all log profiles. Entry point to [LogProfile.prepareLog]. * You usually will not call this method directly. */ fun log(priority: Int, className: String, message: String? = null, t: Throwable? = null) { val _logProfiles = logProfiles for (logProfile in _logProfiles) { logProfile.prepareLog(priority, t, message, className) } } } /** * Enable log for the class which DokiLog interface is attached to. * Override this to enable or disable log for the class. */ val enableClassLog: Boolean get() = true /** * Class name which DokiLog interface is attached to. * This will show the subclass even if DokiLog is implemented in the parent class. * To show the parent class name instead, get them from the [StackTraceElement.getClassName] in [LogProfile.getTag]. */ val className: String get() = javaClass.simpleName } /** * Log at [Log.VERBOSE] level. * * @param message Message. Default = null * @param t Throwable. Default = null */ inline fun DokiLog.v(message: String? = null, t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.VERBOSE, className, message, t) } /** * Log at [Log.VERBOSE] level. * * @param t Throwable. Default = null */ inline fun DokiLog.v(t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.VERBOSE, className, null, t) } /** * Log at [Log.DEBUG] level. * * @param message Message. Default = null * @param t Throwable. Default = null */ inline fun DokiLog.d(message: String? = null, t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.DEBUG, className, message, t) } /** * Log at [Log.DEBUG] level. * * @param t Throwable. Default = null */ inline fun DokiLog.d(t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.DEBUG, className, null, t) } /** * Log at [Log.WARN] level. * * @param message Message. Default = null * @param t Throwable. Default = null */ inline fun DokiLog.w(message: String? = null, t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.WARN, className, message, t) } /** * Log at [Log.WARN] level. * * @param t Throwable. Default = null */ inline fun DokiLog.w(t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.WARN, className, null, t) } /** * Log at [Log.ERROR] level. * * @param message Message. Default = null * @param t Throwable. Default = null */ inline fun DokiLog.e(message: String? = null, t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.ERROR, className, message, t) } /** * Log at [Log.ERROR] level. * * @param t Throwable. Default = null */ inline fun DokiLog.e(t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.ERROR, className, null, t) } /** * Log at [Log.ASSERT] level. * * @param message Message. Default = null * @param t Throwable. Default = null */ inline fun DokiLog.wtf(message: String? = null, t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.ASSERT, className, message, t) } /** * Log at [Log.ASSERT] level. * * @param t Throwable. Default = null */ inline fun DokiLog.wtf(t: Throwable? = null) { if (enableClassLog && DokiLog.hasLogProfiles()) DokiLog.log(Log.ASSERT, className, null, t) }
0
Kotlin
1
4
b66f880451df64f5e1b976bb7360f19af16c1e22
5,663
dokilog
Apache License 2.0
build-logic/conventions/src/main/kotlin/me/gulya/convention/Libs.kt
IlyaGulya
767,511,466
false
{"Kotlin": 53538}
package me.gulya.convention import org.gradle.accessors.dm.LibrariesForLibs import org.gradle.api.Project import org.gradle.kotlin.dsl.the val Project.libs get() = the<LibrariesForLibs>()
1
Kotlin
0
9
49db1e6aae70d4a0d18c20febedb5f972b10a523
193
anvil-utils
Apache License 2.0
src/main/kotlin/com/github/oowekyala/ijcc/lang/psi/TraversalUtil.kt
oowekyala
160,946,520
false
{"Kotlin": 636577, "HTML": 12321, "Lex": 10654, "Shell": 1940, "Just": 101}
package com.github.oowekyala.ijcc.lang.psi import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.openapi.util.Conditions import com.intellij.psi.PsiElement import com.intellij.psi.SyntaxTraverser import com.intellij.psi.SyntaxTraverser.psiTraverser import com.intellij.psi.tree.IElementType /** * @author <NAME> * @since 1.0 */ fun grammarTraverser(root: PsiElement): SyntaxTraverser<PsiElement> = psiTraverser().withRoot(root) .forceDisregardTypes(Conditions.equalTo<IElementType>(GeneratedParserUtilBase.DUMMY_BLOCK)) .filter(Conditions.instanceOf<PsiElement>(JccPsiElement::class.java)) fun grammarTraverserNoJava(root: PsiElement): SyntaxTraverser<PsiElement> = grammarTraverser(root) .forceIgnore { when (it) { is JccJavaCompilationUnit, is JccJavaBlock, is JccJavaExpression -> true else -> false } } fun grammarTraverserOnlyBnf(root: PsiElement): SyntaxTraverser<PsiElement> = grammarTraverserNoJava(root) .forceIgnore(Conditions.instanceOf(JccOptionSection::class.java)) .forceIgnore(Conditions.instanceOf(JccRegexProduction::class.java))
11
Kotlin
6
44
c514083a161db56537d2473e42f2a1d4bf57eee1
1,360
intellij-javacc
MIT License
features/home/src/main/java/com/fappslab/features/home/data/model/AppsResponse.kt
F4bioo
628,097,763
false
null
package com.fappslab.features.home.data.model import com.google.gson.annotations.SerializedName internal data class AppsResponse( @SerializedName("responses") val responses: Responses? ) { internal data class Responses( @SerializedName("listApps") val listApps: ListAppsResponse? ) { internal data class ListAppsResponse( @SerializedName("datasets") val datasets: DatasetsResponse? ) { internal data class DatasetsResponse( @SerializedName("all") val all: AllResponse? ) { internal data class AllResponse( @SerializedName("data") val data: DataResponse? ) { internal data class DataResponse( @SerializedName("total") val total: Int?, @SerializedName("offset") val offset: Int?, @SerializedName("limit") val limit: Int?, @SerializedName("next") val next: Int?, @SerializedName("hidden") val hidden: Int?, @SerializedName("list") val list: List<AppResponse>? ) { internal data class AppResponse( @SerializedName("id") val id: Int?, @SerializedName("name") val name: String?, @SerializedName("package") val packageName: String?, @SerializedName("vercode") val versionCode: Int?, @SerializedName("downloads") val downloads: Int?, @SerializedName("graphic") val graphic: String?, @SerializedName("icon") val icon: String?, @SerializedName("store_name") val storeName: String? ) } } } } } }
0
Kotlin
0
0
d3e0405eae2038ea13c352daa8bc976da85914a4
1,950
faurecia-aptoide-challenge
MIT License
composeApp/src/androidMain/kotlin/io/github/snd_r/komelia/platform/BackPressHandler.android.kt
Snd-R
775,064,249
false
{"Kotlin": 1370443, "C": 37132, "CMake": 17841, "Shell": 2152, "Dockerfile": 1673, "JavaScript": 695, "HTML": 447}
import androidx.activity.OnBackPressedCallback import androidx.activity.OnBackPressedDispatcher import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState @Composable fun BackPressHandler( backPressedDispatcher: OnBackPressedDispatcher? = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher, onBackPressed: () -> Unit ) { val currentOnBackPressed by rememberUpdatedState(newValue = onBackPressed) val backCallback = remember { object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { currentOnBackPressed() } } } DisposableEffect(key1 = backPressedDispatcher) { backPressedDispatcher?.addCallback(backCallback) onDispose { backCallback.remove() } } }
1
Kotlin
5
9
5a16d84ed86321e4c7efa96daea9dd7dbfc2308b
1,053
Komelia
Apache License 2.0
src/main/java/net/gtaun/shoebill/amx/types/ReferenceInt.kt
Shoebill
4,378,544
false
null
package net.gtaun.shoebill.amx.types /** * This class shall be used with the amx interface when passing a reference integer value. * * @author <NAME> */ data class ReferenceInt(var value: Int)
7
null
9
17
b457e1aa432ff00a0591e8097ad80d2b68b8d361
198
shoebill-api
Apache License 2.0
ktor-hosts/ktor-servlet/src/org/jetbrains/ktor/servlet/ServletReadChannel.kt
cbeust
64,515,203
false
null
package org.jetbrains.ktor.servlet import org.jetbrains.ktor.nio.* import java.nio.* import java.util.concurrent.atomic.* import javax.servlet.* class ServletAsyncReadChannel(val servletInputStream: ServletInputStream) : AsyncReadChannel { private val listenerInstalled = AtomicBoolean() private val currentHandler = AtomicReference<AsyncHandler?>() private var currentBuffer: ByteBuffer? = null private val readListener = object : ReadListener { override fun onAllDataRead() { withHandler { handler, buffer -> handler.successEnd() } } override fun onError(t: Throwable) { withHandler { handler, buffer -> handler.failed(t) } } override fun onDataAvailable() { withHandler { handler, buffer -> doRead(handler, buffer) } } } override fun read(dst: ByteBuffer, handler: AsyncHandler) { if (!dst.hasRemaining()) { handler.success(0) return } if (!currentHandler.compareAndSet(null, handler)) { throw IllegalStateException("Read operation is already in progress") } currentBuffer = dst if (listenerInstalled.compareAndSet(false, true)) { servletInputStream.setReadListener(readListener) } else { doRead(handler, dst) } } override fun close() { servletInputStream.close() } private fun doRead(handler: AsyncHandler, buffer: ByteBuffer) { if (servletInputStream.isFinished) { clearReferences() handler.successEnd() } else if (servletInputStream.isReady) { clearReferences() val size = servletInputStream.read(buffer) if (size == -1) { handler.successEnd() } else { handler.success(size) } } } private fun ServletInputStream.read(buffer: ByteBuffer): Int = if (buffer.hasArray()) { val size = read(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()) if (size > 0) { buffer.position(buffer.position() + size) } size } else { val tempArray = ByteArray(buffer.remaining()) val size = read(tempArray) if (size > 0) { buffer.put(tempArray, 0, size) } size } private inline fun withHandler(block: (AsyncHandler, ByteBuffer) -> Unit) { currentHandler.getAndSet(null)?.let { handler -> currentBuffer?.let { buffer -> currentBuffer = null block(handler, buffer) } } } private fun clearReferences() { currentHandler.set(null) currentBuffer = null } }
0
null
0
1
8dc7ac666a336cba0f23a72cc31b8c0b14ad4f09
2,930
ktor
Apache License 2.0
parser/src/main/java/com/malt/parser/struct/xml/XmlNamespaceEndTag.kt
MALTF
679,156,908
false
{"Kotlin": 288486}
package com.malt.parser.struct.xml /** * @author malt */ class XmlNamespaceEndTag( @JvmField val prefix: String, @JvmField val uri: String ) { override fun toString(): String { return "$prefix=$uri" } }
1
Kotlin
0
4
7aabf1d6d9741190d1527744dd168edd751911a4
229
APK-Parser
MIT License
shared/src/main/java/io/github/toyota32k/shared/UtFitter.kt
toyota-m2k
643,174,351
false
null
/** * 矩形サイズをルールに従って配置するためのサイズ決定ロジックの実装 * * @author M.TOYOTA 2018.07.11 Created * Copyright © 2018 M.TOYOTA All Rights Reserved. */ package io.github.toyota32k.lib.player.common import android.util.Size import android.util.SizeF import io.github.toyota32k.shared.MuSize import io.github.toyota32k.utils.UtLog /** * 矩形領域のリサイズ方法 */ enum class FitMode { Width, // 指定された幅になるように高さを調整 Height, // 指定された高さになるよう幅を調整 Inside, // 指定された矩形に収まるよう幅、または、高さを調整 Fit // 指定された矩形にリサイズする } /** * ビデオや画像のサイズ(original)を、指定されたmode:FitModeに従って、配置先のサイズ(layout)に合わせるように変換して resultに返す。 * * @param original 元のサイズ(ビデオ/画像のサイズ) * @param layout レイアウト先の指定サイズ * @param result 結果を返すバッファ */ fun fitSizeTo(originalWidth:Float, originalHeight:Float, layoutWidth:Float, layoutHeight:Float, mode: FitMode, result: MuSize) { try { when (mode) { FitMode.Fit -> result.set(layoutWidth, layoutHeight) FitMode.Width -> result.set(layoutWidth, originalHeight * layoutWidth / originalWidth) FitMode.Height -> result.set(originalWidth * layoutHeight / originalHeight, layoutHeight) FitMode.Inside -> { val rw = layoutWidth / originalWidth val rh = layoutHeight / originalHeight if (rw < rh) { result.set(layoutWidth, originalHeight * rw) } else { result.set(originalWidth * rh, layoutHeight) } } } } catch(e:Exception) { UtFitter.logger.stackTrace(e) result.set(0f,0f) } } fun fitSizeTo(original: MuSize, layout: MuSize, mode: FitMode, result: MuSize) = fitSizeTo(original.width, original.height, layout.width, layout.height, mode, result) interface IUtLayoutHint { val fitMode: FitMode val layoutWidth: Float val layoutHeight: Float } //open class AmvFitter(override var fitMode: FitMode = FitMode.Inside, protected var layoutSize: MuSize = MuSize(1000f, 1000f)) : // IAmvLayoutHint { // override val layoutWidth: Float // get() = layoutSize.width // override val layoutHeight: Float // get() = layoutSize.height // // // fun setHint(fitMode: FitMode, width:Float, height:Float) { // this.fitMode = fitMode // layoutSize.width = width // layoutSize.height = height // } // // fun fit(original: MuSize, result: MuSize) { // fitSizeTo(original, layoutSize, fitMode, result) // } // // fun fit(w:Float, h:Float): ImSize { // val result = MuSize() // fit(MuSize(w,h), result) // return result // } //} class UtFitter(override var fitMode: FitMode, override var layoutWidth:Float, override var layoutHeight:Float) : IUtLayoutHint { constructor():this(FitMode.Inside, 1f, 1f) constructor(fitMode: FitMode):this(fitMode, 1f,1f) constructor(fitMode: FitMode, layoutWidth:Int, layoutHeight:Int):this(fitMode,layoutWidth.toFloat(), layoutHeight.toFloat()) constructor(fitMode: FitMode, layoutSize:Size):this(fitMode,layoutSize.width.toFloat(), layoutSize.height.toFloat()) constructor(fitMode: FitMode, layoutSize:SizeF):this(fitMode,layoutSize.width, layoutSize.height) val result = MuSize() val resultSize:Size get() = result.asSize val resultSizeF:SizeF get() = result.asSizeF val resultWidth get() = result.width val resultHeight get() = result.height fun setMode(fitMode: FitMode):UtFitter { this.fitMode = fitMode return this } fun setLayoutWidth(width:Float): UtFitter { this.layoutWidth = width return this } fun setLayoutWidth(width:Int): UtFitter { this.layoutWidth = width.toFloat() return this } fun setLayoutHeight(height:Float): UtFitter { this.layoutHeight = height return this } fun setLayoutHeight(height:Int): UtFitter { this.layoutHeight = height.toFloat() return this } fun setLayoutSize(width:Float, height:Float):UtFitter { this.layoutWidth = width this.layoutHeight = height return this } fun setLayoutSize(width:Int, height:Int):UtFitter = setLayoutSize(width.toFloat(), height.toFloat()) fun setLayoutSize(size:Size):UtFitter = setLayoutSize(size.width, size.height) fun setLayoutSize(size:SizeF):UtFitter = setLayoutSize(size.width, size.height) fun fit(src: Size): UtFitter { fitSizeTo(src.width.toFloat(), src.height.toFloat(), layoutWidth, layoutHeight, fitMode, result) return this } fun fit(src: SizeF): UtFitter { fitSizeTo(src.width, src.height, layoutWidth, layoutHeight, fitMode, result) return this } fun fit(srcWidth:Int, srcHeight:Int): UtFitter { fitSizeTo(srcWidth.toFloat(), srcHeight.toFloat(), layoutWidth, layoutHeight, fitMode, result) return this } fun fit(srcWidth:Float, srcHeight:Float): UtFitter { fitSizeTo(srcWidth, srcHeight, layoutWidth, layoutHeight, fitMode, result) return this } companion object { val logger: UtLog = UtLog("Fitter", null, UtFitter::class.java) } }
2
Kotlin
0
0
c4da942036eb6e746718e38789ccc53e9aa03bb2
5,211
android-utilities
Apache License 2.0
presentation/src/test/kotlin/io/petros/github/presentation/feature/splash/navigator/SplashActivityNavigatorTest.kt
ParaskP7
140,927,471
false
{"Kotlin": 118109}
package io.petros.github.presentation.feature.splash.navigator import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import io.petros.github.presentation.feature.navigator.Launcher import io.petros.github.presentation.feature.search.navigator.SearchLauncher import org.junit.Before import org.junit.Test class SplashActivityNavigatorTest { private val searchLauncherMock = mock<SearchLauncher>() private val launcherMock = mock<Launcher>() private lateinit var testedClass: SplashActivityNavigator @Before fun setUp() { testedClass = SplashActivityNavigator(searchLauncherMock) testedClass.launcher = launcherMock } @Test fun `When navigating from splash activity, then search activity launches`() { testedClass.navigate() verify(searchLauncherMock).launch() } @Test fun `When navigating from splash activity, then splash activity finishes`() { testedClass.navigate() verify(launcherMock).finish() } }
0
Kotlin
1
9
ad9c53165db32af9ca08e4ae3ca4ea9b30e24d2e
1,036
sample-code-github
Apache License 2.0
app/src/main/java/com/vultisig/wallet/ui/models/home/VaultListViewModel.kt
vultisig
789,965,982
false
{"Kotlin": 1656023, "Ruby": 1713}
package com.vultisig.wallet.ui.models.home import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vultisig.wallet.data.models.Folder import com.vultisig.wallet.data.models.Vault import com.vultisig.wallet.data.repositories.FolderRepository import com.vultisig.wallet.data.repositories.order.VaultOrderRepository import com.vultisig.wallet.data.repositories.order.FolderOrderRepository import com.vultisig.wallet.data.usecases.GetOrderedVaults import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject internal data class VaultListUiModel( val vaults: List<Vault> = emptyList(), val folders: List<Folder> = emptyList() ) @HiltViewModel internal class VaultListViewModel @Inject constructor( private val vaultOrderRepository: VaultOrderRepository, private val folderRepository: FolderRepository, private val folderOrderRepository: FolderOrderRepository, private val getOrderedVaults: GetOrderedVaults, ) : ViewModel() { val state = MutableStateFlow(VaultListUiModel()) private var reIndexJob: Job? = null init { collectFolders() collectVaults() } private fun collectVaults() = viewModelScope.launch { getOrderedVaults(null).collect { orderedVaults -> state.update { it.copy(vaults = orderedVaults) } } } private fun collectFolders() = viewModelScope.launch { combine( folderOrderRepository.loadOrders(null), folderRepository.getAll() ) { orders, folders -> val addressAndOrderMap = mutableMapOf<Folder, Float>() folders.forEach { eachFolder -> addressAndOrderMap[eachFolder] = orders.find { it.value == eachFolder.id.toString() }?.order ?: folderOrderRepository.insert(null,eachFolder.id.toString()) } addressAndOrderMap.entries.sortedByDescending { it.value }.map { it.key } }.collect { orderedFolders -> state.update { it.copy(folders = orderedFolders) } } } fun onMoveFolders(oldOrder: Int, newOrder: Int) { val updatedPositionsList = state.value.folders.toMutableList().apply { add(newOrder, removeAt(oldOrder)) } state.update { it.copy(folders = updatedPositionsList) } reIndexJob?.cancel() reIndexJob = viewModelScope.launch { delay(500) val midOrder = updatedPositionsList[newOrder].id.toString() val upperOrder = updatedPositionsList.getOrNull(newOrder + 1)?.id.toString() val lowerOrder = updatedPositionsList.getOrNull(newOrder - 1)?.id.toString() folderOrderRepository.updateItemOrder(null,upperOrder, midOrder, lowerOrder) } } fun onMoveVaults(oldOrder: Int, newOrder: Int) { val updatedPositionsList = state.value.vaults.toMutableList().apply { add(newOrder, removeAt(oldOrder)) } state.update { it.copy(vaults = updatedPositionsList) } reIndexJob?.cancel() reIndexJob = viewModelScope.launch { delay(500) val midOrder = updatedPositionsList[newOrder].id val upperOrder = updatedPositionsList.getOrNull(newOrder + 1)?.id val lowerOrder = updatedPositionsList.getOrNull(newOrder - 1)?.id vaultOrderRepository.updateItemOrder(null,upperOrder, midOrder, lowerOrder) } } }
58
Kotlin
2
6
106410f378751c6ab276120fcc74c1036b46ab6e
3,692
vultisig-android
Apache License 2.0
src/main/java/ru/itmo/kazakov/autoschedule/algorithm/integration/JmetalMultidimensionalIndividual.kt
AdvancerMan
636,416,766
false
null
package ru.itmo.kazakov.autoschedule.algorithm.integration import org.uma.jmetal.solution.AbstractSolution import org.uma.jmetal.solution.Solution import ru.itmo.kazakov.autoschedule.algorithm.individual.Individual class JmetalMultidimensionalIndividual<I : Individual<I>>( innerIndividual: I, ) : JmetalIndividual<I>, AbstractSolution<I>(1, innerIndividual.fitness.size) { @Volatile override var innerIndividual: I = innerIndividual set(value) { variables()[0] = value System.arraycopy(innerIndividual.fitness, 0, objectives(), 0, objectives().size) field = value } constructor(individualToCopy: JmetalMultidimensionalIndividual<I>) : this(individualToCopy.innerIndividual) { attributes().putAll(individualToCopy.attributes()) } init { this.innerIndividual = innerIndividual } override fun copy(): Solution<I> { return JmetalMultidimensionalIndividual(innerIndividual.copy()) } }
0
Kotlin
0
0
b27a04ba71342c42af17b02654169107afaf23ea
1,000
itmo-ct-thesis-2023
MIT License
src/main/kotlin/dev/binclub/bingait/api/util/tree/AbstactLazyTreeNode.kt
zzurio
421,995,961
false
{"Kotlin": 62750, "Java": 9803}
package dev.binclub.bingait.api.util.tree import dev.binclub.bingait.api.util.EventTreeNode import java.util.Enumeration import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.MutableTreeNode import javax.swing.tree.TreeNode /** * @author cookiedragon234 06/Sep/2020 */ abstract class AbstractLazyTreeNode: DefaultMutableTreeNode(), EventTreeNode { private var loaded = false protected abstract fun createChildrenNodes(): List<AbstractLazyTreeNode> protected open fun willBeLeaf(): Boolean? = null @Synchronized private fun load() { if (!loaded) { loaded = true super.removeAllChildren() createChildrenNodes().withIndex().forEach { (i, node) -> super.insert(node, i) } } } @Synchronized private fun unload() { if (loaded) { super.removeAllChildren() loaded = false } } final override fun isLeaf(): Boolean { if (loaded) { return super.isLeaf() } return willBeLeaf() ?: loadAndReturn { super.isLeaf() } } private inline fun <T> loadAndReturn(op: () -> T): T { load() return op() } override fun onExpansion() = load() override fun onCollapse() = unload() override fun getIndex(aChild: TreeNode?): Int = loadAndReturn { super.getIndex(aChild) } override fun getChildAt(index: Int): TreeNode = loadAndReturn { super.getChildAt(index) } override fun getChildCount(): Int { return if (true) { loadAndReturn { super.getChildCount() } } else { if (loaded) super.getChildCount() else { if (willBeLeaf() == true) 0 else 1 } } } override fun insert(newChild: MutableTreeNode?, childIndex: Int) = loadAndReturn { super.insert(newChild, childIndex) } override fun remove(childIndex: Int) = super.remove(childIndex) override fun children(): Enumeration<*> = loadAndReturn { return super.children() } override fun remove(aChild: MutableTreeNode?) = super.remove(aChild) override fun add(newChild: MutableTreeNode?) = super.add(newChild) override fun isNodeDescendant(anotherNode: DefaultMutableTreeNode?): Boolean = loadAndReturn { super.isNodeDescendant(anotherNode) } override fun isNodeRelated(aNode: DefaultMutableTreeNode?): Boolean = loadAndReturn { super.isNodeRelated(aNode) } override fun getDepth(): Int = loadAndReturn { super.getDepth() } override fun getNextNode(): DefaultMutableTreeNode = loadAndReturn { super.getNextNode() } override fun getPreviousNode(): DefaultMutableTreeNode = loadAndReturn { super.getPreviousNode() } override fun preorderEnumeration(): Enumeration<*> = loadAndReturn { super.preorderEnumeration() } override fun postorderEnumeration(): Enumeration<*> = loadAndReturn { super.postorderEnumeration() } override fun breadthFirstEnumeration(): Enumeration<*> = loadAndReturn { super.breadthFirstEnumeration() } override fun depthFirstEnumeration(): Enumeration<*> = loadAndReturn { super.depthFirstEnumeration() } override fun isNodeChild(aNode: TreeNode?): Boolean = loadAndReturn { super.isNodeChild(aNode) } override fun getFirstChild(): TreeNode = loadAndReturn { super.getFirstChild() } override fun getLastChild(): TreeNode = loadAndReturn { super.getLastChild() } override fun getChildAfter(aChild: TreeNode?): TreeNode = loadAndReturn { super.getChildAfter(aChild) } override fun getChildBefore(aChild: TreeNode?): TreeNode = loadAndReturn { super.getChildBefore(aChild) } override fun getFirstLeaf(): DefaultMutableTreeNode = loadAndReturn { super.getFirstLeaf() } override fun getLastLeaf(): DefaultMutableTreeNode = loadAndReturn { super.getLastLeaf() } override fun getNextLeaf(): DefaultMutableTreeNode = loadAndReturn { super.getNextLeaf() } override fun getPreviousLeaf(): DefaultMutableTreeNode = loadAndReturn { super.getPreviousLeaf() } override fun getLeafCount(): Int = loadAndReturn { super.getLeafCount() } override fun toString(): String = loadAndReturn { super.toString() } override fun equals(other: Any?): Boolean = loadAndReturn { super.equals(other) } }
0
Kotlin
4
20
de2432cc2ab735c3b3a1b763d1695343111ec4ff
4,076
BinGait
BSD Zero Clause License
app/src/main/java/app/accrescent/client/ui/AppDetailsViewModel.kt
accrescent
438,517,305
false
null
package app.FeloStore.client.ui import android.app.Application import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Settings import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import app.FeloStore.client.FeloStore import app.FeloStore.client.R import app.FeloStore.client.data.AppInstallStatuses import app.FeloStore.client.data.InstallStatus import app.FeloStore.client.data.RepoDataRepository import app.FeloStore.client.util.PackageManager import app.FeloStore.client.util.UserRestrictionException import app.FeloStore.client.util.getPackageInstallStatus import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.launch import kotlinx.serialization.SerializationException import java.io.FileNotFoundException import java.io.InvalidObjectException import java.net.ConnectException import java.net.UnknownHostException import java.security.GeneralSecurityException import javax.inject.Inject @HiltViewModel class AppDetailsViewModel @Inject constructor( @ApplicationContext context: Context, private val repoDataRepository: RepoDataRepository, appInstallStatuses: AppInstallStatuses, private val packageManager: PackageManager, savedStateHandle: SavedStateHandle ) : AndroidViewModel(context as Application) { private val appId = savedStateHandle.get<String>("appId")!! val installStatuses = appInstallStatuses.statuses var downloadProgresses = appInstallStatuses.downloadProgresses var uiState by mutableStateOf(AppDetailsUiState(appId = appId)) private set init { viewModelScope.launch { uiState = uiState.copy(isFetchingData = true, error = null) val trustedInfo = repoDataRepository.getApp(appId) if (trustedInfo == null) { uiState = uiState.copy(appExists = false, isFetchingData = false) return@launch } else { uiState = uiState.copy(appName = trustedInfo.name) } uiState = try { val untrustedInfo = repoDataRepository.getAppRepoData(appId) if (appInstallStatuses.statuses[appId] == null) { appInstallStatuses.statuses[appId] = try { context .packageManager .getPackageInstallStatus(appId, untrustedInfo.versionCode) } catch (e: Exception) { InstallStatus.UNKNOWN } } uiState.copy( versionName = untrustedInfo.version, versionCode = untrustedInfo.versionCode, shortDescription = untrustedInfo.shortDescription ?: context.getString(R.string.no_description_provided), ) } catch (e: ConnectException) { uiState.copy( error = context.getString(R.string.network_error, e.message), appExists = false, ) } catch (e: FileNotFoundException) { uiState.copy( error = context.getString(R.string.failed_download_repodata, e.message), appExists = false, ) } catch (e: SerializationException) { uiState.copy( error = context.getString(R.string.failed_decode_repodata, e.message), appExists = false, ) } catch (e: UnknownHostException) { uiState.copy( error = context.getString(R.string.unknown_host_error, e.message), appExists = false, ) } uiState = uiState.copy(isFetchingData = false) } } fun installApp(appId: String) { viewModelScope.launch { uiState.error = null val context = getApplication<FeloStore>().applicationContext try { packageManager.downloadAndInstall( appId = appId, onProgressUpdate = { downloadProgresses[appId] = it }, onDownloadComplete = { downloadProgresses.remove(appId) }, ) } catch (e: ConnectException) { uiState.error = context.getString(R.string.network_error, e.message) } catch (e: FileNotFoundException) { uiState.error = context.getString(R.string.failed_download_files, e.message) } catch (e: GeneralSecurityException) { uiState.error = context.getString(R.string.app_verification_failed, e.message) } catch (e: UserRestrictionException) { uiState.error = context.getString(R.string.user_restriction, e.message) } catch (e: InvalidObjectException) { uiState.error = context.getString(R.string.error_parsing_files, e.message) } catch (e: NoSuchElementException) { uiState.error = context.getString(R.string.app_doesnt_support_device, e.message) } catch (e: SerializationException) { uiState.error = context.getString(R.string.failed_decode_repodata, e.message) } catch (e: UnknownHostException) { uiState.error = context.getString(R.string.unknown_host_error, e.message) } } } fun uninstallApp(appId: String) { uiState.error = null val context = getApplication<FeloStore>().applicationContext try { packageManager.uninstallApp(appId) } catch (e: UserRestrictionException) { uiState.error = context.getString(R.string.user_restriction, e.message) } } fun openApp(appId: String) { uiState.error = null val context = getApplication<FeloStore>().applicationContext val intent = context.packageManager.getLaunchIntentForPackage(appId) if (intent == null) { uiState.error = context.getString(R.string.couldnt_open_app) return } else { context.startActivity(intent) } } fun openAppInfo(appId: String) { uiState.error = null val context = getApplication<FeloStore>().applicationContext val uri = Uri.parse("package:$appId") val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) if (intent.resolveActivity(context.packageManager) == null) { uiState.error = context.getString(R.string.couldnt_open_appinfo) return } else { context.startActivity(intent) } } }
39
null
22
993
b07f89a06f0ca6384b64a79e181676bbf0e2d642
7,076
accrescent
ISC License
bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/command/group/GroupRemoveCommand.kt
Nyrheim
269,929,653
true
{"Kotlin": 2944589, "Java": 1237516, "HTML": 94789, "JavaScript": 640, "CSS": 607}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.permissions.bukkit.command.group import com.rpkit.permissions.bukkit.RPKPermissionsBukkit import com.rpkit.permissions.bukkit.group.RPKGroupProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.players.bukkit.profile.RPKProfile import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Group remove command. * Removes a group. */ class GroupRemoveCommand(private val plugin: RPKPermissionsBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender.hasPermission("rpkit.permissions.command.group.remove")) { if (args.size > 1) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val groupProvider = plugin.core.serviceManager.getServiceProvider(RPKGroupProvider::class) val bukkitPlayer = plugin.server.getPlayer(args[0]) if (bukkitPlayer != null) { val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile != null) { val profile = minecraftProfile.profile if (profile is RPKProfile) { val group = groupProvider.getGroup(args[1]) if (group != null) { groupProvider.removeGroup(profile, group) sender.sendMessage(plugin.messages["group-remove-valid", mapOf( Pair("group", group.name), Pair("player", minecraftProfile.minecraftUsername) )]) } else { sender.sendMessage(plugin.messages["group-remove-invalid-group"]) } } else { sender.sendMessage(plugin.messages["no-profile"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["group-remove-invalid-player"]) } } else { sender.sendMessage(plugin.messages["group-remove-usage"]) } } else { sender.sendMessage(plugin.messages["no-permission-group-remove-group"]) } return true } }
0
null
0
0
f2196a76e0822b2c60e4a551de317ed717bbdc7e
3,283
RPKit
Apache License 2.0
app/src/main/java/com/eneskayiklik/word_diary/util/animation_converter/DpConverter.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.util.animation_converter import androidx.compose.animation.core.AnimationVector1D import androidx.compose.animation.core.TwoWayConverter import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp class DpConverter : TwoWayConverter<Dp, AnimationVector1D> { override val convertFromVector: (AnimationVector1D) -> Dp get() = { it.value.dp } override val convertToVector: (Dp) -> AnimationVector1D get() = { AnimationVector1D(it.value) } }
0
Kotlin
0
3
236d4c497d7e141f1536fb62f7458459420d1fe9
551
WordDiary
MIT License
app/src/main/java/dev/nosuch/luncher/android/App.kt
nealsanche
262,650,410
false
null
package dev.nosuch.luncher.android import android.app.Application import android.content.Context import co.touchlab.kampstarter.initKoin import org.koin.dsl.module class App : Application() { override fun onCreate() { super.onCreate() initKoin { modules(module { single<Context> { this@App } }) } } }
0
Kotlin
0
0
17314ea59fe0ae0711f598e3a89b79e083327f1d
346
Luncher
Apache License 2.0
idea/testData/run/MainInTest/module/src/mainInPackageSimple.kt
JakeWharton
99,388,807
true
null
package pkg1 fun main(args: Array<String>) { // yes }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
56
kotlin
Apache License 2.0
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/custommodel/CustomImageClassifier.kt
SagarBChauhan
216,040,454
false
null
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.samples.apps.mlkit.kotlin.custommodel import android.app.Activity import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Rect import android.graphics.ImageFormat import android.graphics.YuvImage import android.os.SystemClock import android.util.Log import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.firebase.ml.common.FirebaseMLException import com.google.firebase.ml.custom.FirebaseModelInterpreter import com.google.firebase.ml.custom.FirebaseModelInputOutputOptions import com.google.firebase.ml.custom.FirebaseModelOptions import com.google.firebase.ml.common.modeldownload.FirebaseModelManager import com.google.firebase.ml.custom.FirebaseModelDataType import com.google.firebase.ml.custom.FirebaseModelInputs import com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel import com.google.firebase.ml.common.modeldownload.FirebaseLocalModel import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions import java.io.BufferedReader import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStreamReader import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.AbstractMap import java.util.PriorityQueue import kotlin.experimental.and /** * A `FirebaseModelInterpreter` based image classifier. */ class CustomImageClassifier /** * Initializes an `CustomImageClassifier`. */ @Throws(FirebaseMLException::class) internal constructor(activity: Activity, private val useQuantizedModel: Boolean) { /* Preallocated buffers for storing image data in. */ private val intValues = IntArray(DIM_IMG_SIZE_X * DIM_IMG_SIZE_Y) /** * An instance of the driver class to run model inference with Firebase. */ private val interpreter: FirebaseModelInterpreter? /** * Data configuration of input & output data of model. */ private val dataOptions: FirebaseModelInputOutputOptions /** * Labels corresponding to the output of the vision model. */ private val labelList: List<String> private val sortedLabels = PriorityQueue( RESULTS_TO_SHOW, Comparator<AbstractMap.SimpleEntry<String, Float>> { o1, o2 -> o1.value.compareTo(o2.value) }) /** * Gets the top-K labels, to be shown in UI as the results. */ private val topKLabels: List<String> @Synchronized get() { val result = ArrayList<String>() val size = sortedLabels.size for (i in 0 until size) { val label = sortedLabels.poll() result.add("${label.key} : ${label.value}") } return result } init { val localModelName = if (useQuantizedModel) LOCAL_QUANT_MODEL_NAME else LOCAL_FLOAT_MODEL_NAME val hostedModelName = if (useQuantizedModel) HOSTED_QUANT_MODEL_NAME else HOSTED_FLOAT_MODEL_NAME val localModelPath = if (useQuantizedModel) LOCAL_QUANT_MODEL_PATH else LOCAL_FLOAT_MODEL_PATH val modelOptions = FirebaseModelOptions.Builder() .setRemoteModelName(hostedModelName) .setLocalModelName(localModelName) .build() val conditions = FirebaseModelDownloadConditions.Builder() .requireWifi() .build() val localModel = FirebaseLocalModel.Builder(localModelName) .setAssetFilePath(localModelPath).build() val remoteModel = FirebaseRemoteModel.Builder(hostedModelName) .enableModelUpdates(true) .setInitialDownloadConditions(conditions) .setUpdatesDownloadConditions(conditions) // You could also specify different // conditions for updates. .build() val manager = FirebaseModelManager.getInstance() manager.registerLocalModel(localModel) manager.registerRemoteModel(remoteModel) interpreter = FirebaseModelInterpreter.getInstance(modelOptions) labelList = loadLabelList(activity) Log.d(TAG, "Created a Custom Image Classifier.") val inputDims = intArrayOf(DIM_BATCH_SIZE, DIM_IMG_SIZE_X, DIM_IMG_SIZE_Y, DIM_PIXEL_SIZE) val outputDims = intArrayOf(1, labelList.size) val dataType = if (useQuantizedModel) FirebaseModelDataType.BYTE else FirebaseModelDataType.FLOAT32 dataOptions = FirebaseModelInputOutputOptions.Builder() .setInputFormat(0, dataType, inputDims) .setOutputFormat(0, dataType, outputDims) .build() Log.d(TAG, "Configured input & output data for the custom image classifier.") } /** * Classifies a frame from the preview stream. */ @Throws(FirebaseMLException::class) internal fun classifyFrame(buffer: ByteBuffer, width: Int, height: Int): Task<List<String>> { if (interpreter == null) { Log.e(TAG, "Image classifier has not been initialized; Skipped.") val uninitialized = ArrayList<String>() uninitialized.add("Uninitialized Classifier.") Tasks.forResult<List<String>>(uninitialized) } // Create input data. val imgData = convertBitmapToByteBuffer(buffer, width, height) val inputs = FirebaseModelInputs.Builder().add(imgData).build() // Here's where the magic happens!! return interpreter!! .run(inputs, dataOptions) .addOnFailureListener { e -> Log.e(TAG, "Failed to get labels array: ${e.message}") e.printStackTrace() } .continueWith { task -> if (useQuantizedModel) { val labelProbArray = task.result!!.getOutput<Array<ByteArray>>(0) getTopLabels(labelProbArray) } else { val labelProbArray = task.result!!.getOutput<Array<FloatArray>>(0) getTopLabels(labelProbArray) } } } /** * Reads label list from Assets. */ private fun loadLabelList(activity: Activity): List<String> { val labelList = ArrayList<String>() try { BufferedReader(InputStreamReader(activity.assets.open(LABEL_PATH))).use { reader -> var line = reader.readLine() while (line != null) { labelList.add(line) line = reader.readLine() } } } catch (e: IOException) { Log.e(TAG, "Failed to read label list.", e) } return labelList } /** * Writes Image data into a `ByteBuffer`. */ @Synchronized private fun convertBitmapToByteBuffer(buffer: ByteBuffer, width: Int, height: Int): ByteBuffer { val bytesPerChannel = if (useQuantizedModel) QUANT_NUM_OF_BYTES_PER_CHANNEL else FLOAT_NUM_OF_BYTES_PER_CHANNEL val imgData = ByteBuffer.allocateDirect( bytesPerChannel * DIM_BATCH_SIZE * DIM_IMG_SIZE_X * DIM_IMG_SIZE_Y * DIM_PIXEL_SIZE) imgData.order(ByteOrder.nativeOrder()) val bitmap = createResizedBitmap(buffer, width, height) imgData.rewind() bitmap.getPixels(intValues, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) // Convert the image to int points. var pixel = 0 val startTime = SystemClock.uptimeMillis() for (i in 0 until DIM_IMG_SIZE_X) { for (j in 0 until DIM_IMG_SIZE_Y) { val value = intValues[pixel++] // Normalize the values according to the model used: // Quantized model expects a [0, 255] scale while a float model expects [0, 1]. if (useQuantizedModel) { imgData.put((value shr 16 and 0xFF).toByte()) imgData.put((value shr 8 and 0xFF).toByte()) imgData.put((value and 0xFF).toByte()) } else { imgData.putFloat((value shr 16 and 0xFF) / 255.0f) imgData.putFloat((value shr 8 and 0xFF) / 255.0f) imgData.putFloat((value and 0xFF) / 255.0f) } } } val endTime = SystemClock.uptimeMillis() Log.d(TAG, "Timecost to put values into ByteBuffer: ${(endTime - startTime)}") return imgData } /** * Resizes image data from `ByteBuffer`. */ private fun createResizedBitmap(buffer: ByteBuffer, width: Int, height: Int): Bitmap { val img = YuvImage(buffer.array(), ImageFormat.NV21, width, height, null) val out = ByteArrayOutputStream() img.compressToJpeg(Rect(0, 0, img.width, img.height), 50, out) val imageBytes = out.toByteArray() val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) return Bitmap.createScaledBitmap(bitmap, DIM_IMG_SIZE_X, DIM_IMG_SIZE_Y, true) } @Synchronized private fun getTopLabels(labelProbArray: Array<ByteArray>): List<String> { for (i in labelList.indices) { sortedLabels.add( AbstractMap.SimpleEntry(labelList[i], (labelProbArray[0][i] and 0xff.toByte()) / 255.0f)) if (sortedLabels.size > RESULTS_TO_SHOW) { sortedLabels.poll() } } return topKLabels } @Synchronized private fun getTopLabels(labelProbArray: Array<FloatArray>): List<String> { for (i in labelList.indices) { sortedLabels.add( AbstractMap.SimpleEntry(labelList[i], labelProbArray[0][i])) if (sortedLabels.size > RESULTS_TO_SHOW) { sortedLabels.poll() } } return topKLabels } companion object { /** * Tag for the [Log]. */ private const val TAG = "MLKitDemoApp:Classifier" /** * Name of the floating point model file. */ private const val LOCAL_FLOAT_MODEL_NAME = "mobilenet_float_v2_1.0_299" /** * Path of the floating point model file stored in Assets. */ private const val LOCAL_FLOAT_MODEL_PATH = "mobilenet_float_v2_1.0_299.tflite" /** * Name of the floating point model uploaded to the Firebase console. */ private const val HOSTED_FLOAT_MODEL_NAME = "mobilenet_float_v2_1.0_299" /** * Name of the quantized model file. */ private const val LOCAL_QUANT_MODEL_NAME = "mobilenet_quant_v2_1.0_299" /** * Path of the quantized model file stored in Assets. */ private const val LOCAL_QUANT_MODEL_PATH = "mobilenet_quant_v2_1.0_299.tflite" /** * Name of the quantized model uploaded to the Firebase console. */ private const val HOSTED_QUANT_MODEL_NAME = "mobilenet_quant_v2_1.0_299" /** * Name of the label file stored in Assets. */ private const val LABEL_PATH = "labels.txt" /** * Number of results to show in the UI. */ private const val RESULTS_TO_SHOW = 3 /** * Dimensions of inputs. */ private const val DIM_BATCH_SIZE = 1 private const val DIM_PIXEL_SIZE = 3 private const val DIM_IMG_SIZE_X = 299 private const val DIM_IMG_SIZE_Y = 299 private const val QUANT_NUM_OF_BYTES_PER_CHANNEL = 1 private const val FLOAT_NUM_OF_BYTES_PER_CHANNEL = 4 } }
18
null
0
5
d886d348a681f41f02e78d720cb74fb8c162e339
12,464
quickstart-android
Creative Commons Attribution 4.0 International
libraries/stdlib/src/kotlin/util/Preconditions.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:kotlin.jvm.JvmMultifileClass @file:kotlin.jvm.JvmName("PreconditionsKt") package kotlin import kotlin.contracts.contract /** * Throws an [IllegalArgumentException] if the [value] is false. * * @sample samples.misc.Preconditions.failRequireWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun require(value: Boolean): Unit { contract { returns() implies value } require(value) { "Failed requirement." } } /** * Throws an [IllegalArgumentException] with the result of calling [lazyMessage] if the [value] is false. * * @sample samples.misc.Preconditions.failRequireWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun require(value: Boolean, lazyMessage: () -> Any): Unit { contract { returns() implies value } if (!value) { val message = lazyMessage() throw IllegalArgumentException(message.toString()) } } /** * Throws an [IllegalArgumentException] if the [value] is null. Otherwise returns the not null value. */ @kotlin.internal.InlineOnly public inline fun <T : Any> requireNotNull(value: T?): T { contract { returns() implies (value != null) } return requireNotNull(value) { "Required value was null." } } /** * Throws an [IllegalArgumentException] with the result of calling [lazyMessage] if the [value] is null. Otherwise * returns the not null value. * * @sample samples.misc.Preconditions.failRequireNotNullWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun <T : Any> requireNotNull(value: T?, lazyMessage: () -> Any): T { contract { returns() implies (value != null) } if (value == null) { val message = lazyMessage() throw IllegalArgumentException(message.toString()) } else { return value } } /** * Throws an [IllegalStateException] if the [value] is false. * * @sample samples.misc.Preconditions.failCheckWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun check(value: Boolean): Unit { contract { returns() implies value } check(value) { "Check failed." } } /** * Throws an [IllegalStateException] with the result of calling [lazyMessage] if the [value] is false. * * @sample samples.misc.Preconditions.failCheckWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun check(value: Boolean, lazyMessage: () -> Any): Unit { contract { returns() implies value } if (!value) { val message = lazyMessage() throw IllegalStateException(message.toString()) } } /** * Throws an [IllegalStateException] if the [value] is null. Otherwise * returns the not null value. * * @sample samples.misc.Preconditions.failCheckWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun <T : Any> checkNotNull(value: T?): T { contract { returns() implies (value != null) } return checkNotNull(value) { "Required value was null." } } /** * Throws an [IllegalStateException] with the result of calling [lazyMessage] if the [value] is null. Otherwise * returns the not null value. * * @sample samples.misc.Preconditions.failCheckWithLazyMessage */ @kotlin.internal.InlineOnly public inline fun <T : Any> checkNotNull(value: T?, lazyMessage: () -> Any): T { contract { returns() implies (value != null) } if (value == null) { val message = lazyMessage() throw IllegalStateException(message.toString()) } else { return value } } /** * Throws an [IllegalStateException] with the given [message]. * * @sample samples.misc.Preconditions.failWithError */ @kotlin.internal.InlineOnly public inline fun error(message: Any): Nothing = throw IllegalStateException(message.toString())
184
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
3,959
kotlin
Apache License 2.0
java/java-tests/testSrc/com/intellij/java/configurationStore/testUtils.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.java.configurationStore import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.components.stateStore import com.intellij.platform.workspace.jps.CustomModuleEntitySource import com.intellij.platform.workspace.jps.JpsFileEntitySource import com.intellij.platform.workspace.jps.entities.LibraryEntity import com.intellij.platform.workspace.jps.entities.LibraryId import com.intellij.platform.workspace.jps.entities.ModuleEntity import com.intellij.platform.workspace.jps.serialization.impl.* import com.intellij.platform.workspace.storage.DummyParentEntitySource import com.intellij.platform.workspace.storage.EntitySource import com.intellij.platform.workspace.storage.EntityStorage import com.intellij.platform.workspace.storage.WorkspaceEntity import com.intellij.platform.workspace.storage.url.VirtualFileUrl import com.intellij.platform.workspace.storage.url.VirtualFileUrlManager import com.intellij.testFramework.rules.ProjectModelRule import kotlinx.coroutines.runBlocking import java.nio.file.Path import java.nio.file.Paths internal val configurationStoreTestDataRoot: Path get() = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("java/java-tests/testData/configurationStore") internal fun ProjectModelRule.saveProjectState() { runBlocking { project.stateStore.save() } } internal class SampleCustomModuleRootsSerializer : CustomModuleRootsSerializer { override val id: String get() = ID override fun createEntitySource(imlFileUrl: VirtualFileUrl, internalEntitySource: JpsFileEntitySource, customDir: String?, virtualFileManager: VirtualFileUrlManager): EntitySource { return SampleDummyParentCustomModuleEntitySource(internalEntitySource) } override fun loadRoots(moduleEntity: ModuleEntity.Builder, reader: JpsFileContentReader, customDir: String?, imlFileUrl: VirtualFileUrl, internalModuleListSerializer: JpsModuleListSerializer?, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager, moduleLibrariesCollector: MutableMap<LibraryId, LibraryEntity.Builder>) { } override fun saveRoots(module: ModuleEntity, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, writer: JpsFileContentWriter, customDir: String?, imlFileUrl: VirtualFileUrl, storage: EntityStorage, virtualFileManager: VirtualFileUrlManager) { } companion object { const val ID: String = "custom" } } internal class SampleDummyParentCustomModuleEntitySource(override val internalSource: JpsFileEntitySource) : CustomModuleEntitySource, DummyParentEntitySource
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
3,224
intellij-community
Apache License 2.0
app/src/main/kotlin/cz/covid19cz/erouska/utils/Auth.kt
igorsmerda
252,732,461
true
{"Kotlin": 210106, "Java": 1863}
package cz.covid19cz.erouska.utils import android.widget.Toast import androidx.navigation.fragment.findNavController import com.google.firebase.auth.FirebaseAuth import cz.covid19cz.erouska.R import cz.covid19cz.erouska.db.SharedPrefsRepository import cz.covid19cz.erouska.service.CovidService import cz.covid19cz.erouska.ui.base.BaseFragment import org.koin.core.KoinComponent import org.koin.core.inject object Auth: KoinComponent { private val auth: FirebaseAuth = FirebaseAuth.getInstance() private val prefs: SharedPrefsRepository by inject() fun isSignedIn(): Boolean { return auth.currentUser != null && prefs.getDeviceBuid() != null } fun getFuid(): String { return checkNotNull(auth.currentUser?.uid) } fun getPhoneNumber(): String { return checkNotNull(auth.currentUser?.phoneNumber) } fun signOut() { auth.signOut() } } fun BaseFragment<*,*>.logoutWhenNotSignedIn() { with(requireContext()){ startService(CovidService.stopService(this, hideNotification = true, clearData = true)) } Auth.signOut() val nav = findNavController() nav.popBackStack(R.id.nav_graph, false) nav.navigate(R.id.nav_welcome_fragment) Toast.makeText(this.context, getString(R.string.automatic_logout_warning), Toast.LENGTH_LONG).show() }
0
null
0
0
c16a77a9738434ed2bafaa6866029e07912c975d
1,338
erouska-android
MIT License
common-server/src/commonMain/kotlin/com/toxicbakery/game/dungeon/machine/machineModules.kt
ToxicBakery
224,311,645
false
{"Kotlin": 181267, "CSS": 1779, "HTML": 923}
package com.toxicbakery.game.dungeon.machine import com.toxicbakery.game.dungeon.machine.ai.aiMachineModule import com.toxicbakery.game.dungeon.machine.authentication.authenticationMachineModule import com.toxicbakery.game.dungeon.machine.command.commandMachineModule import com.toxicbakery.game.dungeon.machine.init.initMachineModule import com.toxicbakery.game.dungeon.machine.registration.registrationMachineModule import org.kodein.di.DI val machineModules = DI.Module("machineModules") { import(aiMachineModule) import(authenticationMachineModule) import(commandMachineModule) import(initMachineModule) import(registrationMachineModule) }
0
Kotlin
0
1
12ad3caff3973cf0c834878c42981d9b8255cc71
666
dungeon
Apache License 2.0
javalin/src/test/java/io/javalin/TestContextPath.kt
javalin
87,012,358
false
null
/* * Javalin - https://javalin.io * Copyright 2017 <NAME> * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin import io.javalin.core.util.Util import io.javalin.util.TestUtil import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.containsString import org.junit.Test import java.util.function.BiFunction import java.util.function.Function class TestContextPath { @Test fun `context-path is normalized`() { val normalize = Function<String, String> { Util.normalizeContextPath(it) } assertThat(normalize.apply("path"), `is`("/path")) assertThat(normalize.apply("/path"), `is`("/path")) assertThat(normalize.apply("/path/"), `is`("/path")) assertThat(normalize.apply("//path/"), `is`("/path")) assertThat(normalize.apply("/path//"), `is`("/path")) assertThat(normalize.apply("////path////"), `is`("/path")) } @Test fun `context-path is prefixed`() { val prefix = BiFunction<String, String, String> { contextPath, path -> Util.prefixContextPath(contextPath, path) } assertThat(prefix.apply("/c-p", "*"), `is`("*")) assertThat(prefix.apply("/c-p", "/*"), `is`("/c-p/*")) assertThat(prefix.apply("/c-p", "path"), `is`("/c-p/path")) assertThat(prefix.apply("/c-p", "/path"), `is`("/c-p/path")) assertThat(prefix.apply("/c-p", "//path"), `is`("/c-p/path")) assertThat(prefix.apply("/c-p", "/path/"), `is`("/c-p/path/")) assertThat(prefix.apply("/c-p", "//path//"), `is`("/c-p/path/")) } @Test fun `router works with context -path`() = TestUtil.test(Javalin.create().contextPath("/context-path")) { app, http -> app.get("/hello") { ctx -> ctx.result("Hello World") } assertThat(http.getBody("/hello"), `is`("Not found. Request is below context-path (context-path: '/context-path')")) assertThat(http.getBody("/context-path/hello"), `is`("Hello World")) } @Test fun `router works with multi-level context-path`() = TestUtil.test(Javalin.create().contextPath("/context-path/path-context")) { app, http -> app.get("/hello") { ctx -> ctx.result("Hello World") } assertThat(http.get("/context-path/").status, `is`(404)) assertThat(http.getBody("/context-path/path-context/hello"), `is`("Hello World")) } @Test fun `static-files work with context-path`() = TestUtil.test(Javalin.create().contextPath("/context-path").enableStaticFiles("/public")) { app, http -> assertThat(http.get("/script.js").status, `is`(404)) assertThat(http.getBody("/context-path/script.js"), containsString("JavaScript works")) } @Test fun `welcome-files work with context-path`() = TestUtil.test(Javalin.create().contextPath("/context-path").enableStaticFiles("/public")) { app, http -> assertThat(http.getBody("/context-path/subdir/"), `is`("<h1>Welcome file</h1>")) } }
8
null
570
7,573
6e53b6237dc54fcb05b7a8531941bcb60a17e687
3,016
javalin
Apache License 2.0
app/src/test/java/com/blackcrowsys/ui/residents/ResidentsActivityViewModelTest.kt
blackcrowsys
116,029,789
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "JSON": 2, "Kotlin": 80, "XML": 29, "Java": 1}
package com.blackcrowsys.ui.residents import android.arch.lifecycle.Observer import com.blackcrowsys.MockContentHelper import com.blackcrowsys.R import com.blackcrowsys.exceptions.ErrorMapper import com.blackcrowsys.exceptions.ExceptionTransformer import com.blackcrowsys.repository.ResidentRepository import com.blackcrowsys.security.AESCipher import com.blackcrowsys.util.SchedulerProvider import com.blackcrowsys.util.SharedPreferencesHandler import com.blackcrowsys.util.ViewState import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.MockitoAnnotations import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import java.net.UnknownHostException /** * Unit test for [ResidentsActivityViewModel]. */ const val ENCRYPTED_JWT_TOKEN = "encryptedJwt" const val PIN = "1111" const val JWT_TOKEN = "jwt" @RunWith(RobolectricTestRunner::class) class ResidentsActivityViewModelTest { @Mock private lateinit var mockResidentRepository: ResidentRepository @Mock private lateinit var liveDataObserver: Observer<ViewState> @Mock private lateinit var mockAESCipher: AESCipher @Mock private lateinit var mockSharedPreferencesHandler: SharedPreferencesHandler private val schedulerProvider = SchedulerProvider(Schedulers.trampoline(), Schedulers.trampoline()) private lateinit var residentsActivityViewModel: ResidentsActivityViewModel @Before fun setUp() { val exceptionTransformer = ExceptionTransformer(ErrorMapper(RuntimeEnvironment.application)) MockitoAnnotations.initMocks(this) residentsActivityViewModel = ResidentsActivityViewModel( schedulerProvider, mockResidentRepository, mockAESCipher, mockSharedPreferencesHandler, exceptionTransformer ) residentsActivityViewModel.latestResidentsListState.observeForever(liveDataObserver) residentsActivityViewModel.residentsListBySearchState.observeForever(liveDataObserver) } @Test fun getLatestResidentList() { val argumentCaptor = ArgumentCaptor.forClass(ViewState.Success::class.java) mockDecryptCalls() `when`(mockResidentRepository.getResidents(JWT_TOKEN)).thenReturn( Flowable.just( MockContentHelper.provideListResidents() ) ) residentsActivityViewModel.getLatestResidentList(PIN) verify(liveDataObserver).onChanged(argumentCaptor.capture()) assertEquals(MockContentHelper.provideListResidents(), argumentCaptor.value.data) } @Test fun `getLatestResidentList when network error`() { val argumentCaptor = ArgumentCaptor.forClass(ViewState.Error::class.java) mockDecryptCalls() `when`(mockResidentRepository.getResidents(JWT_TOKEN)).thenReturn( Flowable.error(UnknownHostException()) ) residentsActivityViewModel.getLatestResidentList(PIN) verify(liveDataObserver).onChanged(argumentCaptor.capture()) assert(argumentCaptor.value is ViewState.Error) assertEquals( RuntimeEnvironment.application.getString(R.string.unable_to_connect_to_be_error), argumentCaptor.value.throwable.message ) } @Test fun performLetterBasedSearchGivenEmptySearchString() { val argumentCaptor = ArgumentCaptor.forClass(ViewState.Success::class.java) `when`(mockResidentRepository.getResidentsFromCache()).thenReturn( Flowable.just( MockContentHelper.provideListResidents() ) ) residentsActivityViewModel.performLetterBasedSearch("") verify(liveDataObserver).onChanged(argumentCaptor.capture()) verify(mockResidentRepository).getResidentsFromCache() verify( mockResidentRepository, never() ).getResidentsGivenNameQuery(ArgumentMatchers.anyString(), ArgumentMatchers.anyString()) assertEquals(MockContentHelper.provideListResidents(), argumentCaptor.value.data) } @Test fun performLetterBasedSearchGivenSearchString() { val argumentCaptor = ArgumentCaptor.forClass(ViewState.Success::class.java) val searchString = "ted" `when`(mockResidentRepository.getResidentsGivenNameQuery(searchString, searchString)) .thenReturn(Flowable.just(MockContentHelper.provideListResidents())) residentsActivityViewModel.performLetterBasedSearch(searchString) verify(liveDataObserver).onChanged(argumentCaptor.capture()) verify(mockResidentRepository).getResidentsGivenNameQuery(searchString, searchString) verify(mockResidentRepository, never()).getResidentsFromCache() assertEquals(MockContentHelper.provideListResidents(), argumentCaptor.value.data) } private fun mockDecryptCalls() { `when`(mockSharedPreferencesHandler.getEncryptedJwtToken()).thenReturn(Observable.just(ENCRYPTED_JWT_TOKEN)) `when`(mockAESCipher.decrypt(PIN, ENCRYPTED_JWT_TOKEN)).thenReturn(JWT_TOKEN) } }
1
Kotlin
0
1
0610d1474ea83b7b16e9811111e6946ea983d32c
5,471
dinewell-carehome-app
MIT License
library/src/jsMain/kotlin/antd/Align.kt
tonycode
694,166,849
false
{"Kotlin": 106413, "Shell": 511}
package antd @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) // language=JavaScript @JsName("""(/*union*/{ start: 'start', end: 'end', center: 'center', baseline: 'baseline' }/*union*/)""") /** * Align items * * see: https://ant.design/components/space#api "align" property */ sealed external interface Align { companion object { val start: Align val end: Align val center: Align val baseline: Align } }
0
Kotlin
0
3
87a22f907baab2e7605b84bfe6e7fbc3e6b7d8e3
498
kotlin-antd
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLInputBotInlineResultGame.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.computeTLStringSerializedSize import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * inputBotInlineResultGame#4fa417f2 * * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLInputBotInlineResultGame() : TLAbsInputBotInlineResult() { override var id: String = "" var shortName: String = "" override var sendMessage: TLAbsInputBotInlineMessage = TLInputBotInlineMessageGame() private val _constructor: String = "inputBotInlineResultGame#4fa417f2" override val constructorId: Int = CONSTRUCTOR_ID constructor( id: String, shortName: String, sendMessage: TLAbsInputBotInlineMessage ) : this() { this.id = id this.shortName = shortName this.sendMessage = sendMessage } @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { writeString(id) writeString(shortName) writeTLObject(sendMessage) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { id = readString() shortName = readString() sendMessage = readTLObject<TLAbsInputBotInlineMessage>() } override fun computeSerializedSize(): Int { var size = SIZE_CONSTRUCTOR_ID size += computeTLStringSerializedSize(id) size += computeTLStringSerializedSize(shortName) size += sendMessage.computeSerializedSize() return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLInputBotInlineResultGame) return false if (other === this) return true return id == other.id && shortName == other.shortName && sendMessage == other.sendMessage } companion object { const val CONSTRUCTOR_ID: Int = 0x4fa417f2 } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
2,285
kotlogram-resurrected
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLInputBotInlineResultGame.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.computeTLStringSerializedSize import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * inputBotInlineResultGame#4fa417f2 * * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLInputBotInlineResultGame() : TLAbsInputBotInlineResult() { override var id: String = "" var shortName: String = "" override var sendMessage: TLAbsInputBotInlineMessage = TLInputBotInlineMessageGame() private val _constructor: String = "inputBotInlineResultGame#4fa417f2" override val constructorId: Int = CONSTRUCTOR_ID constructor( id: String, shortName: String, sendMessage: TLAbsInputBotInlineMessage ) : this() { this.id = id this.shortName = shortName this.sendMessage = sendMessage } @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { writeString(id) writeString(shortName) writeTLObject(sendMessage) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { id = readString() shortName = readString() sendMessage = readTLObject<TLAbsInputBotInlineMessage>() } override fun computeSerializedSize(): Int { var size = SIZE_CONSTRUCTOR_ID size += computeTLStringSerializedSize(id) size += computeTLStringSerializedSize(shortName) size += sendMessage.computeSerializedSize() return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLInputBotInlineResultGame) return false if (other === this) return true return id == other.id && shortName == other.shortName && sendMessage == other.sendMessage } companion object { const val CONSTRUCTOR_ID: Int = 0x4fa417f2 } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
2,285
kotlogram-resurrected
MIT License
app/src/main/java/com/saraha/paws/View/AnimalViews/AddEditAnimal/Fragment/AddEditAnimalPage3Fragment.kt
SamPaddock
435,092,298
false
{"Kotlin": 193863}
package com.saraha.paws.View.AnimalViews.AddEditAnimal.Fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.widget.addTextChangedListener import androidx.lifecycle.ViewModelProvider import com.google.android.material.textfield.TextInputEditText import com.saraha.paws.Model.Animal import com.saraha.paws.Util.UserHelper import com.saraha.paws.View.AnimalViews.AddEditAnimal.AddEditAnimalActivity import com.saraha.paws.View.AnimalViews.AddEditAnimal.AddEditAnimalViewModel import com.saraha.paws.databinding.FragmentAddEditAnimalPage3Binding class AddEditAnimalPage3Fragment : Fragment() { //View model and binding lateinit property private lateinit var viewModel: AddEditAnimalViewModel lateinit var binding: FragmentAddEditAnimalPage3Binding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentAddEditAnimalPage3Binding.inflate(inflater, container, false) viewModel = ViewModelProvider(requireActivity() as AddEditAnimalActivity)[AddEditAnimalViewModel::class.java] //Get passed data from activity to set in fragment val animal = this.arguments?.getSerializable("animal") if (animal != null) setValues(animal as Animal) onFieldFocus() return binding.root } //Function to set User input when returning to fragment private fun setValues(animal: Animal) { if (animal.grooming.isNotEmpty()){ binding.edittextAddAnimalGrooming.setText(animal.grooming) } if (animal.medical.isNotEmpty()){ binding.edittextAddAnimalMedical.setText(animal.medical) } } //Set onOutOfFocus on textFields private fun onFieldFocus(){ binding.edittextAddAnimalGrooming.addTextChangedListener { viewModel.validateText(binding.edittextAddAnimalGrooming,5) } binding.edittextAddAnimalMedical.addTextChangedListener { viewModel.validateText(binding.edittextAddAnimalMedical,6) } } }
0
Kotlin
0
0
cf8ea4d607c6df79385469f991a3457fa0b42a01
2,165
Project_Tuwaiq
Creative Commons Attribution 3.0 Unported
core/src/test/kotlin/com/github/inflab/spring/data/mongodb/core/extension/MongoTemplateExtensionKtTest.kt
inflearn
686,606,328
false
{"Kotlin": 816570}
package com.github.inflab.spring.data.mongodb.core.extension import com.github.inflab.spring.data.mongodb.core.aggregation.AggregationDsl import io.kotest.core.spec.style.FreeSpec import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.mockk.verifySequence import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.aggregation.Aggregation internal class MongoTemplateExtensionKtTest : FreeSpec({ data class TestCollection(val id: String) data class TestResult(val count: Int) "should call aggregate with aggregation and collectionName" { // given val mongoTemplate = mockk<MongoTemplate>() val aggregation: AggregationDsl.() -> Unit = { count("count") } val collectionName = "SimpleCollection" every { mongoTemplate.aggregate(any<Aggregation>(), any<String>(), any<Class<*>>()) } returns mockk() // when mongoTemplate.aggregate<TestCollection, TestResult>( aggregation = aggregation, collectionName = collectionName, ) // then verify { mongoTemplate.aggregate( any<Aggregation>(), collectionName, TestResult::class.java, ) } } "should call aggregate with aggregation and collectionName from class" { // given val mongoTemplate = mockk<MongoTemplate>() val aggregation: AggregationDsl.() -> Unit = { count("count") } val collectionName = TestCollection::class.java.simpleName every { mongoTemplate.getCollectionName(any()) } returns collectionName every { mongoTemplate.aggregate(any<Aggregation>(), any<String>(), any<Class<*>>()) } returns mockk() // when mongoTemplate.aggregate<TestCollection, TestResult>( aggregation = aggregation, ) // then verifySequence { mongoTemplate.getCollectionName(TestCollection::class.java) mongoTemplate.aggregate( any<Aggregation>(), collectionName, TestResult::class.java, ) } } })
9
Kotlin
6
9
d0a2feb4c518d61003bfd3fcde2f13825ea1e4d5
2,195
spring-data-mongodb-kotlin-dsl
MIT License
integration-tests/resteasy-reactive-kotlin/standard/src/test/kotlin/io/quarkus/it/resteasy/reactive/kotlin/FlowResourceTest.kt
quarkusio
139,914,932
false
null
package io.quarkus.it.resteasy.reactive.kotlin import io.quarkus.test.common.http.TestHTTPResource import io.quarkus.test.junit.QuarkusTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import javax.ws.rs.client.ClientBuilder import javax.ws.rs.client.WebTarget import javax.ws.rs.sse.SseEventSource @QuarkusTest class FlowResourceTest { @TestHTTPResource("/flow") var flowPath: String? = null @Test fun testSeeStrings() { testSse("str", 5) { assertThat(it).containsExactly("Hello", "From", "Kotlin", "Flow") } } @Test fun testSeeJson() { testSse("json", 10) { assertThat(it).containsExactly( "{\"name\":\"Barbados\",\"capital\":\"Bridgetown\"}", "{\"name\":\"Mauritius\",\"capital\":\"Port Louis\"}", "{\"name\":\"Fiji\",\"capital\":\"Suva\"}") } } private fun testSse(path: String, timeout: Long, assertion: (List<String>) -> Unit) { val client = ClientBuilder.newBuilder().build() val target: WebTarget = client.target("$flowPath/$path") SseEventSource.target(target).reconnectingEvery(Int.MAX_VALUE.toLong(), TimeUnit.SECONDS) .build().use { eventSource -> val res = CompletableFuture<List<String>>() val collect = Collections.synchronizedList(ArrayList<String>()) eventSource.register({ inboundSseEvent -> collect.add(inboundSseEvent.readData()) }, { throwable -> res.completeExceptionally(throwable) }) { res.complete(collect) } eventSource.open() val list = res.get(timeout, TimeUnit.SECONDS) assertion(list) } } }
1,831
null
4
9,440
9755810c17969df15dfc3a04f162d4083dfb7400
1,900
quarkus
Apache License 2.0
android/src/main/java/io/mosip/tuvali/exception/ErrorCode.kt
mosip
572,876,523
false
{"Kotlin": 156258, "Swift": 66396, "Java": 11120, "TypeScript": 5017, "Ruby": 1353, "Objective-C": 550, "JavaScript": 77}
package io.mosip.tuvali.exception // Error Code format // <Component(2)+Role(1)>(3char)_<Stage>(3char)_<Number>(3char) Eg: TVW-CON-001 // Stage --> CON(Connection) | KEX(Key Exchange) | ENC(Encryption) | TRA(Transfer) | REP(Report) | DEC(Decryption) // Component+ROLE --> TVW(Tuvali+Wallet) | TVV(Tuvali+Verifier) | TUV(Tuvali where role is unknown) // UNK --> If stage is not known enum class ErrorCode(val value: String) { UnknownException("TUV_UNK_001"), WalletUnknownException("TVW_UNK_001"), CentralStateHandlerException("TVW_UNK_002"), WalletTransferHandlerException("TVW_UNK_003"), VerifierUnknownException("TVV_UNK_001"), PeripheralStateHandlerException("TVV_UNK_002"), VerifierTransferHandlerException("TVV_UNK_003"), InvalidURIException("TVW_CON_001"), MTUNegotiationException("TVW_CON_002"), ServiceNotFoundException("TVW_CON_003"), //TODO: Create specific error codes for the below exception TransferFailedException("TVW_REP_001"), UnsupportedMTUSizeException("TVV_CON_001"), CorruptedChunkReceivedException("TVV_TRA_001"), TooManyFailureChunksException("TVV_TRA_002"), }
26
Kotlin
10
9
987b2d2512e57010c8a115b63b3b9093767c19ac
1,122
tuvali
MIT License
android/src/main/java/io/mosip/tuvali/exception/ErrorCode.kt
mosip
572,876,523
false
{"Kotlin": 156258, "Swift": 66396, "Java": 11120, "TypeScript": 5017, "Ruby": 1353, "Objective-C": 550, "JavaScript": 77}
package io.mosip.tuvali.exception // Error Code format // <Component(2)+Role(1)>(3char)_<Stage>(3char)_<Number>(3char) Eg: TVW-CON-001 // Stage --> CON(Connection) | KEX(Key Exchange) | ENC(Encryption) | TRA(Transfer) | REP(Report) | DEC(Decryption) // Component+ROLE --> TVW(Tuvali+Wallet) | TVV(Tuvali+Verifier) | TUV(Tuvali where role is unknown) // UNK --> If stage is not known enum class ErrorCode(val value: String) { UnknownException("TUV_UNK_001"), WalletUnknownException("TVW_UNK_001"), CentralStateHandlerException("TVW_UNK_002"), WalletTransferHandlerException("TVW_UNK_003"), VerifierUnknownException("TVV_UNK_001"), PeripheralStateHandlerException("TVV_UNK_002"), VerifierTransferHandlerException("TVV_UNK_003"), InvalidURIException("TVW_CON_001"), MTUNegotiationException("TVW_CON_002"), ServiceNotFoundException("TVW_CON_003"), //TODO: Create specific error codes for the below exception TransferFailedException("TVW_REP_001"), UnsupportedMTUSizeException("TVV_CON_001"), CorruptedChunkReceivedException("TVV_TRA_001"), TooManyFailureChunksException("TVV_TRA_002"), }
26
Kotlin
10
9
987b2d2512e57010c8a115b63b3b9093767c19ac
1,122
tuvali
MIT License
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/bugreport/NetworkTypeCollector.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2022 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.mobile.android.vpn.bugreport import android.content.Context import android.content.SharedPreferences import android.net.* import android.net.ConnectivityManager.NetworkCallback import android.os.SystemClock import androidx.core.content.edit import com.duckduckgo.app.di.AppCoroutineScope import com.duckduckgo.app.global.extensions.getPrivateDnsServerName import com.duckduckgo.app.global.extensions.isPrivateDnsActive import com.duckduckgo.di.scopes.VpnScope import com.duckduckgo.mobile.android.vpn.AppTpVpnFeature import com.duckduckgo.mobile.android.vpn.VpnFeaturesRegistry import com.duckduckgo.mobile.android.vpn.feature.AppTpFeatureConfig import com.duckduckgo.mobile.android.vpn.feature.AppTpSetting import com.duckduckgo.mobile.android.vpn.service.TrackerBlockingVpnService import com.duckduckgo.mobile.android.vpn.service.VpnServiceCallbacks import com.duckduckgo.mobile.android.vpn.state.VpnStateCollectorPlugin import com.duckduckgo.mobile.android.vpn.state.VpnStateMonitor.VpnStopReason import com.frybits.harmony.getHarmonySharedPreferences import com.squareup.anvil.annotations.ContributesMultibinding import com.squareup.moshi.Moshi import dagger.SingleInstanceIn import java.net.InetAddress import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import logcat.LogPriority import logcat.asLog import logcat.logcat import org.json.JSONObject @ContributesMultibinding( scope = VpnScope::class, boundType = VpnStateCollectorPlugin::class, ) @ContributesMultibinding( scope = VpnScope::class, boundType = VpnServiceCallbacks::class, ) @SingleInstanceIn(VpnScope::class) class NetworkTypeCollector @Inject constructor( private val context: Context, private val appTpFeatureConfig: AppTpFeatureConfig, @AppCoroutineScope private val coroutineScope: CoroutineScope, private val vpnFeaturesRegistry: VpnFeaturesRegistry, ) : VpnStateCollectorPlugin, VpnServiceCallbacks { private val databaseDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() private val adapter = Moshi.Builder().build().adapter(NetworkInfo::class.java) private val isPrivateDnsSupportEnabled: Boolean get() = appTpFeatureConfig.isEnabled(AppTpSetting.PrivateDnsSupport) private val isInterceptDnsRequestsEnabled: Boolean get() = appTpFeatureConfig.isEnabled(AppTpSetting.InterceptDnsRequests) private val preferences: SharedPreferences get() = context.getHarmonySharedPreferences(FILENAME) private var currentNetworkInfo: String? get() = preferences.getString(NETWORK_INFO_KEY, null) set(value) = preferences.edit { putString(NETWORK_INFO_KEY, value) } private val wifiNetworkRequest = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build() private val cellularNetworkRequest = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) .build() private val privateDnsRequest = NetworkRequest.Builder().build() private val wifiNetworkCallback = object : NetworkCallback() { override fun onAvailable(network: Network) { updateNetworkInfo(Connection(network.networkHandle, NetworkType.WIFI, NetworkState.AVAILABLE)) } override fun onLost(network: Network) { updateNetworkInfo(Connection(network.networkHandle, NetworkType.WIFI, NetworkState.LOST)) } } private val cellularNetworkCallback = object : NetworkCallback() { override fun onAvailable(network: Network) { updateNetworkInfo( Connection(network.networkHandle, NetworkType.CELLULAR, NetworkState.AVAILABLE, context.mobileNetworkCode(NetworkType.CELLULAR)), ) } override fun onLost(network: Network) { updateNetworkInfo( Connection(network.networkHandle, NetworkType.CELLULAR, NetworkState.LOST, context.mobileNetworkCode(NetworkType.CELLULAR)), ) } } private val privateDnsCallback = object : NetworkCallback() { private var privateDnsCacheValue: String? = null override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { super.onLinkPropertiesChanged(network, linkProperties) logcat { "onLinkPropertiesChanged: $linkProperties" } logcat { "network: $network" } val shouldRestart = AtomicBoolean(false) // check for Android Private DNS setting val privateDnsServerName = context.getPrivateDnsServerName() logcat { """ isPrivateDnsActive = ${context.isPrivateDnsActive()}, server = ${context.getPrivateDnsServerName()} (${runCatching { InetAddress.getAllByName(context.getPrivateDnsServerName()) }.getOrNull()?.map { it.hostAddress }}) """.trimIndent() } // Check if VPN reconfiguration is needed if (isPrivateDnsSupportEnabled && privateDnsCacheValue != privateDnsServerName) { logcat { "Private DNS changed, should reconfigure VPN" } shouldRestart.set(true) } // update values cached values anyways privateDnsCacheValue = privateDnsServerName if (shouldRestart.getAndSet(false)) { coroutineScope.launch { // we check for skip here because the check needs a coroutine scope and we don't want to wrap the whole callback // inside a coroutine if (shouldProceedWithVpnRestart()) { logcat { "Reconfiguring VPN now" } TrackerBlockingVpnService.restartVpnService(context) } else { logcat { "Reconfiguring VPN SKIPPED" } } } } } } override val collectorName = "networkInfo" override suspend fun collectVpnRelatedState(appPackageId: String?): JSONObject = withContext(databaseDispatcher) { return@withContext getNetworkInfoJsonObject() } override fun onVpnStarted(coroutineScope: CoroutineScope) { (context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?)?.let { it.safeRegisterNetworkCallback(wifiNetworkRequest, wifiNetworkCallback) it.safeRegisterNetworkCallback(cellularNetworkRequest, cellularNetworkCallback) it.safeRegisterNetworkCallback(privateDnsRequest, privateDnsCallback) } } override fun onVpnStopped( coroutineScope: CoroutineScope, vpnStopReason: VpnStopReason, ) { (context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?)?.let { // always unregistered, even if not previously registered it.safeUnregisterNetworkCallback(wifiNetworkCallback) it.safeUnregisterNetworkCallback(cellularNetworkCallback) it.safeUnregisterNetworkCallback(privateDnsCallback) } } private suspend fun shouldProceedWithVpnRestart(): Boolean { return vpnFeaturesRegistry.getRegisteredFeatures().size == 1 && vpnFeaturesRegistry.isFeatureRegistered(AppTpVpnFeature.APPTP_VPN) && isInterceptDnsRequestsEnabled } private fun updateNetworkInfo(connection: Connection) { coroutineScope.launch(databaseDispatcher) { try { val previousNetworkInfo: NetworkInfo? = currentNetworkInfo?.let { adapter.fromJson(it) } // If android notifies of a lost connection that is not the current one, just return if (connection.state == NetworkState.LOST && previousNetworkInfo?.currentNetwork?.netId != null && connection.netId != previousNetworkInfo.currentNetwork.netId ) { logcat { "Lost of previously switched connection: $connection, current: ${previousNetworkInfo.currentNetwork}" } return@launch } // Calculate timestamp for when the network type last switched val previousNetworkType = previousNetworkInfo?.currentNetwork val didChange = previousNetworkType != connection val lastSwitchTimestampMillis = if (didChange) { SystemClock.elapsedRealtime() } else { previousNetworkInfo?.lastSwitchTimestampMillis ?: SystemClock.elapsedRealtime() } // Calculate how long ago the network type last switched val previousNetwork = previousNetworkInfo?.currentNetwork val secondsSinceLastSwitch = TimeUnit.MILLISECONDS.toSeconds(SystemClock.elapsedRealtime() - lastSwitchTimestampMillis) val jsonInfo = adapter.toJson( NetworkInfo( currentNetwork = connection, previousNetwork = previousNetwork, lastSwitchTimestampMillis = lastSwitchTimestampMillis, secondsSinceLastSwitch = secondsSinceLastSwitch, ), ) currentNetworkInfo = jsonInfo logcat { "New network info $jsonInfo" } } catch (t: Throwable) { logcat(LogPriority.WARN) { t.asLog() } } } } private fun updateSecondsSinceLastSwitch() { val networkInfo: NetworkInfo = currentNetworkInfo?.let { adapter.fromJson(it) } ?: return networkInfo.copy( secondsSinceLastSwitch = TimeUnit.MILLISECONDS.toSeconds(SystemClock.elapsedRealtime() - networkInfo.lastSwitchTimestampMillis), ).run { currentNetworkInfo = adapter.toJson(this) } } private fun getNetworkInfoJsonObject(): JSONObject { updateSecondsSinceLastSwitch() // redact the lastSwitchTimestampMillis from the report val info = currentNetworkInfo?.let { // Redact some values (set to -999) as they could be static values val temp = adapter.fromJson(it) adapter.toJson( temp?.copy( lastSwitchTimestampMillis = -999, currentNetwork = temp.currentNetwork.copy(netId = -999), previousNetwork = temp.previousNetwork?.copy(netId = -999), ), ) } ?: return JSONObject() return JSONObject(info) } private fun ConnectivityManager.safeUnregisterNetworkCallback(networkCallback: NetworkCallback) { kotlin.runCatching { unregisterNetworkCallback(networkCallback) }.onFailure { logcat(LogPriority.ERROR) { it.asLog() } } } private fun ConnectivityManager.safeRegisterNetworkCallback(networkRequest: NetworkRequest, networkCallback: NetworkCallback) { kotlin.runCatching { registerNetworkCallback(networkRequest, networkCallback) }.onFailure { logcat(LogPriority.ERROR) { it.asLog() } } } private fun Context.mobileNetworkCode(networkType: NetworkType): Int? { return if (networkType == NetworkType.WIFI) { null } else { return kotlin.runCatching { resources.configuration.mnc }.getOrNull() } } internal data class NetworkInfo( val currentNetwork: Connection, val previousNetwork: Connection? = null, val lastSwitchTimestampMillis: Long, val secondsSinceLastSwitch: Long, ) internal data class Connection(val netId: Long, val type: NetworkType, val state: NetworkState, val mnc: Int? = null) internal enum class NetworkType { WIFI, CELLULAR, } internal enum class NetworkState { AVAILABLE, LOST, } companion object { private const val FILENAME = "network.type.collector.file.v1" private const val NETWORK_INFO_KEY = "network.info.key" } }
5
null
836
3,148
70b67f25f17cf84ed3cda99d26e5466077e5d9a2
13,087
Android
Apache License 2.0
src/main/kotlin/io/github/hanseter/json/queryengine/queries/GreaterThanQueryBuilder.kt
Hanseter
244,838,139
false
{"Kotlin": 17592}
package io.github.hanseter.json.queryengine.queries import io.github.hanseter.json.queryengine.Query class GreaterThanQueryBuilder : AttributeQueryBuilder<GreaterThanQueryBuilder>() { fun withLowerBound(lowerBound: String): GreaterThanQueryBuilder { this.queryCreator = { path -> Query { data -> val value = path.getString(data.data) ?: return@Query false value >= lowerBound } } return this } fun withLowerBound(lowerBound: Double): GreaterThanQueryBuilder { this.queryCreator = { path -> Query { data -> val value = path.getNumber(data.data) ?: return@Query false value.toDouble() >= lowerBound } } return this } fun withLowerBound(lowerBound: Long): GreaterThanQueryBuilder { this.queryCreator = { path -> Query { data -> val value = path.getNumber(data.data) ?: return@Query false value.toLong() >= lowerBound } } return this } }
1
Kotlin
0
0
b3bb3a434722757eaa286661dd0c04d8c3d573b6
1,102
JSONQueryEngine
MIT License
core/src/main/kotlin/materialui/components/link/enums/LinkUnderline.kt
subroh0508
167,797,152
false
null
package materialui.components.link.enums @Suppress("EnumEntryName") enum class LinkUnderline { none, hover, always }
14
Kotlin
27
81
a959a951ace3b9bd49dc5405bea150d4d53cf162
121
kotlin-material-ui
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/aps/CfnWorkspaceDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.aps import io.cloudshiftdev.awscdkdsl.CfnTagDsl import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.CfnTag import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.aps.CfnWorkspace import software.constructs.Construct /** * The `AWS::APS::Workspace` type specifies an Amazon Managed Service for Prometheus ( Amazon * Managed Service for Prometheus ) workspace. * * A *workspace* is a logical and isolated Prometheus server dedicated to Prometheus resources such * as metrics. You can have one or more workspaces in each Region in your account. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.aps.*; * CfnWorkspace cfnWorkspace = CfnWorkspace.Builder.create(this, "MyCfnWorkspace") * .alertManagerDefinition("alertManagerDefinition") * .alias("alias") * .loggingConfiguration(LoggingConfigurationProperty.builder() * .logGroupArn("logGroupArn") * .build()) * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html) */ @CdkDslMarker public class CfnWorkspaceDsl( scope: Construct, id: String, ) { private val cdkBuilder: CfnWorkspace.Builder = CfnWorkspace.Builder.create(scope, id) private val _tags: MutableList<CfnTag> = mutableListOf() /** * The alert manager definition for the workspace, as a string. * * For more information, see * [Alert manager and templating](https://docs.aws.amazon.com/prometheus/latest/userguide/AMP-alert-manager.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html#cfn-aps-workspace-alertmanagerdefinition) * * @param alertManagerDefinition The alert manager definition for the workspace, as a string. */ public fun alertManagerDefinition(alertManagerDefinition: String) { cdkBuilder.alertManagerDefinition(alertManagerDefinition) } /** * An alias that you assign to this workspace to help you identify it. * * It does not need to be unique. * * The alias can be as many as 100 characters and can include any type of characters. Amazon * Managed Service for Prometheus automatically strips any blank spaces from the beginning and * end of the alias that you specify. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html#cfn-aps-workspace-alias) * * @param alias An alias that you assign to this workspace to help you identify it. */ public fun alias(alias: String) { cdkBuilder.alias(alias) } /** * The LoggingConfiguration attribute is used to set the logging configuration for the * workspace. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html#cfn-aps-workspace-loggingconfiguration) * * @param loggingConfiguration The LoggingConfiguration attribute is used to set the logging * configuration for the workspace. */ public fun loggingConfiguration(loggingConfiguration: IResolvable) { cdkBuilder.loggingConfiguration(loggingConfiguration) } /** * The LoggingConfiguration attribute is used to set the logging configuration for the * workspace. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html#cfn-aps-workspace-loggingconfiguration) * * @param loggingConfiguration The LoggingConfiguration attribute is used to set the logging * configuration for the workspace. */ public fun loggingConfiguration( loggingConfiguration: CfnWorkspace.LoggingConfigurationProperty ) { cdkBuilder.loggingConfiguration(loggingConfiguration) } /** * A list of tag keys and values to associate with the workspace. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html#cfn-aps-workspace-tags) * * @param tags A list of tag keys and values to associate with the workspace. */ public fun tags(tags: CfnTagDsl.() -> Unit) { _tags.add(CfnTagDsl().apply(tags).build()) } /** * A list of tag keys and values to associate with the workspace. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-aps-workspace.html#cfn-aps-workspace-tags) * * @param tags A list of tag keys and values to associate with the workspace. */ public fun tags(tags: Collection<CfnTag>) { _tags.addAll(tags) } public fun build(): CfnWorkspace { if (_tags.isNotEmpty()) cdkBuilder.tags(_tags) return cdkBuilder.build() } }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
5,443
awscdk-dsl-kotlin
Apache License 2.0
build-attribution/testSrc/com/android/build/attribution/analyzers/TasksConfigurationIssuesAnalyzerTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.attribution.analyzers import com.android.SdkConstants import com.android.build.attribution.BuildAttributionManagerImpl import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.gradle.project.build.attribution.BuildAttributionManager import com.android.tools.idea.testing.AndroidGradleProjectRule import com.android.tools.idea.testing.TestProjectPaths import com.android.utils.FileUtils import com.google.common.truth.Truth.assertThat import com.intellij.openapi.util.io.FileUtil import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import java.io.File class TasksConfigurationIssuesAnalyzerTest { @get:Rule val myProjectRule = AndroidGradleProjectRule() @Before fun setUp() { StudioFlags.BUILD_ATTRIBUTION_ENABLED.override(true) } @After fun tearDown() { StudioFlags.BUILD_ATTRIBUTION_ENABLED.clearOverride() } private fun setUpProject() { myProjectRule.load(TestProjectPaths.SIMPLE_APPLICATION) FileUtil.appendToFile(FileUtils.join(File(myProjectRule.project.basePath!!), "app", SdkConstants.FN_BUILD_GRADLE), """ abstract class DummyTask extends DefaultTask { @OutputDirectory abstract DirectoryProperty getOutputDir() @TaskAction def run() { // do nothing } } task dummy1(type: DummyTask) { outputDir = file("${"$"}buildDir/outputs/shared_output") } task dummy2(type: DummyTask) { outputDir = file("${"$"}buildDir/outputs/shared_output") } afterEvaluate { project -> android.applicationVariants.all { variant -> def mergeResourcesTask = tasks.getByPath("merge${"$"}{variant.name.capitalize()}Resources") mergeResourcesTask.dependsOn dummy1 mergeResourcesTask.dependsOn dummy2 } dummy2.dependsOn dummy1 } """.trimIndent()) } @Test fun testTasksConfigurationIssuesAnalyzer() { setUpProject() myProjectRule.invokeTasks("assembleDebug") val buildAttributionManager = myProjectRule.project.getService(BuildAttributionManager::class.java) as BuildAttributionManagerImpl assertThat(buildAttributionManager.analyzersProxy.getTasksSharingOutput()).hasSize(1) val tasksSharingOutput = buildAttributionManager.analyzersProxy.getTasksSharingOutput()[0] assertThat(tasksSharingOutput.outputFilePath).endsWith("app/build/outputs/shared_output") assertThat(tasksSharingOutput.taskList).hasSize(2) assertThat(tasksSharingOutput.taskList[0].getTaskPath()).isEqualTo(":app:dummy1") assertThat(tasksSharingOutput.taskList[0].taskType).isEqualTo("DummyTask") assertThat(tasksSharingOutput.taskList[0].originPlugin.toString()).isEqualTo("script :app:build.gradle") assertThat(tasksSharingOutput.taskList[1].getTaskPath()).isEqualTo(":app:dummy2") assertThat(tasksSharingOutput.taskList[1].taskType).isEqualTo("DummyTask") assertThat(tasksSharingOutput.taskList[1].originPlugin.toString()).isEqualTo("script :app:build.gradle") } }
1
Kotlin
220
857
8d22f48a9233679e85e42e8a7ed78bbff2c82ddb
3,737
android
Apache License 2.0
src/main/java/kr/co/byrobot/petroneapi/Wifi/selector/ExplicitSelectorManager.kt
roylanceMichael
113,386,485
true
{"Kotlin": 171938}
package kr.co.byrobot.petroneapi.Wifi.selector import kotlinx.coroutines.experimental.* import kr.co.byrobot.petroneapi.Wifi.* import java.io.* import java.nio.channels.* import java.util.concurrent.* /** * A selector manager that creates selector and loop thread lazily and only disposes it on [close]. */ class ExplicitSelectorManager : Closeable, DisposableHandle, SelectorManagerSupport() { @Volatile private var closed = false private val selector = lazy { ensureStarted(); Selector.open()!! } private val interestQueue = ArrayBlockingQueue<Selectable>(1000) private val selectorJob = launch(selectorsCoroutineDispatcher, false) { try { selectorLoop(selector.value) } catch (expected: ClosedSelectorException) { } }.apply { invokeOnCompletion { selector.value.close() } } /** * Closes instance, releases all resources. All sockets that were created by this instance becomes illegal * and should be closed as well. */ override fun close() { closed = true if (selector.isInitialized()) { // due to bug in JDK we should never close selector outside of the selector loop // this is why we have to set flag, signal selector to wakeup and wait until // the selector loop completion selector.value.apply { wakeup() if (!selectorJob.isCompleted) { runBlocking { selectorJob.join() } } close() } } } override fun dispose() { close() } override fun notifyClosed(s: Selectable) { if (selector.isInitialized()) { s.channel.keyFor(selector.value)?.let { key -> key.subject?.let { attachment -> notifyClosedImpl(selector.value, key, attachment) } key.subject = null selector.value.wakeup() } } } suspend override fun select(selectable: Selectable, interest: SelectInterest) { select(selectable, interest, { interestQueue.put(it); selector.value.wakeup() }) } private tailrec fun selectorLoop(selector: Selector) { if (!closed && selector.select() > 0) { val keys = selector.selectedKeys().iterator() while (keys.hasNext()) { val key = keys.next() keys.remove() handleSelectedKey(key) } } if (closed) return while (!closed) { val selectable = interestQueue.poll() ?: break applyInterest(selector, selectable) } selectorLoop(selector) } private fun ensureStarted() { if (closed) throw ClosedSelectorException() selectorJob.start() } }
0
Kotlin
0
0
6fadf2cddc754431f15b9e0090e26bf2da7d71a1
2,922
agueirahiewkghua
MIT License
save-backend/src/main/kotlin/com/saveourtool/save/backend/event/UserListener.kt
saveourtool
300,279,336
false
{"Kotlin": 3294618, "SCSS": 43215, "JavaScript": 5532, "HTML": 5481, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
package com.saveourtool.save.backend.event import com.saveourtool.save.backend.service.NotificationService import com.saveourtool.save.backend.service.UserDetailsService import com.saveourtool.save.domain.Role import com.saveourtool.save.entities.Notification import com.saveourtool.save.entities.User import com.saveourtool.save.info.UserStatus import org.springframework.context.event.EventListener import org.springframework.stereotype.Component /** * A user listener for sending notifications. */ @Component class UserListener( private val userDetailsService: UserDetailsService, private val notificationService: NotificationService, ) { /** * @param user new user */ @EventListener fun createUser(user: User) { if (user.status == UserStatus.NOT_APPROVED) { val recipients = userDetailsService.findByRole(Role.SUPER_ADMIN.asSpringSecurityRole()) val notifications = recipients.map { Notification( message = messageNewUser(user), user = it, ) } notificationService.saveAll(notifications) } } companion object { /** * @param user * @return message */ fun messageNewUser(user: User) = """ New user: ${user.name} is waiting for approve of his account. """.trimIndent() } }
194
Kotlin
2
36
d960424ffbb020bd99a06cc93b660467ebe73c66
1,419
save-cloud
MIT License
src/jvmMain/kotlin/com/ktmi/irc/IRC.kt
mkpazon
264,875,261
true
{"Kotlin": 100188}
package com.ktmi.irc import com.ktmi.irc.IrcState.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.launch import okhttp3.* import kotlin.coroutines.CoroutineContext /** Actual implementation of TwitchIRC interface for JVM */ actual class IRC actual constructor( private val token: String, private val username: String, private val secure: Boolean, context: CoroutineContext ) : TwitchIRC, WebSocketListener(), CoroutineScope by CoroutineScope(context) { private val client = OkHttpClient() private var ws: WebSocket? = null private val messageChannel: Channel<RawMessage> = Channel(Channel.UNLIMITED) override val messages: ReceiveChannel<RawMessage> get() = messageChannel private val stateChannel: Channel<IrcState> = Channel(Channel.UNLIMITED) override val states: ReceiveChannel<IrcState> get() = stateChannel private var state: IrcState = DISCONNECTED override val currentState: IrcState get() = state // === API === override fun connect() { disconnect() val port = if (secure) 443 else 80 val protocol = if (secure) "wss" else "ws" val request = Request.Builder().apply { url("$protocol://irc-ws.chat.twitch.tv:$port") }.build() ws = client.newWebSocket(request, this) } override fun disconnect() { ws?.close(1000, null) } override fun sendMessage(message: String) { ws?.send(message) } // === Listeners === override fun onOpen(webSocket: WebSocket, response: Response) { setState(CONNECTING) authorize(token, username) } override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { setState(DISCONNECTED) } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { // When network signal is lost two errors are thrown. Ignore one of them so only one DISCONNECT event is dispatched if (t.localizedMessage != "Network is unreachable: connect") setState(DISCONNECTED) } override fun onMessage(webSocket: WebSocket, text: String) { if (text.startsWith("PING")) sendMessage("PONG :tmi.twitch.tv") else { if (text.startsWith(":tmi.twitch.tv 001")) setState(CONNECTED) launch { for (line in text.trim().lines()) if (!ignored(line)) messageChannel.send(parseMessage(line)) } } } // === Private methods == private fun setState(state: IrcState) { this.state = state launch { stateChannel.send(state) } } private fun authorize(token: String, username: String) { sendMessage("CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership") var pass = token //Check if token is in the correct form if (!pass.startsWith("oauth:")) pass = "oauth:$token" sendMessage("PASS $pass") sendMessage("NICK $username") } private fun ignored(message: String): Boolean { val words = message.split(" ") return when { words[1].let { it == "353" || it == "366" } -> true // NAMES else -> false } } }
0
Kotlin
0
0
f3ad3e182ef989263d00411fe437abe01179460a
3,420
TmiK
MIT License
app/src/main/java/com/nearby/messages/nearbyconnection/ui/views/CustomFlag.kt
Davidvster
149,776,113
false
null
package com.nearby.messages.nearbyconnection.ui.views import android.content.Context import com.skydoves.colorpickerview.ColorEnvelope import com.skydoves.colorpickerview.AlphaTileView import android.widget.TextView import com.nearby.messages.nearbyconnection.R import com.skydoves.colorpickerview.flag.FlagView class CustomFlag(context: Context, layout: Int) : FlagView(context, layout) { private val textView: TextView = findViewById(R.id.flag_color_code) private val alphaTileView: AlphaTileView = findViewById(R.id.flag_color_layout) override fun onRefresh(colorEnvelope: ColorEnvelope) { textView.text = context.resources.getString(R.string.dialog_color_name, colorEnvelope.hexCode) alphaTileView.setPaintColor(colorEnvelope.color) } }
0
Kotlin
0
0
24fcdcf188b1c21e2768fd633201d9ab8bf12861
776
nearbyconnections
The Unlicense
app/src/main/java/com/africablue/awsapp/ui/translate/TranslateLanguageDialog.kt
AfricaBlue72
259,641,836
false
null
package com.africablue.awsapp.ui.translate import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import com.africablue.awsapp.R import com.africablue.awsapp.util.APP_TAG import com.africablue.awsapp.util.getViewModelFactoryForTranslateChat import com.google.android.material.textfield.TextInputLayout class TranslateLanguageDialog(private val listener: LanguageDialogListener) : DialogFragment() { val mLogTag = APP_TAG + this::class.java.simpleName private val viewModel: TranslateChatFragmentViewModel by viewModels{ getViewModelFactoryForTranslateChat() } interface LanguageDialogListener { fun onDialogPositiveClick(sourceLanguage: String?, sourceVoice: String?, targetLanguage: String?, targetVoice: String?, autoPlayTarget: Boolean = false) fun onDialogNegativeClick() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreateDialog(savedInstanceState) return activity?.let { // Build the dialog and set up the button click handlers val builder = AlertDialog.Builder(it) val inflater = requireActivity().layoutInflater; val view = inflater.inflate(R.layout.translate_language_dialog, null) val buttonOk = view.findViewById<Button>(R.id.buttonOK) buttonOk.setOnClickListener{ val sourceLang = view.findViewById<TextInputLayout>(R.id.textFieldSourceLanguage).editText?.text.toString() val sourceVoice = view.findViewById<TextInputLayout>(R.id.textFieldSourceVoice).editText?.text.toString() val targetLang = view.findViewById<TextInputLayout>(R.id.textFieldTargetLanguage).editText?.text.toString() val targetVoice = view.findViewById<TextInputLayout>(R.id.textFieldTargetVoice).editText?.text.toString() var targetAutoPlay = view.findViewById<CheckBox>(R.id.checkBoxTargetAutoPlay).isChecked listener.onDialogPositiveClick(sourceLang, sourceVoice, targetLang, targetVoice, targetAutoPlay) dismiss() } val cancelButton = view.findViewById<Button>(R.id.buttonCancel) cancelButton.setOnClickListener{ listener.onDialogNegativeClick() dismiss() } val map = viewModel.languageMap if(map != null) { val list = ArrayList(map.keys).sorted() setSourceLanguageLayout(view, list) setTargetLanguageLayout(view, list) } builder.setView(view) val dialog = builder.create() dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) isCancelable = false dialog } ?: throw IllegalStateException("Activity cannot be null") } private fun setSourceLanguageLayout( view: View, sourceLanguagelist: List<String> ) { val sourceLanguage = view.findViewById<TextInputLayout>(R.id.textFieldSourceLanguage) val sourceLanguageAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, sourceLanguagelist) val sourceVoice = view.findViewById<TextInputLayout>(R.id.textFieldSourceVoice) (sourceLanguage.editText as? AutoCompleteTextView)?.setAdapter(sourceLanguageAdapter) (sourceLanguage.editText as? AutoCompleteTextView)?.setOnItemClickListener { parent, view, position, id -> setVoiceLayout(parent, position, sourceVoice) } } private fun setTargetLanguageLayout( view: View, targetLanguagelist: List<String> ) { val targetLanguage = view.findViewById<TextInputLayout>(R.id.textFieldTargetLanguage) val targetLanguageAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, targetLanguagelist) (targetLanguage.editText as? AutoCompleteTextView)?.setAdapter(targetLanguageAdapter) val targetVoice = view.findViewById<TextInputLayout>(R.id.textFieldTargetVoice) (targetLanguage.editText as? AutoCompleteTextView)?.setOnItemClickListener { parent, view, position, id -> setVoiceLayout(parent, position, targetVoice) } } private fun setVoiceLayout( parent: AdapterView<*>, position: Int, voiceLayout: TextInputLayout ) { val language = parent.getItemAtPosition(position).toString() val languageCode = viewModel.languageMap?.get(language) val adapterList = mutableListOf<String>() if (languageCode != null && languageCode.isNotEmpty()) { val voicesList = viewModel.voicesMap.get(languageCode) if (voicesList != null) { voicesList.forEach() { adapterList.add(it.compositeVoiceName()) } voiceLayout.isEnabled = true } } else { voiceLayout.isEnabled = false } val voiceAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, adapterList) (voiceLayout.editText as? AutoCompleteTextView)?.setAdapter(voiceAdapter) } }
0
Kotlin
0
0
f5aea4b4e08e69c79f76cd7384308f657d61e21f
5,663
AwsApp
MIT License
platform/projectModel-api/src/com/intellij/configurationStore/xmlSerializer.kt
kirpichik
171,894,935
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("XmlSerializer") package com.intellij.configurationStore import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.util.JDOMUtil import com.intellij.reference.SoftReference import com.intellij.util.io.URLUtil import com.intellij.util.serialization.BindingProducer import com.intellij.util.serialization.MutableAccessor import com.intellij.util.serialization.SerializationException import com.intellij.util.xmlb.* import org.jdom.Element import org.jdom.JDOMException import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.lang.reflect.Type import java.net.URL private val skipDefaultsSerializationFilter = ThreadLocal<SoftReference<SkipDefaultsSerializationFilter>>() @ApiStatus.Internal fun getDefaultSerializationFilter(): SkipDefaultsSerializationFilter { var result = SoftReference.dereference(skipDefaultsSerializationFilter.get()) if (result == null) { result = object : SkipDefaultsSerializationFilter() { override fun accepts(accessor: Accessor, bean: Any): Boolean { return if (bean is BaseState) { bean.accepts(accessor, bean) } else { super.accepts(accessor, bean) } } } skipDefaultsSerializationFilter.set(SoftReference(result)) } return result } @JvmOverloads fun <T : Any> T.serialize(filter: SerializationFilter? = getDefaultSerializationFilter(), createElementIfEmpty: Boolean = false): Element? { try { val clazz = javaClass val binding = serializer.getRootBinding(clazz) return if (binding is BeanBinding) { // top level expects not null (null indicates error, empty element will be omitted) binding.serialize(this, createElementIfEmpty, filter) } else { binding.serialize(this, null, filter) as Element } } catch (e: SerializationException) { throw e } catch (e: Exception) { throw XmlSerializationException("Can't serialize instance of ${this.javaClass}", e) } } fun deserializeBaseStateWithCustomNameFilter(state: BaseState, excludedPropertyNames: Collection<String>): Element? { val binding = serializer.getRootBinding(state.javaClass) as KotlinAwareBeanBinding return binding.serializeBaseStateInto(state, null, getDefaultSerializationFilter(), excludedPropertyNames) } inline fun <reified T: Any> Element.deserialize(): T = deserialize(T::class.java) fun <T> Element.deserialize(clazz: Class<T>): T { if (clazz == Element::class.java) { @Suppress("UNCHECKED_CAST") return this as T } @Suppress("UNCHECKED_CAST") try { return (serializer.getRootBinding(clazz) as NotNullDeserializeBinding).deserialize(null, this) as T } catch (e: SerializationException) { throw e } catch (e: Exception) { throw XmlSerializationException("Cannot deserialize class ${clazz.name}", e) } } fun <T> deserialize(url: URL, aClass: Class<T>): T { try { @Suppress("DEPRECATION") var document = JDOMUtil.loadDocument(URLUtil.openStream(url)) document = JDOMXIncluder.resolve(document, url.toExternalForm()) return document.rootElement.deserialize(aClass) } catch (e: IOException) { throw XmlSerializationException(e) } catch (e: JDOMException) { throw XmlSerializationException(e) } } fun Element.deserializeInto(bean: Any) { try { (serializer.getRootBinding(bean.javaClass) as BeanBinding).deserializeInto(bean, this) } catch (e: SerializationException) { throw e } catch (e: Exception) { throw XmlSerializationException(e) } } @JvmOverloads fun <T> deserializeAndLoadState(component: PersistentStateComponent<T>, element: Element, clazz: Class<T> = ComponentSerializationUtil.getStateClass<T>(component::class.java)) { val state = element.deserialize(clazz) (state as? BaseState)?.resetModificationCount() component.loadState(state) } fun serializeStateInto(component: PersistentStateComponent<*>, element: Element) { component.state?.let { serializeObjectInto(it, element) } } @JvmOverloads fun serializeObjectInto(o: Any, target: Element, filter: SerializationFilter? = null) { if (o is Element) { val iterator = o.children.iterator() for (child in iterator) { iterator.remove() target.addContent(child) } val attributeIterator = o.attributes.iterator() for (attribute in attributeIterator) { attributeIterator.remove() target.setAttribute(attribute) } return } val beanBinding = serializer.getRootBinding(o.javaClass) as KotlinAwareBeanBinding beanBinding.serializeInto(o, target, filter ?: getDefaultSerializationFilter()) } private val serializer by lazy { MyXmlSerializer() } private class MyXmlSerializer : XmlSerializerImpl.XmlSerializerBase() { val bindingProducer = object : BindingProducer<Binding>() { override fun getNestedBinding(accessor: MutableAccessor) = throw IllegalStateException() override fun createRootBinding(aClass: Class<*>, type: Type, map: MutableMap<Type, Binding>): Binding { val binding = createClassBinding(aClass, null, type) ?: KotlinAwareBeanBinding(aClass) map.put(type, binding) try { binding.init(type, this@MyXmlSerializer) } catch (e: RuntimeException) { map.remove(type) throw e } catch (e: Error) { map.remove(type) throw e } return binding } } override fun getRootBinding(aClass: Class<*>, originalType: Type): Binding { return bindingProducer.getRootBinding(aClass, originalType) } } /** * used by MPS. Do not use if not approved. */ fun clearBindingCache() { serializer.bindingProducer.clearBindingCache() }
1
null
1
1
bc2fe124431bd9d73d694517777790c8a119e773
5,882
intellij-community
Apache License 2.0
server/server/src/main/kotlin/org/jetbrains/bsp/bazel/server/bsp/managers/BazelExternalRulesQuery.kt
JetBrains
826,262,028
false
null
package org.jetbrains.bsp.bazel.server.bsp.managers import ch.epfl.scala.bsp4j.BuildTargetIdentifier import com.google.gson.Gson import com.google.gson.JsonObject import org.apache.logging.log4j.LogManager import org.eclipse.lsp4j.jsonrpc.CancelChecker import org.jetbrains.bsp.bazel.bazelrunner.BazelProcessResult import org.jetbrains.bsp.bazel.bazelrunner.BazelRunner import org.jetbrains.bsp.bazel.logger.BspClientLogger import org.jetbrains.bsp.bazel.workspacecontext.EnabledRulesSpec import org.w3c.dom.Document import org.w3c.dom.NodeList import javax.xml.xpath.XPathConstants import javax.xml.xpath.XPathFactory interface BazelExternalRulesQuery { fun fetchExternalRuleNames(cancelChecker: CancelChecker): List<String> } class BazelEnabledRulesQueryImpl(private val enabledRulesSpec: EnabledRulesSpec) : BazelExternalRulesQuery { override fun fetchExternalRuleNames(cancelChecker: CancelChecker): List<String> = enabledRulesSpec.values } private val rulesDisabledFromAutoDetection = listOf("rules_android", "rules_rust") class BazelExternalRulesQueryImpl( private val bazelRunner: BazelRunner, private val isBzlModEnabled: Boolean, private val enabledRules: EnabledRulesSpec, private val bspClientLogger: BspClientLogger, ) : BazelExternalRulesQuery { override fun fetchExternalRuleNames(cancelChecker: CancelChecker): List<String> = when { enabledRules.isNotEmpty() -> BazelEnabledRulesQueryImpl(enabledRules).fetchExternalRuleNames(cancelChecker) isBzlModEnabled -> BazelBzlModExternalRulesQueryImpl(bazelRunner, bspClientLogger).fetchExternalRuleNames(cancelChecker) + BazelWorkspaceExternalRulesQueryImpl( bazelRunner, bspClientLogger, ).fetchExternalRuleNames(cancelChecker) else -> BazelWorkspaceExternalRulesQueryImpl(bazelRunner, bspClientLogger).fetchExternalRuleNames(cancelChecker) } } class BazelWorkspaceExternalRulesQueryImpl(private val bazelRunner: BazelRunner, private val bspClientLogger: BspClientLogger) : BazelExternalRulesQuery { override fun fetchExternalRuleNames(cancelChecker: CancelChecker): List<String> = bazelRunner.run { val command = buildBazelCommand { query { targets.add(BuildTargetIdentifier("//external:*")) options.addAll(listOf("--output=xml", "--order_output=no")) } } runBazelCommand(command, logProcessOutput = false, serverPidFuture = null) .waitAndGetResult(cancelChecker, ensureAllOutputRead = true) .let { result -> if (result.isNotSuccess) { val queryFailedMessage = getQueryFailedMessage(result) bspClientLogger.warn(queryFailedMessage) log.warn(queryFailedMessage) null } else { result.stdout.readXML(log)?.calculateEligibleRules() } }?.removeRulesDisabledFromAutoDetection() .orEmpty() } private fun Document.calculateEligibleRules(): List<String> { val xPath = XPathFactory.newInstance().newXPath() val expression = "/query/rule[contains(@class, 'http_archive') and " + "(not(string[@name='generator_function']) or string[@name='generator_function' and contains(@value, 'http_archive')])" + "]//string[@name='name']" val eligibleItems = xPath.evaluate(expression, this, XPathConstants.NODESET) as NodeList val returnList = mutableListOf<String>() for (i in 0 until eligibleItems.length) { eligibleItems .item(i) .attributes .getNamedItem("value") ?.nodeValue ?.let { returnList.add(it) } } return returnList.toList() } companion object { private val log = LogManager.getLogger(BazelExternalRulesQueryImpl::class.java) } } class BazelBzlModExternalRulesQueryImpl(private val bazelRunner: BazelRunner, private val bspClientLogger: BspClientLogger) : BazelExternalRulesQuery { private val gson = Gson() override fun fetchExternalRuleNames(cancelChecker: CancelChecker): List<String> { val command = bazelRunner.buildBazelCommand { graph { options.add("--output=json") } } val bzlmodGraphJson = bazelRunner .runBazelCommand(command, logProcessOutput = false, serverPidFuture = null) .waitAndGetResult(cancelChecker, ensureAllOutputRead = true) .let { result -> if (result.isNotSuccess) { val queryFailedMessage = getQueryFailedMessage(result) bspClientLogger.warn(queryFailedMessage) log.warn(queryFailedMessage) null } else { result.stdout.toJson(log) } } as? JsonObject return try { gson.fromJson(bzlmodGraphJson, BzlmodGraph::class.java).getAllDirectRuleDependencies().removeRulesDisabledFromAutoDetection() } catch (e: Throwable) { log.warn("The returned bzlmod json is not parsable:\n$bzlmodGraphJson", e) emptyList() } } companion object { private val log = LogManager.getLogger(BazelBzlModExternalRulesQueryImpl::class.java) } } private fun getQueryFailedMessage(result: BazelProcessResult): String = "Bazel query failed with output:\n${result.stderr}" data class BzlmodDependency(val key: String) { /** * Extract dependency name from bzlmod dependency, where the raw format is `<DEP_NAME>@<DEP_VERSION>`. * * There were some issues with (empty) bzlmod projects and android, so the automatic mechanism ignores it. * Use `enabled_rules` to enable `rules_android` instead. */ fun toDependencyName(): String = key.substringBefore('@') } data class BzlmodGraph(val dependencies: List<BzlmodDependency>) { fun getAllDirectRuleDependencies() = dependencies.map { it.toDependencyName() } } private fun List<String>.removeRulesDisabledFromAutoDetection(): List<String> = this.filterNot { rule -> rulesDisabledFromAutoDetection.any { it in rule } }
6
null
8
45
1d79484cfdf8fc31d3a4b214655e857214071723
5,949
hirschgarten
Apache License 2.0
williamchart/src/main/java/com/db/williamchart/view/LineChartView.kt
tchigher
203,339,045
true
{"Kotlin": 55861}
package com.db.williamchart.view import android.content.Context import android.content.res.TypedArray import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Paint import android.graphics.Path import android.graphics.Shader import android.util.AttributeSet import androidx.annotation.Size import androidx.core.view.doOnPreDraw import com.db.williamchart.ChartContract import com.db.williamchart.R import com.db.williamchart.animation.NoAnimation import com.db.williamchart.data.DataPoint import com.db.williamchart.data.Frame import com.db.williamchart.data.Label import com.db.williamchart.data.toRect import com.db.williamchart.renderer.LineChartRenderer class LineChartView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ChartView(context, attrs, defStyleAttr), ChartContract.View { /** * API */ @Suppress("MemberVisibilityCanBePrivate") var smooth: Boolean = false @Suppress("MemberVisibilityCanBePrivate") var lineThickness: Float = 4F @Suppress("MemberVisibilityCanBePrivate") var fillColor: Int = 0 @Suppress("MemberVisibilityCanBePrivate") var lineColor: Int = Color.BLACK @Size(min = 2, max = 2) @Suppress("MemberVisibilityCanBePrivate") var gradientFillColors: IntArray = intArrayOf(0, 0) init { doOnPreDraw { (renderer as LineChartRenderer).lineThickness = lineThickness renderer.preDraw( measuredWidth, measuredHeight, paddingLeft, paddingTop, paddingRight, paddingBottom, axis, labelsSize ) } renderer = LineChartRenderer(this, painter, NoAnimation()) val styledAttributes = context.theme.obtainStyledAttributes( attrs, R.styleable.LineChartAttrs, 0, 0 ) handleAttributes(styledAttributes) } override fun drawData( innerFrame: Frame, entries: List<DataPoint> ) { val linePath = if (!smooth) createLinePath(entries) else createSmoothLinePath(entries) if (fillColor != 0 || gradientFillColors.isNotEmpty()) { // Draw background if (fillColor != 0) painter.prepare(color = fillColor, style = Paint.Style.FILL) else painter.prepare( shader = LinearGradient( innerFrame.left, innerFrame.top, innerFrame.left, innerFrame.bottom, gradientFillColors[0], gradientFillColors[1], Shader.TileMode.MIRROR ), style = Paint.Style.FILL ) canvas.drawPath( createBackgroundPath(linePath, entries, innerFrame.bottom), painter.paint ) } // Draw line painter.prepare(color = lineColor, style = Paint.Style.STROKE, strokeWidth = lineThickness) canvas.drawPath(linePath, painter.paint) } override fun drawLabels(xLabels: List<Label>) { painter.prepare( textSize = labelsSize, color = labelsColor, font = labelsFont ) xLabels.forEach { canvas.drawText(it.label, it.screenPositionX, it.screenPositionY, painter.paint) } } override fun drawDebugFrame(outerFrame: Frame, innerFrame: Frame, labelsFrame: List<Frame>) { painter.prepare(color = -0x1000000, style = Paint.Style.STROKE) canvas.drawRect(outerFrame.toRect(), painter.paint) canvas.drawRect(innerFrame.toRect(), painter.paint) labelsFrame.forEach { canvas.drawRect(it.toRect(), painter.paint) } } private fun createLinePath(points: List<DataPoint>): Path { val res = Path() res.moveTo(points.first().screenPositionX, points.first().screenPositionY) for (i in 1 until points.size) res.lineTo(points[i].screenPositionX, points[i].screenPositionY) return res } /** * Credits: http://www.jayway.com/author/andersericsson/ */ private fun createSmoothLinePath(points: List<DataPoint>): Path { var thisPointX: Float var thisPointY: Float var nextPointX: Float var nextPointY: Float var startDiffX: Float var startDiffY: Float var endDiffX: Float var endDiffY: Float var firstControlX: Float var firstControlY: Float var secondControlX: Float var secondControlY: Float val res = Path() res.moveTo(points.first().screenPositionX, points.first().screenPositionY) for (i in 0 until points.size - 1) { thisPointX = points[i].screenPositionX thisPointY = points[i].screenPositionY nextPointX = points[i + 1].screenPositionX nextPointY = points[i + 1].screenPositionY startDiffX = nextPointX - points[si(points.size, i - 1)].screenPositionX startDiffY = nextPointY - points[si(points.size, i - 1)].screenPositionY endDiffX = points[si(points.size, i + 2)].screenPositionX - thisPointX endDiffY = points[si(points.size, i + 2)].screenPositionY - thisPointY firstControlX = thisPointX + SMOOTH_FACTOR * startDiffX firstControlY = thisPointY + SMOOTH_FACTOR * startDiffY secondControlX = nextPointX - SMOOTH_FACTOR * endDiffX secondControlY = nextPointY - SMOOTH_FACTOR * endDiffY res.cubicTo(firstControlX, firstControlY, secondControlX, secondControlY, nextPointX, nextPointY) } return res } private fun createBackgroundPath( path: Path, points: List<DataPoint>, innerFrameBottom: Float ): Path { val res = Path(path) res.lineTo(points.last().screenPositionX, innerFrameBottom) res.lineTo(points.first().screenPositionX, innerFrameBottom) res.close() return res } /** * Credits: http://www.jayway.com/author/andersericsson/ */ private fun si(setSize: Int, i: Int): Int { return when { i > setSize - 1 -> setSize - 1 i < 0 -> 0 else -> i } } private fun handleAttributes(typedArray: TypedArray) { typedArray.apply { lineColor = getColor(R.styleable.LineChartAttrs_chart_lineColor, lineColor) lineThickness = getDimension(R.styleable.LineChartAttrs_chart_lineThickness, lineThickness) smooth = getBoolean(R.styleable.LineChartAttrs_chart_smoothLine, smooth) recycle() } } companion object { private const val SMOOTH_FACTOR = 0.20f } }
0
Kotlin
0
0
0b099f60c5b35662f573326191c3c6d0999cd07f
6,971
WilliamChart
Apache License 2.0
src/test/kotlin/no/nb/bikube/core/model/CollectionsModelFromJsonListNewspaperItemsTests.kt
NationalLibraryOfNorway
694,135,748
false
{"Kotlin": 299101, "Dockerfile": 109}
package no.nb.bikube.core.model import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import no.nb.bikube.core.enum.AxiellDescriptionType import no.nb.bikube.core.enum.AxiellFormat import no.nb.bikube.core.enum.AxiellRecordType import no.nb.bikube.core.enum.MaterialType import no.nb.bikube.core.model.collections.* import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import java.io.File @SpringBootTest @ActiveProfiles("test") class CollectionsModelFromJsonListNewspaperItemsTests { private fun mapper(): ObjectMapper { val mapper = jacksonObjectMapper() // Disable unknown properties as we are not using all fields, and will test for what we need mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) return mapper } private val itemListJson = File("src/test/resources/CollectionsJsonTestFiles/NewspaperItemList.json") private val items = mapper().readValue<CollectionsModel>(itemListJson).getObjects()!! @Test fun `Collection object should extract all items`() { Assertions.assertEquals(4, items.size) } @Test fun `Collection object should extract priRefs `() { Assertions.assertEquals("5", items.first().priRef) Assertions.assertEquals("6", items[1].priRef) Assertions.assertEquals("19", items[2].priRef) Assertions.assertEquals("21", items[3].priRef) } @Test fun `Collection object should extract submediums`() { Assertions.assertTrue(items.all { it.getMaterialType() == MaterialType.NEWSPAPER }) } @Test fun `Collection object should extract names`() { Assertions.assertEquals("Bikubeavisen 2012.01.02", items.first().getName()) Assertions.assertEquals("Bikubeavisen 2012.01.02", items[1].getName()) Assertions.assertEquals("Bikubeavisen 2011.01.24", items[2].getName()) Assertions.assertEquals("Bikubeavisen 2012.01.09", items[3].getName()) } @Test fun `Collection object should extract record types`() { Assertions.assertTrue(items.all { it.getRecordType() == AxiellRecordType.ITEM }) } @Test fun `Collection object should extract formats`() { Assertions.assertEquals(AxiellFormat.DIGITAL, items.first().getFormat()) Assertions.assertEquals(AxiellFormat.PHYSICAL, items[1].getFormat()) Assertions.assertEquals(AxiellFormat.PHYSICAL, items[2].getFormat()) Assertions.assertEquals(AxiellFormat.DIGITAL, items[3].getFormat()) } @Test fun `Collection object should extract parent manifestations`() { val mani1 = items.first().getFirstPartOf()!! Assertions.assertEquals("10", mani1.priRef) Assertions.assertEquals("Bikubeavisen 2012.01.02", mani1.getName()) Assertions.assertEquals(AxiellRecordType.MANIFESTATION, mani1.getRecordType()) Assertions.assertEquals(MaterialType.NEWSPAPER, mani1.getMaterialType()) // Manifestation 1 and 2 should be the same val mani2 = items[1].getFirstPartOf()!! Assertions.assertEquals(mani1, mani2) val mani3 = items[2].getFirstPartOf()!! Assertions.assertEquals("18", mani3.priRef) Assertions.assertEquals("Bikubeavisen 2011.01.24", mani3.getName()) Assertions.assertEquals(AxiellRecordType.MANIFESTATION, mani3.getRecordType()) Assertions.assertEquals(MaterialType.NEWSPAPER, mani3.getMaterialType()) val mani4 = items[3].getFirstPartOf()!! Assertions.assertEquals("20", mani4.priRef) Assertions.assertEquals("Bikubeavisen 2012.01.09", mani4.getName()) Assertions.assertEquals(AxiellRecordType.MANIFESTATION, mani4.getRecordType()) Assertions.assertEquals(MaterialType.NEWSPAPER, mani4.getMaterialType()) } @Test fun `Collection object should extract parent year works`() { val yearWork1 = items.first().getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals("4", yearWork1.priRef) Assertions.assertEquals("Bikubeavisen 2012", yearWork1.getName()) Assertions.assertEquals(AxiellRecordType.WORK, yearWork1.getRecordType()) Assertions.assertEquals(MaterialType.NEWSPAPER, yearWork1.getMaterialType()) Assertions.assertEquals(AxiellDescriptionType.YEAR, yearWork1.getWorkType()) // Year work 1, 2 and 4 should be the same val yearWork2 = items[1].getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals(yearWork1, yearWork2) val yearWork3 = items[2].getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals("11", yearWork3.priRef) Assertions.assertEquals("Bikubeavisen 2011", yearWork3.getName()) Assertions.assertEquals(AxiellRecordType.WORK, yearWork3.getRecordType()) Assertions.assertEquals(MaterialType.NEWSPAPER, yearWork3.getMaterialType()) Assertions.assertEquals(AxiellDescriptionType.YEAR, yearWork3.getWorkType()) val yearWork4 = items[3].getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals(yearWork1, yearWork4) } @Test fun `Collection object should extract parent serial works`() { // All items are connected to the same title val title1 = items.first().getFirstPartOf()!!.getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals("3", title1.priRef) Assertions.assertEquals("Bikubeavisen", title1.getName()) Assertions.assertEquals(AxiellRecordType.WORK, title1.getRecordType()) Assertions.assertEquals(MaterialType.NEWSPAPER, title1.getMaterialType()) Assertions.assertEquals(AxiellDescriptionType.SERIAL, title1.getWorkType()) val title2 = items[1].getFirstPartOf()!!.getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals(title1, title2) val title3 = items[2].getFirstPartOf()!!.getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals(title1, title3) val title4 = items[3].getFirstPartOf()!!.getFirstPartOf()!!.getFirstPartOf()!! Assertions.assertEquals(title1, title4) } }
0
Kotlin
0
2
bd415ac7cf793761dd408ad9a027cdc2142ed104
6,375
bikube
Apache License 2.0
app/src/main/java/de/lemke/oneurl/domain/generateURL/GenerateDAGDUseCase.kt
Lemkinator
699,106,627
false
{"Kotlin": 225052}
package de.lemke.oneurl.domain.generateURL import android.content.Context import android.util.Log import com.android.volley.NetworkResponse import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.StringRequest import dagger.hilt.android.qualifiers.ApplicationContext import de.lemke.oneurl.R import de.lemke.oneurl.domain.model.ShortURLProvider import de.lemke.oneurl.domain.model.ShortURLProvider.DAGD import javax.inject.Inject class GenerateDAGDUseCase @Inject constructor( @ApplicationContext private val context: Context ) { operator fun invoke( requestQueue: RequestQueue, provider: ShortURLProvider, longURL: String, alias: String?, successCallback: (shortURL: String) -> Unit, errorCallback: (message: String) -> Unit, ): StringRequest { val tag = "GenerateURLUseCase_DAGD" if (alias == null) return requestCreateDAGD(provider, longURL, null, successCallback, errorCallback) val apiURL = provider.getCheckURLApi(alias) Log.d(tag, "start request: $apiURL") return StringRequest( Request.Method.GET, provider.getCheckURLApi(alias), { response -> if (response.trim() != longURL) { Log.e(tag, "error, shortURL already exists, but has different longURL, longURL: $longURL, response: $response") errorCallback(context.getString(R.string.error_alias_already_exists)) return@StringRequest } Log.d(tag, "shortURL already exists (but is not in local db): $response") val shortURL = DAGD.baseURL + alias Log.d(tag, "shortURL: $shortURL") successCallback(shortURL) }, { error -> try { Log.w(tag, "error: $error") val networkResponse: NetworkResponse? = error.networkResponse val statusCode = networkResponse?.statusCode if (networkResponse == null || statusCode == null) { Log.e(tag, "error.networkResponse == null") errorCallback(error.message ?: context.getString(R.string.error_unknown)) return@StringRequest } if (statusCode == 404) { Log.d(tag, "shortURL does not exist yet, creating it") } else { Log.w(tag, "error, statusCode: ${error.networkResponse.statusCode}, trying to create it anyway") } requestQueue.add(requestCreateDAGD(provider, longURL, alias, successCallback, errorCallback)) } catch (e: Exception) { e.printStackTrace() Log.e(tag, "error: $e") errorCallback(context.getString(R.string.error_unknown)) } } ) } private fun requestCreateDAGD( provider: ShortURLProvider, longURL: String, alias: String?, successCallback: (shortURL: String) -> Unit, errorCallback: (message: String) -> Unit, ): StringRequest { val tag = "GenerateURLUseCase_DAGD" val apiURL = provider.getCreateURLApi(longURL, alias) Log.d(tag, "start request: $apiURL") return StringRequest( Request.Method.GET, provider.getCreateURLApi(longURL, alias), { response -> Log.d(tag, "response: $response") if (response.startsWith("https://da.gd")) { val shortURL = response.trim() Log.d(tag, "shortURL: $shortURL") successCallback(shortURL) } else { Log.e(tag, "error, response does not start with https://da.gd, response: $response") errorCallback(context.getString(R.string.error_unknown)) } }, { error -> try { Log.e(tag, "error: $error") val networkResponse: NetworkResponse? = error.networkResponse val statusCode = networkResponse?.statusCode if (networkResponse == null || statusCode == null) { Log.e(tag, "error.networkResponse == null") errorCallback(error.message ?: context.getString(R.string.error_unknown)) return@StringRequest } Log.e(tag, "statusCode: $statusCode") val data = networkResponse.data if (data == null) { Log.e(tag, "error.networkResponse.data == null") errorCallback(error.message ?: (context.getString(R.string.error_unknown) + " ($statusCode)")) return@StringRequest } val message = data.toString(charset("UTF-8")) Log.e(tag, "error: $message ($statusCode)") /* possible error messages: 400: Long URL cannot be empty //should not happen, checked before 400: Long URL must have http:// or https:// scheme. //should not happen, checked before 400: Long URL is not a valid URL. 400: Short URL already taken. Pick a different one. 400: Custom short URL contained invalid characters. //should not happen, checked before */ when { message.contains("Long URL cannot be empty") -> errorCallback(context.getString(R.string.error_invalid_url)) message.contains("Long URL must have http:// or https:// scheme") -> errorCallback(context.getString(R.string.error_invalid_url)) message.contains("Long URL is not a valid URL") -> errorCallback(context.getString(R.string.error_invalid_url)) message.contains("Short URL already taken") -> errorCallback(context.getString(R.string.error_alias_already_exists)) message.contains("Custom short URL contained invalid characters") -> errorCallback(context.getString(R.string.error_invalid_alias)) else -> errorCallback("$message ($statusCode)") } } catch (e: Exception) { Log.e(tag, "error: $e") e.printStackTrace() errorCallback(error.message ?: context.getString(R.string.error_unknown)) } } ) } }
1
Kotlin
1
6
dd73a8785d242770e8e46b4ca666fa1eeae903c0
6,798
OneUrl
MIT License
common/src/commonMain/kotlin/com/displayer/display/parser/Parser.kt
litrik
583,350,986
false
{"Kotlin": 118350, "HTML": 239}
package com.displayer.display.parser import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import com.displayer.config.Parameters import com.displayer.display.Padding import com.displayer.display.Style import com.displayer.display.container.ColumnLayout import com.displayer.display.container.Container import com.displayer.display.container.Empty import com.displayer.display.container.RowLayout import com.displayer.display.container.StackLayout import com.displayer.display.item.Clock import com.displayer.display.item.DrinkItem import com.displayer.display.item.Image import com.displayer.display.item.Item import com.displayer.display.item.RandomItem import com.displayer.display.item.SocialItem import com.displayer.display.item.TextItem import com.displayer.display.item.UnknownItem import com.displayer.display.item.Weather import com.displayer.parse import com.displayer.weather.WeatherData import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.flow.Flow object Parser { fun parseStyle(dto: StyleDto): Result<Style> = Result( Style( id = dto.id, backgroundColor = dto.backgroundColor?.let { Color.parse(it) } ?: Color.Unspecified, contentColor = dto.contentColor?.let { Color.parse(it) } ?: Color.Unspecified, ), emptyList()) private fun parseItem( dto: ItemDto, context: String, resolveStyle: (styleId: String?, context: String) -> Style?, observeCurrentWeather: () -> Flow<List<WeatherData>> ): Result<Item> = when (dto) { is UnknownDto -> UnknownItem(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding)) is ClockDto -> Clock(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding)) is RandomDto -> RandomItem( style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding), items = parseItems( dtos = dto.items, context = context, resolveStyle = resolveStyle, observeCurrentWeather = observeCurrentWeather ).data.toImmutableList() ) is ImageDto -> Image(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding), url = dto.url, scale = parseContentScale(dto.scale)) is TextDto -> TextItem(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding), text = dto.text) is WeatherDto -> Weather(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding), observeCurrentWeather = observeCurrentWeather) is DrinkDto -> DrinkItem(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding), image = dto.image, text = dto.text) is SocialDto -> SocialItem(style = resolveStyle(dto.styleId, context), padding = parsePadding(dto.padding), app = dto.app, account = dto.account, text = dto.text) }.run { val messages = mutableListOf<Message>() if (this is UnknownItem) { messages.add(Message(Severity.Error, "$context is of unknown type")) } else if (this is RandomItem && this.items.isEmpty()) { messages.add(Message(Severity.Error, "$context contains no child items")) } else if (this is Image && !this.url.startsWith("https://")) { messages.add(Message(Severity.Error, "$context uses a URL that does not start with 'https://'")) } Result(this, messages) } private fun parsePadding(dto: PaddingDto?): Padding = Padding(horizontal = dto?.horizontal ?: 0f, vertical = dto?.vertical ?: 0f) private fun parseItems( dtos: List<ItemDto>?, context: String, resolveStyle: (String?, String) -> Style?, observeCurrentWeather: () -> Flow<List<WeatherData>> ): Result<List<Item>> { val messages = mutableListOf<Message>() return (dtos ?.mapIndexed { index, itemDto -> val itemContext = "Item ${index + 1} in ${context.lowercase()}" parseItem( dto = itemDto, context = itemContext, resolveStyle = resolveStyle, observeCurrentWeather = observeCurrentWeather ) .andReport(messages) } ?.filter { it !is UnknownItem } ?: emptyList()) .run { Result(this, messages) } } private fun parseContentScale(dto: ScaleDto?): ContentScale = when (dto) { ScaleDto.Crop -> ContentScale.Crop else -> ContentScale.Fit } fun parseParameters(dto: ParametersDto?): Parameters = with(dto ?: ParametersDto()) { Parameters( language = language, country = country, zip = zip, units = units ?: getUnitsForCountry(country), ) } fun parseContainer( dto: ContainerDto?, context: String, resolveStyle: (String?, String) -> Style?, observeCurrentWeather: () -> Flow<List<WeatherData>>, required: Boolean = false, ): Result<Container> { val messages = mutableListOf<Message>() if (required && dto?.items.isNullOrEmpty()) { messages.add(Message(Severity.Error, "$context contains no items")) return Result(Empty(), messages) } val style = resolveStyle(dto?.styleId, context) val items = parseItems( dtos = dto?.items, context = context, resolveStyle = resolveStyle, observeCurrentWeather = observeCurrentWeather ).andReport(messages) val container = when (dto) { is StackDto -> StackLayout( padding = dto.padding?.let { Padding(it.horizontal, it.vertical) } ?: StackLayout.DEFAULT_PADDING, style = style, items = items.toImmutableList(), autoAdvanceInSeconds = dto.autoAdvanceInSeconds ?: StackLayout.DEFAULT_AUTO_ADVANCE_IN_SECONDS, ) is ColumnDto -> { val scrollSpeedInSeconds = dto.scrollSpeedInSeconds ?: ColumnLayout.DEFAULT_SCROLL_SPEED ColumnLayout( padding = dto.padding?.let { Padding(it.horizontal, it.vertical) } ?: (if (scrollSpeedInSeconds > 0) ColumnLayout.DEFAULT_PADDING_SCROLLING else ColumnLayout.DEFAULT_PADDING_STATIC), style = style, items = injectDivider(items, dto.divider?.let { parseItem(it, "Divider in ${context.lowercase()}", resolveStyle, observeCurrentWeather).andReport(messages) }).toImmutableList(), spacing = dto.spacing, scrollSpeedSeconds = scrollSpeedInSeconds, ) } is RowDto -> { val scrollSpeedInSeconds = dto.scrollSpeedInSeconds ?: RowLayout.DEFAULT_SCROLL_SPEED RowLayout( padding = dto.padding?.let { Padding(it.horizontal, it.vertical) } ?: (if (scrollSpeedInSeconds > 0) RowLayout.DEFAULT_PADDING_SCROLLING else RowLayout.DEFAULT_PADDING_STATIC), style = style, items = injectDivider(items, dto.divider?.let { parseItem(it, "Divider in ${context.lowercase()}", resolveStyle, observeCurrentWeather).andReport(messages) }).toImmutableList(), spacing = dto.spacing, scrollSpeedSeconds = scrollSpeedInSeconds, ) } null -> Empty() } return Result(container, messages) } private fun injectDivider( items: List<Item>, divider: Item?, ): List<Item> = items .mapIndexed { index, item -> listOf( if (index == 0) null else divider, item, ) } .flatten() .filterNotNull() private fun getUnitsForCountry(country: String): Units = when (country) { "US", "LR", "MM" -> Units.Imperial else -> Units.Metric } }
13
Kotlin
3
32
cad2f8a574911233d1a14f190c0b03a5ff4e8ed5
8,393
displayer
Apache License 2.0
app/src/main/java/com/b_lam/resplash/ui/widget/ScrollAwareExtendedFabBehavior.kt
b-lam
69,628,893
false
null
package com.b_lam.resplash.ui.widget import android.content.Context import android.util.AttributeSet import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton class ScrollAwareExtendedFabBehavior( context: Context, attrs: AttributeSet ) : CoordinatorLayout.Behavior<ExtendedFloatingActionButton>(context, attrs) { override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: ExtendedFloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int ): Boolean { return axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type) } override fun onNestedScroll( coordinatorLayout: CoordinatorLayout, child: ExtendedFloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray ) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed) if (dyConsumed > 5 && child.isExtended) { child.shrink() } else if (dyConsumed < -5 && !child.isExtended) { child.extend() } } }
33
null
105
569
4b13d31134d1c31bd331e92ffe8d410984529212
1,543
Resplash
The Unlicense
imgstore-backend/src/main/kotlin/org/kentunc/imgstore/model/ImageMetaData.kt
ken-tunc
295,125,190
false
null
package org.kentunc.imgstore.model class ImageMetaData(val imageId: Int, val caption: String)
0
Kotlin
0
0
e71a92d85afb1618128049f41648f180630ecdbd
95
imgstore
The Unlicense
app/src/main/java/com/fsh/android/wanandroidmvvm/module/collect/model/CollectResponse.kt
fshsoft
506,052,730
false
{"Kotlin": 370644}
package com.fsh.android.wanandroidmvvm.module.collect.model import com.fsh.android.wanandroidmvvm.module.common.model.Article /** * Created with Android Studio. * Description: */ data class CollectResponse( var curPage : Int, var datas : List<Article>, var total : Int )
0
Kotlin
0
1
820418b44745e38e422f35d290754d2d330e24a1
287
WanAndroidMVVM
Apache License 2.0
themes/new-ui/new-ui-standalone/src/main/kotlin/org/jetbrains/jewel/themes/expui/standalone/control/DropdownMenu.kt
JetBrains
440,164,967
false
null
package io.kanro.compose.jetbrains.expui.control import androidx.compose.animation.core.MutableTransitionState import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.awt.awtEventOrNull import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.draw.shadow import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.focus.onFocusEvent import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.drawOutline import androidx.compose.ui.input.InputMode import androidx.compose.ui.input.InputModeManager import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.type import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.rememberCursorPositionProvider import io.kanro.compose.jetbrains.expui.style.AreaColors import io.kanro.compose.jetbrains.expui.style.AreaProvider import io.kanro.compose.jetbrains.expui.style.FocusAreaProvider import io.kanro.compose.jetbrains.expui.style.HoverAreaProvider import io.kanro.compose.jetbrains.expui.style.LocalAreaColors import io.kanro.compose.jetbrains.expui.style.LocalFocusAreaColors import io.kanro.compose.jetbrains.expui.style.LocalHoverAreaColors import io.kanro.compose.jetbrains.expui.style.LocalNormalAreaColors import io.kanro.compose.jetbrains.expui.style.LocalPressedAreaColors import io.kanro.compose.jetbrains.expui.style.PressedAreaProvider import io.kanro.compose.jetbrains.expui.style.areaBackground import io.kanro.compose.jetbrains.expui.style.areaBorder import io.kanro.compose.jetbrains.expui.theme.LightTheme import java.awt.event.KeyEvent import kotlin.math.max import kotlin.math.min class DropdownMenuColors( override val normalAreaColors: AreaColors, override val hoverAreaColors: AreaColors, override val pressedAreaColors: AreaColors, override val focusAreaColors: AreaColors, ) : AreaProvider, HoverAreaProvider, PressedAreaProvider, FocusAreaProvider { @Composable fun provideArea(content: @Composable () -> Unit) { CompositionLocalProvider( LocalNormalAreaColors provides normalAreaColors, LocalAreaColors provides normalAreaColors, LocalHoverAreaColors provides hoverAreaColors, LocalPressedAreaColors provides pressedAreaColors, LocalFocusAreaColors provides focusAreaColors, content = content ) } } val LocalDropdownMenuColors = compositionLocalOf { LightTheme.DropdownMenuColors } @Composable fun DropdownMenu( expanded: Boolean, onDismissRequest: () -> Unit, focusable: Boolean = true, modifier: Modifier = Modifier, offset: DpOffset = DpOffset(0.dp, 0.dp), colors: DropdownMenuColors = LocalDropdownMenuColors.current, content: @Composable ColumnScope.() -> Unit, ) { val expandedStates = remember { MutableTransitionState(false) } expandedStates.targetState = expanded if (expandedStates.currentState || expandedStates.targetState) { val transformOriginState = remember { mutableStateOf(TransformOrigin.Center) } val density = LocalDensity.current // The original [DropdownMenuPositionProvider] is not yet suitable for large screen devices, // so we need to make additional checks and adjust the position of the [DropdownMenu] to // avoid content being cut off if the [DropdownMenu] contains too many items. // See: https://github.com/JetBrains/compose-jb/issues/1388 val popupPositionProvider = DesktopDropdownMenuPositionProvider( offset, density ) { parentBounds, menuBounds -> transformOriginState.value = calculateTransformOrigin(parentBounds, menuBounds) } var focusManager: FocusManager? by mutableStateOf(null) var inputModeManager: InputModeManager? by mutableStateOf(null) Popup( focusable = focusable, onDismissRequest = onDismissRequest, popupPositionProvider = popupPositionProvider, onKeyEvent = { handlePopupOnKeyEvent(it, onDismissRequest, focusManager!!, inputModeManager!!) }, ) { focusManager = LocalFocusManager.current inputModeManager = LocalInputModeManager.current DropdownMenuContent( modifier = modifier, colors = colors, content = content ) } } } @Composable fun DropdownMenuItem( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = RectangleShape, contentPadding: PaddingValues = PaddingValues(horizontal = 8.dp), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit, ) { DropdownMenuItemContent( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, contentPadding = contentPadding, interactionSource = interactionSource, content = content ) } @OptIn(ExperimentalComposeUiApi::class) private fun handlePopupOnKeyEvent( keyEvent: androidx.compose.ui.input.key.KeyEvent, onDismissRequest: () -> Unit, focusManager: FocusManager, inputModeManager: InputModeManager, ): Boolean { return if (keyEvent.type == KeyEventType.KeyDown && keyEvent.awtEventOrNull?.keyCode == KeyEvent.VK_ESCAPE) { onDismissRequest() true } else if (keyEvent.type == KeyEventType.KeyDown) { when (keyEvent.key) { Key.DirectionDown -> { inputModeManager.requestInputMode(InputMode.Keyboard) focusManager.moveFocus(FocusDirection.Next) true } Key.DirectionUp -> { inputModeManager.requestInputMode(InputMode.Keyboard) focusManager.moveFocus(FocusDirection.Previous) true } else -> false } } else { false } } @Composable fun CursorDropdownMenu( expanded: Boolean, onDismissRequest: () -> Unit, focusable: Boolean = true, modifier: Modifier = Modifier, colors: DropdownMenuColors = LocalDropdownMenuColors.current, content: @Composable ColumnScope.() -> Unit, ) { val expandedStates = remember { MutableTransitionState(false) } expandedStates.targetState = expanded if (expandedStates.currentState || expandedStates.targetState) { var focusManager: FocusManager? by mutableStateOf(null) var inputModeManager: InputModeManager? by mutableStateOf(null) Popup( focusable = focusable, onDismissRequest = onDismissRequest, popupPositionProvider = rememberCursorPositionProvider(), onKeyEvent = { handlePopupOnKeyEvent(it, onDismissRequest, focusManager!!, inputModeManager!!) }, ) { focusManager = LocalFocusManager.current inputModeManager = LocalInputModeManager.current DropdownMenuContent( modifier = modifier, colors = colors, content = content ) } } } @Immutable internal data class DesktopDropdownMenuPositionProvider( val contentOffset: DpOffset, val density: Density, val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> }, ) : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize, ): IntOffset { // The min margin above and below the menu, relative to the screen. val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() } // The content offset specified using the dropdown offset parameter. val contentOffsetX = with(density) { contentOffset.x.roundToPx() } val contentOffsetY = with(density) { contentOffset.y.roundToPx() } // Compute horizontal position. val toRight = anchorBounds.left + contentOffsetX val toLeft = anchorBounds.right - contentOffsetX - popupContentSize.width val toDisplayRight = windowSize.width - popupContentSize.width val toDisplayLeft = 0 val x = if (layoutDirection == LayoutDirection.Ltr) { sequenceOf(toRight, toLeft, toDisplayRight) } else { sequenceOf(toLeft, toRight, toDisplayLeft) }.firstOrNull { it >= 0 && it + popupContentSize.width <= windowSize.width } ?: toLeft // Compute vertical position. val toBottom = maxOf(anchorBounds.bottom + contentOffsetY, verticalMargin) val toTop = anchorBounds.top - contentOffsetY - popupContentSize.height val toCenter = anchorBounds.top - popupContentSize.height / 2 val toDisplayBottom = windowSize.height - popupContentSize.height - verticalMargin var y = sequenceOf(toBottom, toTop, toCenter, toDisplayBottom).firstOrNull { it >= verticalMargin && it + popupContentSize.height <= windowSize.height - verticalMargin } ?: toTop // Desktop specific vertical position checking val aboveAnchor = anchorBounds.top + contentOffsetY val belowAnchor = windowSize.height - anchorBounds.bottom - contentOffsetY if (belowAnchor >= aboveAnchor) { y = anchorBounds.bottom + contentOffsetY } if (y + popupContentSize.height > windowSize.height) { y = windowSize.height - popupContentSize.height } y = y.coerceAtLeast(0) onPositionCalculated( anchorBounds, IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height) ) return IntOffset(x, y) } } @Composable internal fun DropdownMenuContent( modifier: Modifier = Modifier, colors: DropdownMenuColors = LocalDropdownMenuColors.current, content: @Composable ColumnScope.() -> Unit, ) { colors.provideArea { val scrollState = rememberScrollState() Box( modifier = modifier.shadow(12.dp) .areaBorder() .areaBackground() .sizeIn(maxHeight = 600.dp, minWidth = 72.dp) .width(IntrinsicSize.Max) ) { Column( modifier = Modifier.verticalScroll(scrollState), content = content ) Box(modifier = Modifier.matchParentSize()) { VerticalScrollbar( rememberScrollbarAdapter(scrollState), modifier = Modifier.fillMaxHeight().align(Alignment.CenterEnd) ) } } } } @Composable internal fun DropdownMenuItemContent( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = RectangleShape, contentPadding: PaddingValues = PaddingValues(horizontal = 8.dp), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit, ) { val focused = remember { mutableStateOf(false) } val focusedColors = LocalFocusAreaColors.current Row( modifier = modifier.drawWithCache { onDrawBehind { if (focused.value) { val outline = shape.createOutline(size, layoutDirection, this) drawOutline(outline, focusedColors.startBackground) } } }.onFocusEvent { focused.value = it.isFocused }.clickable( enabled = enabled, onClick = onClick, interactionSource = interactionSource, indication = HoverOrPressedIndication(shape) ).fillMaxWidth().padding(contentPadding).defaultMinSize(minHeight = 24.dp), verticalAlignment = Alignment.CenterVertically ) { content() } } internal fun calculateTransformOrigin( parentBounds: IntRect, menuBounds: IntRect, ): TransformOrigin { val pivotX = when { menuBounds.left >= parentBounds.right -> 0f menuBounds.right <= parentBounds.left -> 1f menuBounds.width == 0 -> 0f else -> { val intersectionCenter = (max(parentBounds.left, menuBounds.left) + min(parentBounds.right, menuBounds.right)) / 2 (intersectionCenter - menuBounds.left).toFloat() / menuBounds.width } } val pivotY = when { menuBounds.top >= parentBounds.bottom -> 0f menuBounds.bottom <= parentBounds.top -> 1f menuBounds.height == 0 -> 0f else -> { val intersectionCenter = (max(parentBounds.top, menuBounds.top) + min(parentBounds.bottom, menuBounds.bottom)) / 2 (intersectionCenter - menuBounds.top).toFloat() / menuBounds.height } } return TransformOrigin(pivotX, pivotY) } internal val MenuVerticalMargin = 12.dp
17
null
8
318
817adc042a029698983c9686d0f1497204bfdf14
15,137
jewel
Apache License 2.0
app/src/main/java/com/heyanle/easybangumi4/plugin/source/utils/StringHelperImpl.kt
easybangumiorg
413,723,669
false
{"Kotlin": 1490799, "Java": 761739, "Shell": 450}
package com.heyanle.easybangumi4.plugin.source.utils import android.widget.Toast import com.heyanle.easybangumi4.APP import com.heyanle.easybangumi4.source_api.utils.api.StringHelper import com.heyanle.easybangumi4.ui.common.moeDialog import com.heyanle.easybangumi4.ui.common.moeSnackBar /** * Created by HeYanLe on 2023/10/29 16:29. * https://github.com/heyanLE */ object StringHelperImpl: StringHelper { override fun moeDialog(text: String, title: String?) { text.moeDialog(title) } override fun moeSnackBar(string: String) { string.moeSnackBar() } override fun toast(string: String) { Toast.makeText(APP, string, Toast.LENGTH_SHORT).show() } }
30
Kotlin
82
2,892
e1f67cc997884e4f6e0e7074c2bae599d3996c9a
703
EasyBangumi
Apache License 2.0
newm-server/src/main/kotlin/io/newm/server/auth/jwt/JwtConfig.kt
projectNEWM
447,979,150
false
null
package io.newm.server.auth.jwt import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import io.ktor.server.application.ApplicationEnvironment import io.ktor.server.auth.AuthenticationConfig import io.ktor.server.auth.jwt.JWTPrincipal import io.ktor.server.auth.jwt.jwt import io.newm.server.auth.jwt.repo.JwtRepository import io.newm.server.ktx.getSecureConfigString import io.newm.shared.koin.inject import io.newm.shared.ktx.getConfigString import io.newm.shared.ktx.toUUID import io.newm.shared.ktx.warn import kotlinx.coroutines.runBlocking import org.koin.core.parameter.parametersOf import org.slf4j.Logger const val AUTH_JWT = "auth-jwt" const val AUTH_JWT_REFRESH = "auth-jwt-refresh" const val AUTH_JWT_ADMIN = "auth-jwt-admin" fun AuthenticationConfig.configureJwt() { configureJwt(AUTH_JWT, JwtType.Access) configureJwt(AUTH_JWT_REFRESH, JwtType.Refresh) configureJwt(AUTH_JWT_ADMIN, JwtType.Access) } private fun AuthenticationConfig.configureJwt(name: String, type: JwtType) { val environment: ApplicationEnvironment by inject() val repository: JwtRepository by inject() val logger: Logger by inject { parametersOf(javaClass.simpleName) } jwt(name) { this.realm = environment.getConfigString("jwt.realm") verifier( JWT.require(Algorithm.HMAC256(runBlocking { environment.getSecureConfigString("jwt.secret") })) .withAudience(environment.getConfigString("jwt.audience")) .withIssuer(environment.getConfigString("jwt.issuer")) .withClaim("type", type.name) .apply { if (name == AUTH_JWT_ADMIN) { withClaim("admin", true) } } .build() ) validate { credential -> with(credential) { val admin = payload.getClaim("admin")?.asBoolean() == true val exists = payload.id?.let { jwkId -> repository.exists(jwkId.toUUID()) } == true val isValid = if (name == AUTH_JWT_ADMIN) { admin && exists } else { exists } if (isValid) { JWTPrincipal(payload) } else { logger.warn { "JWT Auth Failed: audience: $audience, issuer: $issuer, issuedAt: $issuedAt, expiresAt: $expiresAt, admin: $admin" } null } } } } }
1
null
5
9
5aa1f1b4f6e0c036ca3f66216ff6ad7d9f7d6547
2,521
newm-server
Apache License 2.0
src/main/kotlin/me/emkt/cashflowservice/ApplicationModels.kt
m4rc0s
524,243,434
false
null
package me.emkt.cashflowservice import org.springframework.data.mongodb.core.mapping.DBRef import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.core.mapping.MongoId import java.math.BigDecimal import java.time.LocalDateTime import java.util.UUID @Document("accounts") data class Account( @MongoId val id: UUID = UUID.randomUUID(), val name: String, val description: String, val tags: List<String> = emptyList() ) data class Money( val amount: BigDecimal, val code: String = "BRL" ) @Document("assets") data class Asset( val id: UUID = UUID.randomUUID(), val description: String, val amount: BigDecimal ) @Document("entries") data class Entry( val id: UUID = UUID.randomUUID(), val amount: BigDecimal, val description: String, val type: EntryType, @DBRef val account: Account, val createdAt: LocalDateTime = LocalDateTime.now(), val updatedAt: LocalDateTime = LocalDateTime.now() ) @Document("balances") data class Balance( val id: UUID = UUID.randomUUID(), val accountId: String, val amount: BigDecimal, val createdAt: LocalDateTime = LocalDateTime.now(), val updatedAt: LocalDateTime = LocalDateTime.now() ) enum class EntryType { DEBIT, CREDIT }
0
Kotlin
0
0
125ae775ccdb7fdfe83591497c04b358acc3069f
1,305
money-tracing
MIT License
app/src/main/java/com/mburakcakir/cryptopricetracker/data/model/FavouriteCoinModel.kt
mburakcakir
358,273,321
false
null
package com.aokur.bitcointicker.data.model data class FavouriteCoinModel( val id: String, val image: String, val name: String, val symbol: String ) { constructor() : this("", "", "", "") }
1
Kotlin
3
9
7a1e0a0978e77fcd2c94b8431f39cb32450159bc
209
CryptoPriceTracker
Apache License 2.0
shark-hprof/src/test/java/HprofReaderPrimitiveArrayTest.kt
yisitao
207,528,339
true
{"Kotlin": 685868, "Shell": 1312}
import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import shark.Hprof import shark.HprofRecord import shark.OnHprofRecordListener import kotlin.text.Charsets.UTF_8 class HprofReaderPrimitiveArrayTest { @get:Rule var heapDumpRule = HeapDumpRule() @Test fun skips_primitive_arrays_correctly() { val heapDump = heapDumpRule.dumpHeap() Hprof.open(heapDump).use { hprof -> hprof.reader.readHprofRecords( emptySet(), // skip everything including primitive arrays OnHprofRecordListener { _, _ -> }) } } @Test fun reads_primitive_arrays_correctly() { val byteArray = "mybytes".toByteArray(UTF_8) val heapDump = heapDumpRule.dumpHeap() var myByteArrayIsInHeapDump = false Hprof.open(heapDump).use { hprof -> hprof.reader.readHprofRecords( setOf(HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord::class), OnHprofRecordListener { _, record -> if (record is HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ByteArrayDump) { if (byteArray.contentEquals(record.array)) { myByteArrayIsInHeapDump = true } } }) } assertThat(myByteArrayIsInHeapDump).isTrue() } }
0
null
0
0
e032f55772fbe8432210cfad5529a9b5863e9160
1,490
leakcanary
Apache License 2.0
app/src/main/java/com/idrnd/idvoice/utils/extensions/TabLayoutExtensions.kt
IDRnD
276,359,666
false
{"Kotlin": 125755}
package com.idrnd.idvoice.utils.extensions import com.google.android.material.tabs.TabLayout /** * Add a TabLayout.OnTabSelectedListener that will be invoked when tab selection changes. * * <p>Components that add a listener should take care to remove it when finished via {@link * #removeOnTabSelectedListener(OnTabSelectedListener)}. * */ inline fun TabLayout?.addOnTabSelectedListener( crossinline onTabReselected: (tab: TabLayout.Tab?) -> Unit = { }, crossinline onTabUnselected: (tab: TabLayout.Tab?) -> Unit = { }, crossinline onTabSelected: (tab: TabLayout.Tab?) -> Unit = { }, ) { this?.addOnTabSelectedListener( object : TabLayout.OnTabSelectedListener { override fun onTabReselected(tab: TabLayout.Tab?) = onTabReselected(tab) override fun onTabUnselected(tab: TabLayout.Tab?) = onTabUnselected(tab) override fun onTabSelected(tab: TabLayout.Tab?) = onTabSelected(tab) }, ) }
1
Kotlin
2
14
a3abc574bf054094a9c1565c9f61fb6bf23d0c4d
965
idvoice-android-demo
MIT License
modules/dql-model/src/main/kotlin/com/farcsal/dql/model/DqlCriteriaValue.kt
fzoli
541,286,565
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farcsal.dql.model class DqlCriteriaValue internal constructor( val valueType: DqlCriteriaValueType, /** * null if not a string value or unary */ val stringValue: String? = null, /** * null if not a number value or unary */ val numberValue: DqlNumber? = null, /** * null if not a string list value or unary */ val stringListValue: List<String>? = null, /** * null if not a number list value or unary */ val numberListValue: List<DqlNumber>? = null ) { companion object { fun ofUnary(): DqlCriteriaValue { return DqlCriteriaValue( valueType = DqlCriteriaValueType.UNARY ) } fun ofString(value: String): DqlCriteriaValue { return DqlCriteriaValue( valueType = DqlCriteriaValueType.STRING, stringValue = value ) } fun ofStringList(value: List<String>): DqlCriteriaValue { return DqlCriteriaValue( valueType = DqlCriteriaValueType.STRING_LIST, stringListValue = value ) } fun ofNumber(value: DqlNumber): DqlCriteriaValue { return DqlCriteriaValue( valueType = DqlCriteriaValueType.NUMBER, numberValue = value ) } fun ofNumberList(value: List<DqlNumber>): DqlCriteriaValue { return DqlCriteriaValue( valueType = DqlCriteriaValueType.NUMBER_LIST, numberListValue = value ) } } fun visit(visitor: DqlCriteriaValueVisitor) { when (valueType) { DqlCriteriaValueType.UNARY -> visitor.unary() DqlCriteriaValueType.NUMBER -> visitor.number(numberValue ?: throw NullPointerException("numberValue")) DqlCriteriaValueType.STRING -> visitor.string(stringValue ?: throw NullPointerException("stringValue")) DqlCriteriaValueType.NUMBER_LIST -> visitor.numberList(numberListValue ?: throw NullPointerException("numberListValue")) DqlCriteriaValueType.STRING_LIST -> visitor.stringList(stringListValue ?: throw NullPointerException("stringListValue")) } } override fun toString(): String { return when (valueType) { DqlCriteriaValueType.UNARY -> "" DqlCriteriaValueType.NUMBER -> numberValue.toString() DqlCriteriaValueType.STRING -> stringValue.toString() DqlCriteriaValueType.NUMBER_LIST -> numberListValue.toString() DqlCriteriaValueType.STRING_LIST -> stringListValue.toString() } } fun requireStringValue(): String { return stringValue ?: throw NullPointerException() } fun requireStringListValue(): List<String> { return stringListValue ?: throw NullPointerException() } fun requireNumberValue(): DqlNumber { return numberValue ?: throw NullPointerException() } fun requireNumberListValue(): List<DqlNumber> { return numberListValue ?: throw NullPointerException() } }
0
Kotlin
0
1
9124bbded2e69846270d8d9f2f29b575f21999e7
3,773
dql-kotlin
Apache License 2.0
fir/src/org/jetbrains/kotlin/idea/fir/inspections/diagnosticBased/HLRedundantVisibilityModifierInspection.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.inspections.diagnosticBased import com.intellij.codeInspection.ProblemHighlightType import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.HLApplicator import org.jetbrains.kotlin.idea.api.applicator.with import org.jetbrains.kotlin.idea.fir.api.AbstractHLDiagnosticBasedInspection import org.jetbrains.kotlin.idea.fir.api.applicator.* import org.jetbrains.kotlin.idea.fir.api.inputByDiagnosticProvider import org.jetbrains.kotlin.idea.fir.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.fir.applicators.ModifierApplicators import org.jetbrains.kotlin.idea.frontend.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType class HLRedundantVisibilityModifierInspection : AbstractHLDiagnosticBasedInspection<KtModifierListOwner, KtFirDiagnostic.RedundantVisibilityModifier, ModifierApplicators.Modifier>( elementType = KtModifierListOwner::class, diagnosticType = KtFirDiagnostic.RedundantVisibilityModifier::class ) { override val inputByDiagnosticProvider = inputByDiagnosticProvider<KtModifierListOwner, KtFirDiagnostic.RedundantVisibilityModifier, ModifierApplicators.Modifier> { diagnostic -> val modifier = diagnostic.psi.visibilityModifierType() ?: return@inputByDiagnosticProvider null ModifierApplicators.Modifier(modifier) } override val presentation: HLPresentation<KtModifierListOwner> = presentation { highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) } override val applicabilityRange: HLApplicabilityRange<KtModifierListOwner> = ApplicabilityRanges.VISIBILITY_MODIFIER override val applicator: HLApplicator<KtModifierListOwner, ModifierApplicators.Modifier> = ModifierApplicators.removeModifierApplicator( KtTokens.VISIBILITY_MODIFIERS, KotlinBundle.lazyMessage("redundant.visibility.modifier") ).with { actionName { _, (modifier) -> KotlinBundle.message("remove.redundant.0.modifier", modifier.value) } } }
1
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
2,425
intellij-kotlin
Apache License 2.0
app/src/main/java/pk/sufiishq/app/ui/main/player/PlayerView.kt
sufiishq
427,931,739
false
{"Kotlin": 950135}
/* * Copyright 2022-2023 SufiIshq * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pk.sufiishq.app.ui.main.player import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import pk.sufiishq.app.annotations.ExcludeFromJacocoGeneratedReport import pk.sufiishq.app.feature.player.controller.PlayerController import pk.sufiishq.app.feature.player.controller.PlayerViewModel import pk.sufiishq.app.utils.extention.formatTime import pk.sufiishq.app.utils.fakePlayerController import pk.sufiishq.app.utils.rem import pk.sufiishq.aurora.components.SIText import pk.sufiishq.aurora.layout.SIAuroraSurface import pk.sufiishq.aurora.layout.SIBox import pk.sufiishq.aurora.layout.SIRow import pk.sufiishq.aurora.theme.AuroraColor import pk.sufiishq.aurora.theme.AuroraDark import pk.sufiishq.aurora.theme.AuroraLight @Composable fun PlayerView( playerController: PlayerController = hiltViewModel<PlayerViewModel>(), ) { val sliderThumbPressed = rem(false) val showSliderLabel = remember { derivedStateOf { sliderThumbPressed.value } } val kalamInfo = playerController.getKalamInfo().observeAsState() SIAuroraSurface(modifier = Modifier.fillMaxWidth().height(90.dp)) { SIBox(modifier = Modifier.fillMaxSize()) { SIBox(modifier = Modifier.padding(top = 6.dp)) { TrackInfo(kalamInfo = kalamInfo.value) PlayPauseButton( playerController = playerController, kalamInfo = kalamInfo, boxScope = this, ) } TrackSlider( playerController = playerController, modifier = Modifier .align(Alignment.TopCenter) .fillMaxWidth() .height(0.dp), kalamInfo = kalamInfo.value, onValueChange = { sliderThumbPressed.value = true }, onValueChangeFinished = { sliderThumbPressed.value = false }, ) } } if (showSliderLabel.value) { val localDensity = LocalDensity.current SIBox( modifier = Modifier .fillMaxWidth() .graphicsLayer { translationY = localDensity.run { 80.dp.toPx() * -1 } }, ) { SIRow( bgColor = AuroraColor.SecondaryVariant, padding = 8, radius = 4, ) { SIText( text = kalamInfo.value?.currentProgress?.formatTime ?: 0.formatTime, textColor = it, ) } } } } @ExcludeFromJacocoGeneratedReport @Preview(showBackground = true) @Composable fun PlayerPreviewLight() { AuroraLight { PlayerView( playerController = fakePlayerController(), ) } } @ExcludeFromJacocoGeneratedReport @Preview(showBackground = true) @Composable fun PlayerPreviewDark() { AuroraDark { PlayerView( playerController = fakePlayerController(), ) } }
3
Kotlin
0
2
254eeb6c2b1cad21d2f971d8b49ba3327d446bb5
4,271
sufiishq-mobile
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/autoscaling/SignalsOptionsDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.autoscaling import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Number import software.amazon.awscdk.Duration import software.amazon.awscdk.services.autoscaling.SignalsOptions /** * Customization options for Signal handling. * * Example: * ``` * Vpc vpc; * InstanceType instanceType; * IMachineImage machineImage; * AutoScalingGroup.Builder.create(this, "ASG") * .vpc(vpc) * .instanceType(instanceType) * .machineImage(machineImage) * // ... * .init(CloudFormationInit.fromElements(InitFile.fromString("/etc/my_instance", "This got written * during instance startup"))) * .signals(Signals.waitForAll(SignalsOptions.builder() * .timeout(Duration.minutes(10)) * .build())) * .build(); * ``` */ @CdkDslMarker public class SignalsOptionsDsl { private val cdkBuilder: SignalsOptions.Builder = SignalsOptions.builder() /** * @param minSuccessPercentage The percentage of signals that need to be successful. If this * number is less than 100, a percentage of signals may be failure signals while still * succeeding the creation or update in CloudFormation. */ public fun minSuccessPercentage(minSuccessPercentage: Number) { cdkBuilder.minSuccessPercentage(minSuccessPercentage) } /** * @param timeout How long to wait for the signals to be sent. This should reflect how long it * takes your instances to start up (including instance start time and instance initialization * time). */ public fun timeout(timeout: Duration) { cdkBuilder.timeout(timeout) } public fun build(): SignalsOptions = cdkBuilder.build() }
3
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,904
awscdk-dsl-kotlin
Apache License 2.0
apollo-compiler/src/test/graphql/com/example/unique_type_name/fragment/HeroDetails.kt
apollostack
69,469,299
false
null
// AUTO-GENERATED FILE. DO NOT MODIFY. // // This class was automatically generated by Apollo GraphQL plugin from the GraphQL queries it found. // It should not be modified by hand. // package com.example.fragment_friends_connection.fragment import com.apollographql.apollo.api.GraphqlFragment import com.apollographql.apollo.api.ResponseField import com.apollographql.apollo.api.internal.ResponseFieldMapper import com.apollographql.apollo.api.internal.ResponseFieldMarshaller import com.apollographql.apollo.api.internal.ResponseReader import kotlin.Array import kotlin.Int import kotlin.String import kotlin.Suppress import kotlin.collections.List @Suppress("NAME_SHADOWING", "UNUSED_ANONYMOUS_PARAMETER", "LocalVariableName", "RemoveExplicitTypeArguments", "NestedLambdaShadowedImplicitParameter") data class HeroDetails( val __typename: String = "Character", /** * The name of the character */ val name: String, /** * The friends of the character exposed as a connection with edges */ val friendsConnection: FriendsConnection ) : GraphqlFragment { override fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller.invoke { writer -> writer.writeString(RESPONSE_FIELDS[0], this@HeroDetails.__typename) writer.writeString(RESPONSE_FIELDS[1], [email protected]) writer.writeObject(RESPONSE_FIELDS[2], [email protected]()) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forString("__typename", "__typename", null, false, null), ResponseField.forString("name", "name", null, false, null), ResponseField.forObject("friendsConnection", "friendsConnection", null, false, null) ) val FRAGMENT_DEFINITION: String = """ |fragment HeroDetails on Character { | __typename | name | friendsConnection { | __typename | totalCount | edges { | __typename | node { | __typename | name | } | } | } |} """.trimMargin() operator fun invoke(reader: ResponseReader): HeroDetails = reader.run { val __typename = readString(RESPONSE_FIELDS[0])!! val name = readString(RESPONSE_FIELDS[1])!! val friendsConnection = readObject<FriendsConnection>(RESPONSE_FIELDS[2]) { reader -> FriendsConnection(reader) }!! HeroDetails( __typename = __typename, name = name, friendsConnection = friendsConnection ) } @Suppress("FunctionName") fun Mapper(): ResponseFieldMapper<HeroDetails> = ResponseFieldMapper { invoke(it) } } /** * A character from the Star Wars universe */ data class Node( val __typename: String = "Character", /** * The name of the character */ val name: String ) { fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller.invoke { writer -> writer.writeString(RESPONSE_FIELDS[0], this@Node.__typename) writer.writeString(RESPONSE_FIELDS[1], [email protected]) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forString("__typename", "__typename", null, false, null), ResponseField.forString("name", "name", null, false, null) ) operator fun invoke(reader: ResponseReader): Node = reader.run { val __typename = readString(RESPONSE_FIELDS[0])!! val name = readString(RESPONSE_FIELDS[1])!! Node( __typename = __typename, name = name ) } @Suppress("FunctionName") fun Mapper(): ResponseFieldMapper<Node> = ResponseFieldMapper { invoke(it) } } } /** * An edge object for a character's friends */ data class Edge( val __typename: String = "FriendsEdge", /** * The character represented by this friendship edge */ val node: Node? ) { fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller.invoke { writer -> writer.writeString(RESPONSE_FIELDS[0], this@Edge.__typename) writer.writeObject(RESPONSE_FIELDS[1], [email protected]?.marshaller()) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forString("__typename", "__typename", null, false, null), ResponseField.forObject("node", "node", null, true, null) ) operator fun invoke(reader: ResponseReader): Edge = reader.run { val __typename = readString(RESPONSE_FIELDS[0])!! val node = readObject<Node>(RESPONSE_FIELDS[1]) { reader -> Node(reader) } Edge( __typename = __typename, node = node ) } @Suppress("FunctionName") fun Mapper(): ResponseFieldMapper<Edge> = ResponseFieldMapper { invoke(it) } } } /** * A connection object for a character's friends */ data class FriendsConnection( val __typename: String = "FriendsConnection", /** * The total number of friends */ val totalCount: Int?, /** * The edges for each of the character's friends. */ val edges: List<Edge?>? ) { fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller.invoke { writer -> writer.writeString(RESPONSE_FIELDS[0], this@FriendsConnection.__typename) writer.writeInt(RESPONSE_FIELDS[1], [email protected]) writer.writeList(RESPONSE_FIELDS[2], [email protected]) { value, listItemWriter -> value?.forEach { value -> listItemWriter.writeObject(value?.marshaller())} } } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forString("__typename", "__typename", null, false, null), ResponseField.forInt("totalCount", "totalCount", null, true, null), ResponseField.forList("edges", "edges", null, true, null) ) operator fun invoke(reader: ResponseReader): FriendsConnection = reader.run { val __typename = readString(RESPONSE_FIELDS[0])!! val totalCount = readInt(RESPONSE_FIELDS[1]) val edges = readList<Edge>(RESPONSE_FIELDS[2]) { reader -> reader.readObject<Edge> { reader -> Edge(reader) } } FriendsConnection( __typename = __typename, totalCount = totalCount, edges = edges ) } @Suppress("FunctionName") fun Mapper(): ResponseFieldMapper<FriendsConnection> = ResponseFieldMapper { invoke(it) } } } }
5
Java
531
2,897
f16ef0f4020af7a07c200f0fdcf1dac977d63637
6,710
apollo-android
MIT License
3ds2/src/main/java/com/adyen/checkout/adyen3ds2/Adyen3DS2Component.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2019 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by caiof on 7/5/2019. */ package com.adyen.checkout.adyen3ds2 import android.app.Activity import android.app.Application import android.content.Context import android.content.Intent import android.os.Bundle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import androidx.lifecycle.viewModelScope import com.adyen.checkout.adyen3ds2.exception.Authentication3DS2Exception import com.adyen.checkout.adyen3ds2.exception.Cancelled3DS2Exception import com.adyen.checkout.adyen3ds2.model.ChallengeToken import com.adyen.checkout.adyen3ds2.model.FingerprintToken import com.adyen.checkout.adyen3ds2.repository.SubmitFingerprintRepository import com.adyen.checkout.adyen3ds2.repository.SubmitFingerprintResult import com.adyen.checkout.components.ActionComponentData import com.adyen.checkout.components.ActionComponentProvider import com.adyen.checkout.components.base.BaseActionComponent import com.adyen.checkout.components.base.IntentHandlingComponent import com.adyen.checkout.components.encoding.Base64Encoder import com.adyen.checkout.components.model.payments.response.Action import com.adyen.checkout.components.model.payments.response.Threeds2Action import com.adyen.checkout.components.model.payments.response.Threeds2Action.SubType import com.adyen.checkout.components.model.payments.response.Threeds2ChallengeAction import com.adyen.checkout.components.model.payments.response.Threeds2FingerprintAction import com.adyen.checkout.core.exception.CheckoutException import com.adyen.checkout.core.exception.ComponentException import com.adyen.checkout.core.log.LogUtil import com.adyen.checkout.core.log.Logger import com.adyen.checkout.redirect.RedirectDelegate import com.adyen.threeds2.AuthenticationRequestParameters import com.adyen.threeds2.ChallengeStatusReceiver import com.adyen.threeds2.CompletionEvent import com.adyen.threeds2.ProtocolErrorEvent import com.adyen.threeds2.RuntimeErrorEvent import com.adyen.threeds2.ThreeDS2Service import com.adyen.threeds2.Transaction import com.adyen.threeds2.customization.UiCustomization import com.adyen.threeds2.exception.InvalidInputException import com.adyen.threeds2.exception.SDKAlreadyInitializedException import com.adyen.threeds2.exception.SDKNotInitializedException import com.adyen.threeds2.exception.SDKRuntimeException import com.adyen.threeds2.parameters.ChallengeParameters import com.adyen.threeds2.util.AdyenConfigParameters import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.json.JSONException import org.json.JSONObject @Suppress("TooManyFunctions") class Adyen3DS2Component( application: Application, configuration: Adyen3DS2Configuration, private val submitFingerprintRepository: SubmitFingerprintRepository, private val adyen3DS2Serializer: Adyen3DS2Serializer, private val redirectDelegate: RedirectDelegate ) : BaseActionComponent<Adyen3DS2Configuration>(application, configuration), ChallengeStatusReceiver, IntentHandlingComponent { private var mTransaction: Transaction? = null private var mUiCustomization: UiCustomization? = null private var authorizationToken: String? = null override fun onCleared() { super.onCleared() Logger.d(TAG, "onCleared") if (mTransaction != null) { // We don't save the mTransaction reference if the ViewModel gets cleared. sGotDestroyedWhileChallenging = true } } override fun observe(lifecycleOwner: LifecycleOwner, observer: Observer<ActionComponentData>) { super.observe(lifecycleOwner, observer) if (sGotDestroyedWhileChallenging) { // This is OK if the user goes back and starts a new payment. // TODO notify error to activity? Logger.e(TAG, "Lost challenge result reference.") } } /** * Set a [UiCustomization] object to be passed to the 3DS2 SDK for customizing the challenge screen. * Needs to be set before handling any action. * * @param uiCustomization The customization object. */ fun setUiCustomization(uiCustomization: UiCustomization?) { mUiCustomization = uiCustomization } override fun canHandleAction(action: Action): Boolean { return PROVIDER.canHandleAction(action) } override fun saveState(bundle: Bundle?) { if (bundle != null && authorizationToken != null) { if (bundle.containsKey(AUTHORIZATION_TOKEN_KEY)) { Logger.d(TAG, "bundle already has authorizationToken, overriding") } bundle.putString(AUTHORIZATION_TOKEN_KEY, authorizationToken) } super.saveState(bundle) } override fun restoreState(bundle: Bundle?) { if (bundle != null && bundle.containsKey(AUTHORIZATION_TOKEN_KEY) && authorizationToken == null) { authorizationToken = bundle.getString(AUTHORIZATION_TOKEN_KEY) } super.restoreState(bundle) } @Throws(ComponentException::class) override fun handleActionInternal(activity: Activity, action: Action) { when (action) { is Threeds2FingerprintAction -> { if (action.token.isNullOrEmpty()) { throw ComponentException("Fingerprint token not found.") } identifyShopper(activity, action.token.orEmpty(), submitFingerprintAutomatically = false) } is Threeds2ChallengeAction -> { if (action.token.isNullOrEmpty()) { throw ComponentException("Challenge token not found.") } challengeShopper(activity, action.token.orEmpty()) } is Threeds2Action -> { if (action.token.isNullOrEmpty()) { throw ComponentException("3DS2 token not found.") } if (action.subtype == null) { throw ComponentException("3DS2 Action subtype not found.") } val subtype = SubType.parse(action.subtype.orEmpty()) // We need to keep authorizationToken in memory to access it later when the 3DS2 challenge is done authorizationToken = action.authorisationToken handleActionSubtype(activity, subtype, action.token.orEmpty()) } } } private fun handleActionSubtype(activity: Activity, subtype: SubType, token: String) { when (subtype) { SubType.FINGERPRINT -> identifyShopper(activity, token, submitFingerprintAutomatically = true) SubType.CHALLENGE -> challengeShopper(activity, token) } } override fun completed(completionEvent: CompletionEvent) { Logger.d(TAG, "challenge completed") try { // Check whether authorizationToken was set and create the corresponding details object val token = authorizationToken val details = if (token == null) adyen3DS2Serializer.createChallengeDetails(completionEvent) else adyen3DS2Serializer.createThreeDsResultDetails(completionEvent, token) notifyDetails(details) } catch (e: CheckoutException) { notifyException(e) } finally { closeTransaction(getApplication()) } } override fun cancelled() { Logger.d(TAG, "challenge cancelled") notifyException(Cancelled3DS2Exception("Challenge canceled.")) closeTransaction(getApplication()) } override fun timedout() { Logger.d(TAG, "challenge timed out") notifyException(Authentication3DS2Exception("Challenge timed out.")) closeTransaction(getApplication()) } override fun protocolError(protocolErrorEvent: ProtocolErrorEvent) { with(protocolErrorEvent.errorMessage) { Logger.e(TAG, "protocolError - $errorCode - $errorDescription - $errorDetails") notifyException(Authentication3DS2Exception("Protocol Error - $this")) } closeTransaction(getApplication()) } override fun runtimeError(runtimeErrorEvent: RuntimeErrorEvent) { Logger.d(TAG, "runtimeError") notifyException(Authentication3DS2Exception("Runtime Error - " + runtimeErrorEvent.errorMessage)) closeTransaction(getApplication()) } @Throws(ComponentException::class) private fun identifyShopper(activity: Activity, encodedFingerprintToken: String, submitFingerprintAutomatically: Boolean) { Logger.d(TAG, "identifyShopper - submitFingerprintAutomatically: $submitFingerprintAutomatically") val decodedFingerprintToken = Base64Encoder.decode(encodedFingerprintToken) val fingerprintJson: JSONObject = try { JSONObject(decodedFingerprintToken) } catch (e: JSONException) { throw ComponentException("JSON parsing of FingerprintToken failed", e) } val fingerprintToken = FingerprintToken.SERIALIZER.deserialize(fingerprintJson) val configParameters = AdyenConfigParameters.Builder( fingerprintToken.directoryServerId, fingerprintToken.directoryServerPublicKey ).build() val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable -> Logger.e(TAG, "Unexpected uncaught 3DS2 Exception", throwable) notifyException(CheckoutException("Unexpected 3DS2 exception.", throwable)) } viewModelScope.launch(Dispatchers.Default + coroutineExceptionHandler) { try { Logger.d(TAG, "initialize 3DS2 SDK") ThreeDS2Service.INSTANCE.initialize(activity, configParameters, null, mUiCustomization) } catch (e: SDKRuntimeException) { notifyException(ComponentException("Failed to initialize 3DS2 SDK", e)) return@launch } catch (e: SDKAlreadyInitializedException) { // This shouldn't cause any side effect. Logger.w(TAG, "3DS2 Service already initialized.") } mTransaction = try { Logger.d(TAG, "create transaction") ThreeDS2Service.INSTANCE.createTransaction(null, fingerprintToken.threeDSMessageVersion) } catch (e: SDKNotInitializedException) { notifyException(ComponentException("Failed to create 3DS2 Transaction", e)) return@launch } catch (e: SDKRuntimeException) { notifyException(ComponentException("Failed to create 3DS2 Transaction", e)) return@launch } val authenticationRequestParameters = mTransaction?.authenticationRequestParameters if (authenticationRequestParameters == null) { notifyException(ComponentException("Failed to retrieve 3DS2 authentication parameters")) return@launch } val encodedFingerprint = createEncodedFingerprint(authenticationRequestParameters) if (submitFingerprintAutomatically) { submitFingerprintAutomatically(activity, encodedFingerprint) } else { launch(Dispatchers.Main) { notifyDetails(adyen3DS2Serializer.createFingerprintDetails(encodedFingerprint)) } } } } private suspend fun submitFingerprintAutomatically(activity: Activity, encodedFingerprint: String) { try { val result = submitFingerprintRepository.submitFingerprint(encodedFingerprint, configuration, paymentData) // This flow (calling the internal submitFingerprint endpoint) requires that we do not send paymentData back to the merchant. // Setting it to null ensures that when the flow ends and notifyDetails is called, paymentData will not be included in the response. paymentData = null when (result) { is SubmitFingerprintResult.Completed -> { viewModelScope.launch(Dispatchers.Main) { notifyDetails(result.details) } } is SubmitFingerprintResult.Redirect -> { redirectDelegate.makeRedirect(activity, result.action) } is SubmitFingerprintResult.Threeds2 -> { handleAction(activity, result.action) } } } catch (e: ComponentException) { notifyException(e) } } @Throws(ComponentException::class) private fun challengeShopper(activity: Activity, encodedChallengeToken: String) { Logger.d(TAG, "challengeShopper") if (mTransaction == null) { notifyException(Authentication3DS2Exception("Failed to make challenge, missing reference to initial transaction.")) return } val decodedChallengeToken = Base64Encoder.decode(encodedChallengeToken) val challengeTokenJson: JSONObject = try { JSONObject(decodedChallengeToken) } catch (e: JSONException) { throw ComponentException("JSON parsing of FingerprintToken failed", e) } val challengeToken = ChallengeToken.SERIALIZER.deserialize(challengeTokenJson) val challengeParameters = createChallengeParameters(challengeToken) try { mTransaction?.doChallenge(activity, challengeParameters, this, DEFAULT_CHALLENGE_TIME_OUT) } catch (e: InvalidInputException) { notifyException(CheckoutException("Error starting challenge", e)) } } @Throws(ComponentException::class) fun createEncodedFingerprint(authenticationRequestParameters: AuthenticationRequestParameters): String { val fingerprintJson = JSONObject() try { with(authenticationRequestParameters) { fingerprintJson.put("sdkAppID", sdkAppID) fingerprintJson.put("sdkEncData", deviceData) fingerprintJson.put("sdkEphemPubKey", JSONObject(sdkEphemeralPublicKey)) fingerprintJson.put("sdkReferenceNumber", sdkReferenceNumber) fingerprintJson.put("sdkTransID", sdkTransactionID) fingerprintJson.put("messageVersion", messageVersion) } } catch (e: JSONException) { throw ComponentException("Failed to create encoded fingerprint", e) } return Base64Encoder.encode(fingerprintJson.toString()) } private fun createChallengeParameters(challenge: ChallengeToken): ChallengeParameters { return ChallengeParameters().apply { set3DSServerTransactionID(challenge.threeDSServerTransID) acsTransactionID = challenge.acsTransID acsRefNumber = challenge.acsReferenceNumber acsSignedContent = challenge.acsSignedContent // This field was introduced in version 2.2.0 so older protocols don't expect it to be present and might throw an error. if (challenge.messageVersion != PROTOCOL_VERSION_2_1_0) { threeDSRequestorAppURL = ChallengeParameters.getEmbeddedRequestorAppURL(getApplication()) } } } private fun closeTransaction(context: Context) { mTransaction?.close() mTransaction = null try { ThreeDS2Service.INSTANCE.cleanup(context) } catch (e: SDKNotInitializedException) { // no problem } } /** * Call this method when receiving the return URL from the 3DS redirect with the result data. * This result will be in the [Intent.getData] and begins with the returnUrl you specified on the payments/ call. * * @param intent The received [Intent]. */ override fun handleIntent(intent: Intent) { try { val parsedResult = redirectDelegate.handleRedirectResponse(intent.data) notifyDetails(parsedResult) } catch (e: CheckoutException) { notifyException(e) } } companion object { private val TAG = LogUtil.getTag() private const val AUTHORIZATION_TOKEN_KEY = "authorization_token" @JvmField val PROVIDER: ActionComponentProvider<Adyen3DS2Component, Adyen3DS2Configuration> = Adyen3DS2ComponentProvider() private const val DEFAULT_CHALLENGE_TIME_OUT = 10 private const val PROTOCOL_VERSION_2_1_0 = "2.1.0" private var sGotDestroyedWhileChallenging = false } }
38
null
55
76
7ef3cb60ff12f1421e69b2e380a15504933499e7
16,749
adyen-android
MIT License
initializr-locorepo/src/main/kotlin/io/spring/initializr/locorepo/gradlekts/GradleLanguageMultiProjectSettingsWriter.kt
amirmv2006
304,826,019
false
{"Groovy": 2, "AsciiDoc": 13, "Text": 1, "Shell": 15, "Maven POM": 13, "Batchfile": 7, "Git Attributes": 1, "Ignore List": 1, "Java": 557, "XML": 39, "YAML": 24, "JSON": 21, "Dockerfile": 3, "Gradle": 2, "INI": 11, "Mustache": 10, "Kotlin": 64, "XSLT": 1, "CSS": 1, "Vim Snippet": 1}
package io.spring.initializr.locorepo.gradlekts import io.spring.initializr.generator.buildsystem.gradle.GradleBuild import io.spring.initializr.generator.buildsystem.gradle.KotlinDslGradleSettingsWriter import io.spring.initializr.generator.io.IndentingWriter import io.spring.initializr.locorepo.MpsProjectGenerationContext class GradleLanguageMultiProjectSettingsWriter(private val context: MpsProjectGenerationContext) : KotlinDslGradleSettingsWriter() { override fun writeTo(writer: IndentingWriter, build: GradleBuild) { writer.println("rootProject.name = " + wrapWithQuotes(build.settings.artifact)) writer.println() writer.println("include(") writer.indented { writer.println("\"code:buildscripts\",") writer.println("\"code:${context.projectDescription.artifactId}\"") } writer.println(")") } }
1
null
1
1
1c6c239b4dcb3e55ac8593894359e22fc3ed4295
890
initializr
Apache License 2.0
src/main/kotlin/org/cirruslabs/utils/bazel/model/MavenInstallDefinition.kt
cirruslabs
267,932,378
false
null
package org.cirruslabs.utils.bazel.model class MavenInstallDefinition( var dependency_tree: MavenDependencyTree ) data class MavenDependencyTree( var dependencies: List<MavenDependency> ) data class MavenDependency( var coord: String, var url: String ) { val definition: LibraryDefinition get() { val coordParts = coord.split(':', limit = 3) return LibraryDefinition(coordParts[0], coordParts[1], coordParts[2]) } } data class LibraryDefinition( val group: String, val name: String, val version: String ) { val mavenCoordinate: String get() = "$group:$name:$version" }
3
Kotlin
2
14
1347ac0281c0c65b3da0d046d9ac01514d2a20ac
615
bazel-project-generator
MIT License
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/ExampleWorkspaceModelEventsHandler.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl import com.intellij.openapi.Disposable import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleFileIndex import com.intellij.openapi.roots.ModuleRootManager import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.legacyBridge.module.isModuleUnloaded import com.intellij.workspaceModel.ide.legacyBridge.ModuleDependencyIndex import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl /** * This class is not handling events about global libraries and SDK changes. Such events should * be processed via [com.intellij.openapi.roots.ModuleRootListener] */ class ExampleWorkspaceModelEventsHandler(private val project: Project): Disposable { init { val messageBusConnection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { // Example of handling VirtualFileUrl change at entities with update cache based on the changed urls handleLibraryChanged(event) handleContentRootChanged(event) handleSourceRootChanged(event) // If cache invalidation depends on specific properties e.g. [org.jetbrains.jps.model.java.JavaResourceRootProperties.getRelativeOutputPath] // changes from [JavaResourceRootEntity] should be handled handleJavaSourceRootChanged(event) handleJavaResourceRootChanged(event) handleCustomSourceRootPropertiesChanged(event) handleModuleChanged(event) handleJavaModuleSettingsChanged(event) handleLibraryPropertiesChanged(event) handleModuleGroupPathChanged(event) handleModuleCustomImlDataChanged(event) } }) } private fun handleLibraryChanged(event: VersionedStorageChange) { event.getChanges(LibraryEntity::class.java).forEach { change -> val (entity, _) = getEntityAndStorage(event, change) if (!libraryIsDependency(entity, project)) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf(), listOf({ roots.map { it.url }}, { excludedRoots })) updateCache(addedUrls.urls, removedUrls.urls) } } /** * If your cache invalidation depends on [com.intellij.openapi.roots.impl.libraries.LibraryEx.getKind] or * [com.intellij.openapi.roots.impl.libraries.LibraryEx.getProperties] you should handle changes from [LibraryPropertiesEntity] */ private fun handleLibraryPropertiesChanged(event: VersionedStorageChange) { event.getChanges(LibraryPropertiesEntity::class.java).forEach { change -> val (entity, _) = getEntityAndStorage(event, change) if (!libraryIsDependency(entity.library, project)) return@forEach updateCache() } } private fun handleContentRootChanged(event: VersionedStorageChange) { event.getChanges(ContentRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({url}), listOf({ excludedUrls })) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleSourceRootChanged(event: VersionedStorageChange) { event.getChanges(SourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ contentRoot.module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({url})) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleJavaModuleSettingsChanged(event: VersionedStorageChange) { event.getChanges(JavaModuleSettingsEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach val (addedUrls, removedUrls) = calculateChangedUrls(change, listOf({compilerOutput}, {compilerOutputForTests})) updateCache(addedUrls.urls, removedUrls.urls) } } private fun handleModuleChanged(event: VersionedStorageChange) { event.getChanges(ModuleEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ this }) return@forEach updateCache() } } private fun handleModuleGroupPathChanged(event: VersionedStorageChange) { event.getChanges(ModuleGroupPathEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach updateCache() } } private fun handleModuleCustomImlDataChanged(event: VersionedStorageChange) { event.getChanges(ModuleCustomImlDataEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ module }) return@forEach updateCache() } } private fun handleJavaSourceRootChanged(event: VersionedStorageChange) { event.getChanges(JavaSourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change){ sourceRoot.contentRoot.module }) return@forEach updateCache() } } /** * If cache invalidation depends on specific properties e.g. [org.jetbrains.jps.model.java.JavaResourceRootProperties.getRelativeOutputPath] * changes from [JavaResourceRootEntity] should be handled */ private fun handleJavaResourceRootChanged(event: VersionedStorageChange) { event.getChanges(JavaResourceRootEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change) { sourceRoot.contentRoot.module }) return@forEach updateCache() } } private fun handleCustomSourceRootPropertiesChanged(event: VersionedStorageChange) { event.getChanges(CustomSourceRootPropertiesEntity::class.java).forEach { change -> if (isInUnloadedModule(event, change) { sourceRoot.contentRoot.module }) return@forEach updateCache() } } private fun <T: WorkspaceEntity> getEntityAndStorage(event: VersionedStorageChange, change: EntityChange<T>): Pair<T, EntityStorage> { return when (change) { is EntityChange.Added -> change.entity to event.storageAfter is EntityChange.Removed -> change.entity to event.storageBefore is EntityChange.Replaced -> change.newEntity to event.storageAfter } } private fun <T: WorkspaceEntity> isInUnloadedModule(event: VersionedStorageChange, change: EntityChange<T>, moduleAssessor: T.() -> ModuleEntity): Boolean { val (entity, storage) = getEntityAndStorage(event, change) return entity.moduleAssessor().isModuleUnloaded(storage) } /** * Example of method for calculation changed VirtualFileUrls at entities */ private fun <T: WorkspaceEntity> calculateChangedUrls(change: EntityChange<T>, vfuAssessors: List<T.() -> VirtualFileUrl?>, vfuListAssessors: List<T.() -> List<VirtualFileUrl>> = emptyList()): Pair<Added, Removed> { val addedVirtualFileUrls = mutableSetOf<VirtualFileUrl>() val removedVirtualFileUrls = mutableSetOf<VirtualFileUrl>() vfuAssessors.forEach { fieldAssessor -> when (change) { is EntityChange.Added -> fieldAssessor.invoke(change.entity)?.also { addedVirtualFileUrls.add(it) } is EntityChange.Removed -> fieldAssessor.invoke(change.entity)?.also { removedVirtualFileUrls.add(it) } is EntityChange.Replaced -> { val newVirtualFileUrl = fieldAssessor.invoke(change.newEntity) val oldVirtualFileUrl = fieldAssessor.invoke(change.oldEntity) if (newVirtualFileUrl != oldVirtualFileUrl) { newVirtualFileUrl?.also { addedVirtualFileUrls.add(it) } oldVirtualFileUrl?.also { removedVirtualFileUrls.add(it) } } } } } vfuListAssessors.forEach { fieldAssessor -> when (change) { is EntityChange.Added -> { val virtualFileUrls = fieldAssessor.invoke(change.entity) if (virtualFileUrls.isNotEmpty()) { addedVirtualFileUrls.addAll(virtualFileUrls) } } is EntityChange.Removed -> { val virtualFileUrls = fieldAssessor.invoke(change.entity) if (virtualFileUrls.isNotEmpty()) { removedVirtualFileUrls.addAll(virtualFileUrls) } } is EntityChange.Replaced -> { val newVirtualFileUrls = fieldAssessor.invoke(change.newEntity).toSet() val oldVirtualFileUrls = fieldAssessor.invoke(change.oldEntity).toSet() addedVirtualFileUrls.addAll(newVirtualFileUrls.subtract(oldVirtualFileUrls)) removedVirtualFileUrls.addAll(oldVirtualFileUrls.subtract(newVirtualFileUrls)) } } } return Added(addedVirtualFileUrls) to Removed(removedVirtualFileUrls) } private fun libraryIsDependency(library: LibraryEntity, project: Project): Boolean { return ModuleDependencyIndex.getInstance(project).hasDependencyOn(library.persistentId) } private fun updateCache() { } private fun updateCache(addedVirtualFileUrls: MutableSet<VirtualFileUrl>, removedVirtualFileUrls: MutableSet<VirtualFileUrl>) { } private data class Added(val urls: MutableSet<VirtualFileUrl>) private data class Removed(val urls: MutableSet<VirtualFileUrl>) override fun dispose() { } }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
9,921
intellij-community
Apache License 2.0
android/src/main/java/org/dwbn/plugins/playlist/PlaylistPlugin.kt
phiamo
312,703,046
false
{"Swift": 67475, "TypeScript": 47408, "Kotlin": 43402, "Java": 31664, "Objective-C": 1878, "Ruby": 926, "JavaScript": 453}
package org.dwbn.plugins.playlist import android.os.Handler import android.os.Looper import android.util.Log import com.devbrackets.android.playlistcore.data.MediaProgress import com.getcapacitor.* import com.getcapacitor.annotation.CapacitorPlugin import org.dwbn.plugins.playlist.data.AudioTrack import org.json.JSONArray import org.json.JSONObject import java.util.* @CapacitorPlugin(name = "Playlist") class PlaylistPlugin : Plugin(), OnStatusReportListener { var TAG = "PlaylistPlugin" private var statusCallback: OnStatusCallback? = null private var audioPlayerImpl: RmxAudioPlayer? = null private var resetStreamOnPause = true override fun load() { audioPlayerImpl = RmxAudioPlayer(this, (this.context.applicationContext as App)) } @PluginMethod fun initialize(call: PluginCall) { Handler(Looper.getMainLooper()).post { statusCallback = OnStatusCallback(this) onStatus(RmxAudioStatusMessage.RMXSTATUS_REGISTER, "INIT", null) Log.i(TAG, "Initialized...") audioPlayerImpl!!.resume() call.resolve() } } @PluginMethod fun setOptions(call: PluginCall) { Handler(Looper.getMainLooper()).post { val options: JSObject = call.getObject("options") ?: JSObject() resetStreamOnPause = options.optBoolean("resetStreamOnPause", this.resetStreamOnPause) Log.i("AudioPlayerOptions", options.toString()) audioPlayerImpl!!.resetStreamOnPause = resetStreamOnPause audioPlayerImpl!!.setOptions(options) call.resolve() } } @PluginMethod fun release(call: PluginCall) { Handler(Looper.getMainLooper()).post { destroyResources() call.resolve() Log.i(TAG, "released") } } @PluginMethod fun setLoop(call: PluginCall) { Handler(Looper.getMainLooper()).post { val loop: Boolean = call.getBoolean("loop", audioPlayerImpl!!.playlistManager.loop)!! audioPlayerImpl!!.playlistManager.loop = loop call.resolve() Log.i(TAG, "setLoop: " + (if (loop) "TRUE" else "FALSE")) } } @PluginMethod fun setPlaylistItems(call: PluginCall) { Handler(Looper.getMainLooper()).post { val items: JSArray = call.getArray("items") val optionsArgs: JSONObject = call.getObject("options") val options = PlaylistItemOptions(optionsArgs) val trackItems: ArrayList<AudioTrack> = getTrackItems(items) audioPlayerImpl!!.playlistManager.setAllItems(trackItems, options) for (playerItem in trackItems) { if (playerItem.trackId != null) { onStatus( RmxAudioStatusMessage.RMXSTATUS_ITEM_ADDED, playerItem.trackId, playerItem.toDict() ) } } call.resolve() Log.i(TAG, "setPlaylistItems" + items.length().toString()) } } @PluginMethod fun addItem(call: PluginCall) { Handler(Looper.getMainLooper()).post { val item: JSONObject = call.getObject("item") val playerItem: AudioTrack? = getTrackItem(item) audioPlayerImpl!!.getPlaylistManager().addItem(playerItem) if (playerItem?.trackId != null) { onStatus( RmxAudioStatusMessage.RMXSTATUS_ITEM_ADDED, playerItem.trackId, playerItem.toDict() ) } call.resolve() Log.i(TAG, "addItem") } } @PluginMethod fun addAllItems(call: PluginCall) { Handler(Looper.getMainLooper()).post { val items: JSONArray = call.getArray("items") val trackItems = getTrackItems(items) audioPlayerImpl!!.playlistManager.addAllItems(trackItems) for (playerItem in trackItems) { if (playerItem.trackId != null) { onStatus( RmxAudioStatusMessage.RMXSTATUS_ITEM_ADDED, playerItem.trackId, playerItem.toDict() ) } } call.resolve() Log.i(TAG, "addAllItems") } } @PluginMethod fun removeItem(call: PluginCall) { Handler(Looper.getMainLooper()).post { val trackIndex: Int = call.getInt("index", -1)!! val trackId: String = call.getString("id", "")!! Log.i(TAG, "removeItem trackIn") val item = audioPlayerImpl!!.playlistManager.removeItem(trackIndex, trackId) if (item != null) { onStatus(RmxAudioStatusMessage.RMXSTATUS_ITEM_REMOVED, item.trackId, item.toDict()) call.resolve() } else { call.reject("Could not find item!") } } } @PluginMethod fun removeItems(call: PluginCall) { Handler(Looper.getMainLooper()).post { val items: JSONArray = call.getArray("items") var removed = 0 val removals = ArrayList<TrackRemovalItem>() for (index in 0 until items.length()) { val entry = items.optJSONObject(index) ?: continue val trackIndex = entry.optInt("trackIndex", -1) val trackId = entry.optString("trackId", "") removals.add(TrackRemovalItem(trackIndex, trackId)) val removedTracks = audioPlayerImpl!!.playlistManager.removeAllItems(removals) if (removedTracks.size > 0) { for (removedItem in removedTracks) { onStatus( RmxAudioStatusMessage.RMXSTATUS_ITEM_REMOVED, removedItem.trackId, removedItem.toDict() ) } removed = removedTracks.size } } val result = JSObject() result.put("removed", removed) call.resolve(result) Log.i(TAG, "removeItems") } } @PluginMethod fun clearAllItems(call: PluginCall) { Handler(Looper.getMainLooper()).post { audioPlayerImpl!!.playlistManager.clearItems() onStatus(RmxAudioStatusMessage.RMXSTATUS_PLAYLIST_CLEARED, "INVALID", null) call.resolve() Log.i(TAG, "clearAllItems") } } @PluginMethod fun play(call: PluginCall) { Handler(Looper.getMainLooper()).post { if (audioPlayerImpl!!.playlistManager.playlistHandler != null) { val isPlaying = (audioPlayerImpl!!.playlistManager.playlistHandler?.currentMediaPlayer != null && audioPlayerImpl!!.playlistManager.playlistHandler?.currentMediaPlayer?.isPlaying!!) // There's a bug in the threaded repeater that it stacks up the repeat calls instead of ignoring // additional ones or starting a new one. E.g. every time this is called, you'd get a new repeat cycle, // meaning you get N updates per second. Ew. if (!isPlaying) { audioPlayerImpl!!.playlistManager.playlistHandler?.play() //audioPlayerImpl.getPlaylistManager().playlistHandler.seek(position) } } call.resolve() Log.i(TAG, "play") } } @PluginMethod fun playTrackByIndex(call: PluginCall) { Handler(Looper.getMainLooper()).post { val index: Int = call.getInt("index", audioPlayerImpl!!.playlistManager.currentPosition)!! val seekPosition = (call.getInt("position", 0)!! * 1000.0).toLong() audioPlayerImpl!!.playlistManager.currentPosition = index audioPlayerImpl!!.playlistManager.beginPlayback(seekPosition, false) call.resolve() Log.i(TAG, "playTrackByIndex") } } @PluginMethod fun playTrackById(call: PluginCall) { Handler(Looper.getMainLooper()).post { val id: String = call.getString("id")!! if ("" != id) { // alternatively we could search for the item and set the current index to that item. val code = id.hashCode() val seekPosition = (call.getInt("position", 0)!! * 1000.0).toLong() audioPlayerImpl!!.playlistManager.setCurrentItem(code.toLong()) audioPlayerImpl!!.playlistManager.beginPlayback(seekPosition, false) } call.resolve() Log.i(TAG, "playTrackById") } } @PluginMethod fun selectTrackByIndex(call: PluginCall) { Handler(Looper.getMainLooper()).post { val index: Int = call.getInt("index", audioPlayerImpl!!.playlistManager.currentPosition)!! audioPlayerImpl!!.playlistManager.currentPosition = index val seekPosition = (call.getInt("position", 0)!! * 1000.0).toLong() audioPlayerImpl!!.playlistManager.beginPlayback(seekPosition, true) call.resolve() Log.i(TAG, "selectTrackByIndex") } } @PluginMethod fun selectTrackById(call: PluginCall) { Handler(Looper.getMainLooper()).post { val id: String = call.getString("id")!! if ("" != id) { // alternatively we could search for the item and set the current index to that item. val code = id.hashCode() audioPlayerImpl!!.playlistManager.setCurrentItem(code.toLong()) val seekPosition = (call.getInt("position", 0)!! * 1000.0).toLong() audioPlayerImpl!!.playlistManager.beginPlayback(seekPosition, true) } call.resolve() Log.i(TAG, "selectTrackById") } } @PluginMethod fun pause(call: PluginCall) { Handler(Looper.getMainLooper()).post { audioPlayerImpl!!.playlistManager.invokePausePlay() call.resolve() Log.i(TAG, "pause") } } @PluginMethod fun skipForward(call: PluginCall) { Handler(Looper.getMainLooper()).post { audioPlayerImpl!!.playlistManager.invokeNext() call.resolve() Log.i(TAG, "skipForward") } } @PluginMethod fun skipBack(call: PluginCall) { Handler(Looper.getMainLooper()).post { audioPlayerImpl!!.playlistManager.invokePrevious() call.resolve() Log.i(TAG, "skipBack") } } @PluginMethod fun seekTo(call: PluginCall) { Handler(Looper.getMainLooper()).post { var position: Long = 0 val progress: MediaProgress? = audioPlayerImpl!!.playlistManager.currentProgress if (progress != null) { position = progress.position } val seekPosition = (call.getInt("position", (position / 1000.0f).toInt())!! * 1000.0).toLong() val isPlaying: Boolean? = audioPlayerImpl!!.playlistManager.playlistHandler?.currentMediaPlayer?.isPlaying audioPlayerImpl!!.playlistManager.playlistHandler?.seek(seekPosition) if (isPlaying === null || !isPlaying) { audioPlayerImpl!!.playlistManager.playlistHandler?.pause(false) } call.resolve() Log.i(TAG, "seekTo") } } @PluginMethod fun setPlaybackRate(call: PluginCall) { Handler(Looper.getMainLooper()).post { val speed = call.getFloat("rate", audioPlayerImpl!!.playlistManager.getPlaybackSpeed())!! audioPlayerImpl!!.playlistManager.setPlaybackSpeed(speed) call.resolve() Log.i(TAG, "setPlaybackRate") } } @PluginMethod fun setVolume(call: PluginCall) { Handler(Looper.getMainLooper()).post { val volume = call.getFloat("volume", audioPlayerImpl!!.volume)!! audioPlayerImpl!!.volume = volume call.resolve() Log.i(TAG, "addItem") } } override fun handleOnDestroy() { Log.d(TAG, "Plugin destroy") super.handleOnDestroy() destroyResources() } override fun onError(errorCode: RmxAudioErrorType?, trackId: String?, message: String?) { if (statusCallback == null) { return } val errorObj = OnStatusCallback.createErrorWithCode(errorCode, message) onStatus(RmxAudioStatusMessage.RMXSTATUS_ERROR, trackId, errorObj) } override fun onStatus(what: RmxAudioStatusMessage, trackId: String?, param: JSONObject?) { if (statusCallback == null) { return } statusCallback!!.onStatus(what, trackId, param) } private fun destroyResources() { statusCallback = null audioPlayerImpl!!.playlistManager.clearItems() } private fun getTrackItem(item: JSONObject?): AudioTrack? { if (item != null) { val track = AudioTrack(item) return if (track.trackId != null) { track } else null } return null } private fun getTrackItems(items: JSONArray?): ArrayList<AudioTrack> { val trackItems = ArrayList<AudioTrack>() if (items != null && items.length() > 0) { for (index in 0 until items.length()) { val obj = items.optJSONObject(index) val track: AudioTrack = getTrackItem(obj) ?: continue trackItems.add(track) } } return trackItems } fun emit(name: String, data: JSObject) { this.notifyListeners(name, data, true) } }
5
Swift
20
23
9e780e775ff89469c81c2869572301ae4ab8baaa
14,100
capacitor-plugin-playlist
MIT License
app/src/main/java/pl/polsl/workflow/manager/client/ui/coordinator/group/patch/GroupCoordinatorPatchViewModel.kt
SzymonGajdzica
306,075,061
false
null
package pl.polsl.workflow.manager.client.ui.coordinator.group.patch import android.app.Application import androidx.lifecycle.LiveData import pl.polsl.workflow.manager.client.model.data.Group import pl.polsl.workflow.manager.client.model.data.GroupPatch import pl.polsl.workflow.manager.client.model.data.User import pl.polsl.workflow.manager.client.ui.base.BaseViewModel abstract class GroupCoordinatorPatchViewModel(application: Application): BaseViewModel(application) { abstract val nameInputError: LiveData<String> abstract val initialGroup: LiveData<Group> abstract val managers: LiveData<List<User>> abstract val remainingWorkers: LiveData<List<User>> abstract val selectedManager: LiveData<User> abstract val selectedWorkers: LiveData<List<User>> abstract fun onWorkerDeselected(worker: User) abstract fun onWorkerSelected(worker: User) abstract fun onManagerSelected(manager: User?) abstract fun updateGroup(group: Group, groupPatch: GroupPatch) }
0
Kotlin
0
0
93c99cc67c7af0bc55ca8fb03f077cdd363cb7e8
1,001
workflow-manager-client
MIT License
targetfun/src/main/java/com/cysion/targetfun/FlowableKt.kt
CysionLiu
158,726,380
false
null
package com.cysion.targetfun import io.reactivex.Flowable import io.reactivex.FlowableSubscriber import org.reactivestreams.Subscription class FlowableObj<T> : FlowableSubscriber<T> { private var _a: ((s: Subscription) -> Unit)? = null private var _b: ((t: T) -> Unit)? = null private var _c: (() -> Unit)? = null private var _d: ((e: Throwable) -> Unit)? = null //=== override fun onSubscribe(s: Subscription) { _a?.invoke(s) } fun ifSubscribe(t: ((s: Subscription) -> Unit)) { _a = t } //=== fun ifNext(t: ((t: T) -> Unit)) { _b = t } override fun onNext(t: T) { _b?.invoke(t) } //=== fun ifComplete(t: (() -> Unit)) { _c = t } override fun onComplete() { _c?.invoke() } //=== fun ifError(t: ((e: Throwable) -> Unit)) { _d = t } override fun onError(e: Throwable) { _d?.invoke(e) } } inline fun <reified T> Flowable<T>.withSubscribe(func: FlowableObj<T>.() -> Unit) = subscribe(FlowableObj<T>().apply(func))
0
Kotlin
4
112
db1cecd29c2dc07a11c53a770a4b0a40ad2ca376
1,086
kotlin-targetFun
Apache License 2.0
common/common-mybatis/src/main/kotlin/com/blank/common/mybatis/listener/MyInsertListener.kt
qq781846712
705,955,843
false
{"Kotlin": 847346, "Vue": 376959, "TypeScript": 137544, "Java": 45954, "HTML": 29445, "SCSS": 19657, "JavaScript": 3399, "Batchfile": 2056, "Shell": 1786, "Dockerfile": 1306}
package com.blank.common.mybatis.listener import com.blank.common.mybatis.core.domain.BaseEntity import com.blank.common.satoken.utils.LoginHelper.getLoginUserId import com.mybatisflex.annotation.InsertListener import java.util.* /** * 插入监听器 */ class MyInsertListener : InsertListener { override fun onInsert(entity: Any) { if (entity is BaseEntity) { //设置被新增时的一些默认数据 entity.createBy = getLoginUserId() entity.createTime = Date() } } }
1
Kotlin
0
0
d14c56f4a4e6c777eadbb8b1b9d2743034c6a7f6
500
Ruoyi-Vue-Plus-Kotlin
Apache License 2.0
platform/backend/core/src/main/kotlin/io/hamal/core/adapter/auth/LoginMetaMask.kt
hamal-io
622,870,037
false
{"Kotlin": 2439820, "C": 1398561, "TypeScript": 321391, "Lua": 156281, "C++": 40661, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
package io.hamal.core.adapter.auth import io.hamal.core.adapter.account.AccountCreateMetaMaskPort import io.hamal.core.adapter.request.RequestAwaitPort import io.hamal.core.adapter.request.RequestEnqueuePort import io.hamal.core.adapter.workspace.WorkspaceListPort import io.hamal.core.component.GenerateToken import io.hamal.core.security.SecurityContext import io.hamal.lib.common.domain.Limit import io.hamal.lib.domain.GenerateDomainId import io.hamal.lib.domain._enum.RequestStatus import io.hamal.lib.domain.request.AccountCreateMetaMaskRequest import io.hamal.lib.domain.request.AuthLogInMetaMaskRequest import io.hamal.lib.domain.request.AuthLoginMetaMaskRequested import io.hamal.lib.domain.vo.AccountId import io.hamal.lib.domain.vo.AuthId import io.hamal.lib.domain.vo.RequestId import io.hamal.lib.domain.vo.Web3Address import io.hamal.lib.web3.evm.EvmSignature import io.hamal.lib.web3.evm.abi.type.EvmPrefixedHexString import io.hamal.lib.web3.evm.domain.EvmSignedMessage import io.hamal.repository.api.Auth import io.hamal.repository.api.Workspace import io.hamal.repository.api.WorkspaceQueryRepository.WorkspaceQuery import org.springframework.stereotype.Component fun interface AuthLoginMetaMaskPort { operator fun invoke(req: AuthLogInMetaMaskRequest): AuthLoginMetaMaskRequested } @Component class AuthLoginMetaMaskAdapter( private val authFind: AuthFindPort, private val generateDomainId: GenerateDomainId, private val generateToken: GenerateToken, private val requestEnqueue: RequestEnqueuePort, private val createAccount: AccountCreateMetaMaskPort, private val workspaceList: WorkspaceListPort, private val awaitRequest: RequestAwaitPort ) : AuthLoginMetaMaskPort { override fun invoke(req: AuthLogInMetaMaskRequest): AuthLoginMetaMaskRequested { verifySignature(req) val auth = authFind(req.address) if (auth == null) { val requested = createAccount(object : AccountCreateMetaMaskRequest { override val id: AccountId = generateDomainId(::AccountId) override val address: Web3Address = req.address }) awaitRequest(requested) return AuthLoginMetaMaskRequested( requestId = generateDomainId(::RequestId), requestedBy = SecurityContext.currentAuthId, requestStatus = RequestStatus.Submitted, id = generateDomainId(::AuthId), accountId = requested.id, workspaceIds = listOf(requested.workspaceId), token = generateToken(), address = req.address, signature = req.signature ).also(requestEnqueue::invoke) } else { if (auth !is Auth.Account) { throw NoSuchElementException("Account not found") } return SecurityContext.with(auth) { AuthLoginMetaMaskRequested( requestId = generateDomainId(::RequestId), requestedBy = SecurityContext.currentAuthId, requestStatus = RequestStatus.Submitted, id = generateDomainId(::AuthId), accountId = auth.accountId, workspaceIds = workspaceList( WorkspaceQuery( limit = Limit.all, accountIds = listOf(auth.accountId) ) ).map(Workspace::id), token = generateToken(), address = req.address, signature = req.signature ).also(requestEnqueue::invoke) } } } } internal fun verifySignature(req: AuthLogInMetaMaskRequest) { val challenge = ChallengeMetaMask(req.address) val signedMessage = EvmSignedMessage( data = challenge.value.toByteArray(), signature = EvmSignature(EvmPrefixedHexString(req.signature.value)) ) if (signedMessage.address.toPrefixedHexString().value.lowercase() != req.address.value.lowercase()) { throw NoSuchElementException("Account not found") } }
44
Kotlin
0
0
dc4c112f018e267ff3247c70104f6c33ce5aa235
4,187
hamal
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/ort/howlingwolf/api/view/reserved/ReservedVillageView.kt
h-orito
176,481,255
false
{"Gradle Kotlin DSL": 2, "Shell": 23, "Ignore List": 1, "Batchfile": 28, "Git Attributes": 1, "Markdown": 1, "INI": 6, "Kotlin": 266, "Java Properties": 5, "YAML": 3, "Java": 426, "Roff": 1, "XML": 8, "Text": 22, "Perl": 3, "Python": 1, "XSLT": 14, "HTML": 4, "SQL": 4, "Gradle": 6}
package com.ort.howlingwolf.api.view.reserved import com.ort.howlingwolf.domain.model.reserved.ReservedVillage import java.time.LocalTime data class ReservedVillageView( val startTime: LocalTime, val organization: String, val silentHours: Int, val sayableStart: LocalTime, val sayableEnd: LocalTime, val availableDummySkill: Boolean, val forBeginner: Boolean, val canSkillRequest: Boolean ) { constructor( reservedVillage: ReservedVillage ) : this( startTime = reservedVillage.startTime, organization = reservedVillage.organization, silentHours = reservedVillage.silentHours, sayableStart = reservedVillage.startTime.plusHours(reservedVillage.silentHours.toLong()), sayableEnd = reservedVillage.startTime, availableDummySkill = reservedVillage.availableDummySkill, forBeginner = reservedVillage.forBeginner, canSkillRequest = reservedVillage.canSkillRequest ) }
0
Kotlin
1
3
d87c28e952287ccbc1634c1eee093a5f9f15e472
979
wolf4busy-api
MIT License
app/src/main/java/com/videoengager/demoapp/AvailabilityActivity.kt
VideoEngager
367,585,600
false
{"Kotlin": 77507}
package com.videoengager.demoapp import android.annotation.SuppressLint import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.applandeo.materialcalendarview.CalendarView import com.videoengager.sdk.VideoEngager import com.videoengager.sdk.generic.model.schedule.* import com.videoengager.sdk.model.Error import com.videoengager.sdk.model.Settings import org.acra.ACRA import java.text.SimpleDateFormat import java.util.* class AvailabilityActivity : AppCompatActivity() { var timeSlots = mutableListOf<AvailabilityTimeSlots>() private lateinit var settings:Settings private lateinit var calendarSettings:AvailabilityCalendarSettings lateinit var timeSlotsAdapter:TimeSlotsAdapter lateinit var waitView : ProgressBar lateinit var scheduleSettings : SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_availability) scheduleSettings = getSharedPreferences("schedule", MODE_PRIVATE) settings = intent.getSerializableExtra("settings") as Settings calendarSettings = intent.getSerializableExtra("calendarSettings") as AvailabilityCalendarSettings waitView = findViewById(R.id.progressBar) waitView.isVisible = false val timeSlotsView = findViewById<RecyclerView>(R.id.timeslotsView) timeSlotsAdapter = TimeSlotsAdapter(timeSlots){ settings.MyPhone="+12345678" AlertDialog.Builder(this@AvailabilityActivity) .setMessage("Do you want to schedule video meeting at $it ?") .setPositiveButton("OK"){ _, _ -> waitView.isVisible = true VideoEngager.SDK_DEBUG=true val video = VideoEngager(this, settings, VideoEngager.Engine.genesys) video.onEventListener = listener video.VeVisitorCreateScheduleMeeting(it,true, object : Answer() { override fun onSuccessResult(result: Result) { video.Disconnect() runOnUiThread { waitView.isVisible = false scheduleSettings.edit().putString("callid",result.callId).apply() startActivityForResult(Intent(this@AvailabilityActivity,ScheduleResultActivity::class.java).putExtra("schedule_info",result),1001) } } }) video.Disconnect() } .setNegativeButton("Cancel", null) .show() } timeSlotsView.adapter = timeSlotsAdapter timeSlotsView.layoutManager = GridLayoutManager(this,3,GridLayoutManager.VERTICAL,false) val calendar = Calendar.getInstance() val calendarView = findViewById<CalendarView>(R.id.calendarView) loadSlots(calendar.time) calendarView.setMinimumDate(calendar.apply { add(Calendar.DATE, -1) }) calendarView.setMaximumDate(Calendar.getInstance().apply { add(Calendar.DATE, calendarSettings.numberOfDays-1) }) calendarView.setOnDayClickListener { if(it.isEnabled){ calendarView.setDate(it.calendar) loadSlots(it.calendar.time) } } } @SuppressLint("NotifyDataSetChanged") fun loadSlots(forDate:Date) { timeSlots.clear() timeSlotsAdapter.notifyDataSetChanged() waitView.isVisible = true VideoEngager.SDK_DEBUG = true val video = VideoEngager(this@AvailabilityActivity, settings, VideoEngager.Engine.genesys) video.onEventListener = listener video.VeGetAgentAvailabilityTimeSlots(forDate, 1, object : Availability() { override fun onTimeSlotsResult(timeSlots: List<AvailabilityTimeSlots>) { val currentTime = Calendar.getInstance() val currentHour = currentTime.get(Calendar.HOUR_OF_DAY) val currentMinute = currentTime.get(Calendar.MINUTE) val startTime = Calendar.getInstance().apply { time=forDate } .apply { if(calendarSettings.calendarHours.allDay.openTime.isNullOrEmpty()) { set(Calendar.HOUR_OF_DAY, currentHour) set(Calendar.MINUTE, currentMinute) set(Calendar.SECOND, 0) }else{ val t = calendarSettings.calendarHours.allDay.openTime.split(":") set(Calendar.HOUR_OF_DAY, t[0].toInt()) set(Calendar.MINUTE, t[1].toInt()) set(Calendar.SECOND, 0) } }.time val endTime = Calendar.getInstance().apply { time=forDate } .apply { if(calendarSettings.calendarHours.allDay.closeTime.isNullOrEmpty()) { set(Calendar.HOUR_OF_DAY, 23) set(Calendar.MINUTE, 59) set(Calendar.SECOND, 59) }else{ val t = calendarSettings.calendarHours.allDay.closeTime.split(":") set(Calendar.HOUR_OF_DAY, t[0].toInt()) set(Calendar.MINUTE, t[1].toInt()) set(Calendar.SECOND, 0) } }.time [email protected](timeSlots.filter { it.interval>0 && it.date.after(if(currentTime.time.after(startTime)) currentTime.time else startTime) && it.date.before(endTime) }) runOnUiThread { timeSlotsAdapter.notifyDataSetChanged() waitView.isVisible = false } } }) } private val listener = object : VideoEngager.EventListener(){ override fun onError(error: Error): Boolean { runOnUiThread { waitView.isVisible = false } if(error.severity==Error.Severity.FATAL){ ACRA.log.e("AvailableActivity",error.toString()) Toast.makeText(this@AvailabilityActivity, "Error:${error.message}", Toast.LENGTH_SHORT).show() } return super.onError(error) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if(requestCode == 1001){ if(resultCode==ScheduleResultActivity.DELETE_ACTION) { data?.getStringExtra("callId")?.let { VideoEngager.SDK_DEBUG = true val video = VideoEngager(this@AvailabilityActivity, settings, VideoEngager.Engine.genesys) waitView.isVisible = true video.VeVisitorDeleteScheduleMeeting(it, object : Answer() { override fun onSuccessResult(result: Result) { runOnUiThread { scheduleSettings.edit().remove("callid").apply() waitView.isVisible = false Toast.makeText(this@AvailabilityActivity, "Deleted schedule video meeting", Toast.LENGTH_SHORT).show() finish() } video.Disconnect() } }) } }else{ finish() } } } class TimeSlotsAdapter(private val timeslots : MutableList<AvailabilityTimeSlots>, private val TimeSlotSelectCallback:(date:Date)->Unit) : RecyclerView.Adapter<TimeSlotsAdapter.ViewHolder>(){ private val dateFormat = SimpleDateFormat("HH:mm",Locale.getDefault()) class ViewHolder(view: View, private val SelectCallback:(date:Date)->Unit) : RecyclerView.ViewHolder(view),View.OnClickListener { val textView: TextView var date:Date?=null init { textView = view.findViewById(android.R.id.text1) view.setOnClickListener(this) view.setBackgroundResource(android.R.drawable.list_selector_background) textView.gravity= Gravity.CENTER } override fun onClick(view: View?) { SelectCallback.invoke(date!!) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(android.R.layout.simple_dropdown_item_1line, parent, false) return ViewHolder(view,TimeSlotSelectCallback) } override fun getItemCount(): Int { return timeslots.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val timeSlot = timeslots[position] holder.date = timeSlot.date holder.textView.text = holder.date?.let { dateFormat.format(it) } } } }
0
Kotlin
0
1
cddb6fddbe97e2504dbc6daa26781f57418b912a
9,862
SmartVideo-Android-SDK-Demo-App
MIT License
zinc-poet/zinc-poet/src/main/kotlin/com/ing/zinc/poet/ZincTypeDef.kt
ing-bank
550,239,957
false
{"Kotlin": 1610321, "Shell": 1609}
package com.ing.zinc.poet /** * A [ZincType] that represents a type alias definition, e.g. * ``` * type BitArray16 = [bool; 16]; * ``` */ interface ZincTypeDef : ZincType, ZincFileItem { /** * The alias for the defined type. */ fun getName(): String /** * The actual type. */ fun getType(): ZincType @ZincDslMarker class Builder { var name: String? = null var type: ZincType? = null fun build(): ZincTypeDef = ImmutableZincTypeDef( requireNotNull(name) { "Required value `name` is null." }, requireNotNull(type) { "Required value `type` is null." } ) } companion object { private data class ImmutableZincTypeDef( private val name: String, private val type: ZincType ) : ZincTypeDef { override fun getId(): String = name override fun getName(): String = name override fun getType(): ZincType = type override fun generate(): String = "type ${getName()} = ${getType().getId()};" } fun zincTypeDef(init: Builder.() -> Unit): ZincTypeDef = Builder().apply(init).build() } }
0
Kotlin
4
9
f6e2524af124c1bdb2480f03bf907f6a44fa3c6c
1,197
zkflow
MIT License
compiler/fir/java/src/org/jetbrains/kotlin/fir/java/declarations/FirJavaValueParameter.kt
android
263,405,600
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.java.declarations import org.jetbrains.kotlin.fir.FirImplementationDetail import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.FirSourceElement import org.jetbrains.kotlin.fir.builder.FirBuilderDsl import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.fir.declarations.FirValueParameter import org.jetbrains.kotlin.fir.declarations.builder.FirValueParameterBuilder import org.jetbrains.kotlin.fir.declarations.impl.FirValueParameterImpl import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall import org.jetbrains.kotlin.fir.expressions.FirExpression import org.jetbrains.kotlin.fir.symbols.impl.FirVariableSymbol import org.jetbrains.kotlin.fir.types.FirTypeRef import org.jetbrains.kotlin.name.Name @OptIn(FirImplementationDetail::class) class FirJavaValueParameter @FirImplementationDetail constructor( source: FirSourceElement?, session: FirSession, resolvePhase: FirResolvePhase, returnTypeRef: FirTypeRef, name: Name, symbol: FirVariableSymbol<FirValueParameter>, annotations: MutableList<FirAnnotationCall>, defaultValue: FirExpression?, isCrossinline: Boolean, isNoinline: Boolean, isVararg: Boolean, ) : FirValueParameterImpl( source, session, resolvePhase, FirDeclarationOrigin.Java, returnTypeRef, name, symbol, annotations, defaultValue, isCrossinline, isNoinline, isVararg, ) @FirBuilderDsl class FirJavaValueParameterBuilder : FirValueParameterBuilder() { @OptIn(FirImplementationDetail::class) override fun build(): FirJavaValueParameter { return FirJavaValueParameter( source, session, resolvePhase = FirResolvePhase.ANALYZED_DEPENDENCIES, returnTypeRef, name, symbol = FirVariableSymbol(name), annotations, defaultValue = null, isCrossinline = false, isNoinline = false, isVararg, ) } @Deprecated("Modification of 'resolvePhase' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN) override var resolvePhase: FirResolvePhase get() = throw IllegalStateException() set(value) { throw IllegalStateException() } @Deprecated("Modification of '' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN) override var symbol: FirVariableSymbol<FirValueParameter> get() = throw IllegalStateException() set(value) { throw IllegalStateException() } @Deprecated("Modification of 'defaultValue' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN) override var defaultValue: FirExpression? get() = throw IllegalStateException() set(value) { throw IllegalStateException() } @Deprecated("Modification of 'isCrossinline' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN) override var isCrossinline: Boolean get() = throw IllegalStateException() set(value) { throw IllegalStateException() } @Deprecated("Modification of 'isNoinline' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN) override var isNoinline: Boolean get() = throw IllegalStateException() set(value) { throw IllegalStateException() } @Deprecated("Modification of 'origin' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN) override var origin: FirDeclarationOrigin get() = throw IllegalStateException() set(value) { throw IllegalStateException() } } inline fun buildJavaValueParameter(init: FirJavaValueParameterBuilder.() -> Unit): FirJavaValueParameter { return FirJavaValueParameterBuilder().apply(init).build() }
1
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
4,261
kotlin
Apache License 2.0
processors/src/main/kotlin/com/alecarnevale/claymore/validators/AutoBindsValidator.kt
alecarnevale
559,250,665
false
null
package com.alecarnevale.claymore.validator import com.alecarnevale.claymore.annotation.AutoBinds import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.ClassKind import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.validate /** * This validator check if annotated symbols is a class. */ class AutoBindsValidator(private val logger: KSPLogger) { fun isValid(symbol: KSAnnotated): Boolean { return symbol.validate() && symbol.isAClass() } private fun KSAnnotated.isAClass(): Boolean { if (this !is KSClassDeclaration || this.classKind != ClassKind.CLASS) { logger.error("$TAG ${AutoBinds::class.simpleName} annotation must annotates class") return false } return true } } private const val TAG = "Claymore - AutoBindsValidator:"
1
Kotlin
0
3
69edcb4c8908eb3bc0c6b513b07b3da1c39c4c80
890
claymore
Apache License 2.0
shared/src/androidMain/kotlin/com/architect/kmpessentials/contacts/KmpContacts.kt
TheArchitect123
801,452,364
false
{"Kotlin": 385398, "Swift": 1216}
package com.architect.kmpessentials.contacts import android.content.ContentResolver import android.content.Intent import android.provider.ContactsContract import com.architect.kmpessentials.KmpAndroid import com.architect.kmpessentials.logging.KmpLogging import com.architect.kmpessentials.logging.constants.ErrorCodes import com.architect.kmpessentials.mainThread.KmpMainThread import com.architect.kmpessentials.permissions.KmpPermissionsManager import com.architect.kmpessentials.permissions.Permission actual class KmpContacts { actual companion object { actual fun getAllContacts(contactsResponse: ContactsAction) { KmpPermissionsManager.isPermissionGranted(Permission.Contacts) { if (it) { val contactsData = mutableListOf<Contact>() val contentResolver: ContentResolver = KmpAndroid.applicationContext.contentResolver val cursor = contentResolver.query( ContactsContract.Contacts.CONTENT_URI, null, null, null, null ) if (cursor!!.moveToFirst()) { do { cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) contactsData.add( Contact( cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY) ?: 0 ), cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY) ?: 0 ), cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) ?: 0 ), cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.PHONETIC_NAME) ?: 0 ), cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) ?: 0 ), "", listOf(), listOf(), "", ) ) } while (cursor.moveToNext()) } contactsResponse(contactsData) } else { KmpLogging.writeErrorWithCode(ErrorCodes.MISSING_PERMISSION_CONFIGURATION) } } } actual fun pickContact(contactsResponse: SingleContactAction) { KmpPermissionsManager.isPermissionGranted(Permission.Contacts) { if (it) { KmpMainThread.runViaMainThread { val pickContact = Intent( Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI ).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } KmpAndroid.applicationContext.startActivity(pickContact) } } else { KmpLogging.writeErrorWithCode(ErrorCodes.MISSING_PERMISSION_CONFIGURATION) } } } } }
5
Kotlin
1
138
4a44b264817b80ef9fcb319d5a0ab08a9c00b853
4,108
KmpEssentials
MIT License
app/src/main/java/com/bayraktar/healthybackandneck/ui/Favourite/FavouriteMoveList/MoveListViewModel.kt
OzerBAYRAKTAR
681,364,096
false
{"Kotlin": 353500}
package com.bayraktar.healthybackandneck.ui.Favourite.FavouriteMoveList import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bayraktar.healthybackandneck.data.Models.ExerciseDetailModel.ExerciseDayExercise import com.bayraktar.healthybackandneck.data.Models.ExerciseDetailModel.SubExerciseDayExercise import com.bayraktar.healthybackandneck.data.Repository.RoomRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MoveListViewModel @Inject constructor( private val repo: RoomRepository ): ViewModel() { private val _getFavExercises: MutableLiveData<List<ExerciseDayExercise>> = MutableLiveData() val getFavExercises: LiveData<List<ExerciseDayExercise>> get() = _getFavExercises fun getFavExerciseList() { viewModelScope.launch(Dispatchers.IO){ val exercises = repo.getIsFavouriteTrue() _getFavExercises.postValue(exercises) } } fun updateIsFavouriteToFalse(exerciseId: Int) { viewModelScope.launch(Dispatchers.IO) { repo.updateIsFavouriteToFalse(exerciseId = exerciseId) } } }
0
Kotlin
0
0
4b3fe6bc833e59d5ab95c9b10c751a2e9f139f6d
1,324
HealthyBackandNeck
MIT License
idea/tests/testData/quickfix/modifiers/noLateinitOnNullable.kt
JetBrains
278,369,660
false
null
// "Add 'lateinit' modifier" "false" // ACTION: Add initializer // ACTION: Make 'a' 'abstract' // ACTION: Move to constructor parameters // ACTION: Move to constructor // ACTION: Add getter // ACTION: Add getter and setter // ACTION: Add setter // ERROR: Property must be initialized or be abstract class A { private var a: String?<caret> }
1
null
37
82
cc81d7505bc3e9ad503d706998ae8026c067e838
346
intellij-kotlin
Apache License 2.0
js/js.translator/testData/box/propertyOverride/overrideExtensionProperty.kt
JakeWharton
99,388,807
true
null
// EXPECTED_REACHABLE_NODES: 1004 package foo class T open class A { open val T.foo: Int get() { return 34 } fun test(): Int { return T().foo } } class B : A() { override val T.foo: Int get() = 5 } fun box(): String { if (A().test() != 34) return "A().test() != 34, it: ${A().test() != 34}" if (B().test() != 5) return "B().test() != 5, it: ${B().test() != 5}" return "OK" }
184
Kotlin
5691
83
4383335168338df9bbbe2a63cb213a68d0858104
444
kotlin
Apache License 2.0
app/src/main/java/me/bakumon/moneykeeper/database/entity/Assets.kt
twwbmitnlf
166,140,516
true
{"Gradle": 4, "Markdown": 3, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 4, "Kotlin": 184, "XML": 114, "Java": 2}
/* * Copyright 2018 Bakumon. https://github.com/Bakumon * * 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 me.bakumon.moneykeeper.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable import java.math.BigDecimal import java.util.* /** * 资产 * * @author bakumon https://bakumon.me */ @Entity open class Assets : Serializable { @PrimaryKey(autoGenerate = true) var id: Int? = null @ColumnInfo(name = "name") var name: String @ColumnInfo(name = "img_name") var imgName: String @ColumnInfo(name = "type") var type: Int /** * 状态 * 0:正常 * 1:已删除 */ @ColumnInfo(name = "state") var state: Int @ColumnInfo(name = "remark") var remark: String @ColumnInfo(name = "create_time") var createTime: Date @ColumnInfo(name = "money") var money: BigDecimal /** * 排序 */ @ColumnInfo(name = "ranking") var ranking: Int? = 0 /** * 初始化金额 */ @ColumnInfo(name = "init_money") var initMoney: BigDecimal constructor(name: String, imgName: String, type: Int, remark: String, initMoney: BigDecimal, money: BigDecimal) { this.name = name this.imgName = imgName this.type = type this.state = 0 this.remark = remark this.createTime = Date() this.money = money this.initMoney = initMoney } }
1
Kotlin
1
1
822d49e4c515098ef75d7140512412eff590e269
1,972
MoneyKeeper
Apache License 2.0
app/src/main/java/com/flixclusive/data/usecase/VideoDataProviderUseCaseImpl.kt
rhenwinch
659,237,375
false
{"Kotlin": 905846}
package com.flixclusive.data.usecase import com.flixclusive.R import com.flixclusive.domain.common.Resource import com.flixclusive.domain.model.VideoDataDialogState import com.flixclusive.domain.model.entities.WatchHistoryItem import com.flixclusive.domain.model.tmdb.Film import com.flixclusive.domain.model.tmdb.TMDBEpisode import com.flixclusive.domain.model.tmdb.TvShow import com.flixclusive.domain.repository.FilmSourcesRepository import com.flixclusive.domain.repository.TMDBRepository import com.flixclusive.domain.usecase.VideoDataProviderUseCase import com.flixclusive.domain.utils.FilmProviderUtils.initializeSubtitles import com.flixclusive.domain.utils.WatchHistoryUtils.getNextEpisodeToWatch import com.flixclusive.presentation.utils.FormatterUtils import com.flixclusive_provider.models.common.MediaServer import com.flixclusive_provider.models.common.VideoData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class VideoDataProviderUseCaseImpl @Inject constructor( private val filmSourcesRepository: FilmSourcesRepository, private val tmdbRepository: TMDBRepository ) : VideoDataProviderUseCase { override fun invoke( film: Film, watchHistoryItem: WatchHistoryItem?, server: String?, mediaId: String?, episode: TMDBEpisode?, onSuccess: (VideoData, TMDBEpisode?) -> Unit ): Flow<VideoDataDialogState> = flow { emit(VideoDataDialogState.Fetching) val id = mediaId ?: filmSourcesRepository.getMediaId(film) if (id.isNullOrEmpty()) { emit(VideoDataDialogState.Unavailable()) return@flow } val isNewlyWatchShow = watchHistoryItem == null || watchHistoryItem.episodesWatched.isEmpty() var episodeToUse: TMDBEpisode? = episode if(episodeToUse == null && film is TvShow) { val seasonNumber: Int val episodeNumber: Int if (isNewlyWatchShow) { if (film.totalSeasons == 0 || film.totalEpisodes == 0) { return@flow emit(VideoDataDialogState.Unavailable()) } seasonNumber = 1 episodeNumber = 1 } else { val lastEpisodeWatched = getNextEpisodeToWatch(watchHistoryItem!!) seasonNumber = lastEpisodeWatched.first ?: 1 episodeNumber = lastEpisodeWatched.second ?: 1 } val episodeFromApiService = tmdbRepository.getEpisode( id = film.id, seasonNumber = seasonNumber, episodeNumber = episodeNumber ) if (episodeFromApiService == null) { emit(VideoDataDialogState.Unavailable(R.string.unavailable_episode)) return@flow } episodeToUse = episodeFromApiService } emit(VideoDataDialogState.Extracting) val titleToUse = FormatterUtils.formatPlayerTitle(film, episodeToUse) val serverToUse = server ?: MediaServer.values().first().serverName val episodeId = filmSourcesRepository.getEpisodeId( mediaId = id, filmType = film.filmType, episode = episodeToUse?.episode, season = episodeToUse?.season ) ?: return@flow emit(VideoDataDialogState.Unavailable(R.string.unavailable_episode)) val videoData = filmSourcesRepository.getStreamingLinks( mediaId = id, episodeId = episodeId, server = serverToUse ) when (videoData) { is Resource.Failure -> { emit(VideoDataDialogState.Error(videoData.error)) } Resource.Loading -> Unit is Resource.Success -> { val data = videoData.data if (data != null) { emit(VideoDataDialogState.Success) onSuccess( data.copy(title = titleToUse) .initializeSubtitles(), episodeToUse ) } else { emit(VideoDataDialogState.Unavailable()) } } } } }
4
Kotlin
6
37
6b153eec56c3e68e6da5ecdc645041ad2ed912d1
4,273
Flixclusive
MIT License
app/src/main/java/eu/kanade/presentation/util/Resources.kt
mihonapp
743,704,912
false
null
package eu.kanade.presentation.util import android.content.res.Resources import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.platform.LocalContext import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.toBitmap /** * Create a BitmapPainter from a drawable resource. * Use this only if [androidx.compose.ui.res.painterResource] doesn't work. * * @param id the resource identifier * * @return the bitmap associated with the resource */ @Composable fun rememberResourceBitmapPainter( @DrawableRes id: Int, // KMK --> @ColorInt tint: Int? = null, // KMK <-- ): BitmapPainter { val context = LocalContext.current return remember(id) { val drawable = ContextCompat.getDrawable(context, id) ?: throw Resources.NotFoundException() // KMK --> tint?.let { drawable.setTint(it) } // KMK <-- BitmapPainter(drawable.toBitmap().asImageBitmap()) } }
36
null
447
9,867
f3a2f566c8a09ab862758ae69b43da2a2cd8f1db
1,193
mihon
Apache License 2.0