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
kask-biz/src/jvmTest/kotlin/com/nao4j/otus/kask/web/biz/validation/BizValidationUpdateTest.kt
nao4j
634,960,070
false
{"Kotlin": 125538}
package com.nao4j.otus.kask.web.biz.validation import com.nao4j.otus.kask.common.models.Command import com.nao4j.otus.kask.web.biz.QuestionProcessor import kotlin.test.Test import kotlinx.coroutines.ExperimentalCoroutinesApi @OptIn(ExperimentalCoroutinesApi::class) class BizValidationUpdateTest { private val command = Command.UPDATE private val processor by lazy { QuestionProcessor() } @Test fun correctTitle() = validationTitleCorrect(command, processor) @Test fun trimTitle() = validationTitleTrim(command, processor) @Test fun emptyTitle() = validationTitleEmpty(command, processor) @Test fun badSymbolsTitle() = validationTitleSymbols(command, processor) @Test fun correctDescription() = validationDescriptionCorrect(command, processor) @Test fun trimDescription() = validationDescriptionTrim(command, processor) @Test fun emptyDescription() = validationDescriptionEmpty(command, processor) @Test fun badSymbolsDescription() = validationDescriptionSymbols(command, processor) @Test fun correctId() = validationIdCorrect(command, processor) @Test fun trimId() = validationIdTrim(command, processor) @Test fun emptyId() = validationIdEmpty(command, processor) @Test fun badFormatId() = validationIdFormat(command, processor) }
1
Kotlin
0
0
21ad8ec072ab106dfa97d100a55bbd46f4456dc1
1,448
kotlin-backend-developer-professional-otus
MIT License
feature/player/src/main/kotlin/com/flammky/musicplayer/player/presentation/root/main/MainScreen.kt
flammky
462,795,948
false
{"Kotlin": 5222947}
package com.flammky.musicplayer.player.presentation.root.main import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import com.flammky.musicplayer.base.theme.Theme import com.flammky.musicplayer.base.theme.compose.absoluteBackgroundColorAsState import com.flammky.musicplayer.base.theme.compose.backgroundColorAsState import com.flammky.musicplayer.base.theme.compose.isDarkAsState @Composable fun PlaybackControlScreenCoordinator.MainRenderScope.PlaybackControlMainScreen() { PlaceContents( modifier = modifier, transition = @Composable { state, content -> MainTransition( state = state, content = content ) }, background = @Composable { MainScreenBackground( modifier = Modifier.fillMaxSize(), dataSource = remember(dataSource) { MainScreenBackgroundDataSource(dataSource.observePalette) }, themeInfo = run { val dark = Theme.isDarkAsState().value val back = Theme.backgroundColorAsState().value val absBack = Theme.absoluteBackgroundColorAsState().value MainScreenThemeInfo(dark, back, absBack) } ) }, toolbar = @Composable { MainScreenToolBar(dismiss = intents.dismiss) }, content = @Composable { MainScreenContent() } ) } @Composable private fun PlaybackControlScreenCoordinator.MainRenderScope.PlaceContents( modifier: Modifier, transition: @Composable (state: MainContainerTransitionState, content: @Composable () -> Unit) -> Unit, background: @Composable () -> Unit, toolbar: @Composable () -> Unit, content: @Composable () -> Unit ) = Box(modifier = modifier) { transition( state = transitionState, content = { background() Column(modifier = Modifier.fillMaxSize()) { toolbar() content() } } ) }
0
Kotlin
6
56
a452c453815851257462623be704559d306fb383
2,307
Music-Player
Apache License 2.0
app/src/main/java/fi/haltu/harrastuspassi/utils/DateTimeUtil.kt
City-of-Helsinki
198,590,695
false
null
package fi.haltu.harrastuspassi.utils import android.app.Activity import android.content.Context import fi.haltu.harrastuspassi.R import java.text.SimpleDateFormat import java.util.* fun idToWeekDay(id: Int, activity: Activity): String? { val monday = activity.getString(R.string.monday) val tuesday = activity.getString(R.string.tuesday) val wednesday = activity.getString(R.string.wednesday) val thursday = activity.getString(R.string.thursday) val friday = activity.getString(R.string.friday) val saturday = activity.getString(R.string.saturday) val sunday = activity.getString(R.string.sunday) val weekDays: Map<Int, String> = mapOf( 1 to monday, 2 to tuesday, 3 to wednesday, 4 to thursday, 5 to friday, 6 to saturday, 7 to sunday ) return weekDays[id] } fun idToWeekDay(id: Int, context: Context): String? { val monday = context.getString(R.string.monday) val tuesday = context.getString(R.string.tuesday) val wednesday = context.getString(R.string.wednesday) val thursday = context.getString(R.string.thursday) val friday = context.getString(R.string.friday) val saturday = context.getString(R.string.saturday) val sunday = context.getString(R.string.sunday) val weekDays: Map<Int, String> = mapOf( 1 to monday, 2 to tuesday, 3 to wednesday, 4 to thursday, 5 to friday, 6 to saturday, 7 to sunday ) return weekDays[id] } fun minutesToTime(minutes: Int): String { val hour = minutes / 60 val minutes = minutes % 60 return "${hour.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}" } fun convertToDateRange(startDate: String, endDate: String): String { val parser = SimpleDateFormat("yyyy-MM-dd", Locale.US) val formatterDDMM = SimpleDateFormat("dd.MM", Locale.US) val formatterDDMMYYYY = SimpleDateFormat("dd.MM.yyyy", Locale.US) var startDateForm = "" var endDateForm = "" try { startDateForm = formatterDDMM.format(parser.parse(startDate)) endDateForm = formatterDDMMYYYY.format(parser.parse(endDate)) } catch (e: Exception) { e.printStackTrace() } return "$startDateForm. - $endDateForm" } fun formatDate(date: String): String { val parser = SimpleDateFormat("yyyy-MM-dd", Locale.US) val formatterDDMMYYYY = SimpleDateFormat("dd.MM.yyyy", Locale.US) var dateForm = "" try { dateForm = formatterDDMMYYYY.format(parser.parse(date)) } catch (e: Exception) { e.printStackTrace() } return dateForm } fun convertToTimeRange(startTime: String, endTime: String): String { val timeParser = SimpleDateFormat("HH:mm:ss", Locale.US) val timeFormatter = SimpleDateFormat("HH.mm", Locale.US) var startTimeForm = "" var endTimeForm = "" try { startTimeForm = timeFormatter.format(timeParser.parse(startTime)) endTimeForm = timeFormatter.format(timeParser.parse(endTime)) } catch (e: Exception) { e.printStackTrace() } return "$startTimeForm - $endTimeForm" }
4
Kotlin
3
1
d5aebf9f46b5ffa1775715c62d088f12b96073fe
3,145
harrastuspassi-ui-android
MIT License
kotlin/Leaderboard/src/test/kotlin/tddmicroexercises/leaderboard/TestData.kt
emilybache
10,648,365
false
null
package tddmicroexercises.leaderboard object TestData { var driver1 = Driver("<NAME>", "DE") var driver2 = Driver("<NAME>", "UK") var driver3 = Driver("<NAME>", "DE") var driver4 = SelfDrivingCar("1.2", "Acme") var race1 = Race("Australian Grand Prix", driver1, driver2, driver3) var race2: Race var race3: Race var race4: Race var race5: Race var race6: Race var sampleLeaderboard1: Leaderboard var sampleLeaderboard2: Leaderboard init { race2 = Race("Malaysian Grand Prix", driver3, driver2, driver1) race3 = Race("Chinese Grand Prix", driver2, driver1, driver3) race4 = Race("Fictional Grand Prix 1", driver1, driver2, driver4) race5 = Race("Fictional Grand Prix 2", driver4, driver2, driver1) driver4.algorithmVersion = "1.3" race6 = Race("Fictional Grand Prix 3", driver2, driver1, driver4) sampleLeaderboard1 = Leaderboard(race1, race2, race3) sampleLeaderboard2 = Leaderboard(race4, race5, race6) } }
1
null
351
302
10bb0e9710c5e27205f0891baf7343e941c79210
1,034
Racing-Car-Katas
MIT License
domain/src/main/java/com/nowiwr01p/domain/stories/usecase/SubscribeStoriesUseCase.kt
nowiwr01w
584,138,480
false
null
package com.nowiwr01p.domain.stories.usecase import com.nowiwr01p.domain.UseCase import com.nowiwr01p.domain.app.ReferencedListener import com.nowiwr01p.domain.stories.repository.StoriesRepository class SubscribeStoriesUseCase( private val client: StoriesRepository ): UseCase<Unit, ReferencedListener> { override suspend fun execute(input: Unit): ReferencedListener { return client.subscribeStories() } }
0
Kotlin
1
3
0ebdf8f0cc072cf1f07810a6c36e710f373bfc7f
428
Protest
MIT License
mpp-library/domain/src/commonMain/kotlin/com/jaa/library/domain/useCases/ToggleBooleanPreferenceUseCase.kt
Jaime97
300,568,157
false
null
package com.jaa.library.domain.useCases import com.jaa.library.domain.repository.PreferenceManagerRepository class ToggleBooleanPreferenceUseCase( private val preferenceManagerRepository: PreferenceManagerRepository ) { interface ToggleBooleanPreferenceListener { fun onSuccess() } suspend fun execute(key:String, listener:ToggleBooleanPreferenceListener) { preferenceManagerRepository.saveBooleanPreference(key, !preferenceManagerRepository.getBooleanPreference(key)) listener.onSuccess() } }
1
null
1
2
38611cb56edfafcc5647049a0cf45a695bc97945
542
LikeAStarMpp
Apache License 2.0
app/src/main/java/com/fairfaxmedia/newsapiclient/data/model/RelatedImage.kt
arunvs
497,837,816
false
{"Kotlin": 45378}
package com.fairfaxmedia.newsapiclient.data.model data class RelatedImage( val assetType: String, val description: String, val height: Int, val id: Int, val lastModified: Long, val photographer: String, val sponsored: Boolean, val timeStamp: Long, val type: String, val url: String, val width: Int )
0
Kotlin
0
0
20fb16db36edae310eb5254c21ecd7d886c12f3a
344
NewsAPIClient
MIT License
app/src/main/java/com/rudione/tranquilhaven/ui/store/shop/categories/SmartThingsFragment.kt
Rudione
579,201,331
false
null
package com.rudione.tranquilhaven.ui.store.shop.categories import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.rudione.tranquilhaven.R class GoogleHomeFragment : BaseCategoryFragment()
0
Kotlin
0
0
1198febe3bf8eaa52414457c5c96bfeb0f2f7834
299
TranquilHaven
MIT License
app/src/main/java/com/sakuna63/tumbin/application/di/component/LoginComponent.kt
sakuna63
75,534,876
false
null
package com.sakuna63.tumbin.application.di.component import com.sakuna63.tumbin.application.activity.LoginActivity import com.sakuna63.tumbin.application.di.module.ActivityModule import com.sakuna63.tumbin.application.di.module.LoginPresenterModule import com.sakuna63.tumbin.application.di.scope.ActivityScope import dagger.Subcomponent @ActivityScope @Subcomponent(modules = arrayOf(ActivityModule::class, LoginPresenterModule::class)) interface LoginComponent : ActivityComponent { fun inject(activity: LoginActivity) }
0
Kotlin
1
0
6d9992cbbcdf23fea218d362478545409dfead5c
529
tumbin
Apache License 2.0
app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/TagEntity.kt
pokk
90,497,127
false
null
package taiwan.no1.app.ssfm.models.entities import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.rx2.structure.BaseRXModel import taiwan.no1.app.ssfm.models.data.local.database.MusicDatabase /** * * @author jieyi * @since 8/17/17 */ @Table(database = MusicDatabase::class, allFields = true) data class TagEntity(@PrimaryKey(autoincrement = true) var id: Long = 0, var name: String = "") : BaseRXModel()
0
Kotlin
0
1
1928c2f1a42634ede147517854d06b6fd5d11e7b
544
SSFM
Apache License 2.0
sample-multiplatform/src/commonMain/kotlin/io/keeppro/kcw/sample/viewmodel/UploadViewModel.kt
timhuang1018
842,414,677
false
{"Kotlin": 14206, "Swift": 621, "HTML": 348, "CSS": 102}
package io.keeppro.kcw.sample.viewmodel import io.keeppro.kcw.Res import io.keeppro.kcw.base_url import io.keeppro.kcw.core.KCWClient import io.keeppro.kcw.core.KCWConfig import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.getString @OptIn(ExperimentalResourceApi::class) class UploadViewModel( private val coroutineScope: CoroutineScope, ) { val state = MutableStateFlow<UploadState>(UploadState.Idle) val exceptionHandler = CoroutineExceptionHandler{_, throwable -> state.value = UploadState.Error(throwable.message ?: "Unknown error") } fun upload() { state.value = UploadState.Uploading coroutineScope.launch(exceptionHandler) { //request to worker through KCWClient val kcwClient: KCWClient = KCWClient.create( KCWConfig(baseUrl = getString(Res.string.base_url)) ) kcwClient.uploadFile( path = "projects/test123/logo", contentType = "image/jpeg", byteArray = Res.readBytes("files/display_pad.jpeg") ) state.value = UploadState.Success } } } sealed interface UploadState { data object Idle : UploadState data object Uploading : UploadState data object Success : UploadState data class Error(val message: String) : UploadState }
0
Kotlin
0
0
6920abcf7c527e985c6fe286da5a8b5446165473
1,571
ktor-cloudflare-worker
MIT License
app/src/main/java/com/allentom/diffusion/ui/screens/lora/list/Screen.kt
AllenTom
744,304,887
false
{"Kotlin": 1228732}
package com.allentom.diffusion.ui.screens.lora.list import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer 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.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.AlertDialog import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.allentom.diffusion.R import com.allentom.diffusion.Screens import com.allentom.diffusion.composables.DrawBar import com.allentom.diffusion.composables.LoraGrid import com.allentom.diffusion.composables.MatchOptionDialog import com.allentom.diffusion.composables.gridCountForDeviceWidth import com.allentom.diffusion.store.AppConfigStore import com.allentom.diffusion.store.prompt.PromptStore import com.allentom.diffusion.ui.screens.home.tabs.draw.DrawViewModel import com.allentom.diffusion.ui.screens.lora.detail.LoraDetailViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun LoraListScreen(navController: NavController) { val modelIcon = ImageVector.vectorResource(id = R.drawable.ic_model) var loraList by remember { mutableStateOf(DrawViewModel.loraList) } var itemImageFit by remember { mutableStateOf(AppConfigStore.config.loraViewDisplayMode) } val context = LocalContext.current val scope = rememberCoroutineScope() var isMatchDialogOpen by remember { mutableStateOf(false) } fun refresh() { scope.launch(Dispatchers.IO) { DrawViewModel.loraList = DrawViewModel.loadLora(context) loraList = DrawViewModel.loraList } } LaunchedEffect(Unit) { refresh() } var isActionMenuShow by remember { mutableStateOf(false) } var totalLora by remember { mutableStateOf(1) } var currentLora by remember { mutableStateOf(0) } var isMatchAll by remember { mutableStateOf(false) } val imageFitIcon = ImageVector.vectorResource(id = R.drawable.ic_image_fit) val imageCropIcon = ImageVector.vectorResource(id = R.drawable.ic_image_crop) fun onChangeImageFit(newImageFit: String) { itemImageFit = newImageFit AppConfigStore.updateAndSave(context) { it.copy(loraViewDisplayMode = newImageFit) } } fun matchAll(isSkipExist: Boolean) { if (isMatchAll) { return } scope.launch(Dispatchers.IO) { isMatchAll = true val list = PromptStore.getAllLoraPrompt(context).map { it.toPrompt() }.filter { DrawViewModel.loraList.any { lora -> lora.name == it.name } } totalLora = list.size list.forEach { loraPrompt -> try { if (isSkipExist && loraPrompt.civitaiId != null) { currentLora++ return@forEach } PromptStore.matchLoraByModelId(context, loraPrompt.id) } catch (e: Exception) { e.printStackTrace() } currentLora++ } refresh() isMatchAll = false } } if (isMatchAll) { AlertDialog( onDismissRequest = { }, title = { Text(text = stringResource(R.string.matching_lora)) }, text = { Column( modifier = Modifier .fillMaxWidth() ) { Text(stringResource(R.string.match_lora_progress, currentLora, totalLora)) Text(text = loraList[currentLora].name) Spacer(modifier = Modifier.height(8.dp)) LinearProgressIndicator( progress = currentLora.toFloat() / totalLora.toFloat(), modifier = Modifier.fillMaxWidth(), ) } }, confirmButton = { }, dismissButton = { } ) } if (isMatchDialogOpen) { MatchOptionDialog(onDismiss = { isMatchDialogOpen = false }) { isSkipExist -> matchAll(isSkipExist) } } val columns = gridCountForDeviceWidth(itemWidth = 180) Scaffold( topBar = { TopAppBar( title = { Text(stringResource(R.string.lora_list_screen_title)) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), actions = { if (itemImageFit == "Fit") { IconButton( onClick = { onChangeImageFit("Crop") } ) { Icon( imageCropIcon, contentDescription = "Menu", ) } } else { IconButton( onClick = { onChangeImageFit("Fit") } ) { Icon( imageFitIcon, contentDescription = "Menu", ) } } IconButton(onClick = { isActionMenuShow = true }) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = "More", ) } if (DrawViewModel.enableDiffusionHelperFeat) { DropdownMenu( expanded = isActionMenuShow, onDismissRequest = { isActionMenuShow = false } ) { DropdownMenuItem( text = { Text(stringResource(R.string.match_all_lora)) }, onClick = { isActionMenuShow = false isMatchDialogOpen = true } ) } } } ) }, ) { paddingValues: PaddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { LoraGrid( modifier = Modifier .fillMaxWidth() .weight(1f), columnCount = columns, loraList = loraList, itemImageFit = itemImageFit, onCLick = { LoraDetailViewModel.asNew() navController.navigate( Screens.LoraPromptDetail.route.replace( "{id}", it.entity?.id.toString() ) ) }) DrawBar() } } }
1
Kotlin
19
187
9dcf3f1b466f9fc8f98851cee41aa8bae88f1139
9,003
diffusion-client
MIT License
src/main/kotlin/no/nav/syfo/util/LogUtil.kt
navikt
402,451,651
false
null
package no.nav.syfo.util import net.logstash.logback.argument.StructuredArgument import net.logstash.logback.argument.StructuredArguments fun callIdArgument(callId: String): StructuredArgument = StructuredArguments.keyValue("callId", callId) fun errorMessageArgument(message: String?): StructuredArgument = StructuredArguments.keyValue("message", message) fun statusCodeArgument(statusCode: String): StructuredArgument = StructuredArguments.keyValue("statusCode", statusCode)
2
Kotlin
0
0
bb1933d1610d78fb34ed64a14f361755b9a3a492
478
isproxy
MIT License
kotlin-typescript/src/main/generated/typescript/NavigateToItem.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! package typescript sealed external interface NavigateToItem { var name: String var kind: ScriptElementKind var kindModifiers: String var matchKind: NavigateToItemMatchKind var isCaseSensitive: Boolean var fileName: String var textSpan: TextSpan var containerName: String var containerKind: ScriptElementKind }
38
null
162
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
392
kotlin-wrappers
Apache License 2.0
cryptography/implementation/bouncy-castle/src/main/kotlin/org/sollecitom/chassis/cryptography/implementation/bouncycastle/symmetric/encryption/aes/AESKeyAdapter.kt
sollecitom
669,483,842
false
{"Kotlin": 819878, "Java": 30834}
package org.sollecitom.chassis.cryptography.implementation.bouncycastle.symmetric.encryption.aes import org.sollecitom.chassis.cryptography.domain.key.CryptographicKey import org.sollecitom.chassis.cryptography.domain.symmetric.EncryptionMode import org.sollecitom.chassis.cryptography.domain.symmetric.SecretKeyFactory import org.sollecitom.chassis.cryptography.domain.symmetric.SymmetricKey import org.sollecitom.chassis.cryptography.domain.symmetric.encryption.aes.AES import org.sollecitom.chassis.cryptography.implementation.bouncycastle.BC_PROVIDER import org.sollecitom.chassis.cryptography.implementation.bouncycastle.asymmetric.create import org.sollecitom.chassis.cryptography.implementation.bouncycastle.key.CryptographicKeyAdapter import org.sollecitom.chassis.cryptography.implementation.bouncycastle.utils.BouncyCastleUtils import java.security.SecureRandom import javax.crypto.SecretKey import javax.crypto.spec.SecretKeySpec internal class AESKeyAdapter private constructor(private val keySpec: SecretKey, private val random: SecureRandom) : SymmetricKey, CryptographicKey by CryptographicKeyAdapter(keySpec) { private constructor(encoded: ByteArray, random: SecureRandom) : this(SecretKeySpec(encoded, AES.name), random) override val ctr: EncryptionMode.CTR.Operations by lazy { EncryptionMode.CTR.Operations.create(keySpec, random) } init { require(algorithm == AES.name) { "Key algorithm must be ${AES.name}" } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AESKeyAdapter return encoded.contentEquals(other.encoded) } override fun hashCode() = encoded.contentHashCode() override fun toString() = "JavaAESKeyAdapter(encoded=${encoded.contentToString()}, keySpec=${keySpec})" data class Factory(val random: SecureRandom) : SecretKeyFactory<AES.KeyArguments, SymmetricKey> { override fun invoke(arguments: AES.KeyArguments): SymmetricKey { val rawKey = BouncyCastleUtils.generateSecretKey(algorithm = AES.name, length = arguments.variant.keyLength, provider = BC_PROVIDER) return AESKeyAdapter(keySpec = rawKey, random = random) } override fun from(bytes: ByteArray): SymmetricKey = AESKeyAdapter(encoded = bytes, random = random) } }
0
Kotlin
0
2
801b61a892f3b5fc79c9e3c1eb3def40c6498dc5
2,380
chassis
MIT License
app/src/main/java/id/lemonavy/dalenta/db/entity/CartData.kt
ruderbytes
448,898,568
false
{"Kotlin": 42409}
package id.lemonavy.dalenta.db.entity import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.android.parcel.Parcelize @Entity(tableName = "tb_cart") @Parcelize data class CartData( @PrimaryKey(autoGenerate = true) var id: Long?, @ColumnInfo(name = "item_id")var itemId: String, @ColumnInfo(name = "item_name")var itemName: String, @ColumnInfo(name = "item_size")var itemSize: String, @ColumnInfo(name = "item_quantity")var itemQty: String, @ColumnInfo(name = "item_price")var itemPrice: Int, @ColumnInfo(name = "item_price_topping")var itemPriceTopping: Int, @ColumnInfo(name = "item_note")var itemNote: String?=null, @ColumnInfo(name = "tax_service")var taxService: Boolean, @ColumnInfo(name = "tax_gst")var taxGst: Boolean, ): Parcelable
0
Kotlin
0
0
7d901eaf8d03362584de2151373b567bb6f784ba
902
POS-Simple
MIT License
app/src/test/java/com/aws/amazonlocation/utils/generalutils/GeneralUtilsGetUserNameTest.kt
aws-geospatial
625,008,140
false
null
package com.aws.amazonlocation.utils.generalutils import com.aws.amazonlocation.BaseTest import com.aws.amazonlocation.mock.* // ktlint-disable no-wildcard-imports import com.aws.amazonlocation.utils.getUserName import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class GeneralUtilsGetUserNameTest : BaseTest() { @Test fun getUserNameSuccess() { val result = getUserName(Responses.RESPONSE_SIGN_IN) val expected = Responses.RESPONSE_SIGN_IN.name?.first()?.uppercase() Assert.assertTrue(TEST_FAILED_DUE_TO_INCORRECT_DATA, result == expected) } }
4
Kotlin
1
0
8a31354f6b244ce55e7d50eb803625c212e690ab
694
amazon-location-features-demo-android
MIT No Attribution
src/main/java/org/mtransit/parser/mt/data/MInboundType.kt
mtransitapps
24,851,212
false
null
package org.mtransit.parser.mt.data import org.mtransit.parser.MTLog enum class MInboundType(val id: String) { NONE(""), INBOUND("1"), OUTBOUND("0"); override fun toString(): String { return id } @Suppress("unused") fun intValue(): Int { return when (this) { INBOUND -> 1 OUTBOUND -> 0 else -> throw MTLog.Fatal("Unknown inbound type '%s'!", id) } } companion object { @JvmStatic fun parse(id: String?): MInboundType { return when(id) { INBOUND.id -> INBOUND OUTBOUND.id -> OUTBOUND else -> NONE // default } } } }
1
Kotlin
3
4
1ae31b65a880fb4b79707da74db0095bb81673f6
718
parser
Apache License 2.0
app/src/main/java/io/particle/android/sdk/tinker/TinkerApplication.kt
particle-iot
34,549,566
false
null
package io.particle.android.sdk.tinker import android.app.Application import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.util.Log import io.particle.android.sdk.cloud.ParticleCloudSDK import io.particle.android.sdk.devicesetup.BuildConfig import io.particle.android.sdk.devicesetup.ParticleDeviceSetupLibrary import io.particle.android.sdk.onApplicationCreated import io.particle.android.sdk.ui.devicelist.DeviceListActivity import io.particle.android.sdk.utils.logging.FileLogging import io.particle.mesh.common.QATool import io.particle.mesh.setup.flow.Scopes import mu.KotlinLogging class TinkerApplication : Application() { val fileLogging = FileLogging(this) private val log = KotlinLogging.logger {} override fun onCreate() { super.onCreate() QATool.isDebugBuild = BuildConfig.DEBUG // HI THERE: doing a release build? Read the rest of this comment. (Otherwise, carry on.) // // ReleaseBuildAppInitializer is a per-build type file, intended to avoid initializing // things like analytics when doing debug builds (i.e.: what most people will be doing when // they download the app via GitHub.) // // If you do a release build of an app based on this code, you'll need to manually comment // out this line by hand or otherwise prevent calling the code // inside ReleaseBuildAppInitializer onApplicationCreated(this) fileLogging.initLogging(Scopes()) ParticleDeviceSetupLibrary.init(this, DeviceListActivity::class.java) log.info { "Device make and model=${getDeviceNameAndMfg()},\n" + "OS version=${Build.VERSION.RELEASE},\n" + "App version=$appVersionName," } // Use `Log` class to only log this to the system log, and not the separate logs we store // on disk for export on user request val last4 = ParticleCloudSDK.getCloud().accessToken?.takeLast(4) ?: "No token stored yet!" Log.i("ParticleAuth", "Last 4 digits of auth token: $last4") } } private fun getDeviceNameAndMfg(): String { val manufacturer = Build.MANUFACTURER val model = Build.MODEL return if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) { model.capitalize() } else manufacturer.capitalize() + " " + model } private val Context.appVersionName: String get() { return try { val pInfo = packageManager.getPackageInfo(packageName, 0) pInfo.versionName } catch (e: PackageManager.NameNotFoundException) { QATool.report(e) "(Error getting version)" } }
34
null
38
38
bda215376a916b39b16c091977132e29e616b8e5
2,726
particle-android
Apache License 2.0
RoomAndNavgraph/app/src/main/java/com/nitesh/roomandnavgraph/data/UserDao.kt
nits14
499,115,573
false
{"Kotlin": 13736}
package com.nitesh.roomandnavgraph.data import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun addUser(user: User) @Query("SELECT * FROM user_table ORDER BY id ASC") fun realAllData() : LiveData<List<User>> }
0
Kotlin
0
0
ccc5d0b1f4862a87542494e4b9ced17411cd355b
413
Androids
MIT License
app/src/main/java/com/onereminder/db/helper/ReminderListHelper.kt
thizisarun
270,014,001
false
null
package com.onereminder.db.helper import androidx.room.Embedded import androidx.room.Relation import com.onereminder.db.entity.Call import com.onereminder.db.entity.Reminder class ReminderListHelper { @Embedded var mReminder: Reminder? = null @Relation(parentColumn = "type_id", entityColumn = "r_id", entity = Call::class) var mCallList: List<Call>? = null }
0
Kotlin
0
0
72aca41e71afac26693f58515106d281f40a55cc
379
OneRemnider
Apache License 2.0
app/src/main/java/com/rafaelfelipeac/improov/features/goal/domain/repository/FirstTimeAddRepository.kt
rafaelfelipeac
160,363,382
false
null
package com.rafaelfelipeac.improov.features.goal.domain.repository interface FirstTimeAddRepository { suspend fun getFirstTimeAdd(): Boolean suspend fun save(firstTimeAdd: Boolean) }
1
Kotlin
3
22
6ff4d515f0968a0752817ef4d942f1b3f424611c
194
improov
Apache License 2.0
src/main/kotlin/com/github/animeshz/osdetector/OS.kt
Animeshz
271,188,560
false
null
/* * Copyright 2020 Animesh Sahu <Animeshz> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.animeshz.osdetector import java.util.* /** * Types of Operating Systems */ enum class OSType { Windows, MacOS, Linux, Other } /** * Architecture of Operating System */ @Suppress("EnumEntryName") enum class OSArchitecture { x64, x32, PowerPc, ARM, Other } /** * Helper class to check the operating system this Java VM runs in * * Pseudo-license: * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html */ @Suppress("unused", "MemberVisibilityCanBePrivate") object OS { /** * Lazily computed [OSType] from the os.name System property */ val type: OSType by lazy { val os = System.getProperty("os.name", "unknown").toLowerCase(Locale.ENGLISH) when { "mac" in os || "darwin" in os -> OSType.MacOS "win" in os -> OSType.Windows "nux" in os || "nix" in os || "aix" in os -> OSType.Linux else -> OSType.Other } } /** * Lazily computed [OSArchitecture] from the os.arch System property */ val architecture: OSArchitecture by lazy { val arch = System.getProperty("os.arch", "unknown") when { "aarch64" in arch || "arm" in arch -> OSArchitecture.ARM "64" in arch -> OSArchitecture.x64 "86" in arch || "32" in arch -> OSArchitecture.x32 "powerpc" in arch -> OSArchitecture.PowerPc else -> OSArchitecture.Other } } /** * Checks if the OS [type] is [OSType.MacOS] */ fun isMac() = type == OSType.MacOS /** * Checks if the OS [type] is [OSType.Windows] */ fun isWindows() = type == OSType.Windows /** * Checks if the OS [type] is [OSType.Linux] */ fun isLinux() = type == OSType.Linux /** * Checks if the OS [architecture] is [OSArchitecture.x64] */ fun isx64() = architecture == OSArchitecture.x64 /** * Checks if the OS [architecture] is [OSArchitecture.x64] */ fun isx32() = architecture == OSArchitecture.x32 /** * Checks if the OS [architecture] is [OSArchitecture.x64] */ fun isArm() = architecture == OSArchitecture.ARM /** * Checks if the OS [architecture] is [OSArchitecture.x64] */ fun isPowerPc() = architecture == OSArchitecture.PowerPc }
0
Kotlin
0
1
4f7e6e3883e901d9314184a26b3ce983c8e17684
3,668
os-detector
MIT License
app/src/main/java/io/realworld/android/conduit/di/AppModule.kt
CHRehan
416,862,656
false
{"Kotlin": 49674}
package io.realworld.android.conduit.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import io.realworld.android.conduit.network.ConduitClient import io.realworld.android.conduit.network.ConduitAPI import io.realworld.android.conduit.network.ConduitAuthAPI import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideAuthApi( conduitClient: ConduitClient, ): ConduitAuthAPI { return conduitClient.buildApi(ConduitAuthAPI::class.java) } @Singleton @Provides fun providePublicApi( conduitClient: ConduitClient ): ConduitAPI { return conduitClient.buildApi(ConduitAPI::class.java) } }
0
Kotlin
4
7
169e11393e4c3f5e8456333b42db16b7ec0171b0
803
Conduit
MIT License
core/src/main/kotlin/com/maltaisn/cardgame/game/CardGameJson.kt
maltaisn
766,170,284
false
{"Kotlin": 626766, "Java": 13145}
/* * Copyright 2019 <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.maltaisn.cardgame.game import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.JsonWriter open class CardGameJson : Json() { /** * The version of the card game library that the [CardGame] being currently * deserialized was written by. */ var version = -1 internal set init { setOutputType(JsonWriter.OutputType.javascript) setUsePrototypes(false) setEnumNames(true) setTypeName("type") } }
0
Kotlin
0
0
890772bfd481651ada1bd49f1db3b68507ff4f34
1,079
card-game-base
Apache License 2.0
src/main/kotlin/no/nav/eessi/pensjon/journalforing/journalpost/VurderAvbrutt.kt
navikt
178,813,650
false
{"Kotlin": 782015, "Shell": 1714, "Dockerfile": 155}
package no.nav.eessi.pensjon.journalforing.journalpost import no.nav.eessi.pensjon.eux.model.BucType.* import no.nav.eessi.pensjon.eux.model.SedType.* import no.nav.eessi.pensjon.oppgaverouting.HendelseType import no.nav.eessi.pensjon.oppgaverouting.HendelseType.SENDT import no.nav.eessi.pensjon.personoppslag.pdl.model.IdentifisertPerson class VurderAvbrutt { val bucsIkkeTilAvbrutt = listOf(R_BUC_02, M_BUC_02, M_BUC_03a, M_BUC_03b) val sedsIkkeTilAvbrutt = listOf(X001, X002, X003, X004, X005, X006, X007, X008, X009, X010, X013, X050, H001, H002, H020, H021, H070, H120, H121) /** * Journalposten skal settes til avbrutt ved manglende fnr, sed er sendt og buc/sed er ikke i listen med unntak * * @param identifiedPerson identifisert person. * @param hendelseType Sendt eller mottatt. * @param sedHendelse sed hendelse. * @return true om journalpost settes til avbrutt */ fun skalKanselleres(identifiedPerson: IdentifisertPerson?, hendelseType: HendelseType) = identifiedPerson?.personRelasjon?.fnr == null && hendelseType == SENDT }
2
Kotlin
3
5
a6d6c0e61b8f5a6d74e076747d6cc8710637207f
1,095
eessi-pensjon-journalforing
MIT License
app/src/main/java/com/rozdoum/socialcomponents/main/interactors/PostInteractor.kt
tuantrinh90
179,996,121
false
null
/* * * Copyright 2018 Rozdoum * * 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.rozdoum.socialcomponents.main.interactors import android.content.Context import android.net.Uri import android.util.Log import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.MutableData import com.google.firebase.database.Query import com.google.firebase.database.Transaction import com.google.firebase.database.ValueEventListener import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.storage.UploadTask import com.rozdoum.socialcomponents.ApplicationHelper import com.rozdoum.socialcomponents.Constants import com.rozdoum.socialcomponents.R import com.rozdoum.socialcomponents.enums.UploadImagePrefix import com.rozdoum.socialcomponents.managers.DatabaseHelper import com.rozdoum.socialcomponents.managers.listeners.OnDataChangedListener import com.rozdoum.socialcomponents.managers.listeners.OnObjectExistListener import com.rozdoum.socialcomponents.managers.listeners.OnPostChangedListener import com.rozdoum.socialcomponents.managers.listeners.OnPostCreatedListener import com.rozdoum.socialcomponents.managers.listeners.OnPostListChangedListener import com.rozdoum.socialcomponents.managers.listeners.OnTaskCompleteListener import com.rozdoum.socialcomponents.model.Like import com.rozdoum.socialcomponents.model.Post import com.rozdoum.socialcomponents.model.PostListResult import com.rozdoum.socialcomponents.utils.ImageUtil import com.rozdoum.socialcomponents.utils.LogUtil import java.util.ArrayList import java.util.Collections import java.util.HashMap /** * Created by Alexey on 05.06.18. */ class PostInteractor private constructor(private val context: Context) { private val databaseHelper: DatabaseHelper? init { databaseHelper = ApplicationHelper.databaseHelper } fun generatePostId(): String { return databaseHelper!! .databaseReference .child(DatabaseHelper.POSTS_DB_KEY) .push() .key } fun createOrUpdatePost(post: Post) { try { val postValues = post.toMap() val childUpdates = HashMap<String, Any>() childUpdates["/" + DatabaseHelper.POSTS_DB_KEY + "/" + post.id] = postValues databaseHelper!!.databaseReference.updateChildren(childUpdates) } catch (e: Exception) { Log.e(TAG, e.message) } } fun removePost(post: Post): Task<Void> { val postRef = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY).child(post.id!!) return postRef.removeValue() } fun incrementWatchersCount(postId: String) { val postRef = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/watchersCount") postRef.runTransaction(object : Transaction.Handler { override fun doTransaction(mutableData: MutableData): Transaction.Result { val currentValue = mutableData.getValue(Int::class.java) if (currentValue == null) { mutableData.value = 1 } else { mutableData.value = currentValue + 1 } return Transaction.success(mutableData) } override fun onComplete(databaseError: DatabaseError, b: Boolean, dataSnapshot: DataSnapshot) { LogUtil.logInfo(TAG, "Updating Watchers count transaction is completed.") } }) } fun getPostList(onDataChangedListener: OnPostListChangedListener<Post>, date: Long) { val databaseReference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY) val postsQuery: Query if (date == 0L) { postsQuery = databaseReference.limitToLast(Constants.Post.POST_AMOUNT_ON_PAGE).orderByChild("createdDate") } else { postsQuery = databaseReference.limitToLast(Constants.Post.POST_AMOUNT_ON_PAGE).endAt(date.toDouble()).orderByChild("createdDate") } postsQuery.keepSynced(true) postsQuery.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val objectMap = dataSnapshot.value as Map<String, Any>? val result = parsePostList(objectMap) if (result.posts.isEmpty() && result.isMoreDataAvailable) { getPostList(onDataChangedListener, result.lastItemCreatedDate - 1) } else { onDataChangedListener.onListChanged(parsePostList(objectMap)) } } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "getPostList(), onCancelled", Exception(databaseError.message)) onDataChangedListener.onCanceled(context.getString(R.string.permission_denied_error)) } }) } fun getPostListByUser(onDataChangedListener: OnDataChangedListener<Post>, userId: String) { val databaseReference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY) val postsQuery: Query postsQuery = databaseReference.orderByChild("authorId").equalTo(userId) postsQuery.keepSynced(true) postsQuery.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val result = parsePostList(dataSnapshot.value as Map<String, Any>?) onDataChangedListener.onListChanged(result.posts) } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "getPostListByUser(), onCancelled", Exception(databaseError.message)) } }) } fun getPost(id: String, listener: OnPostChangedListener): ValueEventListener { val databaseReference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY).child(id) val valueEventListener = databaseReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.value != null) { if (isPostValid((dataSnapshot.value as Map<String, Any>?)!!)) { val post = dataSnapshot.getValue(Post::class.java) if (post != null) { post.id = id } listener.onObjectChanged(post!!) } else { listener.onError(String.format(context.getString(R.string.error_general_post), id)) } } else { listener.onObjectChanged(null!!) } } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "getPost(), onCancelled", Exception(databaseError.message)) } }) databaseHelper.addActiveListener(valueEventListener, databaseReference) return valueEventListener } fun getSinglePost(id: String, listener: OnPostChangedListener) { val databaseReference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY).child(id) databaseReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.value != null && dataSnapshot.exists()) { if (isPostValid((dataSnapshot.value as Map<String, Any>?)!!)) { val post = dataSnapshot.getValue(Post::class.java) post!!.id = id listener.onObjectChanged(post) } else { listener.onError(String.format(context.getString(R.string.error_general_post), id)) } } else { listener.onError(context.getString(R.string.message_post_was_removed)) } } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "getSinglePost(), onCancelled", Exception(databaseError.message)) } }) } private fun parsePostList(objectMap: Map<String, Any>?): PostListResult { val result = PostListResult() val list = ArrayList<Post>() var isMoreDataAvailable = true var lastItemCreatedDate: Long = 0 if (objectMap != null) { isMoreDataAvailable = Constants.Post.POST_AMOUNT_ON_PAGE == objectMap.size for (key in objectMap.keys) { val obj = objectMap[key] if (obj is Map<*, *>) { val mapObj = obj as Map<String, Any> if (!isPostValid(mapObj)) { LogUtil.logDebug(TAG, "Invalid post, id: $key") continue } val hasComplain = mapObj.containsKey("hasComplain") && mapObj["hasComplain"] as Boolean val createdDate = mapObj["createdDate"] as Long if (lastItemCreatedDate == 0L || lastItemCreatedDate > createdDate) { lastItemCreatedDate = createdDate } if (!hasComplain) { val post = Post() post.id = key post.title = mapObj["title"] as String post.description = mapObj["description"] as String post.imagePath = mapObj["imagePath"] as String post.imageTitle = mapObj["imageTitle"] as String post.authorId = mapObj["authorId"] as String post.createdDate = createdDate if (mapObj.containsKey("commentsCount")) { post.commentsCount = mapObj["commentsCount"] as Long } if (mapObj.containsKey("likesCount")) { post.likesCount = mapObj["likesCount"] as Long } if (mapObj.containsKey("watchersCount")) { post.watchersCount = mapObj["watchersCount"] as Long } list.add(post) } } } Collections.sort(list) { lhs, rhs -> rhs.createdDate.compareTo(lhs.createdDate) } result.posts = list result.lastItemCreatedDate = lastItemCreatedDate result.isMoreDataAvailable = isMoreDataAvailable } return result } private fun isPostValid(post: Map<String, Any>): Boolean { return (post.containsKey("title") && post.containsKey("description") && post.containsKey("imagePath") && post.containsKey("imageTitle") && post.containsKey("authorId") && post.containsKey("description")) } fun addComplainToPost(post: Post) { databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY).child(post.id!!).child("hasComplain").setValue(true) } fun isPostExistSingleValue(postId: String, onObjectExistListener: OnObjectExistListener<Post>) { val databaseReference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY).child(postId) databaseReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { onObjectExistListener.onDataChanged(dataSnapshot.exists()) } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "isPostExistSingleValue(), onCancelled", Exception(databaseError.message)) } }) } fun subscribeToNewPosts() { FirebaseMessaging.getInstance().subscribeToTopic("postsTopic") } fun removePost(post: Post, onTaskCompleteListener: OnTaskCompleteListener) { val databaseHelper = ApplicationHelper.databaseHelper val removeImageTask = databaseHelper!!.removeImage(post.imageTitle!!) removeImageTask.addOnSuccessListener { aVoid -> removePost(post).addOnCompleteListener { task -> onTaskCompleteListener.onTaskComplete(task.isSuccessful) ProfileInteractor.getInstance(context).updateProfileLikeCountAfterRemovingPost(post) removeObjectsRelatedToPost(post.id) LogUtil.logDebug(TAG, "removePost(), is success: " + task.isSuccessful) } LogUtil.logDebug(TAG, "removeImage(): success") }.addOnFailureListener { exception -> LogUtil.logError(TAG, "removeImage()", exception) onTaskCompleteListener.onTaskComplete(false) } } private fun removeObjectsRelatedToPost(postId: String?) { CommentInteractor.getInstance(context).removeCommentsByPost(postId).addOnSuccessListener { aVoid -> LogUtil.logDebug(TAG, "Comments related to post with id: $postId was removed") }.addOnFailureListener { e -> LogUtil.logError(TAG, "Failed to remove comments related to post with id: " + postId!!, e) } removeLikesByPost(postId).addOnSuccessListener { aVoid -> LogUtil.logDebug(TAG, "Likes related to post with id: $postId was removed") }.addOnFailureListener { e -> LogUtil.logError(TAG, "Failed to remove likes related to post with id: " + postId!!, e) } } fun createOrUpdatePostWithImage(imageUri: Uri, onPostCreatedListener: OnPostCreatedListener, post: Post) { // Register observers to listen for when the download is done or if it fails val databaseHelper = ApplicationHelper.databaseHelper if (post.id == null) { post.id = generatePostId() } val imageTitle = ImageUtil.generateImageTitle(UploadImagePrefix.POST, post.id) val uploadTask = databaseHelper!!.uploadImage(imageUri, imageTitle) uploadTask?.addOnFailureListener { exception -> // Handle unsuccessful uploads onPostCreatedListener.onPostSaved(false) }?.addOnSuccessListener { taskSnapshot -> // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. val downloadUrl = taskSnapshot.downloadUrl LogUtil.logDebug(TAG, "successful upload image, image url: " + downloadUrl.toString()) post.imagePath = downloadUrl.toString() post.imageTitle = imageTitle createOrUpdatePost(post) onPostCreatedListener.onPostSaved(true) } } fun createOrUpdateLike(postId: String, postAuthorId: String) { try { val authorId = FirebaseAuth.getInstance().currentUser!!.uid val mLikesReference = databaseHelper!! .databaseReference .child(DatabaseHelper.POST_LIKES_DB_KEY) .child(postId) .child(authorId) mLikesReference.push() val id = mLikesReference.push().key val like = Like(authorId) like.id = id mLikesReference.child(id).setValue(like, object : DatabaseReference.CompletionListener { override fun onComplete(databaseError: DatabaseError?, databaseReference: DatabaseReference) { if (databaseError == null) { val postRef = databaseHelper .databaseReference .child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/likesCount") incrementLikesCount(postRef) val profileRef = databaseHelper .databaseReference .child(DatabaseHelper.PROFILES_DB_KEY + "/" + postAuthorId + "/likesCount") incrementLikesCount(profileRef) } else { LogUtil.logError(TAG, databaseError.message, databaseError.toException()) } } private fun incrementLikesCount(postRef: DatabaseReference) { postRef.runTransaction(object : Transaction.Handler { override fun doTransaction(mutableData: MutableData): Transaction.Result { val currentValue = mutableData.getValue(Int::class.java) if (currentValue == null) { mutableData.value = 1 } else { mutableData.value = currentValue + 1 } return Transaction.success(mutableData) } override fun onComplete(databaseError: DatabaseError, b: Boolean, dataSnapshot: DataSnapshot) { LogUtil.logInfo(TAG, "Updating likes count transaction is completed.") } }) } }) } catch (e: Exception) { LogUtil.logError(TAG, "createOrUpdateLike()", e) } } fun removeLike(postId: String, postAuthorId: String) { val authorId = FirebaseAuth.getInstance().currentUser!!.uid val mLikesReference = databaseHelper!! .databaseReference .child(DatabaseHelper.POST_LIKES_DB_KEY) .child(postId) .child(authorId) mLikesReference.removeValue(object : DatabaseReference.CompletionListener { override fun onComplete(databaseError: DatabaseError?, databaseReference: DatabaseReference) { if (databaseError == null) { val postRef = databaseHelper .databaseReference .child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/likesCount") decrementLikesCount(postRef) val profileRef = databaseHelper .databaseReference .child(DatabaseHelper.PROFILES_DB_KEY + "/" + postAuthorId + "/likesCount") decrementLikesCount(profileRef) } else { LogUtil.logError(TAG, databaseError.message, databaseError.toException()) } } private fun decrementLikesCount(postRef: DatabaseReference) { postRef.runTransaction(object : Transaction.Handler { override fun doTransaction(mutableData: MutableData): Transaction.Result { val currentValue = mutableData.getValue(Long::class.java) if (currentValue == null) { mutableData.value = 0 } else { mutableData.value = currentValue - 1 } return Transaction.success(mutableData) } override fun onComplete(databaseError: DatabaseError, b: Boolean, dataSnapshot: DataSnapshot) { LogUtil.logInfo(TAG, "Updating likes count transaction is completed.") } }) } }) } fun hasCurrentUserLike(postId: String, userId: String, onObjectExistListener: OnObjectExistListener<Like>): ValueEventListener { val databaseReference = databaseHelper!! .databaseReference .child(DatabaseHelper.POST_LIKES_DB_KEY) .child(postId) .child(userId) val valueEventListener = databaseReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { onObjectExistListener.onDataChanged(dataSnapshot.exists()) } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "hasCurrentUserLike(), onCancelled", Exception(databaseError.message)) } }) databaseHelper.addActiveListener(valueEventListener, databaseReference) return valueEventListener } fun hasCurrentUserLikeSingleValue(postId: String, userId: String, onObjectExistListener: OnObjectExistListener<Like>) { val databaseReference = databaseHelper!! .databaseReference .child(DatabaseHelper.POST_LIKES_DB_KEY) .child(postId) .child(userId) databaseReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { onObjectExistListener.onDataChanged(dataSnapshot.exists()) } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "hasCurrentUserLikeSingleValue(), onCancelled", Exception(databaseError.message)) } }) } fun removeLikesByPost(postId: String?): Task<Void> { return databaseHelper!! .databaseReference .child(DatabaseHelper.POST_LIKES_DB_KEY) .child(postId!!) .removeValue() } fun searchPostsByTitle(searchText: String, onDataChangedListener: OnDataChangedListener<Post>): ValueEventListener { val reference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY) val valueEventListener = getSearchQuery(reference, "title", searchText).addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val result = parsePostList(dataSnapshot.value as Map<String, Any>?) onDataChangedListener.onListChanged(result.posts) } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "searchPostsByTitle(), onCancelled", Exception(databaseError.message)) } }) databaseHelper.addActiveListener(valueEventListener, reference) return valueEventListener } fun filterPostsByLikes(limit: Int, onDataChangedListener: OnDataChangedListener<Post>): ValueEventListener { val reference = databaseHelper!!.databaseReference.child(DatabaseHelper.POSTS_DB_KEY) val valueEventListener = getFilteredQuery(reference, "likesCount", limit).addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val result = parsePostList(dataSnapshot.value as Map<String, Any>?) onDataChangedListener.onListChanged(result.posts) } override fun onCancelled(databaseError: DatabaseError) { LogUtil.logError(TAG, "filterPostsByLikes(), onCancelled", Exception(databaseError.message)) } }) databaseHelper.addActiveListener(valueEventListener, reference) return valueEventListener } private fun getSearchQuery(databaseReference: DatabaseReference, childOrderBy: String, searchText: String): Query { return databaseReference .orderByChild(childOrderBy) .startAt(searchText) .endAt(searchText + "\uf8ff") } private fun getFilteredQuery(databaseReference: DatabaseReference, childOrderBy: String, limit: Int): Query { return databaseReference .orderByChild(childOrderBy) .limitToLast(limit) } companion object { private val TAG = PostInteractor::class.java.simpleName private var instance: PostInteractor? = null fun getInstance(context: Context): PostInteractor { if (instance == null) { instance = PostInteractor(context) } return instance } } }
0
Kotlin
1
0
7702fef53e4da1ff194de1f201b196a14f19c343
25,033
socialKotlin
Apache License 2.0
gradle/android-dagger/app/src/main/java/com/example/dagger/kotlin/BaseApplication.kt
verdigrass
94,095,633
true
{"Kotlin": 66095, "Java": 62211}
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dagger.kotlin import android.app.Application abstract class BaseApplication : Application() { protected fun initDaggerComponent(): ApplicationComponent { return DaggerApplicationComponent.builder().androidModule(AndroidModule(this)).build() } }
0
Kotlin
0
1
12832b0f06bb321d5bd3abb87e9715b32450c2d0
879
kotlin-examples
Apache License 2.0
app/src/main/java/com/creator/waterweather/view/BaseFragment.kt
CreatorFelix
143,235,978
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 6, "XML": 19, "Kotlin": 27}
package com.creator.waterweather.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.trello.rxlifecycle2.components.support.RxFragment abstract class BaseFragment : RxFragment() { abstract val layoutResID: Int override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(layoutResID, container, false) } }
1
null
1
1
c0609a30bcebab8bf7601b8ad14fc4550856d06d
484
WaterWeather
MIT License
ultron-compose/src/commonMain/kotlin/com/atiurin/ultron/core/compose/operation/UltronComposeOperationParams.kt
open-tool
312,407,423
false
{"Kotlin": 861507, "Java": 13304, "HTML": 3222, "Swift": 594, "Batchfile": 236, "Shell": 236, "CSS": 102}
package com.atiurin.ultron.core.compose.operation import com.atiurin.ultron.core.common.UltronOperationType data class UltronComposeOperationParams( val operationName: String, val operationDescription: String, val operationType: UltronOperationType = ComposeOperationType.CUSTOM )
8
Kotlin
10
99
7d19d4e0a653acc87b823b7b0c806b226faafb12
295
ultron
Apache License 2.0
app/src/main/java/org/simple/clinic/bloodsugar/history/BloodSugarHistoryScreenViewEffectHandler.kt
simpledotorg
132,515,649
false
{"Kotlin": 6129044, "Shell": 1660, "HTML": 545}
package org.simple.clinic.bloodsugar.history import org.simple.clinic.mobius.ViewEffectsHandler import org.simple.clinic.util.exhaustive class BloodSugarHistoryScreenViewEffectHandler( private val uiActions: BloodSugarHistoryScreenUiActions ) : ViewEffectsHandler<BloodSugarHistoryScreenViewEffect> { override fun handle(viewEffect: BloodSugarHistoryScreenViewEffect) { when (viewEffect) { is OpenBloodSugarEntrySheet -> uiActions.openBloodSugarEntrySheet(viewEffect.patientUuid) is OpenBloodSugarUpdateSheet -> uiActions.openBloodSugarUpdateSheet(viewEffect.bloodSugarMeasurement) is ShowBloodSugars -> uiActions.showBloodSugars(viewEffect.bloodSugarHistoryListItemDataSourceFactory) }.exhaustive() } }
9
Kotlin
73
236
ff699800fbe1bea2ed0492df484777e583c53714
740
simple-android
MIT License
src/main/kotlin/com/haythammones/kotlin/dsl/factory/ChildFactory.kt
hmones
671,885,869
false
null
package com.haythammones.kotlin.dsl.factory import com.haythammones.kotlin.dsl.domain.Child import com.haythammones.kotlin.dsl.domain.GrandChild import com.haythammones.kotlin.dsl.utils.randomString import java.util.* class ChildFactory { var uuid: UUID = UUID.randomUUID() var name: String = randomString() var order: Int = 0 private var grandChildren = mutableListOf<GrandChild>() var parent: UUID? = null fun grandChildren(block: GrandChildren.() -> Unit) = grandChildren.addAll( GrandChildren() .apply(block) .mapIndexed { index, grandChild -> grandChild.copy(parent = uuid, order = index + 1) }, ) fun build(): Child = Child( uuid = uuid, name = name, order = order, children = grandChildren, parent = parent, ) } class GrandChildren : ArrayList<GrandChild>() { fun grandChild(block: GrandChildFactory.() -> Unit) = add(GrandChildFactory().apply(block).build()) }
4
Kotlin
0
0
829f9ea57ffdb7058f3ef73e431af3dcfe9650d4
986
kotlin-dsl
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/URLSubmit.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: URLSubmit * * Full name: System`URLSubmit * * URLSubmit[url] submits the specified URL to be executed asynchronously. * URLSubmit[url, {param  val , param  val , …}] submits the specified URL, adding elements with names param and values val . * 1 1 2 2 i i * URLSubmit[obj, …] submits the cloud object obj. * Usage: URLSubmit[HTTPRequest[…], …] submits the specified HTTP request. * * Authentication -> Automatic * CharacterEncoding -> Automatic * ConnectionSettings -> <|MaxUploadSpeed -> Automatic, MaxDownloadSpeed -> Automatic|> * CookieFunction -> Automatic * FollowRedirects -> True * HandlerFunctions -> <||> * HandlerFunctionsKeys -> Automatic * Interactive -> False * TimeConstraint -> Infinity * Options: VerifySecurityCertificates -> True * * Protected * Attributes: ReadProtected * * local: paclet:ref/URLSubmit * Documentation: web: http://reference.wolfram.com/language/ref/URLSubmit.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun uRLSubmit(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("URLSubmit", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,957
mathemagika
Apache License 2.0
api/src/main/kotlin/kiinse/me/plugins/minecore/api/commands/CommandManager.kt
kiinse
618,554,549
false
null
package kiinse.me.plugins.minecore.api.commands import kiinse.me.plugins.minecore.api.MineCorePlugin import kiinse.me.plugins.minecore.api.exceptions.CommandException import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.command.PluginCommand import org.bukkit.entity.Player import java.lang.reflect.Method import java.util.logging.Level @Suppress("UNUSED") abstract class CommandManager : CommandExecutor { protected val plugin: MineCorePlugin protected val failureHandler: CommandFailureHandler protected val registeredSubCommandTable: MutableMap<String, RegisteredCommand> = HashMap() protected val registeredMainCommandTable: MutableMap<String, RegisteredCommand> = HashMap() protected val mainCommandTable: MutableMap<MineCoreCommand, String> = HashMap() protected constructor(plugin: MineCorePlugin) { this.plugin = plugin failureHandler = plugin.mineCore.commandFailureHandler } protected constructor(plugin: MineCorePlugin, failureHandler: CommandFailureHandler) { this.plugin = plugin this.failureHandler = failureHandler } /** * Registration class commands * * @param commandClass A class that inherits from CommandClass and contains command methods */ @Throws(CommandException::class) abstract fun registerCommand(commandClass: MineCoreCommand): CommandManager @Throws(CommandException::class) protected fun registerMainCommand(commandClass: MineCoreCommand, method: Method): String { val mainMineCommand = method.getAnnotation(MineCommand::class.java) val command = mainMineCommand.command register(commandClass, method, plugin.server.getPluginCommand(command), command, mainMineCommand, true) return command } @Throws(CommandException::class) protected fun registerMainCommand(mineCoreCommand: MineCoreCommand): String { val mainMineCommand = mineCoreCommand.javaClass.getAnnotation(MineCommand::class.java) val command = mainMineCommand.command register(mineCoreCommand, plugin.server.getPluginCommand(command), mainMineCommand) return command } @Throws(CommandException::class) protected fun registerSubCommand(commandClass: MineCoreCommand, method: Method) { val annotation = method.getAnnotation(MineSubCommand::class.java) val mainCommand = mainCommandTable[commandClass] if (annotation != null && annotation.command != mainCommand) { val cmd = mainCommand + " " + annotation.command register(commandClass, method, plugin.server.getPluginCommand(cmd), cmd, annotation, false) } } @Throws(CommandException::class) protected fun register(commandClass: MineCoreCommand, method: Method, pluginCommand: PluginCommand?, command: String, annotation: Any, isMainCommand: Boolean) { register(pluginCommand, command) (if (isMainCommand) registeredMainCommandTable else registeredSubCommandTable)[command] = object : RegisteredCommand(method, commandClass, annotation) {} plugin.sendLog(Level.CONFIG, "Command '&d$command&6' registered!") } @Throws(CommandException::class) protected fun register(commandClass: MineCoreCommand, pluginCommand: PluginCommand?, annotation: MineCommand) { val command = annotation.command register(pluginCommand, command) registeredMainCommandTable[command] = object : RegisteredCommand(null, commandClass, annotation) {} } @Throws(CommandException::class) protected fun register(pluginCommand: PluginCommand?, command: String) { if (registeredSubCommandTable.containsKey(command) || registeredMainCommandTable.containsKey(command)) throw CommandException("Command '$command' already registered!") if (pluginCommand == null) throw CommandException("Unable to register command command '$command'. Did you put it in plugin.yml?") pluginCommand.setExecutor(this) } @Throws(CommandException::class) protected fun getMainCommandMethod(mineCoreCommand: Class<out MineCoreCommand?>): Method { mineCoreCommand.methods.forEach { if (it.getAnnotation(MineCommand::class.java) != null) return it } val name = mineCoreCommand.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() throw CommandException("Main command in class '${name[name.size - 1]}' not found!") } protected fun isDisAllowNonPlayer(wrapper: RegisteredCommand, sender: CommandSender, disAllowNonPlayer: Boolean): Boolean { if (sender !is Player && disAllowNonPlayer) { failureHandler.handleFailure(CommandFailReason.NOT_PLAYER, sender, wrapper) return true } return false } protected fun hasNotPermissions(wrapper: RegisteredCommand, sender: CommandSender, permission: String): Boolean { if (permission != "" && !sender.hasPermission(permission)) { failureHandler.handleFailure(CommandFailReason.NO_PERMISSION, sender, wrapper) return true } return false } override fun onCommand(sender: CommandSender, command: org.bukkit.command.Command, label: String, args: Array<String>): Boolean { return onExecute(sender, command, label, args) } protected abstract fun onExecute(sender: CommandSender, command: org.bukkit.command.Command, label: String, args: Array<String>): Boolean }
0
Kotlin
0
0
879337b9ccf2aad3c5ebddfcb98b4a5484f36221
5,528
MineCore
MIT License
mastodon/src/commonMain/kotlin/fediapi/mastodon/model/Notification.kt
wingio
739,512,706
false
{"Kotlin": 163528}
package fediapi.mastodon.model import kotlinx.datetime.Instant import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import fediapi.mastodon.model.account.Account import fediapi.mastodon.model.status.Status /** * Represents a notification of an event relevant to the user. * * @param id The id of the notification in the database. * @param type The type of event that resulted in the notification. * @param createdAt The timestamp of the notification. * @param account The account that performed the action that generated the notification. * @param status Status that was the object of the notification. Attached when type of the notification is [favorite][Type.FAVORITE], [reblog][Type.REBLOG], [status][Type.STATUS], [mention][Type.MENTION], [poll][Type.POLL], or [update][Type.UPDATE]. * @param report Report that was the object of the notification. Attached when type of the notification is [admin.report][Type.ADMIN_REPORT]. */ @Serializable public data class Notification( val id: String, val type: Type, @SerialName("created_at") val createdAt: Instant, val account: Account, val status: Status? = null, val report: Report? = null ) { @Serializable public enum class Type { /** * Someone mentioned you in their status */ @SerialName("mention") MENTION, /** * Someone you enabled notifications for has posted a status */ @SerialName("status") STATUS, /** * Someone boosted one of your statuses */ @SerialName("reblog") REBLOG, /** * Someone followed you */ @SerialName("follow") FOLLOW, /** * Someone requested to follow you */ @SerialName("follow_request") FOLLOW_REQUEST, /** * Someone favorited one of your statuses */ @SerialName("favourite") FAVORITE, /** * A poll you have voted in or created has ended */ @SerialName("poll") POLL, /** * A status you interacted with has been edited */ @SerialName("update") UPDATE, /** * Someone signed up (optionally sent to admins) */ @SerialName("admin.sign_up") ADMIN_SIGN_UP, /** * A new report has been filed */ @SerialName("admin.report") ADMIN_REPORT } }
0
Kotlin
0
1
1347d4d65de5d6b76bcc9af6654e200342e3350b
2,435
fediapi
MIT License
app/src/main/java/com/teobaranga/monica/journal/view/ui/JournalEntryScreen.kt
teobaranga
686,113,276
false
null
package com.teobaranga.monica.journal.view.ui import androidx.compose.animation.Crossfade import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.input.TextFieldLineLimits import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Done import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.teobaranga.monica.ui.ConfirmExitDialog import com.teobaranga.monica.ui.FabHeight import com.teobaranga.monica.ui.PreviewPixel4 import com.teobaranga.monica.ui.Zero import com.teobaranga.monica.ui.button.DateButton import com.teobaranga.monica.ui.rememberConfirmExitDialogState import com.teobaranga.monica.ui.text.MonicaTextField import com.teobaranga.monica.ui.theme.MonicaTheme import com.teobaranga.monica.util.compose.CursorVisibilityStrategy import com.teobaranga.monica.util.compose.keepCursorVisible import com.teobaranga.monica.util.compose.rememberCursorData import java.time.LocalDate @OptIn(ExperimentalFoundationApi::class) @Composable fun JournalEntryScreen( uiState: JournalEntryUiState, topBar: @Composable () -> Unit, onSave: () -> Unit, modifier: Modifier = Modifier, ) { Scaffold( modifier = modifier, topBar = topBar, floatingActionButton = { FloatingActionButton( modifier = Modifier .navigationBarsPadding() .imePadding(), onClick = onSave, ) { Icon( imageVector = Icons.Default.Done, contentDescription = "Save journal entry", ) } }, contentWindowInsets = WindowInsets.Zero, ) { contentPadding -> Crossfade( targetState = uiState, label = "Journal Entry Screen", ) { uiState -> when (uiState) { is JournalEntryUiState.Loading -> { LinearProgressIndicator( modifier = Modifier .padding(contentPadding) .fillMaxWidth(), ) } is JournalEntryUiState.Loaded -> { val confirmExitDialogState = rememberConfirmExitDialogState().apply { shouldConfirm = uiState.hasChanges } ConfirmExitDialog( state = confirmExitDialogState, title = "Unsaved changes", text = "You have unsaved changes. Are you sure you want to exit?", positiveText = "Keep editing", negativeText = "Exit", ) Column( modifier = Modifier .padding(contentPadding) .consumeWindowInsets(contentPadding) .imePadding() .navigationBarsPadding() .padding(bottom = FabHeight), ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( modifier = Modifier .weight(1f), text = "How was your day?", style = MaterialTheme.typography.titleMedium, ) DateButton( date = uiState.date, onDateSelect = { date -> uiState.date = date }, ) } val titleInteractionSource = remember { MutableInteractionSource() } MonicaTextField( modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp), interactionSource = titleInteractionSource, state = uiState.title, textStyle = MaterialTheme.typography.bodyMedium, placeholder = { Text( text = "Title (optional)", style = MaterialTheme.typography.bodyMedium, ) }, lineLimits = TextFieldLineLimits.SingleLine, shape = StartVerticalLineShape(titleInteractionSource), keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, autoCorrectEnabled = true, keyboardType = KeyboardType.Text, ), ) val postInteractionSource = remember { MutableInteractionSource() } val cursorData = rememberCursorData( textFieldState = uiState.post, cursorVisibilityStrategy = CursorVisibilityStrategy { cursor, boundsInWindow, screenHeight, scrollState -> boundsInWindow.topLeft.y - scrollState.value + cursor.top - cursor.height > screenHeight / 2 + FabHeight.roundToPx() }, ) MonicaTextField( modifier = Modifier .fillMaxWidth() .weight(1f) .padding(24.dp) .keepCursorVisible(cursorData), interactionSource = postInteractionSource, state = uiState.post, textStyle = MaterialTheme.typography.bodyMedium, placeholder = { Text( text = "Entry", style = MaterialTheme.typography.bodyMedium, ) }, shape = StartVerticalLineShape(postInteractionSource), keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, autoCorrectEnabled = true, keyboardType = KeyboardType.Text, ), onTextLayout = cursorData.textLayoutResult, scrollState = cursorData.scrollState, contentPadding = OutlinedTextFieldDefaults.contentPadding( top = 0.dp, bottom = 0.dp, ), ) } } } } } } @PreviewPixel4 @Composable private fun PreviewJournalEntryScreen() { MonicaTheme { JournalEntryScreen( uiState = JournalEntryUiState.Loaded( id = 1, initialTitle = null, initialPost = "Hello World!", initialDate = LocalDate.now(), ), topBar = { JournalEntryTopAppBar( onBack = { }, onDelete = { }, ) }, onSave = { }, ) } }
3
null
1
16
1fd67b6d5692c50fc29377a33210546f62419cc7
9,135
monica
Apache License 2.0
src/main/kotlin/com/github/rinacm/sayaka/common/plugin/ExcludeType.kt
dylech30th
299,322,553
false
null
package com.github.rinacm.sayaka.common.plugin enum class ExcludeType { GROUP, WHISPER; companion object { fun toExcludeType(str: String): ExcludeType? { return when (str.toLowerCase()) { "group" -> GROUP "whisper" -> WHISPER else -> null } } } }
0
Kotlin
0
2
f27998445fafc1cf0ee66fef2b8abc7a95efecca
348
sayaka
MIT License
app/src/main/java/it/uniparthenope/studenti/nappogiuseppe003/lunaplidher001/magicpot/ui/resultmagicpot/ResultViewModel.kt
PLNSTD
271,840,910
false
null
package it.uniparthenope.studenti.nappogiuseppe003.lunaplidher001.magicpot.ui.resultmagicpot import androidx.lifecycle.ViewModel class ResultViewModel : ViewModel() { // TODO: Implement the ViewModel }
0
Kotlin
0
0
2138f6f87ca8e6edf5b417b6ba626785cc7754d9
208
MagicPot-App
Apache License 2.0
data/src/main/java/com/example/data/cloud/models/AudioBookResponse.kt
yusuf0405
484,801,816
false
null
package com.example.data.cloud.models import com.google.gson.annotations.SerializedName data class AudioBookResponse( @SerializedName("results") var audioBooks: List<AudioBookCloud>, )
1
Kotlin
1
3
067abb34f0348b0dda1f05470a32ecbed59cfb19
194
BookLoverFinalApp
Apache License 1.1
library/src/main/java/com/github/library/base/interfaces/IContextProvider.kt
yangxp108
96,172,065
true
{"Kotlin": 56516, "CSS": 14169, "Java": 12695}
/* * Copyright (C) 2017 Ricky.yao https://github.com/vihuela * * 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 * */ package com.github.library.base.interfaces import android.content.Context interface IContextProvider { fun getContext(): Context? }
0
Kotlin
0
0
25a97992b5d812e191c794cefcfb94ca618374d4
438
Kotlin-mvpro
Apache License 2.0
src/main/kotlin/com/blr19c/falowp/bot/system/listener/events/HelpEvent.kt
falowp-bot
736,172,318
false
{"Kotlin": 227438, "HTML": 3910}
package com.blr19c.falowp.bot.system.listener.events import com.blr19c.falowp.bot.system.plugin.Plugin /** * 发送帮助事件 */ data class HelpEvent( /** * 显示隐藏插件 */ val showHidden: Boolean = false, /** * 显示禁用插件 */ val showDisable: Boolean = true, /** * 获取功能的帮助 */ val pluginName: String? = null, ) : Plugin.Listener.Event
0
Kotlin
0
6
a2eef9ec7b6f7a51f260b64de548fe291b89266c
375
falowp-bot-system
Apache License 2.0
libtd-ktx/src/main/java/kotlinx/telegram/coroutines/QueryFunctionsKtx.kt
tdlibx
262,568,944
false
null
// // NOTE: THIS FILE IS AUTO-GENERATED by the "TdApiKtxGenerator".kt // See: https://github.com/tdlibx/td-ktx-generator/ // package com.rikkimikki.telegramgallery3.feature_node.data.telegram.coroutines import kotlin.Array import kotlin.Boolean import kotlin.Int import kotlin.Long import kotlin.String import com.rikkimikki.telegramgallery3.feature_node.data.telegram.core.TelegramFlow import org.drinkless.td.libcore.telegram.TdApi import org.drinkless.td.libcore.telegram.TdApi.CallbackQueryAnswer import org.drinkless.td.libcore.telegram.TdApi.CallbackQueryPayload import org.drinkless.td.libcore.telegram.TdApi.InlineQueryResults import org.drinkless.td.libcore.telegram.TdApi.InputInlineQueryResult import org.drinkless.td.libcore.telegram.TdApi.Location import org.drinkless.td.libcore.telegram.TdApi.Message import org.drinkless.td.libcore.telegram.TdApi.MessageSendOptions import org.drinkless.td.libcore.telegram.TdApi.ShippingOption /** * Suspend function, which sets the result of a callback query; for bots only. * * @param callbackQueryId Identifier of the callback query. * @param text Text of the answer. * @param showAlert If true, an alert should be shown to the user instead of a toast notification. * @param url URL to be opened. * @param cacheTime Time during which the result of the query can be cached, in seconds. */ suspend fun TelegramFlow.answerCallbackQuery( callbackQueryId: Long, text: String?, showAlert: Boolean, url: String?, cacheTime: Int ) = this.sendFunctionLaunch(TdApi.AnswerCallbackQuery(callbackQueryId, text, showAlert, url, cacheTime)) /** * Suspend function, which answers a custom query; for bots only. * * @param customQueryId Identifier of a custom query. * @param data JSON-serialized answer to the query. */ suspend fun TelegramFlow.answerCustomQuery(customQueryId: Long, data: String?) = this.sendFunctionLaunch(TdApi.AnswerCustomQuery(customQueryId, data)) /** * Suspend function, which sets the result of an inline query; for bots only. * * @param inlineQueryId Identifier of the inline query. * @param isPersonal True, if the result of the query can be cached for the specified user. * @param results The results of the query. * @param cacheTime Allowed time to cache the results of the query, in seconds. * @param nextOffset Offset for the next inline query; pass an empty string if there are no more * results. * @param switchPmText If non-empty, this text should be shown on the button that opens a private * chat with the bot and sends a start message to the bot with the parameter switchPmParameter. * @param switchPmParameter The parameter for the bot start message. */ suspend fun TelegramFlow.answerInlineQuery( inlineQueryId: Long, isPersonal: Boolean, results: Array<InputInlineQueryResult>?, cacheTime: Int, nextOffset: String?, switchPmText: String?, switchPmParameter: String? ) = this.sendFunctionLaunch(TdApi.AnswerInlineQuery(inlineQueryId, isPersonal, results, cacheTime, nextOffset, switchPmText, switchPmParameter)) /** * Suspend function, which sets the result of a pre-checkout query; for bots only. * * @param preCheckoutQueryId Identifier of the pre-checkout query. * @param errorMessage An error message, empty on success. */ suspend fun TelegramFlow.answerPreCheckoutQuery(preCheckoutQueryId: Long, errorMessage: String?) = this.sendFunctionLaunch(TdApi.AnswerPreCheckoutQuery(preCheckoutQueryId, errorMessage)) /** * Suspend function, which sets the result of a shipping query; for bots only. * * @param shippingQueryId Identifier of the shipping query. * @param shippingOptions Available shipping options. * @param errorMessage An error message, empty on success. */ suspend fun TelegramFlow.answerShippingQuery( shippingQueryId: Long, shippingOptions: Array<ShippingOption>?, errorMessage: String? ) = this.sendFunctionLaunch(TdApi.AnswerShippingQuery(shippingQueryId, shippingOptions, errorMessage)) /** * Suspend function, which sends a callback query to a bot and returns an answer. Returns an error * with code 502 if the bot fails to answer the query before the query timeout expires. * * @param chatId Identifier of the chat with the message. * @param messageId Identifier of the message from which the query originated. * @param payload Query payload. * * @return [CallbackQueryAnswer] Contains a bot's answer to a callback query. */ suspend fun TelegramFlow.getCallbackQueryAnswer( chatId: Long, messageId: Long, payload: CallbackQueryPayload? ): CallbackQueryAnswer = this.sendFunctionAsync(TdApi.GetCallbackQueryAnswer(chatId, messageId, payload)) /** * Suspend function, which sends an inline query to a bot and returns its results. Returns an error * with code 502 if the bot fails to answer the query before the query timeout expires. * * @param botUserId The identifier of the target bot. * @param chatId Identifier of the chat where the query was sent. * @param userLocation Location of the user, only if needed. * @param query Text of the query. * @param offset Offset of the first entry to return. * * @return [InlineQueryResults] Represents the results of the inline query. Use * sendInlineQueryResultMessage to send the result of the query. */ suspend fun TelegramFlow.getInlineQueryResults( botUserId: Long, chatId: Long, userLocation: Location?, query: String?, offset: String? ): InlineQueryResults = this.sendFunctionAsync(TdApi.GetInlineQueryResults(botUserId, chatId, userLocation, query, offset)) /** * Suspend function, which sends the result of an inline query as a message. Returns the sent * message. Always clears a chat draft message. * * @param chatId Target chat. * @param replyToMessageId Identifier of a message to reply to or 0. * @param options Options to be used to send the message. * @param queryId Identifier of the inline query. * @param resultId Identifier of the inline result. * @param hideViaBot If true, there will be no mention of a bot, via which the message is sent. Can * be used only for bots GetOption(&quot;animation_search_bot_username&quot;), * GetOption(&quot;photo_search_bot_username&quot;) and * GetOption(&quot;venue_search_bot_username&quot;). * * @return [Message] Describes a message. */ suspend fun TelegramFlow.sendInlineQueryResultMessage( chatId: Long, replyToMessageId: Long, options: MessageSendOptions?, queryId: Long, resultId: String?, hideViaBot: Boolean ): Message = this.sendFunctionAsync(TdApi.SendInlineQueryResultMessage(chatId, replyToMessageId,0, options, queryId, resultId, hideViaBot))
3
Kotlin
7
9
707b7ed24c18122c36ef2dd4ea45b6bbcc3c38dd
6,672
td-ktx
Apache License 2.0
problem-service/src/main/kotlin/com/sevity/problemservice/domain/Submission.kt
sevity
666,266,634
false
{"Java": 59525, "JavaScript": 22411, "CSS": 12314, "Kotlin": 10919, "TypeScript": 3215, "Shell": 2258, "Dockerfile": 454, "HTML": 240}
package com.sevity.problemservice.domain import javax.persistence.* @Entity @Table(name = "submissions") data class Submission( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Int = 0, @Column(name = "problem_id", nullable = false) val problemId: Int, @Column(name = "user_id", nullable = false) val userId: Long, @Column(nullable = false) val code: String, @Column(nullable = true) val result: String? = null, @Column(nullable = false) val status: String // 다른 필요한 필드 )
1
null
1
1
9d4abbcea48f2cdf4a87ea872bc18e0b5d097a2d
545
online_judge
MIT License
src/main/java/dev/sora/relay/cheat/module/impl/player/ModuleNoFall.kt
OIMeowIO
592,181,303
true
{"Batchfile": 1, "Shell": 1, "Markdown": 2, "INI": 2, "Kotlin": 100, "Java": 71}
package dev.sora.relay.cheat.module.impl.player import dev.sora.relay.cheat.module.CheatModule import dev.sora.relay.game.event.Listen import dev.sora.relay.game.event.EventPacketOutbound import dev.sora.relay.game.event.EventTick import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket import com.nukkitx.protocol.bedrock.packet.PlayerActionPacket import com.nukkitx.protocol.bedrock.data.PlayerActionType import dev.sora.relay.cheat.value.ListValue class ModuleNoFall : CheatModule("NoFall","无掉落伤害") { private val modeValue = ListValue("Mode", arrayOf("OnGround","AwayNoGround","Nukkit","CubeCraft"), "OnGround") @Listen fun onPacketOutbound(event: EventPacketOutbound){ val packet = event.packet val session = event.session if(modeValue.get() == "OnGround"){ if(session.thePlayer.motionY >= 5.5){ if (packet is MovePlayerPacket){ packet.isOnGround = true } } }else if(modeValue.get() == "AwayNoGround"){ if (packet is MovePlayerPacket){ packet.isOnGround = false } } } @Listen fun onTick(event: EventTick){ val session = event.session if(modeValue.get() == "Nukkit"){ if(session.thePlayer.motionY >= 5.5){ session.sendPacket(PlayerActionPacket().apply { runtimeEntityId = session.thePlayer.entityId action = PlayerActionType.START_GLIDE }) } }else if(modeValue.get() == "CubeCraft"){ if(session.thePlayer.motionY >= 5.5){ } } } }
0
Java
0
1
1b302e622be69ea7f7a1e5ee4bae82f34c8c63b9
1,680
ProtoHax
MIT License
deprecated/Tools/DaggerPlayground/app/src/main/java/six/ca/dagger101/eleven/EleventhDemo.kt
songzhw
57,045,008
false
{"Java": 363640, "Kotlin": 128659, "JavaScript": 2528, "Groovy": 417}
package six.ca.dagger101.eleven import android.os.Bundle class EleventhDemo : Base11Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DaggerAppSpComonent.builder() .application(this.application) .build() .inject(this) println("szw sp = $sp") } }
1
null
1
1
8c4d47221a56b2e9d96e20419013900de20ec77c
382
AndroidArchitecture
Apache License 2.0
app/src/main/java/com/example/syl/AndroidDesignPatterns/strategy/kotlin/language/SpanishKotlin.kt
hereforlearning
286,617,615
false
{"Java": 18015, "Kotlin": 17265}
/* * Copyright (C) 2018 <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.example.syl.AndroidDesignPatterns.strategy.kotlin.language import com.example.syl.AndroidDesignPatterns.strategy.kotlin.StrategyKotlin class SpanishKotlin: StrategyKotlin { override fun sayHello(): String { return "¡Buenos días!" } }
1
null
1
1
9c4df9156551eceec5b00569b046a5e2e01b66ec
854
Android-Design-Patterns
Apache License 2.0
examples/counter-gtk/src/nativeMain/kotlin/Main.kt
vbsteven
582,302,322
false
null
import bindings.gtk.* import native.gtk.GtkAlign.GTK_ALIGN_CENTER import native.gtk.GtkOrientation.GTK_ORIENTATION_VERTICAL fun main() { val app = Application("com.example.counter") var counter = 0 app.onActivate { // create the window val window = ApplicationWindow(app) window.title = "Hello World" window.defaultSize = Pair(600, 400) // create the widgets val label = Label() val button = Button("Click me") // attach a button click handler button.onClicked { label.text = "You clicked ${++counter} times" } // wrap in a box for layout window.child = Box(GTK_ORIENTATION_VERTICAL, 20).apply { valign = GTK_ALIGN_CENTER append(button) append(label) } // show the window window.show() } app.runApplication() app.unref() }
0
Kotlin
0
24
af5f6c9d32498b6e791a92503dfb45ebfd1af6c3
922
gtk-kotlin-native
MIT License
app/src/main/java/microteam/domain/usecase/ClearArticlesStatusUseCase.kt
yugal-nandurkar
876,869,030
false
{"Kotlin": 114257}
package microteam.domain.usecase import microteam.data.repository.ArticlesRepository class ClearArticlesStatusUseCase(private val articlesRepository: ArticlesRepository) { operator fun invoke() = articlesRepository.clearStatus() }
0
Kotlin
0
0
1a68295d839ec5bbd9ce131fe139d4fe63a6ea13
238
microteam-android-news
MIT License
from-paris-to-berlin-ws-service/src/main/kotlin/org/jesperancinha/fptb/ws/controller/WebController.kt
jesperancinha
416,787,635
false
null
package org.jesperancinha.fptb.ws.controller import org.jesperancinha.fptb.circuit.breaker.dto.RoadRaceDto import org.jesperancinha.fptb.ws.service.RoadBlockageWSService import org.springframework.messaging.handler.annotation.MessageMapping import org.springframework.messaging.handler.annotation.SendTo import org.springframework.stereotype.Controller import java.time.LocalDateTime /** * Created by jofisaes on 16/10/2021 */ @Controller class WebController( private val roadBlockageWSService: RoadBlockageWSService, ) { @MessageMapping("/hello") @SendTo("/topic/game") fun game(message: String): RoadRaceDto { return roadBlockageWSService.getCurrenRoadRace() } @MessageMapping("/clock") @SendTo("/topic/clock") fun clock(message: String): String { return LocalDateTime.now().toString() } }
0
Kotlin
1
4
c331aeb4b73c616947de7e959f9a4d162a78f575
847
from-paris-to-berlin-circuit-breaker
Apache License 2.0
turnip_price/src/main/java/com/hxbreak/turnip_price/TurnipPrice.kt
HxBreak
268,269,758
false
null
package com.hxbreak.turnip_price @UseExperimental(ExperimentalUnsignedTypes::class) public class TurnipPrice { var basePrice: Int = 0 var sellPrices = IntArray(14) var whatPattern: UInt = 0U var tmp40: Int = 0 val rng = TurnipRandom() fun randBool(): Boolean = (rng.getUInt() and 0x80000000U) != 0U fun randInt(min: Int, max: Int): ULong { return ((rng.getUInt().toULong()) * (max - min + 1).toULong() shr 32) + min.toULong() } fun randFloat(a: Float, b: Float) { val fva = (0x3F800000U and (rng.getUInt() shr 9)).toFloat() } } @UseExperimental(ExperimentalUnsignedTypes::class) class TurnipRandom { val mContext = uintArrayOf(0U, 0U, 0U, 0U) fun seed1() = mContext[0] fun seed2() = mContext[1] fun seed3() = mContext[2] fun seed4() = mContext[3] constructor() { TurnipRandom(42069U) } constructor(seed: UInt) { mContext[0] = 0x6C078965U * (seed xor (seed shr 30)) + 1U mContext[1] = 0x6C078965U * (mContext[0] xor (mContext[0] shr 30)) + 2U mContext[2] = 0x6C078965U * (mContext[1] xor (mContext[1] shr 30)) + 3U mContext[3] = 0x6C078965U * (mContext[2] xor (mContext[2] shr 30)) + 4U } constructor(seed1: UInt, seed2: UInt, seed3: UInt, seed4: UInt) { if ((seed1 or seed2 or seed3 or seed4) == 0U) { mContext[0] = 1U mContext[1] = 0x6C078967U mContext[2] = 0x714ACB41U mContext[3] = 0x48077044U } mContext[0] = seed1 mContext[1] = seed2 mContext[2] = seed3 mContext[3] = seed4 } fun getUInt(): UInt { val n = mContext[0] xor (mContext[0] shl 11) mContext[0] = mContext[1] mContext[1] = mContext[2] mContext[2] = mContext[3] mContext[3] = n xor (n shr 8) xor mContext[3] xor (mContext[3] shr 19) return mContext[3] } fun getULong(): ULong { val n1 = mContext[0] xor (mContext[0] shl 11) val n2 = mContext[1] val n3 = n1 xor (n1 shr 8) xor mContext[3] mContext[0] = mContext[2] mContext[1] = mContext[3] mContext[2] = n3 xor (mContext[3] shr 19) mContext[3] = n2 xor (n2 shl 11) xor (n2 xor (n2 shl 11) shr 8) xor mContext[2] xor (n3 shr 19) return (mContext[2].toULong() shl 32) and mContext[3].toULong() } }
0
Kotlin
1
6
ced2cb55e8d6c33da4678b48957428c593c95dbe
2,400
AnimalCrossingTools-Android
MIT License
src/main/kotlin/org/mycorp/blueprint/kotlinboot/model/BaseEntity.kt
bn3t
865,007,584
false
{"Kotlin": 43062, "Dockerfile": 301}
package org.mycorp.blueprint.kotlinboot.model import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.MappedSuperclass /** * The base class for all entities. */ @MappedSuperclass open class BaseEntity( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long? = null)
0
Kotlin
0
0
fda60d296d1ea3624d21435d595dec5474ce958e
377
kotlin-spring-blueprint
MIT License
application/feature/characters/detail/impl/src/main/java/tools/forma/sample/feature/characters/detail/impl/di/CharacterDetailComponent.kt
formatools
289,781,857
false
{"Kotlin": 278883, "C++": 2056, "Shell": 1041, "C": 545, "CMake": 190}
/* * Copyright 2019 <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 tools.forma.sample.feature.characters.detail.impl.di import tools.forma.sample.core.di.library.scopes.FeatureScope import tools.forma.sample.feature.characters.core.api.di.CharactersCoreFeature import tools.forma.sample.feature.characters.detail.impl.ui.CharacterDetailFragment import tools.forma.sample.feature.characters.favorite.api.di.CharacterFavoriteFeature import dagger.Component @FeatureScope @Component( modules = [ CharacterDetailModule::class ], dependencies = [ CharactersCoreFeature::class, CharacterFavoriteFeature::class, ] ) internal interface CharacterDetailComponent { fun inject(detailFragment: CharacterDetailFragment) @Component.Factory interface Factory { fun create( charactersCoreFeature: CharactersCoreFeature, characterFavoriteFeature: CharacterFavoriteFeature ): CharacterDetailComponent } }
24
Kotlin
9
186
fbcc720bdfef6b82ec848364d80372b9c501ced6
1,521
forma
Apache License 2.0
src/test/kotlin/io/github/projectmapk/jackson/module/kogera/_integration/deser/value_class/deserializer/by_annotation/TempTest.kt
ProjectMapK
488,347,906
false
null
package io.github.projectmapk.jackson.module.kogera._integration.deser.value_class.deserializer.by_annotation import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.annotation.JsonDeserialize import io.github.projectmapk.jackson.module.kogera.KotlinFeature import io.github.projectmapk.jackson.module.kogera.KotlinModule import io.github.projectmapk.jackson.module.kogera._integration.deser.value_class.Primitive import io.github.projectmapk.jackson.module.kogera.readValue import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test // Only a temporary test is implemented because the problem that // KNAI.findDeserializationConverter does not work when Deserializer is specified in the annotation, // resulting in an IllegalArgumentException, has not been resolved. class TempTest { data class Dst(@JsonDeserialize(using = Primitive.Deserializer::class) val value: Primitive?) @Test fun test() { val result = KotlinModule.Builder() .enable(KotlinFeature.CopySyntheticConstructorParameterAnnotations) .build() .let { ObjectMapper().registerModule(it) } .readValue<Dst>("""{"value":1}""") assertEquals(Dst(Primitive(101)), result) } }
7
Kotlin
1
89
7d9dbcd2fcdbc48631c01b51a919fe03ac6bb47e
1,280
jackson-module-kogera
Apache License 2.0
core/common/src/iosMain/kotlin/io/spherelabs/common/Uuid.ios.kt
getspherelabs
687,455,894
false
{"Kotlin": 499164, "Ruby": 6984, "Swift": 1167, "Shell": 226}
package io.spherelabs.common import platform.Foundation.NSUUID actual fun uuid4(): String { return "ios-" + NSUUID().UUIDString }
19
Kotlin
13
90
696fbe6f9c4ff9e8a88492a193d6cb080df41ed6
135
anypass-kmp
Apache License 2.0
kotlin/src/main/kotlin/codes.horm.coderetreat/Foo.kt
HormCodes
216,239,507
false
null
package codes.horm.coderetreat fun foo() = true
0
Kotlin
0
0
e79dea59903e8f4ff8b31cc7695987e1e1aa7f5b
49
coderetreat-starters
MIT License
app/src/main/java/dev/tran/nam/chart/chartsong/view/main/chart/ChartSongFragmentModule.kt
Dev-Learn
179,638,602
false
null
package dev.tran.nam.chart.chartsong.view.main.chart import androidx.fragment.app.Fragment import dagger.Binds import dagger.Module import tran.nam.core.di.inject.PerFragment /** * Provides chart song fragment dependencies. */ @Module abstract class ChartSongFragmentModule { @Binds @PerFragment internal abstract fun fragmentInject(fragment: ChartSongFragment): Fragment }
0
Kotlin
0
1
bc3f73162b2f1673cbe85c57ba50f9044b98058d
392
Android-SongChart
Apache License 2.0
domain/src/test/java/com/example/domain/usecase/character/favorite/DeleteCharacterFavoriteTest.kt
msddev
597,641,342
false
null
package com.example.domain.usecase.character.favorite import com.example.repository.character.CharacterRepository import com.example.testutils.MockkUnitTest import io.mockk.coVerify import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.impl.annotations.SpyK import kotlinx.coroutines.flow.single import kotlinx.coroutines.test.runTest import org.junit.Test class DeleteCharacterFavoriteTest : MockkUnitTest() { @MockK(relaxed = true) lateinit var repository: CharacterRepository @SpyK @InjectMockKs private lateinit var deleteFavorite: DeleteCharacterFavoriteUseCase @Test fun verifyExecute() = runTest { // Arrange (Given) val characterId = 1 // Act (When) val params = DeleteCharacterFavoriteUseCase.Params(characterId) deleteFavorite.invoke(params) // Assert (Then) coVerify { deleteFavorite.invoke(any()) } } @Test fun collectExecute() = runTest { // Arrange (Given) val characterId = 1 val params = DeleteCharacterFavoriteUseCase.Params(characterId) // Act (When) deleteFavorite.invoke(params).single() // Assert (Then) coVerify { repository.deleteFavoriteById(characterId) } } }
0
Kotlin
0
0
74537702cbc8b1621a8d202da1bb7fb7890573d0
1,317
Sample-MVI-Clean-Arch
Apache License 2.0
android/beagle/src/main/java/br/com/zup/beagle/android/context/operations/strategy/comparison/ComparisonExtensions.kt
hernandazevedo
289,941,679
true
{"Kotlin": 1719309, "Swift": 896274, "C++": 262909, "Objective-C": 59574, "Java": 26500, "Ruby": 26168, "Shell": 6216, "Dart": 3253, "sed": 1618, "HTML": 1322, "C": 1109}
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.zup.beagle.android.context.operations.strategy.comparison import br.com.zup.beagle.android.context.operations.strategy.Operations import br.com.zup.beagle.android.context.operations.strategy.BaseOperation import br.com.zup.beagle.android.context.operations.parameter.Parameter internal fun BaseOperation<Operations>.toBoolean(parameter: Parameter) : Any { val firstValue = parameter.arguments[0].value.toString().toDouble() val secondValue = parameter.arguments[1].value.toString().toDouble() val isSizeCorrect = parameter.arguments.size == 2 return when (this.operationType) { ComparisionOperationTypes.GREATER_THAN -> isSizeCorrect && firstValue > secondValue ComparisionOperationTypes.GREATER_THAN_EQUALS -> isSizeCorrect && firstValue >= secondValue ComparisionOperationTypes.LESS_THEN -> isSizeCorrect && firstValue < secondValue ComparisionOperationTypes.LESS_THEN_EQUALS -> isSizeCorrect && firstValue <= secondValue ComparisionOperationTypes.EQUALS -> isSizeCorrect && firstValue == secondValue else -> false } }
0
null
0
0
9cb3ed6c28641e69dc4271ec5c2bc18dfd78da16
1,735
beagle
Apache License 2.0
core/common/src/main/java/com/githukudenis/comlib/core/common/ComlibConnectivityManagerImpl.kt
DenisGithuku
707,847,935
false
{"Kotlin": 289725}
package com.githukudenis.comlib.core.common import android.content.Context import android.net.ConnectivityManager import android.net.ConnectivityManager.NetworkCallback import android.net.Network import android.os.Build import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.distinctUntilChanged class ComlibConnectivityManagerImpl( context: Context ): ComlibConnectivityManager { private val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager override val networkStatus: Flow<NetworkStatus> get() = callbackFlow { // val networkRequest = NetworkRequest.Builder() // .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) // .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) // .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) // .build() val connectionCallback = object : NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) trySend(NetworkStatus.Available) } override fun onLost(network: Network) { super.onLost(network) trySend(NetworkStatus.Unavailable) } override fun onUnavailable() { super.onUnavailable() trySend(NetworkStatus.Unavailable) } override fun onLosing(network: Network, maxMsToLive: Int) { super.onLosing(network, maxMsToLive) trySend(NetworkStatus.Losing) } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { connectivityManager.registerDefaultNetworkCallback(connectionCallback) } awaitClose { connectivityManager.unregisterNetworkCallback(connectionCallback) } }.distinctUntilChanged() }
6
Kotlin
1
0
68beba7ad2a6f36842f75ee81969f61125c5af0f
2,149
comlib-android-client
Apache License 2.0
matugr/src/main/java/com/matugr/token_request/domain/TokenSuccessResponseTransformer.kt
judegpinto
453,862,040
false
{"Kotlin": 146527}
package com.matugr.token_request.domain import com.matugr.token_request.external.TokenResult import com.matugr.token_request.networking.TokenNetworkingResponse import com.matugr.token_request.networking.TokenResponseBody import com.squareup.moshi.JsonAdapter import javax.inject.Inject internal class TokenSuccessResponseTransformer @Inject constructor( private val tokenResponseBodyJsonAdapter: JsonAdapter<TokenResponseBody> ) { /** * OAuth error bodies are not necessarily enormous, so the json body will be handled as * a [String] */ fun transformSuccessResponse(success: TokenNetworkingResponse.Success): TokenResult { val jsonAsString = success.jsonBody.readUtf8() val tokenResponse = tokenResponseBodyJsonAdapter.fromJson(jsonAsString) ?: return TokenResult.Error.CannotTransformTokenJson(jsonAsString) return TokenResult.Success( tokenResponse.accessToken, tokenResponse.tokenType, tokenResponse.refreshToken, tokenResponse.expiresIn, tokenResponse.scope ) } }
0
Kotlin
0
3
e79e81c962bb309a422e2ea6ec4c1a67f04de5c2
1,105
matugr
Apache License 2.0
modulecheck-internal-testing/src/main/kotlin/modulecheck/testing/SkipInStackTrace.kt
rickbusarow
316,627,145
false
{"Kotlin": 2149665, "MDX": 85759, "JavaScript": 11460, "CSS": 3389, "Shell": 1798}
/* * Copyright (C) 2021-2023 Rick Busarow * 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 modulecheck.testing import java.lang.StackWalker.StackFrame import java.lang.reflect.AnnotatedElement import java.lang.reflect.Method import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.CLASS import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.annotation.AnnotationTarget.PROPERTY import kotlin.annotation.AnnotationTarget.PROPERTY_GETTER import kotlin.annotation.AnnotationTarget.PROPERTY_SETTER /** * Indicates that the annotated function/property should be ignored when walking a * stack trace, such as in assertions or when trying to parse a test function's name. * * @see StackTraceElement.isSkipped */ @Target( FUNCTION, PROPERTY, PROPERTY_GETTER, PROPERTY_SETTER, CLASS ) @Retention(RUNTIME) annotation class SkipInStackTrace /** * Checks if an [AnnotatedElement] is annotated with [SkipInStackTrace]. * * @receiver [AnnotatedElement] The element to check. * @return `true` if the [AnnotatedElement] is annotated with [SkipInStackTrace], `false` otherwise. */ @PublishedApi internal fun AnnotatedElement.hasSkipAnnotation(): Boolean { return isAnnotationPresent(SkipInStackTrace::class.java) } private val sdkPackagePrefixes = setOf("java", "jdk", "kotlin") /** * Checks if the [StackTraceElement] should be skipped based on the [SkipInStackTrace] annotation. * * @receiver [StackTraceElement] The element to check. * @return `true` if the [StackTraceElement] should be skipped, `false` otherwise. */ @SkipInStackTrace @PublishedApi internal fun StackTraceElement.isSkipped(): Boolean { // return declaringClass().isSkipped(methodName = methodName.removeSuffix("\$default")) return isSkipped(clazz = declaringClass(), methodName = methodName.substringBeforeLast('$')) } /** * Retrieves the class from a [StackTraceElement]. * * @receiver [StackTraceElement] The element to inspect. * @return The class object for the stack trace element. */ @SkipInStackTrace @PublishedApi internal fun StackTraceElement.declaringClass(): Class<*> = Class.forName(className) /** * Checks if the [StackFrame] should be skipped based on the [SkipInStackTrace] annotation. * * @receiver [StackFrame] The frame to check. * @return `true` if the [StackFrame] should be skipped, `false` otherwise. */ @SkipInStackTrace @PublishedApi internal fun StackFrame.isSkipped(): Boolean { val clazz = declaringClass ?: return true return isSkipped( clazz = clazz, methodName = methodName.removeSuffix("\$default") ) } /** * Retrieves the class from a [StackFrame]. * * @receiver [StackFrame] The frame to inspect. * @return The class object for the stack frame. */ @SkipInStackTrace @PublishedApi internal fun StackFrame.declaringClass(): Class<*> = declaringClass /** * Determines whether a method within the given class should be skipped. * * @param clazz The class in which the method is declared. * @param methodName The name of the method. * @return `true` if the method should be skipped, `false` otherwise. */ internal fun isSkipped(clazz: Class<*>, methodName: String): Boolean { // trim off all the stuff like "$$inlined$$execute$1"" val actualClass = clazz.firstNonSyntheticClass() val enclosingClasses = generateSequence(clazz) { c -> c.enclosingClass } if (enclosingClasses.any { it.hasSkipAnnotation() }) return true val packageRoot = clazz.canonicalName?.split('.')?.firstOrNull() if (packageRoot in sdkPackagePrefixes) { return true } // nested classes and functions have the java `$` delimiter // ex: "com.example.MyTest$nested class$my test" fun String.segments(): List<String> = split(".", "$") .filter { it.isNotBlank() } val actualMethodName = clazz.name.removePrefix(actualClass.name) .segments() .firstOrNull() ?: methodName return actualClass .methods .filter { it.name == actualMethodName } .requireAllOrNoneAreAnnotated() } /** * Validates that all methods in the list are either annotated with [SkipInStackTrace] * or not. If only some methods are annotated, an exception will be thrown. * * @receiver List of [Method] to check. * @return `true` if all methods are annotated with [SkipInStackTrace], `false` otherwise. */ @SkipInStackTrace private fun List<Method>.requireAllOrNoneAreAnnotated(): Boolean { val (annotated, notAnnotated) = partition { it.hasSkipAnnotation() } require(annotated.size == size || notAnnotated.size == size) { "The function named '${first().name}' is overloaded, " + "and only some those overloads are annotated with `@SkipInStackTrace`. " + "Either all must be annotated or none of them." } return annotated.size == size }
76
Kotlin
7
129
5934de0bc8edc688b088324437b05a974073267e
5,302
ModuleCheck
Apache License 2.0
app/src/main/java/com/pitchblack/tiviplus/data/localdb/TVDao.kt
ayadiyulianto
320,819,407
false
null
package com.pitchblack.tiviplus.data.localdb interface TVDao { }
0
Kotlin
0
0
cd7a1f838e34a90360707d983ef92a82d2f32e1c
65
tiviplus
Apache License 2.0
rocket-launcher-core/src/main/kotlin/com/github/funczz/kotlin/rocket_launcher/core/state/RocketLauncherState.kt
funczz
812,880,533
false
{"Kotlin": 40557}
package com.github.funczz.kotlin.rocket_launcher.core.state import com.github.funczz.kotlin.fsm.FsmState import com.github.funczz.kotlin.rocket_launcher.core.event.RocketLauncherEvent import com.github.funczz.kotlin.rocket_launcher.core.model.RocketLauncher sealed interface RocketLauncherState : FsmState<RocketLauncherEvent, RocketLauncher>
0
Kotlin
0
0
c2866d3c40c6d47c5f04a0ba23cedc4ccfd36dd3
344
kotlin-rocket-launcher-core
Apache License 2.0
rocket-launcher-core/src/main/kotlin/com/github/funczz/kotlin/rocket_launcher/core/state/RocketLauncherState.kt
funczz
812,880,533
false
{"Kotlin": 40557}
package com.github.funczz.kotlin.rocket_launcher.core.state import com.github.funczz.kotlin.fsm.FsmState import com.github.funczz.kotlin.rocket_launcher.core.event.RocketLauncherEvent import com.github.funczz.kotlin.rocket_launcher.core.model.RocketLauncher sealed interface RocketLauncherState : FsmState<RocketLauncherEvent, RocketLauncher>
0
Kotlin
0
0
c2866d3c40c6d47c5f04a0ba23cedc4ccfd36dd3
344
kotlin-rocket-launcher-core
Apache License 2.0
app/src/main/java/radhika/yusuf/id/mvvmkotlin/utils/constant/DefaultValue.kt
radhikayusuf
157,981,024
false
null
package radhika.yusuf.id.mvvmkotlin.utils.constant object DefaultValue { val GLIDE_FADE_ANIMATION_DURATION = 500 }
0
Kotlin
5
18
28ed409dff680124bac0bedca892083887ed9351
121
mvvm-kotlin-framework
MIT License
app/src/main/java/mhw/inventory/utils/CollectionExtensions.kt
rcdavis
639,187,256
false
null
package mhw.inventory.utils /** * Adds the item if it doesn't exist in the list or will replace existing entry. */ fun <T> MutableList<T>.addOrReplace(item: T, predicate: (T) -> Boolean) { val i = indexOfFirst(predicate) if (i == -1) { add(item) } else { this[i] = item } } /** * Only adds the item if it doesn't already exist within the list based on the * predicate. * * @return True if the item was added or false if not */ fun <T> MutableList<T>.addIfNotExist(item: T, predicate: (T) -> Boolean): Boolean { if (indexOfFirst(predicate) == -1) { add(item) return true } return false }
0
Kotlin
0
0
6f52b80d908f950aacfbcec219803823d51c3f97
657
mhw-boardgame-inventory-Android
MIT License
src/me/anno/utils/callbacks/F2F.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10032501, "C": 236426, "Java": 6754, "Lua": 4404, "C++": 3059, "GLSL": 2698}
package me.anno.utils.callbacks fun interface F2F { fun calculate(x: Float, y: Float): Float }
0
Kotlin
3
22
b5dfc846ae3c44aa4138adc6b80cdcc0db83612f
99
RemsEngine
Apache License 2.0
example-spring/src/main/kotlin/io/github/dehuckakpyt/telegrambotexample/handler/StartHandler.kt
DEHuckaKpyT
670,859,055
false
{"Kotlin": 1719026}
package io.github.dehuckakpyt.telegrambotexample.handler import io.github.dehuckakpyt.telegrambot.annotation.HandlerComponent import io.github.dehuckakpyt.telegrambot.handler.BotHandler import io.github.dehuckakpyt.telegrambotexample.holder.MessageTemplateHolder @HandlerComponent class StartHandler( template: MessageTemplateHolder, ) : BotHandler({ command("/start") { sendMessage(template.start) sendMessage("Hello! My name is ${bot.username} :-)") } })
0
Kotlin
3
24
5912e61857da3f63a7bb383490730f47f7f1f8c6
487
telegram-bot
Apache License 2.0
app/src/main/kotlin/io/github/bsfranca2/athena/exception/issue/IssueNotFoundException.kt
bsfranca2
275,465,877
false
null
package io.github.bsfranca2.athena.exception.issue import io.github.bsfranca2.athena.exception.EntityNotFoundException data class IssueNotFoundException(val id: Long) : EntityNotFoundException("Issue", id)
11
Kotlin
0
0
8a048990c1a6ebf23a567490476fc7e41fdadc71
208
Athena
MIT License
code/mako-rrhh-bc/src/main/customized/kotlin/com/makobrothers/mako/rrhh/persona/infrastructure/input/rest/PersonaDeleteByIdRest.kt
jagilberte
675,312,737
false
null
package com.makobrothers.mako.rrhh.persona.infrastructure.input.rest import com.makobrothers.mako.rrhh.persona.application.port.input.* import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.http.MediaType import javax.inject.Inject import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.media.* import io.swagger.v3.oas.annotations.responses.* import io.swagger.v3.oas.annotations.security.SecurityRequirement @RestController @SecurityRequirement(name = "basicAuth") @RequestMapping("/api/rest/personas", produces = [MediaType.APPLICATION_JSON_VALUE]) class PersonaDeleteByIdRest(@Inject val service: PersonaDeleteByIdUseCase) { @Operation(summary = "Delete existing persona by its id") @ApiResponses(value = [ ApiResponse(responseCode = "200", description = "Deleted the persona", content = [(Content(mediaType = "application/json", schema = Schema(implementation = Integer::class)))])] ) @DeleteMapping("/v1/{id}") fun deleteById(@PathVariable id: String): ResponseEntity<Int> { val presenter = PersonaRestPresenter() service.execute(id, presenter) return presenter.generateResponseDelete() } }
0
Kotlin
0
0
944dc73d51b942af1ab2601cf59f667bdffcd790
1,260
mako
Apache License 2.0
app/src/main/java/com/example/composesample/data/models/WeatherResponse.kt
shahharshil0
768,074,233
false
{"Kotlin": 13569}
package com.example.composesample.data.models import com.google.gson.annotations.SerializedName data class WeatherResponse( @SerializedName("id") val id: Int?, @SerializedName("main") val main: WeatherMainResponse? )
0
Kotlin
0
0
eb49d0e36bb47e796bb8b8bf5a6911e132418fc4
234
weather-app
Apache License 2.0
code/kotlin/ClassGetSet.kts
evmorov
41,193,119
false
{"Java": 20279, "Ruby": 12660, "Python": 8674, "PHP": 8387, "JavaScript": 8285, "Kotlin": 8107, "Haml": 3478, "CoffeeScript": 967, "SCSS": 763, "HTML": 60}
class Animal(var name: String) val animal = Animal("Kelya") println(animal.name)
3
Java
7
24
c1a0608f74bd27f26b5bfb457cfdac23a9a06e53
82
lang-compare
MIT License
app-flavor-liveserver/src/main/java/com/handstandsam/shoppingapp/LiveNetworkGraph.kt
atilabraga
176,736,910
true
{"Kotlin": 79497}
package com.handstandsam.shoppingapp import android.content.Context import com.handstandsam.shoppingapp.di.BaseNetworkGraph import com.handstandsam.shoppingapp.models.LoginRequest import com.handstandsam.shoppingapp.models.NetworkConfig import com.handstandsam.shoppingapp.models.User import com.handstandsam.shoppingapp.repository.UserRepo import io.reactivex.Single class LiveNetworkGraph(appContext: Context) : BaseNetworkGraph( networkConfig = NetworkConfig( baseUrl = "https://shopping-app.s3.amazonaws.com", isWireMockServer = false, port = 443 ) ) { /** * Our S3 server can't support POST calls, * so we are just returning a mock for this call. */ override val userRepo: UserRepo = object : UserRepo { override fun login(loginRequest: LoginRequest): Single<User> { val user = User( firstname = "Live", lastname = "User" ) return Single.fromCallable { user } } } }
0
Kotlin
0
0
756186e92cd4b4d18a123f4fa65cbabeb7911b72
1,056
ShoppingApp
Apache License 2.0
finch-java-core/src/main/kotlin/com/tryfinch/api/models/AtsApplicationListPage.kt
Finch-API
581,317,330
false
null
package com.tryfinch.api.models import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.tryfinch.api.core.ExcludeMissing import com.tryfinch.api.core.JsonField import com.tryfinch.api.core.JsonMissing import com.tryfinch.api.core.JsonValue import com.tryfinch.api.core.NoAutoDetect import com.tryfinch.api.core.toUnmodifiable import com.tryfinch.api.services.blocking.ats.ApplicationService import java.util.Objects import java.util.Optional import java.util.stream.Stream import java.util.stream.StreamSupport class AtsApplicationListPage private constructor( private val applicationsService: ApplicationService, private val params: AtsApplicationListParams, private val response: Response, ) { fun response(): Response = response fun paging(): Paging = response().paging() fun applications(): List<Application> = response().applications() override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is AtsApplicationListPage && this.applicationsService == other.applicationsService && this.params == other.params && this.response == other.response } override fun hashCode(): Int { return Objects.hash( applicationsService, params, response, ) } override fun toString() = "AtsApplicationListPage{applicationsService=$applicationsService, params=$params, response=$response}" fun hasNextPage(): Boolean { if (applications().isEmpty()) { return false } return paging().offset().orElse(0) + applications().count() < paging().count().orElse(Long.MAX_VALUE) } fun getNextPageParams(): Optional<AtsApplicationListParams> { if (!hasNextPage()) { return Optional.empty() } return Optional.of( AtsApplicationListParams.builder() .from(params) .offset(paging().offset().orElse(0) + applications().count()) .build() ) } fun getNextPage(): Optional<AtsApplicationListPage> { return getNextPageParams().map { applicationsService.list(it) } } fun autoPager(): AutoPager = AutoPager(this) companion object { @JvmStatic fun of( applicationsService: ApplicationService, params: AtsApplicationListParams, response: Response ) = AtsApplicationListPage( applicationsService, params, response, ) } @JsonDeserialize(builder = Response.Builder::class) @NoAutoDetect class Response constructor( private val paging: JsonField<Paging>, private val applications: JsonField<List<Application>>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false fun paging(): Paging = paging.getRequired("paging") fun applications(): List<Application> = applications.getRequired("applications") @JsonProperty("paging") fun _paging(): Optional<JsonField<Paging>> = Optional.ofNullable(paging) @JsonProperty("applications") fun _applications(): Optional<JsonField<List<Application>>> = Optional.ofNullable(applications) @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate() = apply { if (!validated) { paging().validate() applications().forEach { it.validate() } validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Response && this.paging == other.paging && this.applications == other.applications && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { return Objects.hash( paging, applications, additionalProperties, ) } override fun toString() = "AtsApplicationListPage.Response{paging=$paging, applications=$applications, additionalProperties=$additionalProperties}" companion object { @JvmStatic fun builder() = Builder() } class Builder { private var paging: JsonField<Paging> = JsonMissing.of() private var applications: JsonField<List<Application>> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() @JvmSynthetic internal fun from(page: Response) = apply { this.paging = page.paging this.applications = page.applications this.additionalProperties.putAll(page.additionalProperties) } fun paging(paging: Paging) = paging(JsonField.of(paging)) @JsonProperty("paging") fun paging(paging: JsonField<Paging>) = apply { this.paging = paging } fun applications(applications: List<Application>) = applications(JsonField.of(applications)) @JsonProperty("applications") fun applications(applications: JsonField<List<Application>>) = apply { this.applications = applications } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun build() = Response( paging, applications, additionalProperties.toUnmodifiable(), ) } } class AutoPager constructor( private val firstPage: AtsApplicationListPage, ) : Iterable<Application> { override fun iterator(): Iterator<Application> = iterator { var page = firstPage var index = 0 while (true) { while (index < page.applications().size) { yield(page.applications()[index++]) } page = page.getNextPage().orElse(null) ?: break index = 0 } } fun stream(): Stream<Application> { return StreamSupport.stream(spliterator(), false) } } }
1
null
0
4
2c53f443c479e0b01499126413569edc5dc0b1ef
6,858
finch-api-java
Apache License 2.0
spring/PlatoChain/src/main/kotlin/com/platonicc/platochain/test/PostTest.kt
Platonicc
278,628,232
false
null
package com.platonicc.platochain.test import com.google.gson.Gson import com.platonicc.platochain.blockchain.Block import com.platonicc.platochain.blockchain.BlockData import com.platonicc.platochain.blockchain.Chain import com.platonicc.platochain.blockchain.Chain.Companion.localChain import com.platonicc.platochain.blockchain.Chain.Companion.isValidChain import com.platonicc.platochain.blockchain.Chain.Companion.replaceChain import com.platonicc.platochain.blockchain.JSONStringToChain import org.jetbrains.annotations.TestOnly import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RestController @RestController class PostTest { var chain2 = localChain @TestOnly @GetMapping(value = ["/post/test/{sender}/{amount}/{message}"], produces = [MediaType.TEXT_EVENT_STREAM_VALUE]) fun testFun(@PathVariable sender: String, @PathVariable amount: String, @PathVariable message: String): String { Chain.addBlock(BlockData(sender, "aman-pc", amount.toDouble(), message)) for(i in localChain){ i.printBlockDetails() } println(isValidChain(JSONStringToChain(Gson().toJson(localChain)))) println(localChain[0].getStruct() == Block.Genesis.getStruct()) return Gson().toJson(localChain) } }
0
Kotlin
1
1
a66ca8ec0d7642432a56f2e56db53130e54179c0
1,465
PlatoChain
MIT License
composeApp/src/commonMain/kotlin/data/api/instance/Platforms.kt
vrcm-team
746,586,818
false
{"Kotlin": 145508, "Swift": 4222}
package io.github.vrcmteam.vrcm.data.api.instance import kotlinx.serialization.Serializable @Serializable data class Platforms( val android: Int, val standalonewindows: Int )
0
Kotlin
0
3
c0f4a147b1ea2a07940a82207d552d9f0a0e7ae7
184
VRCM
MIT License
app/src/main/java/com/apps/musicplayerapp/MainActivity.kt
vinodbobate25
372,803,274
false
null
package com.apps.musicplayerapp import android.media.AudioManager import android.media.MediaPlayer import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.bottomnavigation.BottomNavigationView import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.player_tab.* import java.io.IOException @AndroidEntryPoint class MainActivity : AppCompatActivity() { private var isMediaPlaying: Boolean=false private lateinit var mainViewModel: MainViewModel var mediaPlayer: MediaPlayer? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java) val navView: BottomNavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration(setOf( R.id.navigation_home, R.id.navigation_recent)) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) img_play.setOnClickListener { if(!isMediaPlaying) { img_play.background=resources.getDrawable(R.drawable.ico_pause) playAudio() } else{ img_play.background=resources.getDrawable(R.drawable.ico_play) } } img_prev.setOnClickListener { } img_next.setOnClickListener { } } private fun playAudio() { val audioUrl = "https://rfcmedia.streamguys1.com/70hits.aac" // initializing media player mediaPlayer = MediaPlayer() // below line is use to set the audio // stream type for our media player. mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC) // below line is use to set our // url to our media player. try { mediaPlayer?.setDataSource(audioUrl) // below line is use to prepare // and start our media player. mediaPlayer?.prepare() mediaPlayer?.start() isMediaPlaying=true; } catch (e: IOException) { e.printStackTrace() } // below line is use to display a toast message. Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
1255bbcd86c8ca763f7404f9a78a943213d3695f
2,921
music_player
Apache License 2.0
src/test/kotlin/com/herokuapp/ourairports/features/frequencies/FrequenciesTest.kt
alexmaryin
433,391,973
false
null
package com.herokuapp.ourairports.features.frequencies import com.herokuapp.ourairports.features.FeatureKoinTest import com.herokuapp.ourairports.testObjects.TestFrequencies import io.ktor.http.* import io.ktor.server.testing.* import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.junit.Test import kotlin.test.assertEquals class FrequenciesTest : FeatureKoinTest() { @Test fun `Correct request should return 200 status and frequencies json array`() { withRouting { handleRequest(HttpMethod.Get, "/api/v1/frequencies/UWLL").apply { assertEquals(HttpStatusCode.OK, response.status()) assertEquals(listOf(TestFrequencies.unicom, TestFrequencies.atis), Json.decodeFromString(response.content!!)) } } } @Test fun `Incorrect ICAO request should return 400 status`() { withRouting { handleRequest(HttpMethod.Get, "/api/v1/frequencies/_UWLL").apply { assertEquals(HttpStatusCode.BadRequest, response.status()) assertEquals("You should pass ICAO code instead of _UWLL", response.content) } } } @Test fun `Unknown ICAO request should return 404 status`() { withRouting { handleRequest(HttpMethod.Get, "/api/v1/frequencies/UUUU").apply { assertEquals(HttpStatusCode.NotFound, response.status()) assertEquals("Frequencies of airport with ICAO UUUU not found", response.content) } } } }
0
Kotlin
0
0
0d2a86a2197fa2e289f42bdc54f36e865162a182
1,574
ourairports_json
The Unlicense
sample-screen-second/src/main/java/screenswitchersample/second/SecondScreenDialogFactory.kt
JayNewstrom
48,964,076
false
null
package screenswitchersample.second import android.app.AlertDialog import android.app.Dialog import android.content.Context import com.jaynewstrom.screenswitcher.dialogmanager.DialogFactory import javax.inject.Inject internal class SecondScreenDialogFactory @Inject constructor() : DialogFactory { override fun createDialog(context: Context): Dialog { return AlertDialog.Builder(context).setTitle("Second Dialog").setMessage("Rotate to test!").create() } }
1
Kotlin
2
2
565a513435ba6c1935ca8c3586aee183fd2d7b17
475
ScreenSwitcher
Apache License 2.0
utbot-spring-analyzer/src/main/kotlin/org/utbot/spring/configurators/XmlFilesConfigurator.kt
UnitTestBot
480,810,501
false
null
package org.utbot.spring.configurators import org.utbot.spring.utils.ConfigurationManager import org.utbot.spring.utils.PathsUtils import kotlin.io.path.Path class XmlFilesConfigurator( private val userXmlFilePaths: List<String>, private val configurationManager: ConfigurationManager, ) { fun configure() { configurationManager.clearImportResourceAnnotation() for (userXmlFilePath in userXmlFilePaths) { if(userXmlFilePath == PathsUtils.EMPTY_PATH)continue val xmlConfigurationParser = XmlConfigurationParser(userXmlFilePath, PathsUtils.createFakeFilePath(userXmlFilePath)) xmlConfigurationParser.fillFakeApplicationXml() configurationManager.patchImportResourceAnnotation(Path(userXmlFilePath).fileName) } } }
337
Kotlin
25
70
d93fd5656645b55d3cece6eb13de8835bd0496d3
821
UTBotJava
Apache License 2.0
android-chat-app/app/src/main/java/org/kagami/roommate/chat/domain/model/repository/MatchRepository.kt
k-arabadzhiev
515,181,907
false
{"Kotlin": 309983}
package org.kagami.roommate.chat.domain.model.repository import org.kagami.roommate.chat.data.remote.ws.models.messages.ChatMessage import org.kagami.roommate.chat.domain.model.user.Match interface MatchRepository { suspend fun fetchMatches(token: String): List<Match> suspend fun getMatchMessages(token: String, matchId: String): List<ChatMessage> }
0
Kotlin
0
0
e69e22d6aabffb3b4afe54cf9ef6a92007d5beb5
361
Roommates
MIT License
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/koinitblock/KoInitBlockDeclarationForKoLocalDeclarationProviderTest.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.core.declaration.koinitblock import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope import com.lemonappdev.konsist.api.provider.KoNameProvider import org.amshove.kluent.assertSoftly import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test class KoInitBlockDeclarationForKoLocalDeclarationProviderTest { @Test fun `init-block-contains-no-local-declarations`() { // given val sut = getSnippetFile("init-block-contains-no-local-declarations") .classes() .first() .initBlocks .first() // then assertSoftly(sut) { numLocalDeclarations shouldBeEqualTo 0 countLocalClasses { it.name == "sampleOtherDeclaration" } shouldBeEqualTo 0 containsLocalDeclaration { (it as KoNameProvider).name == "sampleLocalProperty" } shouldBeEqualTo false localDeclarations shouldBeEqualTo emptyList() } } @Test fun `init-block-contains-local-declarations`() { // given val sut = getSnippetFile("init-block-contains-local-declarations") .classes() .first() .initBlocks .first() // then assertSoftly(sut) { numLocalDeclarations shouldBeEqualTo 3 countLocalDeclarations { (it as KoNameProvider).hasNameStartingWith("sampleLocal") } shouldBeEqualTo 2 containsLocalDeclaration { (it as KoNameProvider).name == "sampleLocalProperty" } shouldBeEqualTo true containsLocalDeclaration { (it as KoNameProvider).name == "sampleLocalFunction" } shouldBeEqualTo true containsLocalDeclaration { (it as KoNameProvider).name == "SampleLocalClass" } shouldBeEqualTo true containsLocalDeclaration { (it as KoNameProvider).name == "sampleOtherDeclaration" } shouldBeEqualTo false localDeclarations .filterIsInstance<KoNameProvider>() .map { it.name } .shouldBeEqualTo( listOf( "sampleLocalProperty", "sampleLocalFunction", "SampleLocalClass", ), ) } } private fun getSnippetFile(fileName: String) = getSnippetKoScope("core/declaration/koinitblock/snippet/forkolocaldeclarationprovider/", fileName) }
4
Kotlin
1
71
c3cf91622bab1938fecbc96c119cbbb70e372451
2,444
konsist
Apache License 2.0
src/main/kotlin/io/kjson/serialize/CommonIterableSerializer.kt
pwall567
389,599,808
false
{"Kotlin": 710643, "Java": 8994}
/* * @(#) CommonIterableSerializer.kt * * kjson Reflection-based JSON serialization and deserialization for Kotlin * Copyright (c) 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.kjson.serialize import io.kjson.JSONArray import io.kjson.JSONConfig import net.pwall.util.CoOutput import net.pwall.util.output abstract class CommonIterableSerializer<I : Any>( // use this for List, Sequence etc. private val itemSerializer: Serializer<I>, ) { fun serializeIterator(iterator: Iterator<I?>, config: JSONConfig, references: MutableList<Any>): JSONArray = JSONArray.build { var i = 0 while (iterator.hasNext()) { val item = iterator.next() add(itemSerializer.serializeNested(item, config, references, i.toString())) i++ } } fun appendIteratorTo(a: Appendable, iterator: Iterator<I?>, config: JSONConfig, references: MutableList<Any>) { a.append('[') if (iterator.hasNext()) { var i = 0 while (true) { val item = iterator.next() itemSerializer.appendNestedTo(a, item, config, references, i.toString()) if (!iterator.hasNext()) break i++ a.append(',') } } a.append(']') } suspend fun outputIterator(out: CoOutput, iterator: Iterator<I?>, config: JSONConfig, references: MutableList<Any>) { out.output('[') if (iterator.hasNext()) { var index = 0 while (true) { val item = iterator.next() itemSerializer.outputNestedTo(out, item, config, references, index.toString()) if (!iterator.hasNext()) break index++ out.output(',') } } out.output(']') } }
0
Kotlin
0
9
f7ba0cd4bc51b1ed00707e9b491cd6c1479e454f
2,964
kjson
MIT License
dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/domain/batching/processors/DataProcessor.kt
erawhctim
312,841,525
true
{"Kotlin": 2814343, "Java": 217748, "C": 78947, "C++": 27621, "Python": 4483, "CMake": 2042}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.core.internal.domain.batching.processors import com.datadog.android.core.internal.data.Writer import com.datadog.tools.annotation.NoOpImplementation @NoOpImplementation internal interface DataProcessor<T : Any> { fun consume(event: T) fun consume(events: List<T>) fun getWriter(): Writer<T> }
0
Kotlin
0
0
c429afb8495d6e316a03c7def835e7ac29fe5441
588
dd-sdk-android
Apache License 2.0
app-inventory/src/main/java/com/xsolla/android/inventorysdkexample/ui/fragments/tutorial/TutorialPageFragment.kt
xsolla
233,092,015
false
null
package com.xsolla.android.inventorysdkexample.ui.fragments.tutorial import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import androidx.fragment.app.Fragment import by.kirich1409.viewbindingdelegate.viewBinding import com.xsolla.android.inventorysdkexample.R import com.xsolla.android.inventorysdkexample.databinding.ItemTutorialBinding class TutorialPageFragment : Fragment(R.layout.item_tutorial) { private val binding: ItemTutorialBinding by viewBinding() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val page = requireArguments()[ARG_PAGE] as Int binding.tutorialImage.setImageResource( when (page) { 1 -> R.drawable.page1 2 -> R.drawable.page2 3 -> R.drawable.page3 4 -> R.drawable.page4 else -> throw IllegalArgumentException() } ) binding.tutorialTitle.setText( when (page) { 1 -> R.string.tutorial_1_title 2 -> R.string.tutorial_2_title 3 -> R.string.tutorial_3_title 4 -> R.string.tutorial_4_title else -> throw IllegalArgumentException() } ) binding.tutorialText.movementMethod = LinkMovementMethod.getInstance() binding.tutorialText.setText( when (page) { 1 -> R.string.tutorial_1_text 2 -> R.string.tutorial_2_text 3 -> R.string.tutorial_3_text 4 -> R.string.tutorial_4_text else -> throw IllegalArgumentException() } ) } companion object { private const val ARG_PAGE = "ARG_PAGE" @JvmStatic fun newInstance(page: Int) = TutorialPageFragment().apply { arguments = Bundle().apply { putInt(ARG_PAGE, page) } } } }
0
Kotlin
5
8
b279d7c281bcadeb5cbba9ccc5372238221a8bfd
2,052
store-android-sdk
Apache License 2.0
practice_1/ecommerce/src/main/kotlin/com/api/ecommerce/dtos/responses/BaseResponse.kt
trungung
318,070,008
false
null
package com.api.ecommerce.dtos.responses class BaseResponse() { }
0
Kotlin
0
0
27d3cefd8a49d5f168c1da6dfa8c8e00d6bd8cd2
67
spring-microservice
Apache License 2.0
feature_view_image/src/main/java/com/maxmakarov/feature/view/image/StretchableImageView.kt
maxmakarovdev
666,362,590
false
null
package com.maxmakarov.feature.view.image import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.animation.ValueAnimator.AnimatorUpdateListener import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import android.graphics.Matrix.MSCALE_X import android.graphics.Matrix.MSCALE_Y import android.graphics.Matrix.MTRANS_X import android.graphics.Matrix.MTRANS_Y import android.graphics.PointF import android.graphics.RectF import android.graphics.drawable.Drawable import android.net.Uri import android.util.AttributeSet import android.view.GestureDetector import android.view.GestureDetector.SimpleOnGestureListener import android.view.MotionEvent import android.view.MotionEvent.* import android.view.ScaleGestureDetector import android.view.ScaleGestureDetector.OnScaleGestureListener import androidx.appcompat.widget.AppCompatImageView import androidx.core.view.ScaleGestureDetectorCompat import kotlin.math.abs class StretchableImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatImageView(context, attrs, defStyleAttr), OnScaleGestureListener { private val imgMatrix = Matrix() private var startMatrix = Matrix() private val matrixValues = FloatArray(9) private var startValues: FloatArray? = null private var doubleTapDetected = false private var singleTapDetected = false private var calculatedMinScale = MIN_SCALE private var calculatedMaxScale = MAX_SCALE private val bounds = RectF() private val last = PointF(0f, 0f) private var startScaleType: ScaleType private var startScale = 1f private var scaleBy = 1f private var currentScaleFactor = 1f private var previousPointerCount = 1 private var currentPointerCount = 0 private var scaleDetector: ScaleGestureDetector = ScaleGestureDetector(context, this) private var resetAnimator: ValueAnimator? = null private var startY = 0f private var skip = false private var gestureDetector: GestureDetector var dragDownListener: DragDownListener? = null init { gestureDetector = GestureDetector(context, object : SimpleOnGestureListener() { override fun onDoubleTapEvent(e: MotionEvent): Boolean { doubleTapDetected = e.action == ACTION_UP singleTapDetected = false return false } override fun onSingleTapUp(e: MotionEvent): Boolean { singleTapDetected = true return false } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { singleTapDetected = false return false } override fun onDown(e: MotionEvent) = true }) ScaleGestureDetectorCompat.setQuickScaleEnabled(scaleDetector, false) startScaleType = scaleType } override fun setScaleType(scaleType: ScaleType?) { if (scaleType != null) { super.setScaleType(scaleType) startScaleType = scaleType startValues = null } } override fun setImageResource(resId: Int) { super.setImageResource(resId) scaleType = startScaleType } override fun setImageDrawable(drawable: Drawable?) { super.setImageDrawable(drawable) scaleType = startScaleType } override fun setImageBitmap(bm: Bitmap?) { super.setImageBitmap(bm) scaleType = startScaleType } override fun setImageURI(uri: Uri?) { super.setImageURI(uri) scaleType = startScaleType } /** * Update the bounds of the displayed image based on the current matrix. */ private fun updateBounds(values: FloatArray) { if (drawable != null) { bounds[values[MTRANS_X], values[MTRANS_Y], drawable.intrinsicWidth * values[MSCALE_X] + values[MTRANS_X]] = drawable.intrinsicHeight * values[MSCALE_Y] + values[MTRANS_Y] } } private fun currentDisplayedWidth() = (drawable?.intrinsicWidth ?: 0) * matrixValues[MSCALE_X] private fun currentDisplayedHeight() = (drawable?.intrinsicHeight ?: 0) * matrixValues[MSCALE_Y] /** * Remember our starting values so we can animate our image back to its original position. */ private fun setStartValues() { startValues = FloatArray(9) startMatrix = Matrix(imageMatrix) startMatrix.getValues(startValues) calculatedMinScale = MIN_SCALE * startValues!![MSCALE_X] calculatedMaxScale = MAX_SCALE * startValues!![MSCALE_X] } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (!isClickable && isEnabled) { if (scaleType != ScaleType.MATRIX) { super.setScaleType(ScaleType.MATRIX) } if (startValues == null) { setStartValues() } currentPointerCount = event.pointerCount //get the current state of the image matrix, its values, and the bounds of the drawn bitmap imgMatrix.set(imageMatrix) imgMatrix.getValues(matrixValues) updateBounds(matrixValues) scaleDetector.onTouchEvent(event) gestureDetector.onTouchEvent(event) if (doubleTapDetected) { doubleTapDetected = false singleTapDetected = false if (matrixValues[MSCALE_X] != startValues!![MSCALE_X]) { reset(true) } else { val zoomMatrix = Matrix(imgMatrix) zoomMatrix.postScale( DOUBLE_TAP_SCALE_FACTOR, DOUBLE_TAP_SCALE_FACTOR, scaleDetector.focusX, scaleDetector.focusY ) animateScaleAndTranslationToMatrix(zoomMatrix) } return true } else if (!singleTapDetected) { /* if the event is a down touch, or if the number of touch points changed, * we should reset our start point, as event origins have likely shifted to a * different part of the screen*/ if (event.actionMasked == ACTION_DOWN || currentPointerCount != previousPointerCount) { last[scaleDetector.focusX] = scaleDetector.focusY skip = if (currentPointerCount == 1) event.y < bounds.top else true startY = event.y } else if (event.actionMasked == ACTION_MOVE) { val focusX = scaleDetector.focusX val focusY = scaleDetector.focusY if (allowTranslate()) { val xdistance = getXDistance(focusX, last.x) val ydistance = getYDistance(focusY, last.y) imgMatrix.postTranslate(xdistance, ydistance) } //zoom imgMatrix.postScale(scaleBy, scaleBy, focusX, focusY) currentScaleFactor = matrixValues[MSCALE_X] / startValues!![MSCALE_X] imageMatrix = imgMatrix last[focusX] = focusY if (!skip && currentScaleFactor == 1f) { dragDownListener?.onDragDown(abs(event.y - startY)) } } if (event.actionMasked == ACTION_UP || event.actionMasked == ACTION_CANCEL) { scaleBy = 1f resetImage() if (!skip && currentScaleFactor == 1f) { dragDownListener?.onDragEnded(abs(event.y - startY)) } } } parent.requestDisallowInterceptTouchEvent(disallowParentTouch()) previousPointerCount = currentPointerCount return true } return super.onTouchEvent(event) } private fun disallowParentTouch() = currentPointerCount > 1 || currentScaleFactor > 1.0f || isAnimating() private fun allowTranslate() = currentScaleFactor >= 1.0f private fun isAnimating() = resetAnimator?.isRunning ?: false private fun resetImage() { if (matrixValues[MSCALE_X] <= startValues!![MSCALE_X]) { reset(true) } else { center() } } private fun center() { animateTranslationX() animateTranslationY() } fun reset(animate: Boolean) { if (animate) { animateToStartMatrix() } else { imageMatrix = startMatrix } } private fun animateToStartMatrix() { animateScaleAndTranslationToMatrix(startMatrix) } private fun animateScaleAndTranslationToMatrix(targetMatrix: Matrix) { val targetValues = FloatArray(9) targetMatrix.getValues(targetValues) val beginMatrix = Matrix(imageMatrix) beginMatrix.getValues(matrixValues) val xsDiff = targetValues[MSCALE_X] - matrixValues[MSCALE_X] val ysDiff = targetValues[MSCALE_Y] - matrixValues[MSCALE_Y] val xtDiff = targetValues[MTRANS_X] - matrixValues[MTRANS_X] val ytDiff = targetValues[MTRANS_Y] - matrixValues[MTRANS_Y] resetAnimator = ValueAnimator.ofFloat(0f, 1f).apply { duration = RESET_DURATION.toLong() addUpdateListener(object : AnimatorUpdateListener { val activeMatrix = Matrix(imageMatrix) val values = FloatArray(9) override fun onAnimationUpdate(animation: ValueAnimator) { val value = animation.animatedValue as Float activeMatrix.set(beginMatrix) activeMatrix.getValues(values) values[MTRANS_X] = values[MTRANS_X] + xtDiff * value values[MTRANS_Y] = values[MTRANS_Y] + ytDiff * value values[MSCALE_X] = values[MSCALE_X] + xsDiff * value values[MSCALE_Y] = values[MSCALE_Y] + ysDiff * value activeMatrix.setValues(values) imageMatrix = activeMatrix } }) addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { imageMatrix = targetMatrix } }) start() } } private fun animateTranslationX() { if (currentDisplayedWidth() > width) { when { bounds.left > 0 -> animateMatrixIndex(MTRANS_X, 0f) bounds.right < width -> animateMatrixIndex(MTRANS_X, bounds.left + width - bounds.right) } } else { when { bounds.left < 0 -> animateMatrixIndex(MTRANS_X, 0f) bounds.right > width -> animateMatrixIndex(MTRANS_X, bounds.left + width - bounds.right) } } } private fun animateTranslationY() { if (currentDisplayedHeight() > height) { when { bounds.top > 0 -> animateMatrixIndex(MTRANS_Y, 0f) bounds.bottom < height -> animateMatrixIndex(MTRANS_Y, bounds.top + height - bounds.bottom) } } else { animateMatrixIndex(MTRANS_Y, height / 2f - currentDisplayedHeight() / 2f) } } private fun animateMatrixIndex(index: Int, to: Float) { ValueAnimator.ofFloat(matrixValues[index], to).apply { duration = RESET_DURATION.toLong() addUpdateListener(object : AnimatorUpdateListener { val values = FloatArray(9) var current = Matrix() override fun onAnimationUpdate(animation: ValueAnimator) { current.set(imageMatrix) current.getValues(values) values[index] = animation.animatedValue as Float current.setValues(values) imageMatrix = current } }) start() } } private fun getXDistance(toX: Float, fromX: Float): Float { var xdistance = toX - fromX when { bounds.right + xdistance < 0 -> xdistance = -bounds.right bounds.left + xdistance > width -> xdistance = width - bounds.left } return xdistance } private fun getYDistance(toY: Float, fromY: Float): Float { var ydistance = toY - fromY when { bounds.bottom + ydistance < 0 -> ydistance = -bounds.bottom bounds.top + ydistance > height -> ydistance = height - bounds.top } return ydistance } override fun onScale(detector: ScaleGestureDetector): Boolean { //calculate value we should scale by, ultimately the scale will be startScale*scaleFactor scaleBy = startScale * detector.scaleFactor / matrixValues[MSCALE_X] //what the scaling should end up at after the transformation val projectedScale = scaleBy * matrixValues[MSCALE_X] //clamp to the min/max if it's going over when { projectedScale < calculatedMinScale -> scaleBy = calculatedMinScale / matrixValues[MSCALE_X] projectedScale > calculatedMaxScale -> scaleBy = calculatedMaxScale / matrixValues[MSCALE_X] } return false } override fun onScaleBegin(detector: ScaleGestureDetector): Boolean { startScale = matrixValues[MSCALE_X] return true } override fun onScaleEnd(detector: ScaleGestureDetector) { scaleBy = 1f } interface DragDownListener { fun onDragDown(distance: Float) fun onDragEnded(distance: Float) } companion object { private const val MIN_SCALE = 0.6f private const val MAX_SCALE = 8f private const val RESET_DURATION = 150 private const val DOUBLE_TAP_SCALE_FACTOR = 3f } }
0
Kotlin
0
1
684e69452b9a5cb3549dc9412265c437f8dbb753
14,233
android-unsplash-gallery-sample
Apache License 2.0
actions-kotlin/src/main/kotlin/actions/io/which.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! @file:JsModule("@actions/io") package actions.io import kotlin.js.Promise external fun which( tool: String, check: Boolean = definedExternally, ): Promise<String>
0
Kotlin
5
18
83aa7866b2353ee7daf1521611bf7f91ea8b0a9b
219
types-kotlin
Apache License 2.0
mongodb-search-core/src/main/kotlin/io/github/yearnlune/search/core/operator/AverageOperator.kt
yearnlune
512,971,890
false
{"Kotlin": 140382, "JavaScript": 1896, "TypeScript": 91}
package io.github.yearnlune.search.core.operator import org.springframework.data.mongodb.core.aggregation.AccumulatorOperators import org.springframework.data.mongodb.core.aggregation.AggregationExpression import org.springframework.data.mongodb.core.aggregation.AggregationOperation import org.springframework.data.mongodb.core.aggregation.GroupOperation class AverageOperator( private val propertyPath: String?, private val propertyExpression: AggregationExpression? = null, alias: String? = null ) : AggregateOperator() { override val finalAlias: String by lazy { alias ?: "${propertyPath}_avg" } override fun validate(): Boolean = !propertyPath.isNullOrBlank() || propertyExpression != null override fun buildOperation(aggregationOperation: AggregationOperation?): AggregationOperation { return when (aggregationOperation) { is GroupOperation -> { if (propertyPath != null) { aggregationOperation.avg(propertyPath).`as`(finalAlias) } else { aggregationOperation.avg(propertyExpression!!).`as`(finalAlias) } } else -> throw IllegalArgumentException() } } override fun buildExpression(): AggregationExpression = AccumulatorOperators.Avg.avgOf(propertyPath!!) }
0
Kotlin
0
2
f68dc088551c0174c5104007703aa50ad4b361bc
1,340
mongodb-search
Apache License 2.0
src/main/kotlin/com/ps/demo/contracts/FreeBusyContract.kt
sugarp
150,076,100
false
null
package com.ps.kotlinjs.demo.contracts interface FreeBusyContract { class Item { var name : String = "" var draggable : Boolean = false } interface Presenter { } interface View { fun setItems(items: List<Item>) } }
0
Kotlin
0
0
a6f90e7c377223ce34da6b253c0c995bac10fe95
266
react-scroller
Apache License 2.0
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/NoWildcardImportsRule.kt
pinterest
64,293,719
false
null
package com.pinterest.ktlint.ruleset.standard import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.ast.ElementType.IMPORT_DIRECTIVE import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.psi.KtImportDirective class NoWildcardImportsRule : Rule("no-wildcard-imports") { override fun visit( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit ) { if (node.elementType == IMPORT_DIRECTIVE) { val importDirective = node.psi as KtImportDirective val path = importDirective.importPath?.pathStr if (path != null && !path.startsWith("kotlinx.android.synthetic") && path.contains('*')) { emit(node.startOffset, "Wildcard import", false) } } } }
102
null
401
4,765
e1674f8810c8bed6d6ee43c7e97737855c848975
806
ktlint
MIT License
app/src/main/java/com/zobaer53/starwars/app/starship/presentation/StarshipScreen.kt
zobaer53
718,458,210
false
{"Kotlin": 99449}
package com.zobaer53.starwars.app.starship.presentation import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.paging.LoadState import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import com.zobaer53.starwars.app.starship.domain.entity.Starship import com.zobaer53.starwars.app.starship.presentation.component.StarshipItem import com.zobaer53.starwars.app.util.ErrorMessage import com.zobaer53.starwars.app.util.LoadingNextPageItem import com.zobaer53.starwars.app.util.PageLoader import com.zobaer53.starwars.app.util.route.AppScreen @Composable fun StarshipScreen( navController: NavController, viewModel: StarshipViewModel= hiltViewModel(navController.getBackStackEntry(AppScreen.MainScreen.route)) ){ val starshipPagingItems : LazyPagingItems<Starship> = viewModel.starshipsState.collectAsLazyPagingItems() LazyColumn( modifier = Modifier.padding(horizontal = 16.dp) ) { item { Spacer(modifier = Modifier.padding(4.dp)) } items(starshipPagingItems.itemCount) { index -> val starship =starshipPagingItems[index]!! StarshipItem( starship = starship ) { navController.navigate("${AppScreen.StarshipDetailsScreen.route}/${starship.id}", builder = { // Pop up to the CharacterScreen route, excluding it from the back stack popUpTo(AppScreen.MainScreen.route) { inclusive = false } }) } } starshipPagingItems.apply { when { loadState.refresh is LoadState.Loading -> { item { PageLoader(modifier = Modifier.fillParentMaxSize()) } } loadState.refresh is LoadState.Error -> { val error = starshipPagingItems.loadState.refresh as LoadState.Error item { ErrorMessage( modifier = Modifier.fillParentMaxSize(), message = error.error.localizedMessage!!, onClickRetry = { retry() }) } } loadState.append is LoadState.Loading -> { item { LoadingNextPageItem(modifier = Modifier) } } loadState.append is LoadState.Error -> { val error = starshipPagingItems.loadState.append as LoadState.Error item { ErrorMessage( modifier = Modifier, message = error.error.localizedMessage!!, onClickRetry = { retry() }) } } } } item { Spacer(modifier = Modifier.padding(4.dp)) } } }
0
Kotlin
0
0
f2afd064918b69c8f2e69691162006e33224c8e2
3,261
StarWars
Apache License 2.0
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/Brown.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: RGBColor[0.6, 0.4, 0.2] * * Full name: Information[RGBColor[0.6, 0.4, 0.2], FullName] * * Usage: Information[RGBColor[0.6, 0.4, 0.2], Usage] * * Options: Information[RGBColor[0.6, 0.4, 0.2], Options] * * Attributes: Information[RGBColor[0.6, 0.4, 0.2], Attributes] * * local: <>Information[RGBColor[0.6, 0.4, 0.2], Documentation][Local] * Documentation: web: <>Information[RGBColor[0.6, 0.4, 0.2], Documentation][Web] * * Definitions: Information[RGBColor[0.6, 0.4, 0.2], Definitions] * * Own values: Information[RGBColor[0.6, 0.4, 0.2], OwnValues] * * Down values: Information[RGBColor[0.6, 0.4, 0.2], DownValues] * * Up values: Information[RGBColor[0.6, 0.4, 0.2], UpValues] * * Sub values: Information[RGBColor[0.6, 0.4, 0.2], SubValues] * * Default value: Information[RGBColor[0.6, 0.4, 0.2], DefaultValues] * * Numeric values: Information[RGBColor[0.6, 0.4, 0.2], NValues] */ fun brown(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("Brown", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,383
mathemagika
Apache License 2.0
app/src/main/java/com/example/recipeapp/SearchedRecipe.kt
minseoBae
762,071,254
false
{"Kotlin": 69383}
package com.example.recipeapp import java.io.Serializable data class SearchedRecipe ( val id: Int, val title: String, val image: String, val usedIngredientCount: Int, val missedIngredientCount: Int, val likes: Int ): Serializable
0
Kotlin
0
0
b1365d7bcbe2dc483777d8367a603444fc621df7
255
RecipeApp
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/oauth2server/resource/api/AuthUserRolesIntTest.kt
uk-gov-mirror
356,783,105
true
{"Kotlin": 1669768, "HTML": 158306, "CSS": 9895, "Shell": 8311, "Mustache": 7004, "PLSQL": 6379, "TSQL": 1100, "Dockerfile": 1015, "Groovy": 780, "JavaScript": 439}
package uk.gov.justice.digital.hmpps.oauth2server.resource.api import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.web.reactive.function.BodyInserters import uk.gov.justice.digital.hmpps.oauth2server.resource.DeliusExtension import uk.gov.justice.digital.hmpps.oauth2server.resource.IntegrationTest @ExtendWith(DeliusExtension::class) class AuthUserRolesIntTest : IntegrationTest() { @Test fun `Auth User Roles add role endpoint adds a role to a user`() { webTestClient .put().uri("/api/authuser/AUTH_RO_USER/roles/licence_vary") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isNoContent checkRolesForUser("AUTH_RO_USER", listOf("GLOBAL_SEARCH", "LICENCE_RO", "LICENCE_VARY")) } @Test fun `Auth User Roles add role endpoint adds a role to a user that already exists`() { webTestClient .put().uri("/api/authuser/AUTH_RO_USER/roles/licence_ro") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isEqualTo(HttpStatus.CONFLICT) .expectBody() .json("""{error: "role.exists", error_description: "Modify role failed for field role with reason: role.exists", field: "role"}""") } @Test fun `Auth User Roles add role endpoint adds a role to a user not in their group`() { webTestClient .put().uri("/api/authuser/AUTH_ADM/roles/licence_vary") .headers(setAuthorisation("AUTH_GROUP_MANAGER", listOf("ROLE_AUTH_GROUP_MANAGER"))) .exchange() .expectStatus().isEqualTo(HttpStatus.CONFLICT) .expectBody() .json("""{error: "User not with your groups", error_description: "Unable to maintain user: Auth Adm with reason: User not with your groups", field: "username"}""") } @Test fun `Auth User Roles add role endpoint adds a role that doesn't exist`() { webTestClient .put().uri("/api/authuser/AUTH_RO_USER_TEST/roles/licence_bob") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isBadRequest .expectBody() .json("""{error: "role.notfound", error_description: "Modify role failed for field role with reason: role.notfound", field: "role"}""") } @Test fun `Auth User Roles add role endpoint adds a role requires role`() { webTestClient .put().uri("/api/authuser/AUTH_RO_USER_TEST/roles/licence_bob") .headers(setAuthorisation("AUTH_GROUP_MANAGER", listOf("ROLE_GLOBAL_SEARCH"))) .exchange() .expectStatus().isForbidden .expectBody().json("""{error: "access_denied", error_description: "Access is denied"}""") } @Test fun `Auth User Roles remove role endpoint removes a role from a user`() { webTestClient .delete().uri("/api/authuser/AUTH_RO_USER_TEST/roles/licence_ro") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isNoContent checkRolesForUser("AUTH_RO_USER_TEST", listOf("GLOBAL_SEARCH")) } @Test fun `Auth User Roles remove role endpoint removes a role from a user that isn't found`() { webTestClient .delete().uri("/api/authuser/AUTH_RO_USER_TEST/roles/licence_bob") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isBadRequest .expectBody() .json("""{error: "role.notfound", error_description: "Modify role failed for field role with reason: role.notfound", field: "role"}""") } @Test fun `Auth User Roles remove role endpoint removes a role from a user that isn't on the user`() { webTestClient .delete().uri("/api/authuser/AUTH_RO_USER_TEST/roles/VIDEO_LINK_COURT_USER") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isBadRequest .expectBody() .json("""{error: "role.missing", error_description: "Modify role failed for field role with reason: role.missing", field: "role"}""") } @Test fun `Auth User Roles remove role endpoint removes a role from a user not in their group`() { webTestClient .delete().uri("/api/authuser/AUTH_ADM/roles/licence_ro") .headers(setAuthorisation("AUTH_GROUP_MANAGER", listOf("ROLE_AUTH_GROUP_MANAGER"))) .exchange() .expectStatus().isEqualTo(HttpStatus.CONFLICT) .expectBody() .json("""{error: "User not with your groups", error_description: "Unable to maintain user: Auth Adm with reason: User not with your groups", field: "username"}""") } @Test fun `Auth User Roles remove role endpoint requires role`() { webTestClient .delete().uri("/api/authuser/AUTH_ADM/roles/licence_ro") .headers(setAuthorisation("AUTH_GROUP_MANAGER", listOf("ROLE_GLOBAL_SEARCH"))) .exchange() .expectStatus().isForbidden .expectBody().json("""{error: "access_denied", error_description: "Access is denied"}""") } @Test fun `Auth User Roles endpoint returns user roles`() { checkRolesForUser("auth_ro_vary_user", listOf("GLOBAL_SEARCH", "LICENCE_RO", "LICENCE_VARY")) } @Test fun `Auth User Roles endpoint returns user roles not allowed`() { webTestClient .get().uri("/api/authuser/AUTH_ADM/roles") .exchange() .expectStatus().isUnauthorized .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() .json("""{error: "unauthorized", error_description: "Full authentication is required to access this resource"}""") } @Test fun `Auth Roles endpoint returns all assignable auth roles for a group for admin maintainer`() { webTestClient .get().uri("/api/authuser/auth_ro_vary_user/assignable-roles") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .exchange() .expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.[*].roleCode").value<List<String>> { assertThat(it).hasSizeGreaterThan(5) assertThat(it).contains("PECS_COURT") } } @Test fun `Auth Roles endpoint returns all assignable auth roles for a group for group manager`() { webTestClient .get().uri("/api/authuser/AUTH_RO_USER_TEST2/assignable-roles") .headers(setAuthorisation("AUTH_GROUP_MANAGER", listOf("ROLE_AUTH_GROUP_MANAGER"))) .exchange() .expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.[*].roleCode").value<List<String>> { assertThat(it).containsExactlyInAnyOrder("LICENCE_RO", "LICENCE_VARY") } } @Test fun `Auth User Roles add role POST endpoint adds a role to a user`() { webTestClient .post().uri("/api/authuser/AUTH_ADD_ROLE_TEST/roles") .headers(setAuthorisation("ITAG_USER_ADM", listOf("ROLE_MAINTAIN_OAUTH_USERS"))) .body(BodyInserters.fromValue(listOf("GLOBAL_SEARCH", "LICENCE_RO"))) .exchange() .expectStatus().isNoContent checkRolesForUser("AUTH_RO_USER", listOf("GLOBAL_SEARCH", "LICENCE_RO")) } private fun checkRolesForUser(user: String, roles: List<String>) { webTestClient .get().uri("/api/authuser/$user/roles") .headers(setAuthorisation("ITAG_USER_ADM")) .exchange() .expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.[*].roleCode").value<List<String>> { assertThat(it).containsExactlyInAnyOrderElementsOf(roles) } } }
0
Kotlin
0
0
f5a2a2f4eecc76459e206e7c84fde15d2c781758
7,824
ministryofjustice.hmpps-auth
MIT License
app/src/main/java/com/example/chefai/dto/PostData.kt
abenezermario
480,656,546
false
{"Kotlin": 32036}
package com.example.chefai data class PostData( // val logprobs: Any, val max_tokens: Int, // val n: Int, val prompt: String, // val stop: String, // val stream: Boolean, val temperature: Double, val top_p: Double, val presence_penalty: Double, )
0
Kotlin
1
0
f47f460d0268be3bebc3901b943c3ed802c8dbfd
279
Chefai
MIT License
app/common/src/androidMain/kotlin/com/denchic45/studiversity/widget/extendedAdapter/IAdapterManager.kt
denchic45
435,895,363
false
{"Kotlin": 2033820, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.widget.extendedAdapter import com.denchic45.studiversity.widget.extendedAdapter.action.AdapterAction interface IAdapterManager : AdapterAction, IAdapter
0
Kotlin
0
7
9d1744ffd9e1652e93af711951e924b739e96dcc
189
Studiversity
Apache License 2.0
app/src/main/java/org/covidwatch/android/presentation/HomeFragment.kt
markbyrne
256,520,253
true
{"Kotlin": 89495}
package org.covidwatch.android.presentation import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import org.covidwatch.android.BuildConfig import org.covidwatch.android.R import org.covidwatch.android.databinding.FragmentHomeBinding import org.covidwatch.android.domain.FirstTimeUser import org.covidwatch.android.domain.ReturnUser import org.covidwatch.android.domain.Setup import org.covidwatch.android.domain.UserFlow import org.covidwatch.android.presentation.home.HomeViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class HomeFragment : Fragment(R.layout.fragment_home) { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! private val homeViewModel: HomeViewModel by viewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) homeViewModel.setup() homeViewModel.userFlow.observe(viewLifecycleOwner, Observer { handleUserFlow(it) }) initClickListeners() } private fun initClickListeners() { binding.testedButton.setOnClickListener { findNavController().navigate(R.id.testQuestionsFragment) } binding.menuButton.setOnClickListener { findNavController().navigate(R.id.menuFragment) } binding.shareAppButton.setOnClickListener { shareApp() } } private fun shareApp() { val shareText = getString(R.string.share_intent_text) val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra( Intent.EXTRA_TEXT, "$shareText https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID ) sendIntent.type = "text/plain" startActivity(sendIntent) } private fun handleUserFlow(userFlow: UserFlow) { when (userFlow) { is FirstTimeUser -> { updateUiForFirstTimeUser() } is Setup -> { findNavController().navigate(R.id.splashFragment) } is ReturnUser -> { updateUiForReturnUser() } } } private fun updateUiForFirstTimeUser() { binding.homeTitle.setText(R.string.you_re_all_set_title) binding.homeSubtitle.setText(R.string.thank_you_text) } private fun updateUiForReturnUser() { binding.homeTitle.setText(R.string.welcome_back_title) binding.homeSubtitle.setText(R.string.not_detected_text) } }
0
null
0
0
78d9706f3a5a599de63f018d7fa760da7921ac41
3,173
covidwatch-android
Apache License 2.0
app/src/main/java/com/gpillaca/mapa19/util/ContextExtensions.kt
gpillaca
253,679,501
false
null
package com.gpillaca.mapa19.util import android.content.Context import android.widget.Toast fun Context.showMessage(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }
8
Kotlin
0
0
80bb3f6d24e378a64b7fee24851a73adef64408a
199
mapa19
MIT License
app/src/main/java/com/example/userlist/model/chars/Characters.kt
namdum
388,623,308
false
null
package com.example.userlist.model.chars import com.google.gson.annotations.SerializedName import java.io.Serializable //class Characters : ArrayList<CharModelItem>() data class Characters( @SerializedName("attributionHTML") val attributionHTML: String, @SerializedName("attributionText") val attributionText: String, @SerializedName("code") val code: String, @SerializedName("copyright") val copyright: String, @SerializedName("data") val data: Data, @SerializedName("etag") val etag: String, @SerializedName("status") val status: String ) :Serializable
0
Kotlin
0
0
90697fcb3b71a498add8b77ab2bd8791ac73c78a
602
User_List
MIT License