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
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/DeclarationContainer.kt
arrow-kt
217,378,939
false
null
package arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements interface DeclarationContainer { val declarations: List<Declaration> }
97
Kotlin
40
316
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
154
arrow-meta
Apache License 2.0
compiler/fir/tree/gen/org/jetbrains/kotlin/fir/expressions/builder/FirLazyBlockBuilder.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:Suppress("DuplicatedCode", "unused") package org.jetbrains.kotlin.fir.expressions.builder import kotlin.contracts.* import org.jetbrains.kotlin.KtSourceElement import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder import org.jetbrains.kotlin.fir.builder.FirBuilderDsl import org.jetbrains.kotlin.fir.builder.toMutableOrEmpty import org.jetbrains.kotlin.fir.expressions.FirAnnotation import org.jetbrains.kotlin.fir.expressions.FirLazyBlock import org.jetbrains.kotlin.fir.expressions.FirStatement import org.jetbrains.kotlin.fir.expressions.UnresolvedExpressionTypeAccess import org.jetbrains.kotlin.fir.expressions.builder.FirExpressionBuilder import org.jetbrains.kotlin.fir.expressions.impl.FirLazyBlockImpl import org.jetbrains.kotlin.fir.types.ConeKotlinType import org.jetbrains.kotlin.fir.visitors.* /* * This file was generated automatically * DO NOT MODIFY IT MANUALLY */ fun buildLazyBlock(): FirLazyBlock { return FirLazyBlockImpl() }
163
null
5686
46,039
f98451e38169a833f60b87618db4602133e02cf2
1,189
kotlin
Apache License 2.0
core/src/commonMain/kotlin/it/unibo/pulvreakt/dsl/model/PulvreaktConfiguration.kt
pulvreakt
540,771,410
false
{"Kotlin": 189528, "JavaScript": 404, "HTML": 93}
package it.unibo.pulvreakt.dsl.model import it.unibo.pulvreakt.core.protocol.Protocol typealias DevicesConfiguration = Map<String, DeviceSpecification> /** * Represents the container of configurations and additional information for the communication. * [devicesConfiguration] is the map that associates a device name to its specification. * [protocol] is the [Protocol] that will be used for the communication. */ data class PulvreaktConfiguration( val devicesConfiguration: DevicesConfiguration, val protocol: Protocol, ) { /** * Returns the device specification of the device with the given [deviceName]. */ operator fun get(deviceName: String): DeviceSpecification? = devicesConfiguration[deviceName] }
2
Kotlin
1
3
df71f7ae792fd7484569a1a222666111fd030fa2
739
pulvreakt
MIT License
service/src/main/kotlin/com/openlivery/service/common/system/SystemParameters.kt
heliohfs
366,046,617
false
null
package com.openlivery.service.common.system import com.openlivery.service.common.domain.entity.Parameters import com.openlivery.service.common.repository.ParametersRepository import org.springframework.stereotype.Service import java.math.BigDecimal import java.time.LocalTime import java.time.ZoneOffset @Service class SystemParameters( private val repository: ParametersRepository ) { fun getParameters(): Parameters = repository.findById(1) .orElse(Parameters()) fun setMinOrderValue(value: BigDecimal): Parameters { val parameters = getParameters() parameters.minOrderValue = value return repository.save(parameters) } fun setMinDeliveryFeeValue(value: BigDecimal): Parameters { val parameters = getParameters() parameters.minDeliveryFeeValue = value return repository.save(parameters) } fun setDeliveryFeeValuePerUnit(value: BigDecimal): Parameters { val parameters = getParameters() parameters.deliveryFeeValuePerUnit = value return repository.save(parameters) } fun setMinDeliveryFeeDistanceThreshold(value: Int): Parameters { val parameters = getParameters() parameters.minDeliveryFeeDistanceThreshold = value return repository.save(parameters) } fun setMaximumDeliveryRadius(value: Int): Parameters { val parameters = getParameters() parameters.maximumDeliveryRadius = value return repository.save(parameters) } fun setShutdownOrderCreationAt(value: LocalTime?): Parameters { val parameters = getParameters() parameters.shutdownOrderCreationAt = value return repository.save(parameters) } fun setStartupOrderCreationAt(value: LocalTime?): Parameters { val parameters = getParameters() parameters.startupOrderCreationAt = value return repository.save(parameters) } //TODO: fix fun isOpenedToOrders(): Boolean { val parameters = getParameters() val start = parameters.startupOrderCreationAt val stop = parameters.shutdownOrderCreationAt if (start != null && stop != null) { val now = LocalTime.now(ZoneOffset.UTC) val isBetween = !now.isBefore(start) && now.isBefore(stop) return if (start.isAfter(stop)) !isBetween else isBetween } return true } }
0
Kotlin
0
0
bf403d7fa6a216f064475dd63b0f870d932c44e4
2,411
openlivery
Apache License 2.0
service/src/main/kotlin/com/openlivery/service/common/system/SystemParameters.kt
heliohfs
366,046,617
false
null
package com.openlivery.service.common.system import com.openlivery.service.common.domain.entity.Parameters import com.openlivery.service.common.repository.ParametersRepository import org.springframework.stereotype.Service import java.math.BigDecimal import java.time.LocalTime import java.time.ZoneOffset @Service class SystemParameters( private val repository: ParametersRepository ) { fun getParameters(): Parameters = repository.findById(1) .orElse(Parameters()) fun setMinOrderValue(value: BigDecimal): Parameters { val parameters = getParameters() parameters.minOrderValue = value return repository.save(parameters) } fun setMinDeliveryFeeValue(value: BigDecimal): Parameters { val parameters = getParameters() parameters.minDeliveryFeeValue = value return repository.save(parameters) } fun setDeliveryFeeValuePerUnit(value: BigDecimal): Parameters { val parameters = getParameters() parameters.deliveryFeeValuePerUnit = value return repository.save(parameters) } fun setMinDeliveryFeeDistanceThreshold(value: Int): Parameters { val parameters = getParameters() parameters.minDeliveryFeeDistanceThreshold = value return repository.save(parameters) } fun setMaximumDeliveryRadius(value: Int): Parameters { val parameters = getParameters() parameters.maximumDeliveryRadius = value return repository.save(parameters) } fun setShutdownOrderCreationAt(value: LocalTime?): Parameters { val parameters = getParameters() parameters.shutdownOrderCreationAt = value return repository.save(parameters) } fun setStartupOrderCreationAt(value: LocalTime?): Parameters { val parameters = getParameters() parameters.startupOrderCreationAt = value return repository.save(parameters) } //TODO: fix fun isOpenedToOrders(): Boolean { val parameters = getParameters() val start = parameters.startupOrderCreationAt val stop = parameters.shutdownOrderCreationAt if (start != null && stop != null) { val now = LocalTime.now(ZoneOffset.UTC) val isBetween = !now.isBefore(start) && now.isBefore(stop) return if (start.isAfter(stop)) !isBetween else isBetween } return true } }
0
Kotlin
0
0
bf403d7fa6a216f064475dd63b0f870d932c44e4
2,411
openlivery
Apache License 2.0
src/test/kotlin/com/kirakishou/photoexchange/handlers/GetReceivedPhotosHandlerTest.kt
K1rakishou
109,591,197
false
null
package com.kirakishou.photoexchange.handlers import com.kirakishou.photoexchange.AbstractTest import com.kirakishou.photoexchange.TestUtils.createPhoto import com.kirakishou.photoexchange.core.ExchangeState import com.kirakishou.photoexchange.core.UserUuid import com.kirakishou.photoexchange.database.entity.PhotoEntity import com.kirakishou.photoexchange.database.repository.PhotosRepository import com.kirakishou.photoexchange.routers.Router import com.kirakishou.photoexchange.service.JsonConverterService import core.ErrorCode import junit.framework.Assert.assertEquals import kotlinx.coroutines.Dispatchers import net.response.ReceivedPhotosResponse import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.springframework.http.MediaType import org.springframework.test.context.junit4.SpringJUnit4ClassRunner import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.reactive.function.server.router import java.time.Duration @RunWith(SpringJUnit4ClassRunner::class) class GetReceivedPhotosHandlerTest : AbstractTest() { private fun getWebTestClient(jsonConverterService: JsonConverterService, photosRepository: PhotosRepository): WebTestClient { val handler = GetReceivedPhotosHandler( photosRepository, Dispatchers.Unconfined, jsonConverterService ) return WebTestClient.bindToRouterFunction(router { "/v1".nest { "/api".nest { accept(MediaType.APPLICATION_JSON).nest { GET( "/get_page_of_received_photos/{${Router.USER_UUID_VARIABLE}}/{${Router.LAST_UPLOADED_ON_VARIABLE}}/{${Router.COUNT_VARIABLE}}", handler::handle ) } } } }) .configureClient().responseTimeout(Duration.ofMillis(1_000_000)) .build() } @Before override fun setUp() { super.setUp() } @After override fun tearDown() { super.tearDown() } @Test fun `should return received photos with receiver coordinates`() { val webClient = getWebTestClient(jsonConverterService, photosRepository) dbQuery { assertEquals(1, usersDao.save(UserUuid("111")).userId.id) assertEquals(2, usersDao.save(UserUuid("222")).userId.id) photosDao.save(PhotoEntity.fromPhoto(createPhoto(1, ExchangeState.Exchanged, 1L, 9, -1L, "photo1", true, 11.1, 11.1, 1L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(2, ExchangeState.Exchanged, 1L, 10, -1L, "photo2", true, 11.1, 11.1, 2L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(3, ExchangeState.Exchanged, 1L, 11, -1L, "photo3", true, 11.1, 11.1, 3L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(4, ExchangeState.Exchanged, 1L, 12, -1L, "photo4", true, 11.1, 11.1, 4L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(5, ExchangeState.Exchanged, 1L, 13, -1L, "photo5", true, 11.1, 11.1, 5L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(6, ExchangeState.Exchanged, 1L, 14, -1L, "photo6", true, 11.1, 11.1, 6L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(7, ExchangeState.Exchanged, 1L, 15, -1L, "photo7", true, 11.1, 11.1, 7L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(8, ExchangeState.Exchanged, 1L, 16, -1L, "photo8", true, 11.1, 11.1, 8L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(9, ExchangeState.Exchanged, 2L, 1, -1L, "photo9", true, 22.2, 22.2, 1L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(10,ExchangeState.Exchanged, 2L, 2, -1L, "photo10", true, 22.2, 22.2, 2L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(11,ExchangeState.Exchanged, 2L, 3, -1L, "photo11", true, 22.2, 22.2, 3L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(12,ExchangeState.Exchanged, 2L, 4, -1L, "photo12", true, 22.2, 22.2, 4L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(13,ExchangeState.Exchanged, 2L, 5, -1L, "photo13", true, 22.2, 22.2, 5L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(14,ExchangeState.Exchanged, 2L, 6, -1L, "photo14", true, 22.2, 22.2, 6L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(15,ExchangeState.Exchanged, 2L, 7, -1L, "photo15", true, 22.2, 22.2, 7L, 0L, "123"))) photosDao.save(PhotoEntity.fromPhoto(createPhoto(16,ExchangeState.Exchanged, 2L, 8, -1L, "photo16", true, 22.2, 22.2, 8L, 0L, "123"))) } kotlin.run { val content = webClient .get() .uri("/v1/api/get_page_of_received_photos/111/8/6") .exchange() .expectStatus().is2xxSuccessful .expectBody() val response = fromBodyContent<ReceivedPhotosResponse>(content) assertEquals(ErrorCode.Ok.value, response.errorCode) assertEquals(6, response.receivedPhotos.size) assertEquals(15, response.receivedPhotos[0].photoId) assertEquals("photo7", response.receivedPhotos[0].uploadedPhotoName) assertEquals("photo15", response.receivedPhotos[0].receivedPhotoName) assertEquals(22.2, response.receivedPhotos[0].lon, EPSILON) assertEquals(22.2, response.receivedPhotos[0].lat, EPSILON) assertEquals(false, response.receivedPhotos[0].uploadedPhotoName == response.receivedPhotos[0].receivedPhotoName) assertEquals(14, response.receivedPhotos[1].photoId) assertEquals("photo6", response.receivedPhotos[1].uploadedPhotoName) assertEquals("photo14", response.receivedPhotos[1].receivedPhotoName) assertEquals(22.2, response.receivedPhotos[1].lon, EPSILON) assertEquals(22.2, response.receivedPhotos[1].lat, EPSILON) assertEquals(false, response.receivedPhotos[1].uploadedPhotoName == response.receivedPhotos[1].receivedPhotoName) assertEquals(13, response.receivedPhotos[2].photoId) assertEquals("photo5", response.receivedPhotos[2].uploadedPhotoName) assertEquals("photo13", response.receivedPhotos[2].receivedPhotoName) assertEquals(22.2, response.receivedPhotos[2].lon, EPSILON) assertEquals(22.2, response.receivedPhotos[2].lat, EPSILON) assertEquals(false, response.receivedPhotos[2].uploadedPhotoName == response.receivedPhotos[2].receivedPhotoName) assertEquals(12, response.receivedPhotos[3].photoId) assertEquals("photo4", response.receivedPhotos[3].uploadedPhotoName) assertEquals("photo12", response.receivedPhotos[3].receivedPhotoName) assertEquals(22.2, response.receivedPhotos[3].lon, EPSILON) assertEquals(22.2, response.receivedPhotos[3].lat, EPSILON) assertEquals(false, response.receivedPhotos[3].uploadedPhotoName == response.receivedPhotos[3].receivedPhotoName) assertEquals(11, response.receivedPhotos[4].photoId) assertEquals("photo3", response.receivedPhotos[4].uploadedPhotoName) assertEquals("photo11", response.receivedPhotos[4].receivedPhotoName) assertEquals(22.2, response.receivedPhotos[4].lon, EPSILON) assertEquals(22.2, response.receivedPhotos[4].lat, EPSILON) assertEquals(false, response.receivedPhotos[4].uploadedPhotoName == response.receivedPhotos[4].receivedPhotoName) assertEquals(10, response.receivedPhotos[5].photoId) assertEquals("photo2", response.receivedPhotos[5].uploadedPhotoName) assertEquals("photo10", response.receivedPhotos[5].receivedPhotoName) assertEquals(22.2, response.receivedPhotos[5].lon, EPSILON) assertEquals(22.2, response.receivedPhotos[5].lat, EPSILON) assertEquals(false, response.receivedPhotos[5].uploadedPhotoName == response.receivedPhotos[5].receivedPhotoName) } kotlin.run { val content = webClient .get() .uri("/v1/api/get_page_of_received_photos/222/8/6") .exchange() .expectStatus().is2xxSuccessful .expectBody() val response = fromBodyContent<ReceivedPhotosResponse>(content) assertEquals(ErrorCode.Ok.value, response.errorCode) assertEquals(6, response.receivedPhotos.size) assertEquals(7, response.receivedPhotos[0].photoId) assertEquals("photo15", response.receivedPhotos[0].uploadedPhotoName) assertEquals("photo7", response.receivedPhotos[0].receivedPhotoName) assertEquals(11.1, response.receivedPhotos[0].lon, EPSILON) assertEquals(11.1, response.receivedPhotos[0].lat, EPSILON) assertEquals(false, response.receivedPhotos[0].uploadedPhotoName == response.receivedPhotos[0].receivedPhotoName) assertEquals(6, response.receivedPhotos[1].photoId) assertEquals("photo14", response.receivedPhotos[1].uploadedPhotoName) assertEquals("photo6", response.receivedPhotos[1].receivedPhotoName) assertEquals(11.1, response.receivedPhotos[1].lon, EPSILON) assertEquals(11.1, response.receivedPhotos[1].lat, EPSILON) assertEquals(false, response.receivedPhotos[1].uploadedPhotoName == response.receivedPhotos[1].receivedPhotoName) assertEquals(5, response.receivedPhotos[2].photoId) assertEquals("photo13", response.receivedPhotos[2].uploadedPhotoName) assertEquals("photo5", response.receivedPhotos[2].receivedPhotoName) assertEquals(11.1, response.receivedPhotos[2].lon, EPSILON) assertEquals(11.1, response.receivedPhotos[2].lat, EPSILON) assertEquals(false, response.receivedPhotos[2].uploadedPhotoName == response.receivedPhotos[2].receivedPhotoName) assertEquals(4, response.receivedPhotos[3].photoId) assertEquals("photo12", response.receivedPhotos[3].uploadedPhotoName) assertEquals("photo4", response.receivedPhotos[3].receivedPhotoName) assertEquals(11.1, response.receivedPhotos[3].lon, EPSILON) assertEquals(11.1, response.receivedPhotos[3].lat, EPSILON) assertEquals(false, response.receivedPhotos[3].uploadedPhotoName == response.receivedPhotos[3].receivedPhotoName) assertEquals(3, response.receivedPhotos[4].photoId) assertEquals("photo11", response.receivedPhotos[4].uploadedPhotoName) assertEquals("photo3", response.receivedPhotos[4].receivedPhotoName) assertEquals(11.1, response.receivedPhotos[4].lon, EPSILON) assertEquals(11.1, response.receivedPhotos[4].lat, EPSILON) assertEquals(false, response.receivedPhotos[4].uploadedPhotoName == response.receivedPhotos[4].receivedPhotoName) assertEquals(2, response.receivedPhotos[5].photoId) assertEquals("photo10", response.receivedPhotos[5].uploadedPhotoName) assertEquals("photo2", response.receivedPhotos[5].receivedPhotoName) assertEquals(11.1, response.receivedPhotos[5].lon, EPSILON) assertEquals(11.1, response.receivedPhotos[5].lat, EPSILON) assertEquals(false, response.receivedPhotos[5].uploadedPhotoName == response.receivedPhotos[5].receivedPhotoName) } } }
0
Kotlin
0
1
eb6343fbac212833755d22de6dc9b12b4b022d39
10,921
photoexchange-backend
Do What The F*ck You Want To Public License
app/src/main/java/com/orange/ods/app/ui/components/textfields/TextField.kt
Orange-OpenSource
440,548,737
false
null
/* * * Copyright 2021 Orange * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * / */ package com.orange.ods.app.ui.components.textfields import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardCapitalization import com.orange.ods.app.R import com.orange.ods.app.ui.components.textfields.TextFieldCustomizationState.Companion.TextFieldMaxChars import com.orange.ods.app.ui.components.utilities.clickOnElement import com.orange.ods.app.ui.utilities.composable.CodeImplementationColumn import com.orange.ods.app.ui.utilities.composable.FunctionCallCode import com.orange.ods.compose.OdsComposable import com.orange.ods.compose.component.textfield.OdsIconTrailing import com.orange.ods.compose.component.textfield.OdsTextField import com.orange.ods.compose.component.textfield.OdsTextFieldCharacterCounter import com.orange.ods.compose.component.textfield.OdsTextTrailing @Composable fun TextField(customizationState: TextFieldCustomizationState) { val context = LocalContext.current val trailingIconName = stringResource(id = R.string.component_element_trailing) val modifier = Modifier .fillMaxWidth() .padding(top = dimensionResource(id = com.orange.ods.R.dimen.spacing_s)) with(customizationState) { val leadingIcon = if (hasLeadingIcon) painterResource(id = R.drawable.ic_heart) else null val errorMessage = if (isError) stringResource(id = R.string.component_text_field_error_message) else null val onValueChange: (String) -> Unit = { updateText(it) } val label = stringResource(id = R.string.component_element_label) val placeholder = stringResource(id = R.string.component_text_field_placeholder) val characterCounter: (@Composable () -> Unit)? = if (hasCharacterCounter) { { TextFieldCharacterCounter(valueLength = displayedText.length, enabled = isEnabled) } } else null val hasTrailing = hasTrailingText || hasTrailingIcon Column { if (hasTrailing) { OdsTextField( modifier = modifier, leadingIcon = leadingIcon, enabled = isEnabled, isError = isError, errorMessage = errorMessage, value = displayedText, onValueChange = onValueChange, label = label, placeholder = placeholder, trailing = if (hasTrailingIcon) { OdsIconTrailing( painter = painterResource(id = com.orange.ods.R.drawable.ic_eye), onClick = { clickOnElement(context = context, trailingIconName) }) } else { OdsTextTrailing(text = "units") }, singleLine = isSingleLine, keyboardOptions = keyboardOptions, characterCounter = characterCounter ) } else { OdsTextField( modifier = modifier, leadingIcon = leadingIcon, enabled = isEnabled, isError = isError, errorMessage = errorMessage, value = displayedText, onValueChange = onValueChange, label = label, placeholder = placeholder, singleLine = isSingleLine, keyboardOptions = keyboardOptions, characterCounter = characterCounter ) } TextFieldCodeImplementationColumn( componentName = OdsComposable.OdsTextField.name, customizationState = customizationState, label = label, placeholder = placeholder, errorMessage = errorMessage, hasTrailing = hasTrailing ) } } } @Composable fun TextFieldCharacterCounter(valueLength: Int, enabled: Boolean) { OdsTextFieldCharacterCounter( valueLength = valueLength, maxChars = TextFieldMaxChars, enabled = enabled ) } @Composable fun TextFieldCodeImplementationColumn( componentName: String, customizationState: TextFieldCustomizationState, label: String, placeholder: String, errorMessage: String?, hasTrailing: Boolean ) { with(customizationState) { val capitalizationValue = if (softKeyboardCapitalization.value) KeyboardCapitalization.Characters.toString() else KeyboardCapitalization.None.toString() CodeImplementationColumn { FunctionCallCode( name = componentName, exhaustiveParameters = false, parameters = { string("value", displayedText) lambda("onValueChange") label(label) placeholder(placeholder) classInstance("keyboardOptions", KeyboardOptions::class.java) { simple("capitalization", capitalizationValue) stringRepresentation("keyboardType", softKeyboardType.value.keyboardType) stringRepresentation("imeAction", softKeyboardAction.value.imeAction) } if (hasLeadingIcon) icon() if (!hasVisualisationIcon) stringRepresentation("visualisationIcon", false) if (!isEnabled) enabled(false) if (isError) { stringRepresentation("isError", true) errorMessage?.let { string("errorMessage", it) } } if (isSingleLine) stringRepresentation("singleLine", true) if (hasTrailing) simple("trailing", "<trailing composable>") if (hasCharacterCounter) { function("characterCounter", OdsComposable.OdsTextFieldCharacterCounter.name) { stringRepresentation("valueLength", displayedText.length) enabled(isEnabled) } } }) } } }
86
null
7
8
9e99ed5d398a4a4fa6a8d719a10f2f0061cb50e5
6,844
ods-android
MIT License
2022/project/src/test/kotlin/Day09KtTest.kt
ric2b
159,961,626
false
{"TypeScript": 144924, "Haskell": 117945, "Kotlin": 97335, "Svelte": 89864, "HTML": 3763, "JavaScript": 3612}
import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class Day09KtTest { private val testInput = """ R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 """.trimIndent() val myInput = this::class.java.classLoader.getResource("day09.txt")!!.readText() @Test fun `test part 1 with example`() = assertEquals(13, day09.part1(testInput)) @Test fun `test part 1 with my input`() = assertEquals(6209, day09.part1(myInput)) @Test fun `test part 2 with example`() = assertEquals(1, day09.part2(testInput)) @Test fun `test part 2 with larger example`() { val largerInput = """ R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 """.trimIndent() assertEquals(36, day09.part2(largerInput)) } @Test fun `test part 2 with my input`() = assertEquals(2460, day09.part2(myInput)) }
0
TypeScript
0
0
04b68836b582c241e6c854b40b6be35d406a2c7e
1,088
advent-of-code
MIT License
src/main/kotlin/org/jire/strukt/internal/FindDelegate.kt
Jire
69,727,181
false
{"Gradle": 2, "Shell": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Java Properties": 1, "Java": 1, "Kotlin": 16}
/* * Copyright 2016 <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 org.jire.strukt.internal import kotlin.reflect.KClass import kotlin.reflect.declaredMemberProperties import kotlin.reflect.jvm.javaField inline fun <reified T : Any, DELEGATE : Any> findDelegate( instance: T, delegatingTo: KClass<DELEGATE>): DELEGATE? { for (prop in T::class.declaredMemberProperties) { val javaField = prop.javaField ?: continue if (delegatingTo.java.isAssignableFrom(javaField.type)) { javaField.isAccessible = true @Suppress("UNCHECKED_CAST") return javaField.get(instance) as DELEGATE } } return null }
1
null
1
1
1885867ce96af26cc3bb709397a43cc37b110459
1,148
Strukt-Old
Apache License 2.0
app/src/main/java/com/inz/z/note_book/database/controller/TaskInfoController.kt
Memory-Z
234,554,362
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "Java": 94, "Kotlin": 161, "XML": 301, "INI": 2}
package com.inz.z.note_book.database.controller import com.inz.z.note_book.database.TaskInfoDao import com.inz.z.note_book.database.bean.TaskInfo import com.inz.z.note_book.database.util.GreenDaoHelper /** * 任务控制 * * @author Zhenglj * @version 1.0.0 * Create by inz in 2020/05/13 13:57. */ object TaskInfoController { private fun getTaskInfoDao(): TaskInfoDao? { return GreenDaoHelper.getInstance().getDaoSession()?.taskInfoDao } /** * 添加任务 */ fun insertTaskInfo(taskInfo: TaskInfo) { val dao = getTaskInfoDao() if (dao != null) { val taskId = taskInfo.taskId val t = queryTaskInfoById(taskId) if (t == null) { dao.insert(taskInfo) LogController.log("insert", taskInfo, "添加任务", dao.tablename) } else { updateTaskInfo(taskInfo) } } } fun queryTaskInfoById(taskId: String): TaskInfo? = getTaskInfoDao()?.queryBuilder()?.where(TaskInfoDao.Properties.TaskId.eq(taskId))?.unique() fun updateTaskInfo(taskInfo: TaskInfo) { val dao = getTaskInfoDao() if (dao != null) { dao.update(taskInfo) LogController.log("update", taskInfo, "更新任务", dao.tablename) } } }
1
null
1
1
387a68ede15df55eb95477515452f415fdd23e19
1,302
NoteBook
Apache License 2.0
app/src/main/java/com/example/pedro/feedsense/models/Session.kt
mugbug
144,412,118
false
null
package com.example.pedro.feedsense.models import java.util.* data class SessionModel( val pin: String, val time: Date, val owner: String, val isActive: Boolean)
0
Kotlin
1
2
3286f82b545d1feec10a714dbf50d0a760c536c9
195
feedsense
MIT License
core/src/test/java/com/facebook/ktfmt/kdoc/KDocFormatterTest.kt
facebook
218,383,922
false
null
/* * Portions Copyright (c) Meta Platforms, Inc. and affiliates. * * 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. */ /* * Copyright (c) <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.facebook.ktfmt.kdoc import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import kotlin.io.path.createTempDirectory import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class KDocFormatterTest { private val tempDir = createTempDirectory().toFile() private fun checkFormatter( task: FormattingTask, expected: String, verify: Boolean = true, verifyDokka: Boolean = true, ) { val reformatted = reformatComment(task) val indent = task.initialIndent val options = task.options val source = task.comment // Because .trimIndent() will remove it: val indentedExpected = expected.split("\n").joinToString("\n") { indent + it } assertThat(reformatted).isEqualTo(indentedExpected) if (verifyDokka && !options.addPunctuation) { DokkaVerifier(tempDir).verify(source, reformatted) } // Make sure that formatting is stable -- format again and make sure it's the same if (verify) { val again = FormattingTask( options, reformatted.trim(), task.initialIndent, task.secondaryIndent, task.orderedParameterNames) val formattedAgain = reformatComment(again) if (reformatted != formattedAgain) { assertWithMessage("Formatting is unstable: if formatted a second time, it changes") .that("$indent// FORMATTED TWICE (implies unstable formatting)\n\n$formattedAgain") .isEqualTo("$indent// FORMATTED ONCE\n\n$reformatted") } } } private fun checkFormatter( source: String, options: KDocFormattingOptions, expected: String, indent: String = " ", verify: Boolean = true, verifyDokka: Boolean = true ) { val task = FormattingTask(options, source.trim(), indent) checkFormatter(task, expected, verify, verifyDokka) } private fun reformatComment(task: FormattingTask): String { val formatter = KDocFormatter(task.options) val formatted = formatter.reformatComment(task) return task.initialIndent + formatted } @Test fun test1() { checkFormatter( """ /** * Returns whether lint should check all warnings, * including those off by default, or null if *not configured in this configuration. This is a really really really long sentence which needs to be broken up. * And ThisIsALongSentenceWhichCannotBeBrokenUpAndMustBeIncludedAsAWholeWithoutNewlinesInTheMiddle. * * This is a separate section * which should be flowed together with the first one. * *bold* should not be removed even at beginning. */ """ .trimIndent(), KDocFormattingOptions(72), """ /** * Returns whether lint should check all warnings, including those * off by default, or null if not configured in this configuration. * This is a really really really long sentence which needs to be * broken up. And * ThisIsALongSentenceWhichCannotBeBrokenUpAndMustBeIncludedAsAWholeWithoutNewlinesInTheMiddle. * * This is a separate section which should be flowed together with * the first one. *bold* should not be removed even at beginning. */ """ .trimIndent()) } @Test fun testWithOffset() { val source = """ /** Returns whether lint should check all warnings, * including those off by default */ """ .trimIndent() val reformatted = """ /** * Returns whether lint should check all warnings, including those * off by default */ """ .trimIndent() checkFormatter(source, KDocFormattingOptions(72), reformatted, indent = " ") val initialOffset = source.indexOf("default") val newOffset = findSamePosition(source, initialOffset, reformatted) assertThat(newOffset).isNotEqualTo(initialOffset) assertThat(reformatted.substring(newOffset, newOffset + "default".length)).isEqualTo("default") } @Test fun testWordBreaking() { // Without special handling, the "-" in the below would be placed at the // beginning of line 2, which then implies a list item. val source = """ /** Returns whether lint should check all warnings, * including aaaaaa - off by default */ """ .trimIndent() val reformatted = """ /** * Returns whether lint should check all warnings, including * aaaaaa - off by default */ """ .trimIndent() checkFormatter(source, KDocFormattingOptions(72), reformatted, indent = " ") val initialOffset = source.indexOf("default") val newOffset = findSamePosition(source, initialOffset, reformatted) assertThat(newOffset).isNotEqualTo(initialOffset) assertThat(reformatted.substring(newOffset, newOffset + "default".length)).isEqualTo("default") } @Test fun testHeader() { val source = """ /** * Information about a request to run lint. * * **NOTE: This is not a public or final API; if you rely on this be prepared * to adjust your code for the next tools release.** */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Information about a request to run lint. * * **NOTE: This is not a public or final API; if you rely on this be * prepared to adjust your code for the next tools release.** */ """ .trimIndent()) checkFormatter( source, KDocFormattingOptions(40), """ /** * Information about a request to run * lint. * * **NOTE: This is not a public or final * API; if you rely on this be prepared * to adjust your code for the next * tools release.** */ """ .trimIndent(), indent = "") checkFormatter( source, KDocFormattingOptions(100, 100), """ /** * Information about a request to run lint. * * **NOTE: This is not a public or final API; if you rely on this be prepared to adjust your code * for the next tools release.** */ """ .trimIndent(), indent = "") } @Test fun testSingle() { val source = """ /** * The lint client requesting the lint check * * @return the client, never null */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * The lint client requesting the lint check * * @return the client, never null */ """ .trimIndent()) } @Test fun testEmpty() { val source = """ /** */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** */ """ .trimIndent()) checkFormatter( source, KDocFormattingOptions(72).apply { collapseSingleLine = false }, """ /** */ """ .trimIndent()) } @Test fun testJavadocParams() { val source = """ /** * Sets the scope to use; lint checks which require a wider scope set * will be ignored * * @param scope the scope * * @return this, for constructor chaining */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Sets the scope to use; lint checks which require a wider scope * set will be ignored * * @param scope the scope * @return this, for constructor chaining */ """ .trimIndent()) } @Test fun testBracketParam() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/72 val source = """ /** * Summary * @param [ param1 ] some value * @param[param2] another value */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Summary * * @param param1 some value * @param param2 another value */ """ .trimIndent()) } @Test fun testMultiLineLink() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/70 val source = """ /** * Single line is converted {@link foo} * * Multi line is converted {@link * foo} * * Single line with hash is converted {@link #foo} * * Multi line with has is converted {@link * #foo} * * Don't interpret {@code * # This is not a header * * this is * * not a nested list * } */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Single line is converted [foo] * * Multi line is converted [foo] * * Single line with hash is converted [foo] * * Multi line with has is converted [foo] * * Don't interpret {@code # This is not a header * this is * not a * nested list } */ """ .trimIndent(), // {@link} text is not rendered by dokka when it cannot resolve the symbols verifyDokka = false) } @Test fun testPreformattedWithinCode() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/77 val source = """ /** * Some summary. * {@code * * foo < bar?} * Done. * * * {@code * ``` * Some code. * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Some summary. {@code * * foo < bar?} Done. * * {@code * * ``` * Some code. * ``` */ """ .trimIndent()) } @Test fun testPreStability() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/78 val source = """ /** * Some summary * * <pre> * line one * ``` * line two * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Some summary * <pre> * line one * ``` * line two * ``` */ """ .trimIndent()) } @Test fun testPreStability2() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/78 // (second scenario val source = """ /** * Some summary * * <pre> * ``` * code * ``` * </pre> */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Some summary * <pre> * ``` * code * ``` * </pre> */ """ .trimIndent()) } @Test fun testConvertParamReference() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/79 val source = """ /** * Some summary. * * Another summary about {@param someParam}. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * Some summary. * * Another summary about [someParam]. */ """ .trimIndent(), // {@param reference} text is not rendered by dokka when it cannot resolve the symbols verifyDokka = false) } @Test fun testLineWidth1() { // Perform in KDocFileFormatter test too to make sure we properly account // for indent! val source = """ /** * 89 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 * * 10 20 30 40 50 60 70 80 */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * 89 123456789 123456789 123456789 123456789 123456789 123456789 * 123456789 123456789 * * 10 20 30 40 50 60 70 80 */ """ .trimIndent()) checkFormatter( source, KDocFormattingOptions(40), """ /** * 89 123456789 123456789 123456789 * 123456789 123456789 123456789 * 123456789 123456789 * * 10 20 30 40 50 60 70 80 */ """ .trimIndent()) } @Test fun testBlockTagsNoSeparators() { checkFormatter( """ /** * Marks the given warning as "ignored". * * @param context The scanning context * @param issue the issue to be ignored * @param location The location to ignore the warning at, if any * @param message The message for the warning */ """ .trimIndent(), KDocFormattingOptions(72), """ /** * Marks the given warning as "ignored". * * @param context The scanning context * @param issue the issue to be ignored * @param location The location to ignore the warning at, if any * @param message The message for the warning */ """ .trimIndent()) } @Test fun testBlockTagsHangingIndents() { val options = KDocFormattingOptions(40) options.hangingIndent = 6 checkFormatter( """ /** * Creates a list of class entries from the given class path and specific set of files within * it. * * @param client the client to report errors to and to use to read files * @param classFiles the specific set of class files to look for * @param classFolders the list of class folders to look in (to determine the package root) * @param sort if true, sort the results * @return the list of class entries, never null. */ """ .trimIndent(), options, """ /** * Creates a list of class entries * from the given class path and * specific set of files within it. * * @param client the client to * report errors to and to use * to read files * @param classFiles the specific * set of class files to look * for * @param classFolders the list of * class folders to look in * (to determine the package * root) * @param sort if true, sort the * results * @return the list of class * entries, never null. */ """ .trimIndent()) } @Test fun testGreedyBlockIndent() { val options = KDocFormattingOptions(100, 72) options.hangingIndent = 6 checkFormatter( """ /** * Returns the project resources, if available * * @param includeModuleDependencies if true, include merged view of * all module dependencies * @param includeLibraries if true, include merged view of all * library dependencies (this also requires all module dependencies) * @return the project resources, or null if not available */ """ .trimIndent(), options, """ /** * Returns the project resources, if available * * @param includeModuleDependencies if true, include merged view of all * module dependencies * @param includeLibraries if true, include merged view of all library * dependencies (this also requires all module dependencies) * @return the project resources, or null if not available */ """ .trimIndent()) } @Test fun testBlockTagsHangingIndents2() { checkFormatter( """ /** * @param client the client to * report errors to and to use to * read files */ """ .trimIndent(), KDocFormattingOptions(40), """ /** * @param client the client to * report errors to and to use to * read files */ """ .trimIndent()) } @Test fun testSingleLine() { // Also tests punctuation feature. val source = """ /** * This could all fit on one line */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** This could all fit on one line */ """ .trimIndent()) val options = KDocFormattingOptions(72) options.collapseSingleLine = false options.addPunctuation = true checkFormatter( source, options, """ /** * This could all fit on one line. */ """ .trimIndent()) } @Test fun testPunctuationWithLabelLink() { val source = """ /** Default implementation of [MyInterface] */ """ .trimIndent() val options = KDocFormattingOptions(72) options.addPunctuation = true checkFormatter( source, options, """ /** Default implementation of [MyInterface]. */ """ .trimIndent()) } @Test fun testWrapingOfLinkText() { val source = """ /** * Sometimes the text of a link can have spaces, like [this link's text](https://example.com). * The following text should wrap like usual. */ """ .trimIndent() val options = KDocFormattingOptions(72) checkFormatter( source, options, """ /** * Sometimes the text of a link can have spaces, like * [this link's text](https://example.com). The following text * should wrap like usual. */ """ .trimIndent()) } @Test fun testPreformattedTextIndented() { val source = """ /** * Parser for the list of forward socket connection returned by the * `host:forward-list` command. * * Input example * * ``` * * HT75B1A00212 tcp:51222 tcp:5000 HT75B1A00212 tcp:51227 tcp:5001 * HT75B1A00212 tcp:51232 tcp:5002 HT75B1A00212 tcp:51239 tcp:5003 * HT75B1A00212 tcp:51244 tcp:5004 * * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72).apply { convertMarkup = true }, source, indent = "") } @Test fun testPreformattedText() { val source = """ /** * Code sample: * * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * * This is not preformatted and can be combined into multiple sentences again. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * Code sample: * * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * * This is not preformatted and * can be combined into multiple * sentences again. */ """ .trimIndent()) } @Test fun testPreformattedText2() { val source = """ /** * Code sample: * ```kotlin * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * ``` * * This is not preformatted and can be combined into multiple sentences again. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * Code sample: * ```kotlin * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * ``` * * This is not preformatted and * can be combined into multiple * sentences again. */ """ .trimIndent()) } @Test fun testPreformattedText3() { val source = """ /** * Code sample: * <PRE> * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * </pre> * This is not preformatted and can be combined into multiple sentences again. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * Code sample: * ``` * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * ``` * * This is not preformatted and * can be combined into multiple * sentences again. */ """ .trimIndent(), // <pre> and ``` are rendered differently; this is an intentional diff verifyDokka = false) } @Test fun testPreformattedTextWithBlankLines() { val source = """ /** * Code sample: * ```kotlin * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * * println(s); * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * Code sample: * ```kotlin * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * * println(s); * ``` */ """ .trimIndent()) } @Test fun testPreformattedTextWithBlankLinesAndTrailingSpaces() { val source = """ /** * Code sample: * ```kotlin * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * * println(s); * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * Code sample: * ```kotlin * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * * println(s); * ``` */ """ .trimIndent()) } @Test fun testPreformattedTextSeparation() { val source = """ /** * For example, * * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * And here's another example: * This is not preformatted text. * * And a third example, * * ``` * Preformatted. * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * For example, * * val s = "hello, and this is code so should not be line broken at all, it should stay on one line"; * println(s); * * And here's another example: This * is not preformatted text. * * And a third example, * ``` * Preformatted. * ``` */ """ .trimIndent()) } @Test fun testSeparateParagraphMarkers1() { // If the markup still contains HTML paragraph separators, separate // paragraphs val source = """ /** * Here's paragraph 1. * * And here's paragraph 2. * <p>And here's paragraph 3. * <P/>And here's paragraph 4. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40).apply { convertMarkup = true }, """ /** * Here's paragraph 1. * * And here's paragraph 2. * * And here's paragraph 3. * * And here's paragraph 4. */ """ .trimIndent()) } @Test fun testSeparateParagraphMarkers2() { // From ktfmt Tokenizer.kt val source = """ /** * Tokenizer traverses a Kotlin parse tree (which blessedly contains whitespaces and comments, * unlike Javac) and constructs a list of 'Tok's. * * <p>The google-java-format infra expects newline Toks to be separate from maximal-whitespace Toks, * but Kotlin emits them together. So, we split them using Java's \R regex matcher. We don't use * 'split' et al. because we want Toks for the newlines themselves. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100, 100).apply { convertMarkup = true optimal = false }, """ /** * Tokenizer traverses a Kotlin parse tree (which blessedly contains whitespaces and comments, * unlike Javac) and constructs a list of 'Tok's. * * The google-java-format infra expects newline Toks to be separate from maximal-whitespace Toks, * but Kotlin emits them together. So, we split them using Java's \R regex matcher. We don't use * 'split' et al. because we want Toks for the newlines themselves. */ """ .trimIndent(), indent = "") } @Test fun testConvertMarkup() { // If the markup still contains HTML paragraph separators, separate // paragraphs val source = """ /** * This is <b>bold</b>, this is <i>italics</i>, but nothing * should be converted in `<b>code</b>` or in * ``` * <i>preformatted text</i> * ``` * And this \` is <b>not code and should be converted</b>. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40).apply { convertMarkup = true }, """ /** * This is **bold**, this is * *italics*, but nothing should be * converted in `<b>code</b>` or in * * ``` * <i>preformatted text</i> * ``` * * And this \` is **not code and * should be converted**. */ """ .trimIndent()) } @Test fun testFormattingList() { val source = """ /** * 1. This is a numbered list. * 2. This is another item. We should be wrapping extra text under the same item. * 3. This is the third item. * * Unordered list: * * First * * Second * * Third * * Other alternatives: * - First * - Second */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * 1. This is a numbered list. * 2. This is another item. We * should be wrapping extra text * under the same item. * 3. This is the third item. * * Unordered list: * * First * * Second * * Third * * Other alternatives: * - First * - Second */ """ .trimIndent()) } @Test fun testList1() { val source = """ /** * * pre.errorlines: General > Text > Default Text * * .prefix: XML > Namespace Prefix * * .attribute: XML > Attribute name * * .value: XML > Attribute value * * .tag: XML > Tag name * * .lineno: For color, General > Code > Line number, Foreground, and for background-color, * Editor > Gutter background * * .error: General > Errors and Warnings > Error */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * * pre.errorlines: General > * Text > Default Text * * .prefix: XML > Namespace Prefix * * .attribute: XML > Attribute * name * * .value: XML > Attribute value * * .tag: XML > Tag name * * .lineno: For color, General > * Code > Line number, Foreground, * and for background-color, * Editor > Gutter background * * .error: General > Errors and * Warnings > Error */ """ .trimIndent()) } @Test fun testIndentedList() { val source = """ /** * Basic usage: * 1. Create a configuration via [UastEnvironment.Configuration.create] and mutate it as needed. * 2. Create a project environment via [UastEnvironment.create]. * You can create multiple environments in the same process (one for each "module"). * 3. Call [analyzeFiles] to initialize PSI machinery and precompute resolve information. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * Basic usage: * 1. Create a configuration via * [UastEnvironment.Configuration.create] * and mutate it as needed. * 2. Create a project environment * via [UastEnvironment.create]. * You can create multiple * environments in the same * process (one for each * "module"). * 3. Call [analyzeFiles] to * initialize PSI machinery and * precompute resolve * information. */ """ .trimIndent()) } @Test fun testDocTags() { val source = """ /** * @param configuration the configuration to look up which issues are * enabled etc from * @param platforms the platforms applying to this analysis */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * @param configuration the * configuration to look up which * issues are enabled etc from * @param platforms the platforms * applying to this analysis */ """ .trimIndent()) } @Test fun testAtInMiddle() { val source = """ /** * If non-null, this issue can **only** be suppressed with one of the * given annotations: not with @Suppress, not with @SuppressLint, not * with lint.xml, not with lintOptions{} and not with baselines. * * Test @IntRange and @FloatRange support annotation applied to * arrays and vargs. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * If non-null, this issue can **only** be suppressed with * one of the given annotations: not with @Suppress, not * with @SuppressLint, not with lint.xml, not with lintOptions{} and * not with baselines. * * Test @IntRange and @FloatRange support annotation applied to * arrays and vargs. */ """ .trimIndent(), ) } @Test fun testMaxCommentWidth() { checkFormatter( """ /** * Returns whether lint should check all warnings, * including those off by default, or null if *not configured in this configuration. This is a really really really long sentence which needs to be broken up. * This is a separate section * which should be flowed together with the first one. * *bold* should not be removed even at beginning. */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 30), """ /** * Returns whether lint should * check all warnings, including * those off by default, or * null if not configured in * this configuration. This is * a really really really long * sentence which needs to be * broken up. This is a separate * section which should be flowed * together with the first one. * *bold* should not be removed * even at beginning. */ """ .trimIndent()) } @Test fun testHorizontalRuler() { checkFormatter( """ /** * This is a header. Should appear alone. * -------------------------------------- * * This should not be on the same line as the header. */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 30), """ /** * This is a header. Should * appear alone. * -------------------------------------- * This should not be on the same * line as the header. */ """ .trimIndent(), verifyDokka = false) } @Test fun testQuoteOnlyOnFirstLine() { checkFormatter( """ /** * More: * > This whole paragraph should be treated as a block quote. * This whole paragraph should be treated as a block quote. * This whole paragraph should be treated as a block quote. * This whole paragraph should be treated as a block quote. * @sample Sample */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 30), """ /** * More: * > This whole paragraph should * > be treated as a block quote. * > This whole paragraph should * > be treated as a block quote. * > This whole paragraph should * > be treated as a block quote. * > This whole paragraph should * > be treated as a block quote. * * @sample Sample */ """ .trimIndent()) } @Test fun testNoBreakUrl() { checkFormatter( """ /** * # Design * The splash screen icon uses the same specifications as * [Adaptive Icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 100), """ /** * # Design * The splash screen icon uses the same specifications as * [Adaptive Icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) */ """ .trimIndent()) } @Test fun testAsciiArt() { // Comment from // https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-master-dev:build-system/integration-test/application/src/test/java/com/android/build/gradle/integration/bundle/DynamicFeatureAndroidTestBuildTest.kt checkFormatter( """ /** * Base <------------ Middle DF <------------- DF <--------- Android Test DF * / \ / \ | / \ \ * v v v v v v \ \ * appLib sharedLib midLib sharedMidLib featureLib testFeatureLib \ \ * ^ ^_______________________________________/ / * |________________________________________________________________/ * * DF has a feature-on-feature dep on Middle DF, both depend on Base, Android Test DF is an * android test variant for DF. * * Base depends on appLib and sharedLib. * Middle DF depends on midLib and sharedMidLib. * DF depends on featureLib. * DF also has an android test dependency on testFeatureLib, shared and sharedMidLib. */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 30), """ /** * Base <------------ Middle DF <------------- DF <--------- Android Test DF * / \ / \ | / \ \ * v v v v v v \ \ * appLib sharedLib midLib sharedMidLib featureLib testFeatureLib \ \ * ^ ^_______________________________________/ / * |________________________________________________________________/ * * DF has a feature-on-feature * dep on Middle DF, both depend * on Base, Android Test DF is an * android test variant for DF. * * Base depends on appLib and * sharedLib. Middle DF depends * on midLib and sharedMidLib. DF * depends on featureLib. DF also * has an android test dependency * on testFeatureLib, shared and * sharedMidLib. */ """ .trimIndent()) } @Test fun testAsciiArt2() { checkFormatter( """ /** * +-> lib1 * | * feature1 ---+-> javalib1 * | * +-> baseModule */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 30), """ /** * +-> lib1 * | * feature1 ---+-> javalib1 * | * +-> baseModule */ """ .trimIndent()) } @Test fun testAsciiArt3() { val source = """ /** * This test creates a layout of this shape: * * --------------- * | t | | * | | | * | |-------| | * | | t | | * | | | | * | | | | * |--| |-------| * | | | t | * | | | | * | | | | * | |--| | * | | | * --------------- * * There are 3 staggered children and 3 pointers, the first is on child 1, the second is on * child 2 in a space that overlaps child 1, and the third is in a space in child 3 that * overlaps child 2. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 30), """ /** * This test creates a layout of * this shape: * --------------- * | t | | | | | | |-------| | | * | t | | | | | | | | | | |--| * |-------| | | | t | | | | | | * | | | | |--| | | | | * --------------- * There are 3 staggered children * and 3 pointers, the first is * on child 1, the second is * on child 2 in a space that * overlaps child 1, and the * third is in a space in child * 3 that overlaps child 2. */ """ .trimIndent(), indent = "") } @Test fun testBrokenAsciiArt() { // The first illustration has indentation 3, not 4, so isn't preformatted. // The formatter will garble this -- but so will Dokka! // From androidx' TwoDimensionalFocusTraversalOutTest.kt checkFormatter( """ /** * ___________________________ * | grandparent | * | _____________________ | * | | parent | | * | | _______________ | | ____________ * | | | focusedItem | | | | nextItem | * | | |______________| | | |___________| * | |____________________| | * |__________________________| * * __________________________ * | grandparent | * | ____________________ | * | | parent | | * | | ______________ | | * | | | focusedItem | | | * | | |_____________| | | * | |___________________| | * |_________________________| */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, 100), """ /** * ___________________________ | grandparent | | _____________________ | | | parent * | | | | _______________ | | ____________ | | | focusedItem | | | | nextItem | | | * |______________| | | |___________| | |____________________| | |__________________________| * * __________________________ * | grandparent | * | ____________________ | * | | parent | | * | | ______________ | | * | | | focusedItem | | | * | | |_____________| | | * | |___________________| | * |_________________________| */ """ .trimIndent(), verifyDokka = false) } @Test fun testHtmlLists() { checkFormatter( """ /** * <ul> * <li>Incremental merge will never clean the output. * <li>The inputs must be able to tell which changes to relative files have been made. * <li>Intermediate state must be saved between merges. * </ul> */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 60), """ /** * <ul> * <li>Incremental merge will never clean the output. * <li>The inputs must be able to tell which changes to * relative files have been made. * <li>Intermediate state must be saved between merges. * </ul> */ """ .trimIndent()) } @Test fun testVariousMarkup() { val source = """ /** * This document contains a bunch of markup examples * that I will use * to verify that things are handled * correctly via markdown. * * This is a header. Should appear alone. * -------------------------------------- * This should not be on the same line as the header. * * This is a header. Should appear alone. * - * This should not be on the same line as the header. * * This is a header. Should appear alone. * ====================================== * This should not be on the same line as the header. * * This is a header. Should appear alone. * = * This should not be on the same line as the header. * Note that we don't treat this as a header * because it's not on its own line. Instead * it's considered a separating line. * --- * More text. Should not be on the previous line. * * --- This usage of --- where it's not on its own * line should not be used as a header or separator line. * * List stuff: * 1. First item * 2. Second item * 3. Third item * * # Text styles # * **Bold**, *italics*. \*Not italics\*. * * ## More text styles * ~~strikethrough~~, _underlined_. * * ### Blockquotes # * * More: * > This whole paragraph should be treated as a block quote. * This whole paragraph should be treated as a block quote. * This whole paragraph should be treated as a block quote. * This whole paragraph should be treated as a block quote. * * ### Lists * Plus lists: * + First * + Second * + Third * * Dash lists: * - First * - Second * - Third * * List items with multiple paragraphs: * * * This is my list item. It has * text on many lines. * * This is a continuation of the first bullet. * * And this is the second. * * ### Code blocks in list items * * Escapes: I should look for cases where I place a number followed * by a period (or asterisk) at the beginning of a line and if so, * escape it: * * The meaning of life: * 42\. This doesn't seem to work in IntelliJ's markdown formatter. * * ### Horizontal rules * ********* * --------- * *** * * * * * - - - */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100, 100), """ /** * This document contains a bunch of markup examples that I will use to verify that things are * handled correctly via markdown. * * This is a header. Should appear alone. * -------------------------------------- * This should not be on the same line as the header. * * This is a header. Should appear alone. * - * This should not be on the same line as the header. * * This is a header. Should appear alone. * ====================================== * This should not be on the same line as the header. * * This is a header. Should appear alone. * = * This should not be on the same line as the header. Note that we don't treat this as a header * because it's not on its own line. Instead it's considered a separating line. * --- * More text. Should not be on the previous line. * * --- This usage of --- where it's not on its own line should not be used as a header or * separator line. * * List stuff: * 1. First item * 2. Second item * 3. Third item * * # Text styles # * **Bold**, *italics*. \*Not italics\*. * * ## More text styles * ~~strikethrough~~, _underlined_. * * ### Blockquotes # * * More: * > This whole paragraph should be treated as a block quote. This whole paragraph should be * > treated as a block quote. This whole paragraph should be treated as a block quote. This whole * > paragraph should be treated as a block quote. * * ### Lists * Plus lists: * + First * + Second * + Third * * Dash lists: * - First * - Second * - Third * * List items with multiple paragraphs: * * This is my list item. It has text on many lines. * * This is a continuation of the first bullet. * * And this is the second. * * ### Code blocks in list items * * Escapes: I should look for cases where I place a number followed by a period (or asterisk) at * the beginning of a line and if so, escape it: * * The meaning of life: 42\. This doesn't seem to work in IntelliJ's markdown formatter. * * ### Horizontal rules * ********* * --------- * *** * * * * * - - - */ """ .trimIndent()) } @Test fun testLineComments() { val source = """ // // Information about a request to run lint. // // **NOTE: This is not a public or final API; if you rely on this be prepared // to adjust your code for the next tools release.** // """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ // Information about a request to // run lint. // // **NOTE: This is not a public or // final API; if you rely on this be // prepared to adjust your code for // the next tools release.** """ .trimIndent()) } @Test fun testMoreLineComments() { val source = """ // Do not clean // this """ .trimIndent() checkFormatter( source, KDocFormattingOptions(70), """ // Do not clean this """ .trimIndent()) } @Test fun testListContinuations() { val source = """ /** * * This is my list item. It has * text on many lines. * * This is a continuation of the first bullet. * * And this is the second. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * * This is my list item. It has * text on many lines. * * This is a continuation of the * first bullet. * * And this is the second. */ """ .trimIndent()) } @Test fun testListContinuations2() { val source = "/**\n" + """ List items with multiple paragraphs: * This is my list item. It has text on many lines. This is a continuation of the first bullet. * And this is the second. """ .trimIndent() .split("\n") .joinToString(separator = "\n") { " * $it".trimEnd() } + "\n */" checkFormatter( source, KDocFormattingOptions(100), """ /** * List items with multiple paragraphs: * * This is my list item. It has text on many lines. * * This is a continuation of the first bullet. * * And this is the second. */ """ .trimIndent()) } @Test fun testAccidentalHeader() { val source = """ /** * Constructs a simplified version of the internal JVM description of the given method. This is * in the same format as {@link #getMethodDescription} above, the difference being we don't have * the actual PSI for the method type, we just construct the signature from the [method] name, * the list of [argumentTypes] and optionally include the [returnType]. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), // Note how this places the "#" in column 0 which will then // be re-interpreted as a header next time we format it! // Idea: @{link #} should become {@link#} or with a nbsp; """ /** * Constructs a simplified version of the internal JVM * description of the given method. This is in the same format as * [getMethodDescription] above, the difference being we don't * have the actual PSI for the method type, we just construct the * signature from the [method] name, the list of [argumentTypes] and * optionally include the [returnType]. */ """ .trimIndent(), // {@link} text is not rendered by dokka when it cannot resolve the symbols verifyDokka = false) } @Test fun testTODO() { val source = """ /** * Adds the given dependency graph (the output of the Gradle dependency task) * to be constructed when mocking a Gradle model for this project. * <p> * To generate this, run for example * <pre> * ./gradlew :app:dependencies * </pre> * and then look at the debugCompileClasspath (or other graph that you want * to model). * TODO: Adds the given dependency graph (the output of the Gradle dependency task) * to be constructed when mocking a Gradle model for this project. * TODO: More stuff to do here * @param dependencyGraph the graph description * @return this for constructor chaining * TODO: Consider looking at the localization="suggested" attribute in * the platform attrs.xml to catch future recommended attributes. * TODO: Also adds the given dependency graph (the output of the Gradle dependency task) * to be constructed when mocking a Gradle model for this project. * TODO(b/144576310): Cover multi-module search. * Searching in the search bar should show an option to change module if there are resources in it. * TODO(myldap): Cover filter usage. Eg: Look for a framework resource by enabling its filter. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72).apply { orderDocTags = true }, // Note how this places the "#" in column 0 which will then // be re-interpreted as a header next time we format it! // Idea: @{link #} should become {@link#} or with a nbsp; """ /** * Adds the given dependency graph (the output of the Gradle * dependency task) to be constructed when mocking a Gradle model * for this project. * * To generate this, run for example * * ``` * ./gradlew :app:dependencies * ``` * * and then look at the debugCompileClasspath (or other graph that * you want to model). * * @param dependencyGraph the graph description * @return this for constructor chaining * * TODO: Adds the given dependency graph (the output of the Gradle * dependency task) to be constructed when mocking a Gradle model * for this project. * TODO: More stuff to do here * TODO: Consider looking at the localization="suggested" attribute * in the platform attrs.xml to catch future recommended * attributes. * TODO: Also adds the given dependency graph (the output of the * Gradle dependency task) to be constructed when mocking a Gradle * model for this project. * TODO(b/144576310): Cover multi-module search. Searching in the * search bar should show an option to change module if there are * resources in it. * TODO(myldap): Cover filter usage. Eg: Look for a framework * resource by enabling its filter. */ """ .trimIndent(), // We indent TO-DO text deliberately, though this changes the structure to // make each item have its own paragraph which doesn't happen by default. // Working as intended. verifyDokka = false) } @Test fun testReorderTags() { val source = """ /** * Constructs a new location range for the given file, from start to * end. If the length of the range is not known, end may be null. * * @return Something * @sample Other * @param file the associated file (but see the documentation for * [Location.file] for more information on what the file * represents) * * @param end the ending position, or null * @param[ start ] the starting position, or null * @see More */ """ .trimIndent() checkFormatter( FormattingTask( KDocFormattingOptions(72), source, " ", orderedParameterNames = listOf("file", "start", "end")), // Note how this places the "#" in column 0 which will then // be re-interpreted as a header next time we format it! // Idea: @{link #} should become {@link#} or with a nbsp; """ /** * Constructs a new location range for the given file, from start to * end. If the length of the range is not known, end may be null. * * @param file the associated file (but see the documentation for * [Location.file] for more information on what the file * represents) * @param start the starting position, or null * @param end the ending position, or null * @return Something * @sample Other * @see More */ """ .trimIndent(), ) } @Test fun testKDocOrdering() { // From AndroidX' // frameworks/support/biometric/biometric-ktx/src/main/java/androidx/biometric/auth/CredentialAuthExtensions.kt val source = """ /** * Shows an authentication prompt to the user. * * @param host A wrapper for the component that will host the prompt. * @param crypto A cryptographic object to be associated with this authentication. * * @return [AuthenticationResult] for a successful authentication. * * @throws AuthPromptErrorException when an unrecoverable error has been encountered and * authentication has stopped. * @throws AuthPromptFailureException when an authentication attempt by the user has been rejected. * * @see CredentialAuthPrompt.authenticate( * AuthPromptHost host, * BiometricPrompt.CryptoObject, * AuthPromptCallback * ) * * @sample androidx.biometric.samples.auth.credentialAuth */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * Shows an authentication prompt to the user. * * @param host A wrapper for the component that will host the prompt. * @param crypto A cryptographic object to be associated with this * authentication. * @return [AuthenticationResult] for a successful authentication. * @throws AuthPromptErrorException when an unrecoverable error has been * encountered and authentication has stopped. * @throws AuthPromptFailureException when an authentication attempt by * the user has been rejected. * @sample androidx.biometric.samples.auth.credentialAuth * @see CredentialAuthPrompt.authenticate( AuthPromptHost host, * BiometricPrompt.CryptoObject, AuthPromptCallback ) */ """ .trimIndent(), indent = "", ) } @Test fun testHtml() { // Comment from lint's SourceCodeScanner class doc. Tests a number of // things -- markup conversion (<h2> to ##, <p> to blank lines), list item // indentation, trimming blank lines from the end, etc. val source = """ /** * Interface to be implemented by lint detectors that want to analyze * Java source files (or other similar source files, such as Kotlin files.) * <p> * There are several different common patterns for detecting issues: * <ul> * <li> Checking calls to a given method. For this see * {@link #getApplicableMethodNames()} and * {@link #visitMethodCall(JavaContext, UCallExpression, PsiMethod)}</li> * <li> Instantiating a given class. For this, see * {@link #getApplicableConstructorTypes()} and * {@link #visitConstructor(JavaContext, UCallExpression, PsiMethod)}</li> * <li> Referencing a given constant. For this, see * {@link #getApplicableReferenceNames()} and * {@link #visitReference(JavaContext, UReferenceExpression, PsiElement)}</li> * <li> Extending a given class or implementing a given interface. * For this, see {@link #applicableSuperClasses()} and * {@link #visitClass(JavaContext, UClass)}</li> * <li> More complicated scenarios: perform a general AST * traversal with a visitor. In this case, first tell lint which * AST node types you're interested in with the * {@link #getApplicableUastTypes()} method, and then provide a * {@link UElementHandler} from the {@link #createUastHandler(JavaContext)} * where you override the various applicable handler methods. This is * done rather than a general visitor from the root node to avoid * having to have every single lint detector (there are hundreds) do a full * tree traversal on its own.</li> * </ul> * <p> * {@linkplain SourceCodeScanner} exposes the UAST API to lint checks. * UAST is short for "Universal AST" and is an abstract syntax tree library * which abstracts away details about Java versus Kotlin versus other similar languages * and lets the client of the library access the AST in a unified way. * <p> * UAST isn't actually a full replacement for PSI; it <b>augments</b> PSI. * Essentially, UAST is used for the <b>inside</b> of methods (e.g. method bodies), * and things like field initializers. PSI continues to be used at the outer * level: for packages, classes, and methods (declarations and signatures). * There are also wrappers around some of these for convenience. * <p> * The {@linkplain SourceCodeScanner} interface reflects this fact. For example, * when you indicate that you want to check calls to a method named {@code foo}, * the call site node is a UAST node (in this case, {@link UCallExpression}, * but the called method itself is a {@link PsiMethod}, since that method * might be anywhere (including in a library that we don't have source for, * so UAST doesn't make sense.) * <p> * <h2>Migrating JavaPsiScanner to SourceCodeScanner</h2> * As described above, PSI is still used, so a lot of code will remain the * same. For example, all resolve methods, including those in UAST, will * continue to return PsiElement, not necessarily a UElement. For example, * if you resolve a method call or field reference, you'll get a * {@link PsiMethod} or {@link PsiField} back. * <p> * However, the visitor methods have all changed, generally to change * to UAST types. For example, the signature * {@link JavaPsiScanner#visitMethodCall(JavaContext, JavaElementVisitor, PsiMethodCallExpression, PsiMethod)} * should be changed to {@link SourceCodeScanner#visitMethodCall(JavaContext, UCallExpression, PsiMethod)}. * <p> * Similarly, replace {@link JavaPsiScanner#createPsiVisitor} with {@link SourceCodeScanner#createUastHandler}, * {@link JavaPsiScanner#getApplicablePsiTypes()} with {@link SourceCodeScanner#getApplicableUastTypes()}, etc. * <p> * There are a bunch of new methods on classes like {@link JavaContext} which lets * you pass in a {@link UElement} to match the existing {@link PsiElement} methods. * <p> * If you have code which does something specific with PSI classes, * the following mapping table in alphabetical order might be helpful, since it lists the * corresponding UAST classes. * <table> * <caption>Mapping between PSI and UAST classes</caption> * <tr><th>PSI</th><th>UAST</th></tr> * <tr><th>com.intellij.psi.</th><th>org.jetbrains.uast.</th></tr> * <tr><td>IElementType</td><td>UastBinaryOperator</td></tr> * <tr><td>PsiAnnotation</td><td>UAnnotation</td></tr> * <tr><td>PsiAnonymousClass</td><td>UAnonymousClass</td></tr> * <tr><td>PsiArrayAccessExpression</td><td>UArrayAccessExpression</td></tr> * <tr><td>PsiBinaryExpression</td><td>UBinaryExpression</td></tr> * <tr><td>PsiCallExpression</td><td>UCallExpression</td></tr> * <tr><td>PsiCatchSection</td><td>UCatchClause</td></tr> * <tr><td>PsiClass</td><td>UClass</td></tr> * <tr><td>PsiClassObjectAccessExpression</td><td>UClassLiteralExpression</td></tr> * <tr><td>PsiConditionalExpression</td><td>UIfExpression</td></tr> * <tr><td>PsiDeclarationStatement</td><td>UDeclarationsExpression</td></tr> * <tr><td>PsiDoWhileStatement</td><td>UDoWhileExpression</td></tr> * <tr><td>PsiElement</td><td>UElement</td></tr> * <tr><td>PsiExpression</td><td>UExpression</td></tr> * <tr><td>PsiForeachStatement</td><td>UForEachExpression</td></tr> * <tr><td>PsiIdentifier</td><td>USimpleNameReferenceExpression</td></tr> * <tr><td>PsiIfStatement</td><td>UIfExpression</td></tr> * <tr><td>PsiImportStatement</td><td>UImportStatement</td></tr> * <tr><td>PsiImportStaticStatement</td><td>UImportStatement</td></tr> * <tr><td>PsiJavaCodeReferenceElement</td><td>UReferenceExpression</td></tr> * <tr><td>PsiLiteral</td><td>ULiteralExpression</td></tr> * <tr><td>PsiLocalVariable</td><td>ULocalVariable</td></tr> * <tr><td>PsiMethod</td><td>UMethod</td></tr> * <tr><td>PsiMethodCallExpression</td><td>UCallExpression</td></tr> * <tr><td>PsiNameValuePair</td><td>UNamedExpression</td></tr> * <tr><td>PsiNewExpression</td><td>UCallExpression</td></tr> * <tr><td>PsiParameter</td><td>UParameter</td></tr> * <tr><td>PsiParenthesizedExpression</td><td>UParenthesizedExpression</td></tr> * <tr><td>PsiPolyadicExpression</td><td>UPolyadicExpression</td></tr> * <tr><td>PsiPostfixExpression</td><td>UPostfixExpression or UUnaryExpression</td></tr> * <tr><td>PsiPrefixExpression</td><td>UPrefixExpression or UUnaryExpression</td></tr> * <tr><td>PsiReference</td><td>UReferenceExpression</td></tr> * <tr><td>PsiReference</td><td>UResolvable</td></tr> * <tr><td>PsiReferenceExpression</td><td>UReferenceExpression</td></tr> * <tr><td>PsiReturnStatement</td><td>UReturnExpression</td></tr> * <tr><td>PsiSuperExpression</td><td>USuperExpression</td></tr> * <tr><td>PsiSwitchLabelStatement</td><td>USwitchClauseExpression</td></tr> * <tr><td>PsiSwitchStatement</td><td>USwitchExpression</td></tr> * <tr><td>PsiThisExpression</td><td>UThisExpression</td></tr> * <tr><td>PsiThrowStatement</td><td>UThrowExpression</td></tr> * <tr><td>PsiTryStatement</td><td>UTryExpression</td></tr> * <tr><td>PsiTypeCastExpression</td><td>UBinaryExpressionWithType</td></tr> * <tr><td>PsiWhileStatement</td><td>UWhileExpression</td></tr> * </table> * Note however that UAST isn't just a "renaming of classes"; there are * some changes to the structure of the AST as well. Particularly around * calls. * * <h3>Parents</h3> * In UAST, you get your parent {@linkplain UElement} by calling * {@code getUastParent} instead of {@code getParent}. This is to avoid * method name clashes on some elements which are both UAST elements * and PSI elements at the same time - such as {@link UMethod}. * <h3>Children</h3> * When you're going in the opposite direction (e.g. you have a {@linkplain PsiMethod} * and you want to look at its content, you should <b>not</b> use * {@link PsiMethod#getBody()}. This will only give you the PSI child content, * which won't work for example when dealing with Kotlin methods. * Normally lint passes you the {@linkplain UMethod} which you should be procesing * instead. But if for some reason you need to look up the UAST method * body from a {@linkplain PsiMethod}, use this: * <pre> * UastContext context = UastUtils.getUastContext(element); * UExpression body = context.getMethodBody(method); * </pre> * Similarly if you have a {@link PsiField} and you want to look up its field * initializer, use this: * <pre> * UastContext context = UastUtils.getUastContext(element); * UExpression initializer = context.getInitializerBody(field); * </pre> * * <h3>Call names</h3> * In PSI, a call was represented by a PsiCallExpression, and to get to things * like the method called or to the operand/qualifier, you'd first need to get * the "method expression". In UAST there is no method expression and this * information is available directly on the {@linkplain UCallExpression} element. * Therefore, here's how you'd change the code: * <pre> * &lt; call.getMethodExpression().getReferenceName(); * --- * &gt; call.getMethodName() * </pre> * <h3>Call qualifiers</h3> * Similarly, * <pre> * &lt; call.getMethodExpression().getQualifierExpression(); * --- * &gt; call.getReceiver() * </pre> * <h3>Call arguments</h3> * PSI had a separate PsiArgumentList element you had to look up before you could * get to the actual arguments, as an array. In UAST these are available directly on * the call, and are represented as a list instead of an array. * <pre> * &lt; PsiExpression[] args = call.getArgumentList().getExpressions(); * --- * &gt; List<UExpression> args = call.getValueArguments(); * </pre> * Typically you also need to go through your code and replace array access, * arg\[i], with list access, {@code arg.get(i)}. Or in Kotlin, just arg\[i]... * * <h3>Instanceof</h3> * You may have code which does something like "parent instanceof PsiAssignmentExpression" * to see if something is an assignment. Instead, use one of the many utilities * in {@link UastExpressionUtils} - such as {@link UastExpressionUtils#isAssignment(UElement)}. * Take a look at all the methods there now - there are methods for checking whether * a call is a constructor, whether an expression is an array initializer, etc etc. * * <h3>Android Resources</h3> * Don't do your own AST lookup to figure out if something is a reference to * an Android resource (e.g. see if the class refers to an inner class of a class * named "R" etc.) There is now a new utility class which handles this: * {@link ResourceReference}. Here's an example of code which has a {@link UExpression} * and wants to know it's referencing a R.styleable resource: * <pre> * ResourceReference reference = ResourceReference.get(expression); * if (reference == null || reference.getType() != ResourceType.STYLEABLE) { * return; * } * ... * </pre> * * <h3>Binary Expressions</h3> * If you had been using {@link PsiBinaryExpression} for things like checking comparator * operators or arithmetic combination of operands, you can replace this with * {@link UBinaryExpression}. <b>But you normally shouldn't; you should use * {@link UPolyadicExpression} instead</b>. A polyadic expression is just like a binary * expression, but possibly with more than two terms. With the old parser backend, * an expression like "A + B + C" would be represented by nested binary expressions * (first A + B, then a parent element which combined that binary expression with C). * However, this will now be provided as a {@link UPolyadicExpression} instead. And * the binary case is handled trivially without the need to special case it. * <h3>Method name changes</h3> * The following table maps some common method names and what their corresponding * names are in UAST. * <table> * <caption>Mapping between PSI and UAST method names</caption></caption> * <tr><th>PSI</th><th>UAST</th></tr> * <tr><td>getArgumentList</td><td>getValueArguments</td></tr> * <tr><td>getCatchSections</td><td>getCatchClauses</td></tr> * <tr><td>getDeclaredElements</td><td>getDeclarations</td></tr> * <tr><td>getElseBranch</td><td>getElseExpression</td></tr> * <tr><td>getInitializer</td><td>getUastInitializer</td></tr> * <tr><td>getLExpression</td><td>getLeftOperand</td></tr> * <tr><td>getOperationTokenType</td><td>getOperator</td></tr> * <tr><td>getOwner</td><td>getUastParent</td></tr> * <tr><td>getParent</td><td>getUastParent</td></tr> * <tr><td>getRExpression</td><td>getRightOperand</td></tr> * <tr><td>getReturnValue</td><td>getReturnExpression</td></tr> * <tr><td>getText</td><td>asSourceString</td></tr> * <tr><td>getThenBranch</td><td>getThenExpression</td></tr> * <tr><td>getType</td><td>getExpressionType</td></tr> * <tr><td>getTypeParameters</td><td>getTypeArguments</td></tr> * <tr><td>resolveMethod</td><td>resolve</td></tr> * </table> * <h3>Handlers versus visitors</h3> * If you are processing a method on your own, or even a full class, you should switch * from JavaRecursiveElementVisitor to AbstractUastVisitor. * However, most lint checks don't do their own full AST traversal; they instead * participate in a shared traversal of the tree, registering element types they're * interested with using {@link #getApplicableUastTypes()} and then providing * a visitor where they implement the corresponding visit methods. However, from * these visitors you should <b>not</b> be calling super.visitX. To remove this * whole confusion, lint now provides a separate class, {@link UElementHandler}. * For the shared traversal, just provide this handler instead and implement the * appropriate visit methods. It will throw an error if you register element types * in {@linkplain #getApplicableUastTypes()} that you don't override. * * <p> * <h3>Migrating JavaScanner to SourceCodeScanner</h3> * First read the javadoc on how to convert from the older {@linkplain JavaScanner} * interface over to {@linkplain JavaPsiScanner}. While {@linkplain JavaPsiScanner} is itself * deprecated, it's a lot closer to {@link SourceCodeScanner} so a lot of the same concepts * apply; then follow the above section. * <p> */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(120, 120), """ /** * Interface to be implemented by lint detectors that want to analyze Java source files (or other similar source * files, such as Kotlin files.) * * There are several different common patterns for detecting issues: * <ul> * <li> Checking calls to a given method. For this see [getApplicableMethodNames] and [visitMethodCall]</li> * <li> Instantiating a given class. For this, see [getApplicableConstructorTypes] and [visitConstructor]</li> * <li> Referencing a given constant. For this, see [getApplicableReferenceNames] and [visitReference]</li> * <li> Extending a given class or implementing a given interface. For this, see [applicableSuperClasses] and * [visitClass]</li> * <li> More complicated scenarios: perform a general AST traversal with a visitor. In this case, first tell lint * which AST node types you're interested in with the [getApplicableUastTypes] method, and then provide a * [UElementHandler] from the [createUastHandler] where you override the various applicable handler methods. This * is done rather than a general visitor from the root node to avoid having to have every single lint detector * (there are hundreds) do a full tree traversal on its own.</li> * </ul> * * {@linkplain SourceCodeScanner} exposes the UAST API to lint checks. UAST is short for "Universal AST" and is an * abstract syntax tree library which abstracts away details about Java versus Kotlin versus other similar languages * and lets the client of the library access the AST in a unified way. * * UAST isn't actually a full replacement for PSI; it **augments** PSI. Essentially, UAST is used for the **inside** * of methods (e.g. method bodies), and things like field initializers. PSI continues to be used at the outer level: * for packages, classes, and methods (declarations and signatures). There are also wrappers around some of these * for convenience. * * The {@linkplain SourceCodeScanner} interface reflects this fact. For example, when you indicate that you want to * check calls to a method named {@code foo}, the call site node is a UAST node (in this case, [UCallExpression], * but the called method itself is a [PsiMethod], since that method might be anywhere (including in a library that * we don't have source for, so UAST doesn't make sense.) * * ## Migrating JavaPsiScanner to SourceCodeScanner * As described above, PSI is still used, so a lot of code will remain the same. For example, all resolve methods, * including those in UAST, will continue to return PsiElement, not necessarily a UElement. For example, if you * resolve a method call or field reference, you'll get a [PsiMethod] or [PsiField] back. * * However, the visitor methods have all changed, generally to change to UAST types. For example, the signature * [JavaPsiScanner.visitMethodCall] should be changed to [SourceCodeScanner.visitMethodCall]. * * Similarly, replace [JavaPsiScanner.createPsiVisitor] with [SourceCodeScanner.createUastHandler], * [JavaPsiScanner.getApplicablePsiTypes] with [SourceCodeScanner.getApplicableUastTypes], etc. * * There are a bunch of new methods on classes like [JavaContext] which lets you pass in a [UElement] to match the * existing [PsiElement] methods. * * If you have code which does something specific with PSI classes, the following mapping table in alphabetical * order might be helpful, since it lists the corresponding UAST classes. * <table> * <caption>Mapping between PSI and UAST classes</caption> * <tr><th>PSI</th><th>UAST</th></tr> * <tr><th>com.intellij.psi.</th><th>org.jetbrains.uast.</th></tr> * <tr><td>IElementType</td><td>UastBinaryOperator</td></tr> * <tr><td>PsiAnnotation</td><td>UAnnotation</td></tr> * <tr><td>PsiAnonymousClass</td><td>UAnonymousClass</td></tr> * <tr><td>PsiArrayAccessExpression</td><td>UArrayAccessExpression</td></tr> * <tr><td>PsiBinaryExpression</td><td>UBinaryExpression</td></tr> * <tr><td>PsiCallExpression</td><td>UCallExpression</td></tr> * <tr><td>PsiCatchSection</td><td>UCatchClause</td></tr> * <tr><td>PsiClass</td><td>UClass</td></tr> * <tr><td>PsiClassObjectAccessExpression</td><td>UClassLiteralExpression</td></tr> * <tr><td>PsiConditionalExpression</td><td>UIfExpression</td></tr> * <tr><td>PsiDeclarationStatement</td><td>UDeclarationsExpression</td></tr> * <tr><td>PsiDoWhileStatement</td><td>UDoWhileExpression</td></tr> * <tr><td>PsiElement</td><td>UElement</td></tr> * <tr><td>PsiExpression</td><td>UExpression</td></tr> * <tr><td>PsiForeachStatement</td><td>UForEachExpression</td></tr> * <tr><td>PsiIdentifier</td><td>USimpleNameReferenceExpression</td></tr> * <tr><td>PsiIfStatement</td><td>UIfExpression</td></tr> * <tr><td>PsiImportStatement</td><td>UImportStatement</td></tr> * <tr><td>PsiImportStaticStatement</td><td>UImportStatement</td></tr> * <tr><td>PsiJavaCodeReferenceElement</td><td>UReferenceExpression</td></tr> * <tr><td>PsiLiteral</td><td>ULiteralExpression</td></tr> * <tr><td>PsiLocalVariable</td><td>ULocalVariable</td></tr> * <tr><td>PsiMethod</td><td>UMethod</td></tr> * <tr><td>PsiMethodCallExpression</td><td>UCallExpression</td></tr> * <tr><td>PsiNameValuePair</td><td>UNamedExpression</td></tr> * <tr><td>PsiNewExpression</td><td>UCallExpression</td></tr> * <tr><td>PsiParameter</td><td>UParameter</td></tr> * <tr><td>PsiParenthesizedExpression</td><td>UParenthesizedExpression</td></tr> * <tr><td>PsiPolyadicExpression</td><td>UPolyadicExpression</td></tr> * <tr><td>PsiPostfixExpression</td><td>UPostfixExpression or UUnaryExpression</td></tr> * <tr><td>PsiPrefixExpression</td><td>UPrefixExpression or UUnaryExpression</td></tr> * <tr><td>PsiReference</td><td>UReferenceExpression</td></tr> * <tr><td>PsiReference</td><td>UResolvable</td></tr> * <tr><td>PsiReferenceExpression</td><td>UReferenceExpression</td></tr> * <tr><td>PsiReturnStatement</td><td>UReturnExpression</td></tr> * <tr><td>PsiSuperExpression</td><td>USuperExpression</td></tr> * <tr><td>PsiSwitchLabelStatement</td><td>USwitchClauseExpression</td></tr> * <tr><td>PsiSwitchStatement</td><td>USwitchExpression</td></tr> * <tr><td>PsiThisExpression</td><td>UThisExpression</td></tr> * <tr><td>PsiThrowStatement</td><td>UThrowExpression</td></tr> * <tr><td>PsiTryStatement</td><td>UTryExpression</td></tr> * <tr><td>PsiTypeCastExpression</td><td>UBinaryExpressionWithType</td></tr> * <tr><td>PsiWhileStatement</td><td>UWhileExpression</td></tr> </table> Note however that UAST isn't just a * "renaming of classes"; there are some changes to the structure of the AST as well. Particularly around calls. * * ### Parents * In UAST, you get your parent {@linkplain UElement} by calling {@code getUastParent} instead of {@code getParent}. * This is to avoid method name clashes on some elements which are both UAST elements and PSI elements at the same * time - such as [UMethod]. * * ### Children * When you're going in the opposite direction (e.g. you have a {@linkplain PsiMethod} and you want to look at its * content, you should **not** use [PsiMethod.getBody]. This will only give you the PSI child content, which won't * work for example when dealing with Kotlin methods. Normally lint passes you the {@linkplain UMethod} which you * should be procesing instead. But if for some reason you need to look up the UAST method body from a {@linkplain * PsiMethod}, use this: * ``` * UastContext context = UastUtils.getUastContext(element); * UExpression body = context.getMethodBody(method); * ``` * * Similarly if you have a [PsiField] and you want to look up its field initializer, use this: * ``` * UastContext context = UastUtils.getUastContext(element); * UExpression initializer = context.getInitializerBody(field); * ``` * * ### Call names * In PSI, a call was represented by a PsiCallExpression, and to get to things like the method called or to the * operand/qualifier, you'd first need to get the "method expression". In UAST there is no method expression and * this information is available directly on the {@linkplain UCallExpression} element. Therefore, here's how you'd * change the code: * ``` * &lt; call.getMethodExpression().getReferenceName(); * --- * &gt; call.getMethodName() * ``` * * ### Call qualifiers * Similarly, * ``` * &lt; call.getMethodExpression().getQualifierExpression(); * --- * &gt; call.getReceiver() * ``` * * ### Call arguments * PSI had a separate PsiArgumentList element you had to look up before you could get to the actual arguments, as an * array. In UAST these are available directly on the call, and are represented as a list instead of an array. * * ``` * &lt; PsiExpression[] args = call.getArgumentList().getExpressions(); * --- * &gt; List<UExpression> args = call.getValueArguments(); * ``` * * Typically you also need to go through your code and replace array access, arg\[i], with list access, {@code * arg.get(i)}. Or in Kotlin, just arg\[i]... * * ### Instanceof * You may have code which does something like "parent instanceof PsiAssignmentExpression" to see if * something is an assignment. Instead, use one of the many utilities in [UastExpressionUtils] - such * as [UastExpressionUtils.isAssignment]. Take a look at all the methods there now - there are methods * for checking whether a call is a constructor, whether an expression is an array initializer, etc etc. * * ### Android Resources * Don't do your own AST lookup to figure out if something is a reference to an Android resource (e.g. see if the * class refers to an inner class of a class named "R" etc.) There is now a new utility class which handles this: * [ResourceReference]. Here's an example of code which has a [UExpression] and wants to know it's referencing a * R.styleable resource: * ``` * ResourceReference reference = ResourceReference.get(expression); * if (reference == null || reference.getType() != ResourceType.STYLEABLE) { * return; * } * ... * ``` * * ### Binary Expressions * If you had been using [PsiBinaryExpression] for things like checking comparator operators or arithmetic * combination of operands, you can replace this with [UBinaryExpression]. **But you normally shouldn't; you should * use [UPolyadicExpression] instead**. A polyadic expression is just like a binary expression, but possibly with * more than two terms. With the old parser backend, an expression like "A + B + C" would be represented by nested * binary expressions (first A + B, then a parent element which combined that binary expression with C). However, * this will now be provided as a [UPolyadicExpression] instead. And the binary case is handled trivially without * the need to special case it. * * ### Method name changes * The following table maps some common method names and what their corresponding names are in UAST. * <table> * <caption>Mapping between PSI and UAST method names</caption></caption> * <tr><th>PSI</th><th>UAST</th></tr> * <tr><td>getArgumentList</td><td>getValueArguments</td></tr> * <tr><td>getCatchSections</td><td>getCatchClauses</td></tr> * <tr><td>getDeclaredElements</td><td>getDeclarations</td></tr> * <tr><td>getElseBranch</td><td>getElseExpression</td></tr> * <tr><td>getInitializer</td><td>getUastInitializer</td></tr> * <tr><td>getLExpression</td><td>getLeftOperand</td></tr> * <tr><td>getOperationTokenType</td><td>getOperator</td></tr> * <tr><td>getOwner</td><td>getUastParent</td></tr> * <tr><td>getParent</td><td>getUastParent</td></tr> * <tr><td>getRExpression</td><td>getRightOperand</td></tr> * <tr><td>getReturnValue</td><td>getReturnExpression</td></tr> * <tr><td>getText</td><td>asSourceString</td></tr> * <tr><td>getThenBranch</td><td>getThenExpression</td></tr> * <tr><td>getType</td><td>getExpressionType</td></tr> * <tr><td>getTypeParameters</td><td>getTypeArguments</td></tr> * <tr><td>resolveMethod</td><td>resolve</td></tr> </table> * * ### Handlers versus visitors * If you are processing a method on your own, or even a full class, you should switch from * JavaRecursiveElementVisitor to AbstractUastVisitor. However, most lint checks don't do their own full AST * traversal; they instead participate in a shared traversal of the tree, registering element types they're * interested with using [getApplicableUastTypes] and then providing a visitor where they implement the * corresponding visit methods. However, from these visitors you should **not** be calling super.visitX. To remove * this whole confusion, lint now provides a separate class, [UElementHandler]. For the shared traversal, just * provide this handler instead and implement the appropriate visit methods. It will throw an error if you register * element types in {@linkplain #getApplicableUastTypes()} that you don't override. * * ### Migrating JavaScanner to SourceCodeScanner * First read the javadoc on how to convert from the older {@linkplain JavaScanner} interface over to {@linkplain * JavaPsiScanner}. While {@linkplain JavaPsiScanner} is itself deprecated, it's a lot closer to [SourceCodeScanner] * so a lot of the same concepts apply; then follow the above section. */ """ .trimIndent(), // {@link} tags are not rendered from [references] when Dokka cannot resolve the symbols verifyDokka = false) } @Test fun testPreserveParagraph() { // Make sure that when we convert <p>, it's preserved. val source = """ /** * <ul> * <li>test</li> * </ul> * <p> * After. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(120, 120), """ /** * <ul> * <li>test</li> * </ul> * * After. */ """ .trimIndent()) } @Test fun testWordJoining() { // "-" alone can mean beginning of a list, but not as part of a word val source = """ /** * which you can render with something like this: * `dot -Tpng -o/tmp/graph.png toString.dot` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(65), """ /** * which you can render with something like this: `dot -Tpng * -o/tmp/graph.png toString.dot` */ """ .trimIndent()) val source2 = """ /** * ABCDE which you can render with something like this: * `dot - Tpng -o/tmp/graph.png toString.dot` */ """ .trimIndent() checkFormatter( source2, KDocFormattingOptions(65), """ /** * ABCDE which you can render with something like this: * `dot - Tpng -o/tmp/graph.png toString.dot` */ """ .trimIndent()) } @Test fun testEarlyBreakForTodo() { // Don't break before a TODO val source = """ /** * This is a long line that will break a little early to breaking at TODO: * * This is a long line that wont break a little early to breaking at DODO: */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72).apply { optimal = false }, """ /** * This is a long line that will break a little early to breaking * at TODO: * * This is a long line that wont break a little early to breaking at * DODO: */ """ .trimIndent()) } @Test fun testPreformat() { // Don't join preformatted text with previous TODO comment val source = """ /** * TODO: Work. * ``` * Preformatted. * * More preformatted. * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * TODO: Work. * * ``` * Preformatted. * * More preformatted. * ``` */ """ .trimIndent()) } @Test fun testConvertLinks() { // Make sure we convert {@link} and NOT {@linkplain} if convertMarkup is true. val source = """ /** * {@link SourceCodeScanner} exposes the UAST API to lint checks. * The {@link SourceCodeScanner} interface reflects this fact. * * {@linkplain SourceCodeScanner} exposes the UAST API to lint checks. * The {@linkplain SourceCodeScanner} interface reflects this fact. * * It will throw an error if you register element types in * {@link #getApplicableUastTypes()} that you don't override. * * First read the javadoc on how to convert from the older {@link * JavaScanner} interface over to {@link JavaPsiScanner}. * * 1. A file header, which is the exact contents of {@link FILE_HEADER} encoded * as ASCII characters. * * Given an error message produced by this lint detector for the * given issue type, determines whether this corresponds to the * warning (produced by {@link #reportBaselineIssues(LintDriver, * Project)} above) that one or more issues have been * fixed (present in baseline but not in project.) * * {@link #getQualifiedName(PsiClass)} method. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * [SourceCodeScanner] exposes the UAST API to lint checks. The * [SourceCodeScanner] interface reflects this fact. * * {@linkplain SourceCodeScanner} exposes the UAST API to lint * checks. The {@linkplain SourceCodeScanner} interface reflects * this fact. * * It will throw an error if you register element types in * [getApplicableUastTypes] that you don't override. * * First read the javadoc on how to convert from the older * [JavaScanner] interface over to [JavaPsiScanner]. * 1. A file header, which is the exact contents of [FILE_HEADER] * encoded as ASCII characters. * * Given an error message produced by this lint detector for the * given issue type, determines whether this corresponds to the * warning (produced by [reportBaselineIssues] above) that one or * more issues have been fixed (present in baseline but not in * project.) * * [getQualifiedName] method. */ """ .trimIndent(), // When dokka cannot resolve the links it doesn't render {@link} which makes // before and after not match verifyDokka = false) } @Test fun testNestedBullets() { // Regression test for https://github.com/tnorbye/kdoc-formatter/issues/36 val source = """ /** * Paragraph * * Top Bullet * * Sub-Bullet 1 * * Sub-Bullet 2 * * Sub-Sub-Bullet 1 * 1. Top level * 1. First item * 2. Second item */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * Paragraph * * Top Bullet * * Sub-Bullet 1 * * Sub-Bullet 2 * * Sub-Sub-Bullet 1 * 1. Top level * 1. First item * 2. Second item */ """ .trimIndent()) checkFormatter( source, KDocFormattingOptions(72, 72).apply { nestedListIndent = 4 }, """ /** * Paragraph * * Top Bullet * * Sub-Bullet 1 * * Sub-Bullet 2 * * Sub-Sub-Bullet 1 * 1. Top level * 1. First item * 2. Second item */ """ .trimIndent()) } @Test fun testTripledQuotedPrefixNotBreakable() { // Corresponds to b/189247595 val source = """ /** * Gets current ABCD Workspace information from the output of ```abcdtools info```. * * Migrated from * http://com.example */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * Gets current ABCD Workspace information from the output * of ```abcdtools info```. * * Migrated from http://com.example */ """ .trimIndent()) } @Test fun testGreedyLineBreak() { // Make sure we correctly break at the max line width val source = """ /** * Handles a chain of qualified expressions, i.e. `a[5].b!!.c()[4].f()` * * This is by far the most complicated part of this formatter. We start by breaking the expression * to the steps it is executed in (which are in the opposite order of how the syntax tree is * built). * * We then calculate information to know which parts need to be groups, and finally go part by * part, emitting it to the [builder] while closing and opening groups. * * @param brokeBeforeBrace used for tracking if a break was taken right before the lambda * expression. Useful for scoping functions where we want good looking indentation. For example, * here we have correct indentation before `bar()` and `car()` because we can detect the break * after the equals: */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100, 100).apply { optimal = false }, """ /** * Handles a chain of qualified expressions, i.e. `a[5].b!!.c()[4].f()` * * This is by far the most complicated part of this formatter. We start by breaking the * expression to the steps it is executed in (which are in the opposite order of how the syntax * tree is built). * * We then calculate information to know which parts need to be groups, and finally go part by * part, emitting it to the [builder] while closing and opening groups. * * @param brokeBeforeBrace used for tracking if a break was taken right before the lambda * expression. Useful for scoping functions where we want good looking indentation. For * example, here we have correct indentation before `bar()` and `car()` because we can detect * the break after the equals: */ """ .trimIndent()) } @Test fun test193246766() { val source = // Nonsensical text derived from the original using the lorem() method and // replacing same-length & same capitalization words from lorem ipsum """ /** * * Do do occaecat sunt in culpa: * * Id id reprehenderit cillum non `adipiscing` enim enim ad occaecat * * Cupidatat non officia anim adipiscing enim non reprehenderit in officia est: * * Do non officia anim voluptate esse non mollit mollit id tempor, enim u consequat. irure * in occaecat * * Cupidatat, in qui officia anim voluptate esse eu fugiat fugiat in mollit, anim anim id * occaecat * * In h anim id laborum: * * Do non sunt voluptate esse non culpa mollit id tempor, enim u consequat. irure in occaecat * * Cupidatat, in qui anim voluptate esse non culpa mollit est do tempor, enim enim ad occaecat */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * * Do do occaecat sunt in culpa: * * Id id reprehenderit cillum non `adipiscing` enim enim ad * occaecat * * Cupidatat non officia anim adipiscing enim non reprehenderit * in officia est: * * Do non officia anim voluptate esse non mollit mollit id * tempor, enim u consequat. irure in occaecat * * Cupidatat, in qui officia anim voluptate esse eu fugiat * fugiat in mollit, anim anim id occaecat * * In h anim id laborum: * * Do non sunt voluptate esse non culpa mollit id tempor, enim * u consequat. irure in occaecat * * Cupidatat, in qui anim voluptate esse non culpa mollit est * do tempor, enim enim ad occaecat */ """ .trimIndent(), // We indent the last bullets as if they are nested list items; this // is likely the intent (though with indent only being 2, dokka would // interpret it as top level text.) verifyDokka = false) } @Test fun test203584301() { // https://github.com/facebookincubator/ktfmt/issues/310 val source = """ /** * This is my SampleInterface interface. * @sample com.example.java.sample.library.extra.long.path.MyCustomSampleInterfaceImplementationForTesting */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * This is my SampleInterface interface. * * @sample * com.example.java.sample.library.extra.long.path.MyCustomSampleInterfaceImplementationForTesting */ """ .trimIndent()) } @Test fun test209435082() { // b/209435082 val source = // Nonsensical text derived from the original using the lorem() method and // replacing same-length & same capitalization words from lorem ipsum """ /** * eiusmod.com * - - - * PARIATUR_MOLLIT * - - - * Laborum: 1.4 * - - - * Pariatur: * https://officia.officia.com * https://id.laborum.laborum.com * https://sit.eiusmod.com * https://non-in.officia.com * https://anim.laborum.com * https://exercitation.ullamco.com * - - - * Adipiscing do tempor: * - NON: IN/IN * - in 2IN officia? EST * - do EIUSMOD eiusmod? NON * - Mollit est do incididunt Nostrud non? IN * - Mollit pariatur pariatur culpa? QUI * - - - * Lorem eiusmod magna/adipiscing: * - Do eiusmod magna/adipiscing */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * eiusmod.com * - - - * PARIATUR_MOLLIT * - - - * Laborum: 1.4 * - - - * Pariatur: https://officia.officia.com * https://id.laborum.laborum.com https://sit.eiusmod.com * https://non-in.officia.com https://anim.laborum.com * https://exercitation.ullamco.com * - - - * Adipiscing do tempor: * - NON: IN/IN * - in 2IN officia? EST * - do EIUSMOD eiusmod? NON * - Mollit est do incididunt Nostrud non? IN * - Mollit pariatur pariatur culpa? QUI * - - - * Lorem eiusmod magna/adipiscing: * - Do eiusmod magna/adipiscing */ """ .trimIndent()) } @Test fun test236743270() { val source = // Nonsensical text derived from the original using the lorem() method and // replacing same-length & same capitalization words from lorem ipsum """ /** * @return Amet do non adipiscing sed consequat duis non Officia ID (amet sed consequat non * adipiscing sed eiusmod), magna consequat. */ """ .trimIndent() val lorem = loremize(source) assertThat(lorem).isEqualTo(source) checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * @return Amet do non adipiscing sed consequat duis non Officia ID * (amet sed consequat non adipiscing sed eiusmod), magna * consequat. */ """ .trimIndent()) } @Test fun test238279769() { val source = // Nonsensical text derived from the original using the lorem() method and // replacing same-length & same capitalization words from lorem ipsum """ /** * @property dataItemOrderRandomizer sit tempor enim pariatur non culpa id [Pariatur]z in qui anim. * Anim id-lorem sit magna [Consectetur] pariatur. * @property randomBytesProvider non mollit anim pariatur non culpa qui qui `mollit` lorem amet * consectetur [Pariatur]z in IssuerSignedItem culpa. * @property preserveMapOrder officia id pariatur non culpa id lorem pariatur culpa culpa id o est * amet consectetur sed sed do ENIM minim. * @property reprehenderit p esse cillum officia est do enim enim nostrud nisi d non sunt mollit id * est tempor enim. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * @property dataItemOrderRandomizer sit tempor enim pariatur non * culpa id [Pariatur]z in qui anim. Anim id-lorem sit magna * [Consectetur] pariatur. * @property randomBytesProvider non mollit anim pariatur non culpa * qui qui `mollit` lorem amet consectetur [Pariatur]z in * IssuerSignedItem culpa. * @property preserveMapOrder officia id pariatur non culpa id lorem * pariatur culpa culpa id o est amet consectetur sed sed do ENIM * minim. * @property reprehenderit p esse cillum officia est do enim enim * nostrud nisi d non sunt mollit id est tempor enim. */ """ .trimIndent()) } @Test fun testKnit() { // Some tests for the knit plugin -- https://github.com/Kotlin/kotlinx-knit val source = """ /** * <!--- <directive> [<parameters>] --> * <!--- <directive> [<parameters>] * Some text here. * This should all be merged into one * line. * --> * <!--- super long text here; this not be broken into lines; super long text here super long text here super long text here super long text here --> * * <!--- INCLUDE * import kotlin.system.* * --> * ```kotlin * fun exit(): Nothing = exitProcess(0) * ``` * <!--- PREFIX --> * <!--- TEST_NAME BasicTest --> * <!--- TEST * Hello, world! * --> * <!--- TEST lines.single().toInt() in 1..100 --> * <!--- TOC --> * <!--- END --> * <!--- MODULE kotlinx-knit-test --> * <!--- INDEX kotlinx.knit.test --> * [captureOutput]: https://example.com/kotlinx-knit-test/kotlinx.knit.test/capture-output.html * <!--- END --> * * Make sure we never line break <!--- to the beginning a line: <!--- <!--- <!--- end. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * <!--- <directive> [<parameters>] --> * <!--- <directive> [<parameters>] * Some text here. This should all be merged into one line. * --> * <!--- super long text here; this not be broken into lines; super long text here super long text here super long text here super long text here --> * <!--- INCLUDE * import kotlin.system.* * --> * ```kotlin * fun exit(): Nothing = exitProcess(0) * ``` * <!--- PREFIX --> * <!--- TEST_NAME BasicTest --> * <!--- TEST * Hello, world! * --> * <!--- TEST lines.single().toInt() in 1..100 --> * <!--- TOC --> * <!--- END --> * <!--- MODULE kotlinx-knit-test --> * <!--- INDEX kotlinx.knit.test --> * [captureOutput]: * https://example.com/kotlinx-knit-test/kotlinx.knit.test/capture-output.html * <!--- END --> * * Make sure we never line break <!--- to the beginning a * line: <!--- <!--- <!--- end. */ """ .trimIndent()) } @Test fun testNPE() { // Reproduces formatting bug found in androidx' SplashScreen.kt: val source = """ /** * ## Specs * - With icon background (`Theme.SplashScreen.IconBackground`) * + Image Size: 240x240 dp * + Inner Circle diameter: 160 dp */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * ## Specs * - With icon background (`Theme.SplashScreen.IconBackground`) * + Image Size: 240x240 dp * + Inner Circle diameter: 160 dp */ """ .trimIndent()) } @Test fun testExtraNewlines() { // Reproduced a bug which was inserting extra newlines in preformatted text val source = """ /** * Simple helper class useful for creating a message bundle for your module. * * It creates a soft reference to an underlying text bundle, which means that it can * be garbage collected if needed (although it will be reallocated again if you request * a new message from it). * * You might use it like so: * * ``` * # In module 'custom'... * * # resources/messages/CustomBundle.properties: * sample.text.key=This is a sample text value. * * # src/messages/CustomBundle.kt: * private const val BUNDLE_NAME = "messages.CustomBundle" * object CustomBundle { * private val bundleRef = MessageBundleReference(BUNDLE_NAME) * fun message(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any) = bundleRef.message(key, *params) * } * ``` * * That's it! Now you can call `CustomBundle.message("sample.text.key")` to fetch the text value. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * Simple helper class useful for creating a message bundle for your * module. * * It creates a soft reference to an underlying text bundle, which * means that it can be garbage collected if needed (although it * will be reallocated again if you request a new message from it). * * You might use it like so: * ``` * # In module 'custom'... * * # resources/messages/CustomBundle.properties: * sample.text.key=This is a sample text value. * * # src/messages/CustomBundle.kt: * private const val BUNDLE_NAME = "messages.CustomBundle" * object CustomBundle { * private val bundleRef = MessageBundleReference(BUNDLE_NAME) * fun message(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any) = bundleRef.message(key, *params) * } * ``` * * That's it! Now you can call * `CustomBundle.message("sample.text.key")` * to fetch the text value. */ """ .trimIndent()) } @Test fun testQuotedBug() { // Reproduced a bug which was mishandling quoted strings: when you have // *separate* but adjacent quoted lists, make sure we preserve line break // between them val source = """ /** * Eg: * > anydpi-v26 &emsp; | &emsp; Adaptive icon - ic_launcher.xml * * * > hdpi &emsp;&emsp;&emsp;&emsp;&nbsp; | &emsp; Mip Map File - ic_launcher.png */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100, 72), """ /** * Eg: * > anydpi-v26 &emsp; | &emsp; Adaptive icon - ic_launcher.xml * * > hdpi &emsp;&emsp;&emsp;&emsp;&nbsp; | &emsp; Mip Map File - * > ic_launcher.png */ """ .trimIndent(), indent = " ") } @Test fun testListBreaking() { // If we have, in a list, "* very-long-word", we cannot break this line // with a bullet on its line by itself. In the below, prior to the bug fix, // the "- spec:width..." would get split into "-" and "spec:width..." on // its own hanging indent line. val source = """ /** * In other words, completes the parameters so that either of these declarations can be achieved: * - spec:width=...,height=...,dpi=...,isRound=...,chinSize=...,orientation=... * - spec:parent=...,orientation=... * > spec:width=...,height=...,dpi=...,isRound=...,chinSize=...,orientation=... */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100, 72), """ /** * In other words, completes the parameters so that either of these * declarations can be achieved: * - spec:width=...,height=...,dpi=...,isRound=...,chinSize=...,orientation=... * - spec:parent=...,orientation=... * > spec:width=...,height=...,dpi=...,isRound=...,chinSize=...,orientation=... */ """ .trimIndent(), indent = "") } @Test fun testNewList() { // Make sure we never place "1)" or "+" at the beginning of a new line. val source = """ /** * Handles both the START_ALLOC_TRACKING and STOP_ALLOC_TRACKING commands in tests. This is responsible for generating a status event. * For the start tracking command, if |trackStatus| is set to be |SUCCESS|, this generates a start event with timestamp matching what is * specified in |trackStatus|. For the end tracking command, an event (start timestamp + 1) is only added if a start event already * exists in the input event list. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100, 72), """ /** * Handles both the START_ALLOC_TRACKING and STOP_ALLOC_TRACKING commands * in tests. This is responsible for generating a status event. For the * start tracking command, if |trackStatus| is set to be |SUCCESS|, this * generates a start event with timestamp matching what is specified * in |trackStatus|. For the end tracking command, an event (start * timestamp + 1) is only added if a start event already exists in the * input event list. */ """ .trimIndent(), indent = "") } @Test fun testSplashScreen() { val source = """ /** * Provides control over the splash screen once the application is started. * * On API 31+ (Android 12+) this class calls the platform methods. * * Prior API 31, the platform behavior is replicated with the exception of the Animated Vector * Drawable support on the launch screen. * * # Usage of the `core-splashscreen` library: * * To replicate the splash screen behavior from Android 12 on older APIs the following steps need to * be taken: * 1. Create a new Theme (e.g `Theme.App.Starting`) and set its parent to `Theme.SplashScreen` or * `Theme.SplashScreen.IconBackground` * * 2. In your manifest, set the `theme` attribute of the whole `<application>` or just the * starting `<activity>` to `Theme.App.Starting` * * 3. In the `onCreate` method the starting activity, call [installSplashScreen] just before * `super.onCreate()`. You also need to make sure that `postSplashScreenTheme` is set * to the application's theme. Alternatively, this call can be replaced by [Activity#setTheme] * if a [SplashScreen] instance isn't needed. * * ## Themes * * The library provides two themes: [R.style.Theme_SplashScreen] and * [R.style.Theme_SplashScreen_IconBackground]. If you wish to display a background right under * your icon, the later needs to be used. This ensure that the scale and masking of the icon are * similar to the Android 12 Splash Screen. * * `windowSplashScreenAnimatedIcon`: The splash screen icon. On API 31+ it can be an animated * vector drawable. * * `windowSplashScreenAnimationDuration`: Duration of the Animated Icon Animation. The value * needs to be > 0 if the icon is animated. * * **Note:** This has no impact on the time during which the splash screen is displayed and is * only used in [SplashScreenViewProvider.iconAnimationDurationMillis]. If you need to display the * splash screen for a longer time, you can use [SplashScreen.setKeepOnScreenCondition] * * `windowSplashScreenIconBackgroundColor`: _To be used in with * `Theme.SplashScreen.IconBackground`_. Sets a background color under the splash screen icon. * * `windowSplashScreenBackground`: Background color of the splash screen. Defaults to the theme's * `?attr/colorBackground`. * * `postSplashScreenTheme`* Theme to apply to the Activity when [installSplashScreen] is called. * * **Known incompatibilities:** * - On API < 31, `windowSplashScreenAnimatedIcon` cannot be animated. If you want to provide an * animated icon for API 31+ and a still icon for API <31, you can do so by overriding the still * icon with an animated vector drawable in `res/drawable-v31`. * * - On API < 31, if the value of `windowSplashScreenAnimatedIcon` is an * [adaptive icon](http://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) * , it will be cropped and scaled. The workaround is to respectively assign * `windowSplashScreenAnimatedIcon` and `windowSplashScreenIconBackgroundColor` to the values of * the adaptive icon `foreground` and `background`. * * - On API 21-22, The icon isn't displayed until the application starts, only the background is * visible. * * # Design * The splash screen icon uses the same specifications as * [Adaptive Icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) * . This means that the icon needs to fit within a circle whose diameter is 2/3 the size of the * icon. The actual values don't really matter if you use a vector icon. * * ## Specs * - With icon background (`Theme.SplashScreen.IconBackground`) * + Image Size: 240x240 dp * + Inner Circle diameter: 160 dp * - Without icon background (`Theme.SplashScreen`) * + Image size: 288x288 dp * + Inner circle diameter: 192 dp * * _Example:_ if the full size of the image is 300dp*300dp, the icon needs to fit within a * circle with a diameter of 200dp. Everything outside the circle will be invisible (masked). * */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * Provides control over the splash screen once the application is * started. * * On API 31+ (Android 12+) this class calls the platform methods. * * Prior API 31, the platform behavior is replicated with the * exception of the Animated Vector Drawable support on the launch * screen. * * # Usage of the `core-splashscreen` library: * * To replicate the splash screen behavior from Android 12 on older * APIs the following steps need to be taken: * 1. Create a new Theme (e.g `Theme.App.Starting`) and set its * parent to `Theme.SplashScreen` or * `Theme.SplashScreen.IconBackground` * 2. In your manifest, set the `theme` attribute of the whole * `<application>` or just the starting `<activity>` to * `Theme.App.Starting` * 3. In the `onCreate` method the starting activity, call * [installSplashScreen] just before `super.onCreate()`. You also * need to make sure that `postSplashScreenTheme` is set to the * application's theme. Alternatively, this call can be replaced * by [Activity#setTheme] if a [SplashScreen] instance isn't * needed. * * ## Themes * * The library provides two themes: [R.style.Theme_SplashScreen] * and [R.style.Theme_SplashScreen_IconBackground]. If you wish to * display a background right under your icon, the later needs to * be used. This ensure that the scale and masking of the icon are * similar to the Android 12 Splash Screen. * * `windowSplashScreenAnimatedIcon`: The splash screen icon. On API * 31+ it can be an animated vector drawable. * * `windowSplashScreenAnimationDuration`: Duration of the Animated * Icon Animation. The value needs to be > 0 if the icon is * animated. * * **Note:** This has no impact on the time during which * the splash screen is displayed and is only used in * [SplashScreenViewProvider.iconAnimationDurationMillis]. If you * need to display the splash screen for a longer time, you can use * [SplashScreen.setKeepOnScreenCondition] * * `windowSplashScreenIconBackgroundColor`: _To be used in with * `Theme.SplashScreen.IconBackground`_. Sets a background color * under the splash screen icon. * * `windowSplashScreenBackground`: Background color of the splash * screen. Defaults to the theme's `?attr/colorBackground`. * * `postSplashScreenTheme`* Theme to apply to the Activity when * [installSplashScreen] is called. * * **Known incompatibilities:** * - On API < 31, `windowSplashScreenAnimatedIcon` cannot be * animated. If you want to provide an animated icon for API 31+ * and a still icon for API <31, you can do so by overriding the * still icon with an animated vector drawable in * `res/drawable-v31`. * - On API < 31, if the value of `windowSplashScreenAnimatedIcon` * is an * [adaptive icon](http://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) * , it will be cropped and scaled. The workaround is to * respectively assign `windowSplashScreenAnimatedIcon` and * `windowSplashScreenIconBackgroundColor` to the values of the * adaptive icon `foreground` and `background`. * - On API 21-22, The icon isn't displayed until the application * starts, only the background is visible. * * # Design * The splash screen icon uses the same specifications as * [Adaptive Icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive) * . This means that the icon needs to fit within a circle whose * diameter is 2/3 the size of the icon. The actual values don't * really matter if you use a vector icon. * * ## Specs * - With icon background (`Theme.SplashScreen.IconBackground`) * + Image Size: 240x240 dp * + Inner Circle diameter: 160 dp * - Without icon background (`Theme.SplashScreen`) * + Image size: 288x288 dp * + Inner circle diameter: 192 dp * * _Example:_ if the full size of the image is 300dp*300dp, the icon * needs to fit within a circle with a diameter of 200dp. Everything * outside the circle will be invisible (masked). */ """ .trimIndent()) } @Test fun testRaggedIndentation() { // From Dokka's plugins/base/src/main/kotlin/translators/psi/parsers/JavadocParser.kt val source = """ /** * We would like to know if we need to have a space after a this tag * * The space is required when: * - tag spans multiple lines, between every line we would need a space * * We wouldn't like to render a space if: * - tag is followed by an end of comment * - after a tag there is another tag (eg. multiple @author tags) * - they end with an html tag like: <a href="...">Something</a> since then the space will be displayed in the following text * - next line starts with a <p> or <pre> token */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * We would like to know if we need to have a space after a this tag * * The space is required when: * - tag spans multiple lines, between every line we would need a * space * * We wouldn't like to render a space if: * - tag is followed by an end of comment * - after a tag there is another tag (eg. multiple @author tags) * - they end with an html tag like: <a href="...">Something</a> * since then the space will be displayed in the following text * - next line starts with a <p> or <pre> token */ """ .trimIndent()) } @Test fun testCustomKDocTag() { // From Dokka's core/testdata/comments/multilineSection.kt val source = """ /** * Summary * @one * line one * line two */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72, 72), """ /** * Summary * * @one line one line two */ """ .trimIndent()) } @Test fun testTables() { val source = """ /** * ### Tables * column 1 | column 2 * ---------|--------- * value\| 1 | value 2 */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * ### Tables * | column 1 | column 2 | * |-----------|----------| * | value\| 1 | value 2 | */ """ .trimIndent()) } @Test fun testTableMixedWithHtml() { // https://stackoverflow.com/questions/19950648/how-to-write-lists-inside-a-markdown-table val source = """ /** | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | right-aligned | 1600 | | col 2 is | centered | 12 | | zebra stripes | are neat | 1 | | <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column| */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100), """ /** * | Tables | Are | Cool | * |---------------------------------------|:-------------:|----------------------:| * | col 3 is | right-aligned | 1600 | * | col 2 is | centered | 12 | * | zebra stripes | are neat | 1 | * | <ul><li>item1</li><li>item2</li></ul> | See the list | from the first column | */ """ .trimIndent()) // Reduce formatting width to 40; table won't fit, but we'll skip the padding checkFormatter( source, KDocFormattingOptions(40), """ /** * |Tables |Are |Cool | * |-------------------------------------|:-----------:|--------------------:| * |col 3 is |right-aligned| 1600| * |col 2 is | centered | 12| * |zebra stripes | are neat | 1| * |<ul><li>item1</li><li>item2</li></ul>|See the list |from the first column| */ """ .trimIndent()) checkFormatter( source, KDocFormattingOptions(40).apply { alignTableColumns = false }, """ /** * | Tables | Are | Cool | * | ------------- |:-------------:| -----:| * | col 3 is | right-aligned | 1600 | * | col 2 is | centered | 12 | * | zebra stripes | are neat | 1 | * | <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column| */ """ .trimIndent()) } @Test fun testTableExtraCells() { // If there are extra columns in a row (after the header and divider), // preserve these (though Dokka will drop them from the rendering); don't // widen the table to accommodate it. val source = """ /** | Tables | Are | Cool | | ------------- |:-------------:| -----:| | col 3 is | right-aligned | 1600 | | col 2 is | centered | 12 | extra | zebra stripes | are neat | 1 | */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(100), """ /** * | Tables | Are | Cool | * |---------------|:-------------:|-----:| * | col 3 is | right-aligned | 1600 | * | col 2 is | centered | 12 | extra | * | zebra stripes | are neat | 1 | */ """ .trimIndent()) } @Test fun testTables2() { // See https://github.com/Kotlin/dokka/issues/199 val source = """ /** * | Level | Color | * | ----- | ----- | * | ERROR | RED | * | WARN | YELLOW | */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * | Level | Color | * |-------|--------| * | ERROR | RED | * | WARN | YELLOW | */ """ .trimIndent()) // With alignTableColumns=false, leave formatting within table cells alone checkFormatter( source, KDocFormattingOptions(40).apply { alignTableColumns = false }, """ /** * | Level | Color | * | ----- | ----- | * | ERROR | RED | * | WARN | YELLOW | */ """ .trimIndent()) } @Test fun testTables3() { val source = """ /** * Line Before * # test * |column 1 | column 2 | column3 * |---|---|--- * value 1 | value 3 * this is missing * this is more */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40).apply { alignTableColumns = true }, """ /** * Line Before * * # test * | column 1 | column 2 | column3 | * |----------|----------|---------| * | value 1 | value 3 | | * * this is missing this is more */ """ .trimIndent()) checkFormatter( source, KDocFormattingOptions(40).apply { alignTableColumns = false }, """ /** * Line Before * * # test * |column 1 | column 2 | column3 * |---|---|--- * value 1 | value 3 * * this is missing this is more */ """ .trimIndent()) } @Test fun testTables4() { // Test short dividers (:--, :-:, --:) val source = """ /** * ### Tables * column 1 | column 2 | column3 * :-:|--:|:-- * cell 1|cell2|cell3 */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /** * ### Tables * | column 1 | column 2 | column3 | * |:--------:|---------:|---------| * | cell 1 | cell2 | cell3 | */ """ .trimIndent(), // Dokka doesn't actually handle this right; it looks for --- verifyDokka = false) } @Test fun testTablesEmptyCells() { // Checks what happens with blank cells (here in column 0 on the last row). Test case from // Studio's // designer/testSrc/com/android/tools/idea/uibuilder/property/testutils/AndroidAttributeTypeLookup.kt val source = """ /** * | Function | Type | Notes | * | -------------------------------- | ------------------------------- | --------------------------------------| * | TypedArray.getDrawable | NlPropertyType.DRAWABLE | | * | TypedArray.getColor | NlPropertyType.COLOR | Make sure this is not a color list !! | * | TypedArray.getColorStateList | NlPropertyType.COLOR_STATE_LIST | | * | TypedArray.getDimensionPixelSize | NlPropertyType.DIMENSION | | * | TypedArray.getResourceId | NlPropertyType.ID | | * | TypedArray.getInt | NlPropertyType.ENUM | If attrs.xml defines this as an enum | * | | NlPropertyType.INTEGER | If this is not an enum | */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * |Function |Type |Notes | * |--------------------------------|-------------------------------|-------------------------------------| * |TypedArray.getDrawable |NlPropertyType.DRAWABLE | | * |TypedArray.getColor |NlPropertyType.COLOR |Make sure this is not a color list !!| * |TypedArray.getColorStateList |NlPropertyType.COLOR_STATE_LIST| | * |TypedArray.getDimensionPixelSize|NlPropertyType.DIMENSION | | * |TypedArray.getResourceId |NlPropertyType.ID | | * |TypedArray.getInt |NlPropertyType.ENUM |If attrs.xml defines this as an enum | * | |NlPropertyType.INTEGER |If this is not an enum | */ """ .trimIndent()) } @Test fun testTables5() { // Test case from Studio's // project-system-gradle-upgrade/src/com/android/tools/idea/gradle/project/upgrade/AgpUpgradeRefactoringProcessor.kt val source = """ /** | 1 | 2 | 3 | 4 | Necessity |---|---|---|---|---------- |v_n|v_o|cur|new| [IRRELEVANT_PAST] |cur|new|v_n|v_o| [IRRELEVANT_FUTURE] |cur|v_n|v_o|new| [MANDATORY_CODEPENDENT] (must do the refactoring in the same action as the AGP version upgrade) |v_n|cur|v_o|new| [MANDATORY_INDEPENDENT] (must do the refactoring, but can do it before the AGP version upgrade) |cur|v_n|new|v_o| [OPTIONAL_CODEPENDENT] (need not do the refactoring, but if done must be with or after the AGP version upgrade) |v_n|cur|new|v_o| [OPTIONAL_INDEPENDENT] (need not do the refactoring, but if done can be at any point in the process) For the possibly-simpler case where we have a discontinuity in behaviour, v_o = v_n = vvv, and the three possible cases are: | 1 | 2 | 3 | Necessity +---+---+---+---------- |vvv|cur|new| [IRRELEVANT_PAST] |cur|vvv|new| [MANDATORY_CODEPENDENT] |cur|new|vvv| [IRRELEVANT_FUTURE] (again in case of equality, vvv sorts before cur and new) */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * |1 |2 |3 |4 |Necessity | * |---|---|---|---|---------------------------------------------------------------------------------------------------------------| * |v_n|v_o|cur|new|[IRRELEVANT_PAST] | * |cur|new|v_n|v_o|[IRRELEVANT_FUTURE] | * |cur|v_n|v_o|new|[MANDATORY_CODEPENDENT] (must do the refactoring in the same action as the AGP version upgrade) | * |v_n|cur|v_o|new|[MANDATORY_INDEPENDENT] (must do the refactoring, but can do it before the AGP version upgrade) | * |cur|v_n|new|v_o|[OPTIONAL_CODEPENDENT] (need not do the refactoring, but if done must be with or after the AGP version upgrade)| * |v_n|cur|new|v_o|[OPTIONAL_INDEPENDENT] (need not do the refactoring, but if done can be at any point in the process) | * * For the possibly-simpler case where we have a discontinuity in * behaviour, v_o = v_n = vvv, and the three possible cases are: * * | 1 | 2 | 3 | Necessity +---+---+---+---------- |vvv|cur|new| * [IRRELEVANT_PAST] |cur|vvv|new| [MANDATORY_CODEPENDENT] |cur|new|vvv| * [IRRELEVANT_FUTURE] * * (again in case of equality, vvv sorts before cur and new) */ """ .trimIndent(), indent = "") } @Test fun testTables6() { // Test case from IntelliJ's // plugins/kotlin/idea/tests/testData/editor/quickDoc/OnFunctionDeclarationWithGFMTable.kt val source = """ /** * | left | center | right | default | * | :---- | :----: | ----: | ------- | * | 1 | 2 | 3 | 4 | * * * | foo | bar | baz | * | --- | --- | --- | * | 1 | 2 | * | 3 | 4 | 5 | 6 | * * | header | only | * | ------ | ---- | */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * | left | center | right | default | * |------|:------:|------:|---------| * | 1 | 2 | 3 | 4 | * * | foo | bar | baz | * |-----|-----|-----| * | 1 | 2 | | * | 3 | 4 | 5 | 6 | * * | header | only | * |--------|------| */ """ .trimIndent(), indent = "") } @Test fun testTables7() { val source = """ /** * This is my code * @author Me * And here's. * Another. * Thing. * * my | table * ---|--- * item 1|item 2 * item 3| * item 4|item 5 */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72), """ /** * This is my code * * @author Me And here's. Another. Thing. * * | my | table | * |--------|--------| * | item 1 | item 2 | * | item 3 | | * | item 4 | item 5 | */ """ .trimIndent(), indent = "") } @Test fun testTables7b() { val source = """ /** * This is my code * @author Me * Plain text. * * my | table * ---|--- * item 1|item 2 * item 3| * item 4|item 5 */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(72).apply { orderDocTags = false alignTableColumns = false }, """ /** * This is my code * * @author Me Plain text. * * my | table * ---|--- * item 1|item 2 * item 3| * item 4|item 5 */ """ .trimIndent(), indent = "") } @Test fun testBulletsUnderParamTags() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/56 val source = """ /** * This supports bullets * - one * - two * * @param thisDoesNot * Here's some parameter text. * - a * - b * Here's some more text * * And here's even more parameter doc text. * * @param another paragraph * * With some bulleted items * * Even nested ones * ``` * and some preformatted text * ``` */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72).apply { orderDocTags = false }, """ /** * This supports bullets * - one * - two * * @param thisDoesNot Here's some parameter text. * - a * - b Here's some more text * * And here's even more parameter doc text. * * @param another paragraph * * With some bulleted items * * Even nested ones * * ``` * and some preformatted text * ``` */ """ .trimIndent()) } @Test fun testLineBreaking() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/57 val source = """ /** aa aa aa aa a */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 20, maxCommentWidth = 20).apply { optimal = false }, """ /** aa aa aa aa a */ """ .trimIndent(), indent = "") } @Test fun testPreTag() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/58 val source = """ /** * This tag messes things up. * <pre> * This is pre. * * @return some correct * value */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * This tag messes things up. * <pre> * This is pre. * * @return some correct * value */ """ .trimIndent(), verifyDokka = false // this triggers a bug in the diff lookup; TODO investigate ) } @Test fun testPreTag2() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/58 val source = """ /** * Even if it's closed. * <pre>My Pre</pre> * * @return some correct * value */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Even if it's closed. * * ``` * My Pre * ``` * * @return some correct value */ """ .trimIndent(), // <pre> and ``` are rendered differently; this is an intentional diff verifyDokka = false) } @Test fun testPreTag3() { // From Studio's // build-system/builder-model/src/main/java/com/android/builder/model/DataBindingOptions.kt val source = """ /** * Whether we want tests to be able to use data binding as well. * * <p> * Data Binding classes generated from the application can always be * accessed in the test code but test itself cannot introduce new * Data Binding layouts, bindables etc unless this flag is turned * on. * * <p> * This settings help with an issue in older devices where class * verifier throws an exception when the application class is * overwritten by the test class. It also makes it easier to run * proguarded tests. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Whether we want tests to be able to use data binding as well. * * Data Binding classes generated from the application can always be * accessed in the test code but test itself cannot introduce new * Data Binding layouts, bindables etc unless this flag is turned * on. * * This settings help with an issue in older devices where class * verifier throws an exception when the application class is * overwritten by the test class. It also makes it easier to run * proguarded tests. */ """ .trimIndent()) } @Test fun testNoConversionInReferences() { val source = """ /** * A thread safe in-memory cache of [Key&lt;T&gt;][Key] to `T` values whose lifetime is tied * to a [CoroutineScope]. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * A thread safe in-memory cache of [Key&lt;T&gt;][Key] to `T` values * whose lifetime is tied to a [CoroutineScope]. */ """ .trimIndent(), indent = "") } @Test fun testCaseSensitiveMarkup() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/59 val source = """ /** <A> to <B> should remain intact, not <b>bolded</b> */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** <A> to <B> should remain intact, not **bolded** */ """ .trimIndent(), // This is a broken comment (unterminated <B> etc) so the behaviors differ verifyDokka = false) } @Test fun testAsteriskRemoval() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/60 val source = """ /** *** Testing */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** *** Testing */ """ .trimIndent()) } @Test fun testParagraphTagRemoval() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/61 val source = """ /** * Ptag removal should remove extra space * * <p> Some paragraph */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Ptag removal should remove extra space * * Some paragraph */ """ .trimIndent()) } @Test fun testDashedLineIndentation() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/62 val source = """ /** * Some summary. * * - Some bullet. * * ------------------------------------------------------------------------------ * * Some paragraph. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Some summary. * - Some bullet. * * ------------------------------------------------------------------------------ * * Some paragraph. */ """ .trimIndent()) } @Test fun testParagraphRemoval() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/63 val source = """ /** * 1. Test * * <p>2. Test */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * 1. Test * 2. Test */ """ .trimIndent(), // We deliberately allow list items to jump up across blank lines verifyDokka = false) } @Test fun testParagraphRemoval2() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/69 val source = """ /** * Some title * * <p>1. Test * 2. Test */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Some title * 1. Test * 2. Test */ """ .trimIndent(), // We deliberately allow list items to jump up across blank lines verifyDokka = false) } @Test fun testAtBreak2() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/64 // This behavior is deliberate: we cannot put @aa at the beginning of a new line; // if so KDoc will treat it as a doc and silently drop it because it isn't a known // custom tag. val source = """ /** * aa aa aa aa aa @aa */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 20, maxCommentWidth = 20), """ /** * aa aa aa aa * aa @aa */ """ .trimIndent()) } @Test fun testNoBreakAfterAt() { // Regression test for // https://github.com/tnorbye/kdoc-formatter/issues/65 val source = """ /** * Weird break * * alink aaaaaaa * * @param a aaaaaa * @link aaaaaaa */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 20, maxCommentWidth = 20), """ /** * Weird break * * alink aaaaaaa * * @param a aaaaaa * @link aaaaaaa */ """ .trimIndent(), indent = "") } @Test fun testPreCodeConversion() { val source = """ /** * <pre><code> * More sample code. * </code></pre> */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * ``` * More sample code. * ``` */ """ .trimIndent(), indent = " ", // <pre> and ``` are rendered differently; this is an intentional diff verifyDokka = false) } @Test fun testPreConversion2() { // From AndroidX and Studio methods val source = """ /** * Checks if any of the GL calls since the last time this method was called set an error * condition. Call this method immediately after calling a GL method. Pass the name of the GL * operation. For example: * * <pre> * mColorHandle = GLES20.glGetUniformLocation(mProgram, "uColor"); * MyGLRenderer.checkGlError("glGetUniformLocation");</pre> * * If the operation is not successful, the check throws an exception. * * <pre>public performItemClick(T item) { * ... * sendEventForVirtualView(item.id, AccessibilityEvent.TYPE_VIEW_CLICKED) * } * </pre> * *Note* This is quite slow so it's best to use it sparingly in production builds. * Injector to load associated file. It will create code like: * <pre>file = FileUtil.loadLabels(extractor.getAssociatedFile(fileName))</pre> */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Checks if any of the GL calls since the last time this * method was called set an error condition. Call this method * immediately after calling a GL method. Pass the name of the * GL operation. For example: * ``` * mColorHandle = GLES20.glGetUniformLocation(mProgram, "uColor"); * MyGLRenderer.checkGlError("glGetUniformLocation"); * ``` * * If the operation is not successful, the check throws an * exception. * * ``` * public performItemClick(T item) { * ... * sendEventForVirtualView(item.id, AccessibilityEvent.TYPE_VIEW_CLICKED) * } * ``` * * *Note* This is quite slow so it's best to use it sparingly in * production builds. Injector to load associated file. It will * create code like: * ``` * file = FileUtil.loadLabels(extractor.getAssociatedFile(fileName)) * ``` */ """ .trimIndent(), indent = " ", // <pre> and ``` are rendered differently; this is an intentional diff verifyDokka = false) } @Test fun testOpenRange() { // https://github.com/tnorbye/kdoc-formatter/issues/84 val source = """ /** * This is a line that has the length such that this [link gets * broken across lines]() which is not valid. * * Input is a float in range * [0, 1) where 0 is fully settled and 1 is dismissed. Will be continue to be called after the user's finger has lifted. Will not be called for if not dismissible. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * This is a line that has the length such that this * [link gets broken across lines]() which is not valid. * * Input is a float in range [0, 1) where 0 is fully settled and 1 is * dismissed. Will be continue to be called after the user's finger has * lifted. Will not be called for if not dismissible. */ """ .trimIndent(), indent = "") } @Test fun testPropertiesWithBrackets() { val source = // From AOSP // tools/base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/cxx/prefab/PackageModel.kt """ /** * The Android abi.json schema. * * @property[abi] The ABI name of the described library. These names match the tag field for * [com.android.build.gradle.internal.core.Abi]. * @property[api] The minimum OS version supported by the library. i.e. the * library's `minSdkVersion`. * @property[ndk] The major version of the NDK that this library was built with. * @property[stl] The STL that this library was built with. * @property[static] If true then the library is .a, if false then .so. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * The Android abi.json schema. * * @property[abi] The ABI name of the described library. These names * match the tag field for * [com.android.build.gradle.internal.core.Abi]. * @property[api] The minimum OS version supported by the library. i.e. * the library's `minSdkVersion`. * @property[ndk] The major version of the NDK that this library was * built with. * @property[stl] The STL that this library was built with. * @property[static] If true then the library is .a, if false then .so. */ """ .trimIndent(), indent = "") } @Test fun testHandingIndent() { val source = """ /** * @param count this is how many you * can fit in a [Bag] * @param weight how heavy this would * be in [Grams] */ """ checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * @param count this is how many you can fit in a [Bag] * @param weight how heavy this would be in [Grams] */ """ .trimIndent(), indent = "") } @Test fun testMarkupAcrossLines() { val source = """ /** * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter * has changed. * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes * respectively. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Broadcast Action: Indicates the Bluetooth scan mode of the local * Adapter has changed. * * Always contains the extra fields [EXTRA_SCAN_MODE] and * [EXTRA_PREVIOUS_SCAN_MODE] containing the new and old scan modes * respectively. */ """ .trimIndent(), indent = "") } @Test fun testReferences() { val source = """ /** * Construct a rectangle from its left and top edges as well as its width and height. * @param offset Offset to represent the top and left parameters of the Rect * @param size Size to determine the width and height of this [Rect]. * @return Rect with [Rect.left] and [Rect.top] configured to [Offset.x] and [Offset.y] as * [Rect.right] and [Rect.bottom] to [Offset.x] + [Size.width] and [Offset.y] + [Size.height] * respectively */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Construct a rectangle from its left and top edges as well as its * width and height. * * @param offset Offset to represent the top and left parameters of the * Rect * @param size Size to determine the width and height of this [Rect]. * @return Rect with [Rect.left] and [Rect.top] configured to [Offset.x] * and [Offset.y] as [Rect.right] and [Rect.bottom] to * [Offset.x] + [Size.width] and [Offset.y] + [Size.height] * respectively */ """ .trimIndent(), indent = "") } @Test fun testDecapitalizeKdocTags() { val source = """ /** * Represents a component that handles scroll events, so that other components in the hierarchy * can adjust their behaviour. * @See [provideScrollContainerInfo] and [consumeScrollContainerInfo] */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72).apply { convertMarkup = true }, """ /** * Represents a component that handles scroll events, so that other * components in the hierarchy can adjust their behaviour. * * @see [provideScrollContainerInfo] and [consumeScrollContainerInfo] */ """ .trimIndent(), indent = "") } @Test fun testLineBreak() { // Makes sure a scenario where we used to put "0." at the beginning of a new line. // From AOSP's // frameworks/support/graphics/graphics-core/src/main/java/androidx/graphics/surface/SurfaceControlWrapper.kt val source = """ /** * Updates z order index for [SurfaceControlWrapper]. Note that the z order for a * surface is relative to other surfaces that are siblings of this surface. * Behavior of siblings with the same z order is undefined. * * Z orders can range from Integer.MIN_VALUE to Integer.MAX_VALUE. Default z order * index is 0. [SurfaceControlWrapper] instances are positioned back-to-front. That is * lower z order values are rendered below other [SurfaceControlWrapper] instances with * higher z order values. * * @param surfaceControl surface control to set the z order of. * * @param zOrder desired layer z order to set the surfaceControl. */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Updates z order index for [SurfaceControlWrapper]. Note that * the z order for a surface is relative to other surfaces that * are siblings of this surface. Behavior of siblings with the * same z order is undefined. * * Z orders can range from Integer.MIN_VALUE * to Integer.MAX_VALUE. Default z order index * is 0. [SurfaceControlWrapper] instances are positioned * back-to-front. That is lower z order values are rendered * below other [SurfaceControlWrapper] instances with higher z * order values. * * @param surfaceControl surface control to set the z order of. * @param zOrder desired layer z order to set the * surfaceControl. */ """ .trimIndent(), indent = " ") } @Test fun testDocTagsInsidePreformatted() { // Makes sure we don't treat markup inside preformatted text as potential // doc tags (with the fix to make us flexible recognize @See as a doctag // it revealed we were also looking inside preformatted text and started // treating annotations like @Retention as a doc tag.) val source = """ /** * Denotes that the annotated element of integer type, represents * a logical type and that its value should be one of the explicitly * named constants. If the IntDef#flag() attribute is set to true, * multiple constants can be combined. * * Example: * ``` * @Retention(SOURCE) * @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS}) * public @interface NavigationMode {} * public static final int NAVIGATION_MODE_STANDARD = 0; * public static final int NAVIGATION_MODE_LIST = 1; * public static final int NAVIGATION_MODE_TABS = 2; * ... * public abstract void setNavigationMode(@NavigationMode int mode); * * @NavigationMode * public abstract int getNavigationMode(); * ``` * * For a flag, set the flag attribute: * ``` * @IntDef( * flag = true, * value = {NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS} * ) * ``` * * @see LongDef */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Denotes that the annotated element of integer type, represents a * logical type and that its value should be one of the explicitly named * constants. If the IntDef#flag() attribute is set to true, multiple * constants can be combined. * * Example: * ``` * @Retention(SOURCE) * @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS}) * public @interface NavigationMode {} * public static final int NAVIGATION_MODE_STANDARD = 0; * public static final int NAVIGATION_MODE_LIST = 1; * public static final int NAVIGATION_MODE_TABS = 2; * ... * public abstract void setNavigationMode(@NavigationMode int mode); * * @NavigationMode * public abstract int getNavigationMode(); * ``` * * For a flag, set the flag attribute: * ``` * @IntDef( * flag = true, * value = {NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS} * ) * ``` * * @see LongDef */ """ .trimIndent(), indent = "") } @Test fun testConvertMarkup2() { // Bug where the markup conversion around <p></p> wasn't working correctly // From AOSP's // frameworks/support/bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothAdapter.kt val source = """ /** * Fundamentally, this is your starting point for all * Bluetooth actions. * </p> * <p>This class is thread safe.</p> * * @hide */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(maxLineWidth = 72), """ /** * Fundamentally, this is your starting point for all Bluetooth actions. * * This class is thread safe. * * @hide */ """ .trimIndent(), indent = "") } /** * Test utility method: from a source kdoc, derive an "equivalent" kdoc (same punctuation, * whitespace, capitalization and length of words) with words from Lorem Ipsum. Useful to create * test cases for the formatter without checking in original comments. */ private fun loremize(s: String): String { val lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt " + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " + "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " + "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " + "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum" val loremWords = lorem.filter { it.isLetter() || it == ' ' }.lowercase().split(" ") var next = 0 fun adjustCapitalization(word: String, original: String): String { return if (original[0].isUpperCase()) { if (original.all { it.isUpperCase() }) { word.uppercase() } else { word.replaceFirstChar { it.uppercase() } } } else { word } } fun nextLorem(word: String): String { val length = word.length val start = next while (next < loremWords.size) { val nextLorem = loremWords[next] if (nextLorem.length == length) { return adjustCapitalization(nextLorem, word) } next++ } next = 0 while (next < start) { val nextLorem = loremWords[next] if (nextLorem.length == length) { return adjustCapitalization(nextLorem, word) } next++ } if (length == 1) { return ('a' + (start % 26)).toString() } // No match for this word return word } val sb = StringBuilder() var i = 0 while (i < s.length) { val c = s[i] if (c.isLetter()) { var end = i + 1 while (end < s.length && s[end].isLetter()) { end++ } val word = s.substring(i, end) if (i > 0 && s[i - 1] == '@' || word == "http" || word == "https" || word == "com") { // Don't translate URL prefix/suffixes and doc tags sb.append(word) } else { sb.append(nextLorem(word)) } i = end } else { sb.append(c) i++ } } return sb.toString() } // -------------------------------------------------------------------- // A few failing test cases here for corner cases that aren't handled // right yet. // -------------------------------------------------------------------- @Ignore("Lists within quoted blocks not yet supported") @Test fun testNestedWithinQuoted() { val source = """ /* * Lists within a block quote: * > Here's my quoted text. * > 1. First item * > 2. Second item * > 3. Third item */ """ .trimIndent() checkFormatter( source, KDocFormattingOptions(40), """ /* * Lists within a block quote: * > Here's my quoted text. * > 1. First item * > 2. Second item * > 3. Third item */ """ .trimIndent()) checkFormatter( """ /** * Here's some text. * > Here's some more text that * > is indented. More text. * > > And here's some even * > > more indented text * > Back to the top level */ """ .trimIndent(), KDocFormattingOptions(maxLineWidth = 100, maxCommentWidth = 60), """ /** * Here's some text. * > Here's some more text that * > is indented. More text. * > > And here's some even * > > more indented text * > Back to the top level */ """ .trimIndent()) } }
93
null
76
910
ed949e89eea22843ac10d4fb91685453754abd25
189,070
ktfmt
Apache License 2.0
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/usecases/coroutines/usecase15/WorkManagerActivity.kt
LukasLechnerDev
248,218,113
false
null
package com.lukaslechner.coroutineusecasesonandroid.usecases.coroutines.usecase15 import android.os.Bundle import androidx.activity.viewModels import com.lukaslechner.coroutineusecasesonandroid.base.BaseActivity import com.lukaslechner.coroutineusecasesonandroid.base.useCase15Description import com.lukaslechner.coroutineusecasesonandroid.databinding.ActivityWorkmangerBinding class WorkManagerActivity : BaseActivity() { override fun getToolbarTitle() = useCase15Description private val binding by lazy { ActivityWorkmangerBinding.inflate(layoutInflater) } private val viewModel: WorkManagerViewModel by viewModels { ViewModelFactory(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) viewModel.performAnalyticsRequest() } }
5
null
436
2,664
636b1038c42073a45bfccb25afbedc294b0f032d
861
Kotlin-Coroutines-and-Flow-UseCases-on-Android
Apache License 2.0
app/src/main/java/com/example/android/navigation/TitleFragment.kt
xxxDNxxx
259,377,964
true
{"Kotlin": 393378}
package com.example.android.navigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView /** * A simple [Fragment] subclass. */ class TitleFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return TextView(activity).apply { setText(R.string.hello_blank_fragment) } } }
0
Kotlin
0
0
8cfe4f96240cda731eb75c4973dd28fde27ae151
563
android-kotlin-fundamentals-starter-apps
Apache License 2.0
sykepenger-api/src/test/kotlin/no/nav/helse/spleis/graphql/SpeilBuilderFlereAGTest.kt
navikt
193,907,367
false
{"Kotlin": 6568073, "PLpgSQL": 2738, "Dockerfile": 168}
package no.nav.helse.spleis.graphql import java.time.LocalDate.EPOCH import java.time.Month import java.time.YearMonth import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom import no.nav.helse.hendelser.til import no.nav.helse.januar import no.nav.helse.spleis.speil.dto.BeregnetPeriode import no.nav.helse.spleis.testhelpers.OverstyrtArbeidsgiveropplysning import no.nav.helse.desember import no.nav.helse.februar import no.nav.helse.hendelser.OverstyrArbeidsforhold import no.nav.helse.mars import no.nav.helse.oktober import no.nav.helse.spleis.speil.dto.Arbeidsgiverinntekt import no.nav.helse.spleis.speil.dto.GhostPeriodeDTO import no.nav.helse.spleis.speil.dto.Inntekt import no.nav.helse.spleis.speil.dto.InntekterFraAOrdningen import no.nav.helse.spleis.speil.dto.Inntektkilde import no.nav.helse.spleis.speil.dto.SpleisVilkårsgrunnlag import no.nav.helse.økonomi.Inntekt.Companion.månedlig import no.nav.helse.økonomi.Prosentdel.Companion.prosent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertInstanceOf import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test internal class SpeilBuilderFlereAGTest : AbstractE2ETest() { @Test fun `lager ikke hvit pølse i helg`() { håndterSøknad(1.januar til 19.januar) håndterSøknad(22.januar til 31.januar) håndterInntektsmelding(1.januar) håndterVilkårsgrunnlagTilGodkjenning() val speilJson = speilApi() assertEquals(emptyList<GhostPeriodeDTO>(), speilJson.arbeidsgivere.single().ghostPerioder) } @Test fun `sender med ghost tidslinjer til speil`() { håndterSøknad(1.januar til 20.januar, orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() val speilJson = speilApi() assertEquals( emptyList<GhostPeriodeDTO>(), speilJson.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder ) val perioder = speilJson.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId assertEquals(1, perioder.size) val actual = perioder.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 20.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } @Test fun `sender med ghost tidslinjer til speil med flere arbeidsgivere ulik fom`() { håndterSøknad(Sykdom(1.januar, 20.januar, 100.prosent), orgnummer = a1) håndterSøknad(Sykdom(4.januar, 31.januar, 100.prosent), orgnummer = a2) håndterInntektsmelding(1.januar, orgnummer = a1) håndterInntektsmelding(listOf(4.januar til 19.januar), beregnetInntekt = 5000.månedlig, orgnummer = a2) håndterVilkårsgrunnlag( inntekter = listOf(a1 to INNTEKT, a2 to 5000.månedlig, a3 to 10000.månedlig), arbeidsforhold = listOf(a1 to EPOCH, a3 to EPOCH) ) håndterYtelserTilGodkjenning() val speilJson1 = speilApi() val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId speilJson1.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder.also { ghostPerioder -> assertEquals(1, ghostPerioder.size) ghostPerioder[0].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 21.januar, tom = 31.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } } speilJson1.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder.also { ghostPerioder -> assertEquals(1, ghostPerioder.size) ghostPerioder[0].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 3.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } } speilJson1.arbeidsgivere.single { it.organisasjonsnummer == a3 }.ghostPerioder.also { perioder -> assertEquals(1, perioder.size) val actual = perioder.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 31.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } } @Test fun `lager ikke ghosts for forkastede perioder med vilkårsgrunnlag fra spleis`() { håndterSøknad(Sykdom(1.januar, 20.januar, 100.prosent), orgnummer = a2) håndterInntektsmelding(listOf(1.januar til 16.januar), orgnummer = a2) håndterVilkårsgrunnlagTilGodkjenning() håndterUtbetalingsgodkjenning(utbetalingGodkjent = false) håndterSøknad(Sykdom(1.februar, 20.februar, 100.prosent), orgnummer = a1) håndterInntektsmelding(listOf(1.februar til 16.februar), orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() val speilJson = speilApi() assertEquals(emptyList<GhostPeriodeDTO>(), speilJson.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder) val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.februar }.vilkårsgrunnlagId val perioder = speilJson.arbeidsgivere.find { it.organisasjonsnummer == a2 }?.ghostPerioder assertEquals(1, perioder?.size) val actual = perioder!!.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 1.februar, tom = 20.februar, skjæringstidspunkt = 1.februar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } @Test fun `skal ikke lage ghosts for gamle arbeidsgivere`() { håndterSøknad(Sykdom(1.januar(2017), 20.januar(2017), 100.prosent), sendtTilNAV = 20.januar(2017).atStartOfDay(), orgnummer = a3) håndterInntektsmelding(1.januar(2017), orgnummer = a3) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a3 to INNTEKT)) håndterYtelserTilUtbetalt() håndterSøknad(Sykdom(1.januar, 20.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() val speilJson = speilApi() assertEquals(emptyList<GhostPeriodeDTO>(), speilJson.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder) val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId val perioder = speilJson.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder assertEquals(1, perioder.size) val actual = perioder.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 20.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) assertEquals(emptyList<GhostPeriodeDTO>(), speilJson.arbeidsgivere.single { it.organisasjonsnummer == a3 }.ghostPerioder) } @Test fun `ghost periode kuttes ved skjæringstidspunkt`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(3.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() val speilJson = speilApi() assertEquals( emptyList<GhostPeriodeDTO>(), speilJson.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder ) val perioder = speilJson.arbeidsgivere.find { it.organisasjonsnummer == a2 }?.ghostPerioder val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 3.januar }.vilkårsgrunnlagId assertEquals(1, perioder?.size) val actual = perioder!!.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 3.januar, tom = 31.januar, skjæringstidspunkt = 3.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } @Test fun `arbeidsforhold uten sykepengegrunnlag de tre siste månedene før skjæringstidspunktet skal ikke ha ghostperioder`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag( inntekter = listOf(a1 to INNTEKT), arbeidsforhold = listOf(a1 to EPOCH, a2 to EPOCH) ) håndterYtelserTilGodkjenning() val personDto = speilApi() val ghostpølser = personDto.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder assertEquals(0, ghostpølser.size) } @Test fun `legger ved sammenlignignsgrunnlag og sykepengegrunnlag for deaktiverte arbeidsforhold`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 1000.månedlig)) håndterYtelserTilGodkjenning() håndterOverstyrArbeidsforhold(1.januar, listOf(OverstyrArbeidsforhold.ArbeidsforholdOverstyrt(a2, true, "forklaring"))) håndterYtelserTilGodkjenning() val personDto = speilApi() val vilkårsgrunnlagId = (personDto.arbeidsgivere.first().generasjoner.first().perioder.first() as BeregnetPeriode).vilkårsgrunnlagId val vilkårsgrunnlag = personDto.vilkårsgrunnlag[vilkårsgrunnlagId] assertEquals(listOf(a1, a2), vilkårsgrunnlag?.inntekter?.map { it.organisasjonsnummer }) assertEquals( Arbeidsgiverinntekt( organisasjonsnummer = a2, omregnetÅrsinntekt = Inntekt( kilde = Inntektkilde.AOrdningen, beløp = 12000.0, månedsbeløp = 1000.0, inntekterFraAOrdningen = listOf( InntekterFraAOrdningen(YearMonth.of(2017, Month.OCTOBER), 1000.0), InntekterFraAOrdningen(YearMonth.of(2017, Month.NOVEMBER), 1000.0), InntekterFraAOrdningen(YearMonth.of(2017, Month.DECEMBER), 1000.0) ) ), deaktivert = true ), vilkårsgrunnlag?.inntekter?.find { it.organisasjonsnummer == a2 } ) } @Test fun `deaktiverte arbeidsforhold vises i speil selvom sammenligninggrunnlag og sykepengegrunnlag ikke er rapportert til A-ordningen enda`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag( inntekter = listOf(a1 to INNTEKT), arbeidsforhold = listOf(a1 to EPOCH, a2 to 1.desember(2017)) ) håndterYtelserTilGodkjenning() håndterOverstyrArbeidsforhold(1.januar, listOf(OverstyrArbeidsforhold.ArbeidsforholdOverstyrt(a2, true, "forklaring"))) håndterYtelserTilGodkjenning() val personDto = speilApi() val vilkårsgrunnlagId = (personDto.arbeidsgivere.first().generasjoner.first().perioder.first() as BeregnetPeriode).vilkårsgrunnlagId val vilkårsgrunnlag = personDto.vilkårsgrunnlag[vilkårsgrunnlagId] assertEquals(listOf(a1, a2), vilkårsgrunnlag?.inntekter?.map { it.organisasjonsnummer }) assertTrue(personDto.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder.isNotEmpty()) } @Test fun `deaktivert arbeidsforhold blir med i vilkårsgrunnlag`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar)) håndterVilkårsgrunnlag( arbeidsforhold = listOf(a1 to EPOCH, a2 to 1.desember(2017)) ) håndterYtelserTilGodkjenning() val skjæringstidspunkt = 1.januar håndterOverstyrArbeidsforhold(skjæringstidspunkt, listOf(OverstyrArbeidsforhold.ArbeidsforholdOverstyrt(a2, true, "forklaring"))) håndterYtelserTilGodkjenning() val personDto = speilApi() val vilkårsgrunnlagId = (personDto.arbeidsgivere.first().generasjoner.first().perioder.first() as BeregnetPeriode).vilkårsgrunnlagId val vilkårsgrunnlag = personDto.vilkårsgrunnlag[vilkårsgrunnlagId] val forventet = listOf( Arbeidsgiverinntekt( organisasjonsnummer = a1, omregnetÅrsinntekt = Inntekt( kilde = Inntektkilde.Inntektsmelding, beløp = 576000.0, månedsbeløp = 48000.0, inntekterFraAOrdningen = null ), deaktivert = false ), Arbeidsgiverinntekt( organisasjonsnummer = a2, omregnetÅrsinntekt = Inntekt( kilde = Inntektkilde.IkkeRapportert, beløp = 0.0, månedsbeløp = 0.0, inntekterFraAOrdningen = null ), deaktivert = true ) ) assertEquals(forventet, vilkårsgrunnlag?.inntekter) } @Test fun `Skal ikke ta med inntekt på vilkårsgrunnlaget som mangler både sykepengegrunnlag og sammenligningsgrunnlag på skjæringstidspunktet`() { nyttVedtak(1.januar(2017), 31.januar(2017), orgnummer = a2) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsforhold = listOf(a1 to 1.oktober(2017))) håndterYtelserTilGodkjenning() val personDto = speilApi() val vilkårsgrunnlagId = (personDto.arbeidsgivere.find { it.organisasjonsnummer == a1 }!!.generasjoner.first().perioder.first() as BeregnetPeriode).vilkårsgrunnlagId val vilkårsgrunnlag = personDto.vilkårsgrunnlag[vilkårsgrunnlagId] assertEquals(listOf(a1), vilkårsgrunnlag?.inntekter?.map { it.organisasjonsnummer }) assertEquals(listOf(a2, a1), personDto.arbeidsgivere.map { it.organisasjonsnummer }) } @Test fun `Ghostpølse forsvinner ikke etter overstyring av ghost-inntekt`() { håndterSøknad(Sykdom(1.januar, 20.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() håndterOverstyrArbeidsgiveropplysninger(1.januar, listOf(OverstyrtArbeidsgiveropplysning(a2, 9000.månedlig, ""))) håndterYtelserTilGodkjenning() val speilJson = speilApi() val perioder = speilJson.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId assertEquals(1, perioder.size) val actual = perioder.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 20.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } @Test fun `Ghosten finnes ikke i vilkårsgrunnlaget`() { håndterSøknad(Sykdom(1.januar, 20.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelser() val speilJson = speilApi() val vilkårsgrunnlag = speilJson.vilkårsgrunnlag assertEquals(1, vilkårsgrunnlag.size) val arbeidsgiverA1 = speilJson.arbeidsgivere.singleOrNull { it.organisasjonsnummer == a1 } assertEquals(1, arbeidsgiverA1?.generasjoner?.size) assertEquals(1, arbeidsgiverA1?.generasjoner?.single()?.perioder?.size) val beregnetPeriode = arbeidsgiverA1?.generasjoner?.single()?.perioder?.single() assertInstanceOf(BeregnetPeriode::class.java, beregnetPeriode) val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId val arbeidsgiverA2 = speilJson.arbeidsgivere.singleOrNull { it.organisasjonsnummer == a2 } assertEquals(0, arbeidsgiverA2?.generasjoner?.size) val perioder = arbeidsgiverA2?.ghostPerioder val actual = perioder?.single()!! assertEquals( GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 20.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ), actual ) } @Test fun `lager ikke Ghostperiode på et vilkårsgrunnlag som ingen beregnede perioder peker på`() { håndterSøknad(1.januar til 16.januar) håndterSøknad(17.januar til 31.januar) håndterInntektsmelding(listOf(1.januar til 16.januar)) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() håndterUtbetalingsgodkjenning(utbetalingGodkjent = false) val personDto = speilApi() val ghostPerioder = personDto.arbeidsgivere.singleOrNull { it.organisasjonsnummer == a2 }?.ghostPerioder assertNull(ghostPerioder) } @Test fun `Finner riktig ghostpølse etter overstyring av ghost-inntekt selvom begge arbeidsgiverne har saksbehandlerinntekt`() { håndterSøknad(Sykdom(1.januar, 20.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to 10000.månedlig)) håndterYtelserTilGodkjenning() håndterOverstyrArbeidsgiveropplysninger(1.januar, listOf(OverstyrtArbeidsgiveropplysning(a1, 30000.månedlig, ""))) håndterYtelserTilGodkjenning() håndterOverstyrArbeidsgiveropplysninger(1.januar, listOf(OverstyrtArbeidsgiveropplysning(a2, 9000.månedlig, ""))) håndterYtelserTilGodkjenning() val speilJson = speilApi() val perioder = speilJson.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId assertEquals(1, perioder.size) val actual = perioder.first() val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 20.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } @Test fun `ghost-perioder før og etter søknad`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterInntektsmelding(1.januar, orgnummer = a1) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to INNTEKT)) håndterYtelserTilGodkjenning() håndterUtbetalingsgodkjenning() håndterUtbetalt() håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent), orgnummer = a2) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent), orgnummer = a1) håndterSøknad(Sykdom(1.mars, 31.mars, 100.prosent), orgnummer = a1) val speilJson = speilApi() val perioder = speilJson.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder assertEquals(2, perioder.size) val skjæringstidspunkt = 1.januar val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId perioder[0].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 31.januar, skjæringstidspunkt = skjæringstidspunkt, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } perioder[1].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 1.mars, tom = 31.mars, skjæringstidspunkt = skjæringstidspunkt, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } } @Test fun `refusjon for flere arbeidsgivere`() { nyeVedtak(1.januar, 31.januar, a1, a2) val personDto = speilApi() val speilVilkårsgrunnlagIdForAG1 = (personDto.arbeidsgivere.first().generasjoner.first().perioder.first() as BeregnetPeriode).vilkårsgrunnlagId val speilVilkårsgrunnlagIdForAG2 = (personDto.arbeidsgivere.last().generasjoner.first().perioder.first() as BeregnetPeriode).vilkårsgrunnlagId val vilkårsgrunnlag = personDto.vilkårsgrunnlag[speilVilkårsgrunnlagIdForAG1] as? SpleisVilkårsgrunnlag val vilkårsgrunnlag2 = personDto.vilkårsgrunnlag[speilVilkårsgrunnlagIdForAG2] as? SpleisVilkårsgrunnlag assertEquals(vilkårsgrunnlag, vilkårsgrunnlag2) assertTrue(vilkårsgrunnlag!!.arbeidsgiverrefusjoner.isNotEmpty()) val arbeidsgiverrefusjonForAG1 = vilkårsgrunnlag.arbeidsgiverrefusjoner.find { it.arbeidsgiver == a1 }!! val arbeidsgiverrefusjonForAG2 = vilkårsgrunnlag.arbeidsgiverrefusjoner.find { it.arbeidsgiver == a2 }!! val refusjonsopplysningerForAG1 = arbeidsgiverrefusjonForAG1.refusjonsopplysninger.single() val refusjonsopplysningerForAG2 = arbeidsgiverrefusjonForAG2.refusjonsopplysninger.single() assertEquals(1.januar, refusjonsopplysningerForAG1.fom) assertEquals(null, refusjonsopplysningerForAG1.tom) assertEquals(48000.månedlig,refusjonsopplysningerForAG1.beløp.månedlig) assertEquals(1.januar, refusjonsopplysningerForAG2.fom) assertEquals(null, refusjonsopplysningerForAG2.tom) assertEquals(48000.månedlig,refusjonsopplysningerForAG2.beløp.månedlig) } @Test fun `flere førstegangsaker for begge arbeidsgivere med samme skjæringstidspunkt`() { håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), orgnummer = a1) håndterSøknad(Sykdom(12.februar, 12.mars, 100.prosent), orgnummer = a1) håndterSøknad(Sykdom(17.januar, 26.januar, 100.prosent), orgnummer = a2) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent), orgnummer = a2) håndterSøknad(Sykdom(13.mars, 31.mars, 100.prosent), orgnummer = a2) håndterInntektsmelding(1.januar, orgnummer = a1) håndterInntektsmelding(listOf(1.januar til 16.januar), orgnummer = a1) håndterInntektsmelding(listOf(17.januar til 26.januar, 1.februar til 6.februar), orgnummer = a2) håndterInntektsmelding(listOf(17.januar til 26.januar, 1.februar til 6.februar), orgnummer = a2) håndterVilkårsgrunnlag(arbeidsgivere = listOf(a1 to INNTEKT, a2 to INNTEKT)) håndterYtelserTilGodkjenning() val speilJson = speilApi() val spleisVilkårsgrunnlagId = dto().vilkårsgrunnlagHistorikk.historikk.first().vilkårsgrunnlag.single { it.skjæringstidspunkt == 1.januar }.vilkårsgrunnlagId speilJson.arbeidsgivere.single { it.organisasjonsnummer == a1 }.ghostPerioder.also { perioder -> assertEquals(2, perioder.size) perioder[0].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 1.februar, tom = 11.februar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } perioder[1].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 13.mars, tom = 31.mars, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } } speilJson.arbeidsgivere.single { it.organisasjonsnummer == a2 }.ghostPerioder.also { perioder -> assertEquals(2, perioder.size) perioder[0].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 1.januar, tom = 16.januar, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } perioder[1].also { actual -> val expected = GhostPeriodeDTO( id = actual.id, fom = 1.mars, tom = 12.mars, skjæringstidspunkt = 1.januar, vilkårsgrunnlagId = spleisVilkårsgrunnlagId, deaktivert = false ) assertEquals(expected, actual) } } } }
2
Kotlin
7
3
e7f4b5536caf37b4c4ce493233af1eb9e9d8c788
27,421
helse-spleis
MIT License
app/src/main/java/com/ghstudios/android/features/weapons/detail/WeaponBowgunDetailViewHolder.kt
theMaelstro
513,896,693
false
{"Kotlin": 743563, "Java": 406389}
package com.ghstudios.android.features.weapons.detail import android.content.Context import android.graphics.Typeface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.ghstudios.android.data.classes.Weapon import com.ghstudios.android.mhgendatabase.R import com.ghstudios.android.util.getColorCompat import kotlinx.android.synthetic.main.view_weapon_detail_bowgun.view.* private fun getWaitString(context: Context, wait: Int) = when (wait) { 0 -> context.getString(R.string.rapid_fire_short_wait) 1 -> context.getString(R.string.rapid_fire_medium_wait) 2 -> context.getString(R.string.rapid_fire_long_wait) 3 -> context.getString(R.string.rapid_fire_very_long_wait) else -> "" } class WeaponBowgunDetailViewHolder(parent: ViewGroup): WeaponDetailViewHolder { private val view: View private val ammoCells: List<TextView> private val internalAmmoCells: List<TextView> private val extraAmmoCells: List<TextView> val context get() = view.context init { val inflater = LayoutInflater.from(parent.context) view = inflater.inflate(R.layout.view_weapon_detail_bowgun, parent, true) ammoCells = listOf( view.findViewById(R.id.normal1), view.findViewById(R.id.normal2), view.findViewById(R.id.normal3), view.findViewById(R.id.pierce1), view.findViewById(R.id.pierce2), view.findViewById(R.id.pierce3), view.findViewById(R.id.pellet1), view.findViewById(R.id.pellet2), view.findViewById(R.id.pellet3), view.findViewById(R.id.crag1), view.findViewById(R.id.crag2), view.findViewById(R.id.crag3), view.findViewById(R.id.clust1), view.findViewById(R.id.clust2), view.findViewById(R.id.clust3), view.findViewById(R.id.flaming), view.findViewById(R.id.water), view.findViewById(R.id.thunder), view.findViewById(R.id.freeze), view.findViewById(R.id.dragon), view.findViewById(R.id.poison1), view.findViewById(R.id.poison2), view.findViewById(R.id.para1), view.findViewById(R.id.para2), view.findViewById(R.id.sleep1), view.findViewById(R.id.sleep2), view.findViewById(R.id.exhaust1), view.findViewById(R.id.exhaust2), view.findViewById(R.id.recov1), view.findViewById(R.id.recov2) ) internalAmmoCells = listOf( view.findViewById(R.id.internal_ammo_1), view.findViewById(R.id.internal_ammo_2), view.findViewById(R.id.internal_ammo_3), view.findViewById(R.id.internal_ammo_4), view.findViewById(R.id.internal_ammo_5) ) extraAmmoCells = listOf( view.findViewById(R.id.rapid_ammo_1), view.findViewById(R.id.rapid_ammo_2), view.findViewById(R.id.rapid_ammo_3), view.findViewById(R.id.rapid_ammo_4), view.findViewById(R.id.rapid_ammo_5) ) } override fun bindWeapon(weapon: Weapon) { // Usual weapon parameters view.attack_value.text = weapon.attack.toString() view.affinity_value.text = weapon.affinity + "%" view.defense_value.text = weapon.defense.toString() view.slots.setSlots(weapon.numSlots, 0) // Bowgun basic data view.reload_value.text = weapon.reloadSpeed view.recoil_value.text = weapon.recoil view.deviation_value.text = weapon.deviation // weapon ammo (todo: move this parsing to the weapon model) val ammos = weapon.ammo?.split("\\|".toRegex()) ?: emptyList() for ((ammoView, valueStr) in ammoCells.zip(ammos)) { val innate = valueStr[valueStr.lastIndex] == '*' val value = when (innate) { true -> valueStr.substring(0, valueStr.length - 1) false -> valueStr } ammoView.text = value if (innate) { ammoView.setTypeface(null, Typeface.BOLD) ammoView.setTextColor(context.getColorCompat(R.color.text_color_focused)) } } // Bind gun internal and rapid/siege bindInternalAmmo(weapon) if (weapon.wtype == Weapon.LIGHT_BOWGUN) { bindRapidFire(weapon) } else { bindSiegeFire(weapon) } } private fun bindInternalAmmo(weapon: Weapon) { // todo: move parsing to model... val internal = weapon.specialAmmo?.split("\\*".toRegex()) ?: emptyList() if (internal.isEmpty()) { internalAmmoCells[0].setText(R.string.ammo_none) internalAmmoCells[0].visibility = View.VISIBLE return } for ((ammoView, internalValue) in internalAmmoCells.zip(internal)) { val s = internalValue.split(":") ammoView.text = context.getString(R.string.weapon_internal_row, s[0], s[1], s[2]) ammoView.visibility = View.VISIBLE } } private fun bindRapidFire(weapon: Weapon) { view.weapon_extra_title.setText(R.string.rapid_fire) val rapid = weapon.rapidFire?.split("\\*".toRegex()) ?: emptyList() if (rapid.isEmpty()) { showEmptyExtra() return } for ((ammoView, rapidValue) in extraAmmoCells.zip(rapid)) { val s = rapidValue.split(":") val name = s[0] val count = s[1] val rfModifier = s[2] // % damage for extra shots val waitString = getWaitString(context, s[3].toInt()) ammoView.text = context.getString(R.string.weapon_rapid_row, name, count, rfModifier, waitString) ammoView.visibility = View.VISIBLE } } private fun bindSiegeFire(weapon: Weapon) { view.weapon_extra_title.setText(R.string.siege_mode) val siege = weapon.rapidFire?.split("\\*".toRegex()) ?: emptyList() if (siege.isEmpty()) { showEmptyExtra() return } for ((ammoView, siegeValue) in extraAmmoCells.zip(siege)) { val s = siegeValue.split(":") ammoView.text = context.getString(R.string.weapon_siege_row, s[0], s[1]) ammoView.visibility = View.VISIBLE } } /** * Helper used to show none in the extra ammo section (siege/rapid) */ private fun showEmptyExtra() { extraAmmoCells[0].let { it.visibility = View.VISIBLE it.setText(R.string.ammo_none) } } }
0
Kotlin
1
13
1ff7ce3430d4472a80682b61020f232ea19bf8cb
6,807
MHFZZDatabase
MIT License
features/mpcredits/src/main/java/com/jpp/mpcredits/CreditsFragment.kt
perettijuan
156,444,935
false
null
package com.jpp.mpcredits import android.content.Context import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.jpp.mp.common.extensions.observeValue import com.jpp.mp.common.extensions.setScreenTitle import com.jpp.mp.common.viewmodel.MPGenericSavedStateViewModelFactory import com.jpp.mpcredits.databinding.CreditsFragmentBinding import dagger.android.support.AndroidSupportInjection import javax.inject.Inject /** * Fragment used to show the list of credits that belongs to a particular movie selected by the user. * * When instantiated, this fragment invokes the [CreditsViewModel] methods in order to retrieve * and show the credits of the movie that has been selected by the user. The VM will perform the * fetch and will update the UI states represented by [CreditsViewState] and this Fragment will * render those updates. * * Pre-condition: in order to instantiate this Fragment, a movie ID must be provided in the arguments * of the Fragment. */ class CreditsFragment : Fragment() { @Inject lateinit var creditsViewModelFactory: CreditsViewModelFactory private var viewBinding: CreditsFragmentBinding? = null private val viewModel: CreditsViewModel by viewModels { MPGenericSavedStateViewModelFactory( creditsViewModelFactory, this ) } private var movieCreditsRv: RecyclerView? = null // used to restore the position of the RecyclerView on view re-creation // TODO we can simplify this once RecyclerView 1.2.0 is released // ==> https://medium.com/androiddevelopers/restore-recyclerview-scroll-position-a8fbdc9a9334 private var rvState: Parcelable? = null override fun onAttach(context: Context) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewBinding = DataBindingUtil.inflate(inflater, R.layout.credits_fragment, container, false) return viewBinding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews(view) rvState = savedInstanceState?.getParcelable(CREDITS_RV_STATE_KEY) ?: rvState viewModel.viewState.observeValue(viewLifecycleOwner, ::renderViewState) viewModel.onInit(CreditsInitParam.create(this@CreditsFragment)) } override fun onDestroyView() { viewBinding = null movieCreditsRv = null super.onDestroyView() } override fun onPause() { rvState = movieCreditsRv?.layoutManager?.onSaveInstanceState() super.onPause() } override fun onSaveInstanceState(outState: Bundle) { outState.putParcelable( CREDITS_RV_STATE_KEY, movieCreditsRv?.layoutManager?.onSaveInstanceState() ) super.onSaveInstanceState(outState) } private fun setupViews(view: View) { movieCreditsRv = view.findViewById<RecyclerView>(R.id.creditsRv).apply { layoutManager = LinearLayoutManager(context) layoutManager?.onRestoreInstanceState(rvState) addItemDecoration( DividerItemDecoration(context, (layoutManager as LinearLayoutManager).orientation) ) } } private fun renderViewState(viewState: CreditsViewState) { setScreenTitle(viewState.screenTitle) movieCreditsRv?.adapter = CreditsAdapter(viewState.creditsViewState.creditItems) { viewModel.onCreditItemSelected(it) } viewBinding?.viewState = viewState viewBinding?.executePendingBindings() } private companion object { const val CREDITS_RV_STATE_KEY = "creditsRvStateKey" } }
9
null
7
46
7921806027d5a9b805782ed8c1cad447444f476b
4,227
moviespreview
Apache License 2.0
lint-rules-androidarch-lint/src/test/java/fr/afaucogney/mobile/android/lint/rules/contract/WellSegregationOfFeatureContractInterfaceDetectorTest.kt
afaucogney
314,580,067
true
{"Kotlin": 340326, "Shell": 1027}
package fr.niji.mobile.android.socle.lint.rules.contract import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin import com.android.tools.lint.checks.infrastructure.TestLintTask import fr.niji.mobile.android.socle.lint.rules.contract.WellSegregationOfFeatureContractInterfaceDetector.Companion.ISSUE_FEATURE_CONTRACT_SEGREGATION import org.junit.Test class WellSegregationOfFeatureContractInterfaceDetectorTest { @Test fun testSuccess() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewCapabilities { | fun bar(): Any | } | interface ViewModel { | fun bar(): Any | } | interface ViewNavigation { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectClean() } @Test fun testSuccessOther() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContractt { | interface ViewCapabilities { | fun bar(): Any | } | interface ViewModel { | fun bar(): Any | } | interface ViewNavigation { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectClean() } @Test fun testViewCapabilitiesMissing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewCapabilities { | fun bar(): Any | } | | interface ViewNavigation { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(1) } @Test fun testViewModelMissing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewCapabilities { | fun bar(): Any | } | interface ViewNavigation { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(1) } @Test fun testViewTagMissing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewCapabilities { | fun bar(): Any | } | interface ViewModel { | fun bar(): Any | } | interface ViewNavigation { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(1) } @Test fun testViewEventMissing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewCapabilities { | fun bar(): Any | } | interface ViewModel { | fun bar(): Any | } | interface ViewNavigation { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(1) } @Test fun testViewNavigationMissing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewCapabilities { | fun bar(): Any | } | interface ViewModel { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(1) } @Test fun test2Missing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewModel { | fun bar(): Any | } | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(2) } @Test fun test3Missing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewTag { | fun bar(): Any | } | interface ViewEvent { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(3) } @Test fun test4Missing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { | interface ViewTag { | fun bar(): Any | } |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(4) } @Test fun testAllMissing() { TestLintTask.lint() .allowMissingSdk() .files(kotlin(""" |package foo | |interface IMyFeatureContract { |}""".trimMargin())) .issues(ISSUE_FEATURE_CONTRACT_SEGREGATION) .run() .expectErrorCount(5) } }
0
Kotlin
0
0
69180be08e8c36d5971827a8113447e3ba7be166
8,564
lint-rules
Apache License 2.0
tmp/arrays/youTrackTests/6878.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-25974 fun test(a: UInt) = when (a) { 0u -> "zero" 1u -> "one" 2u -> "two" 3u -> "three" else -> "other" }
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
203
bbfgradle
Apache License 2.0
modules/Plugin_Main/src/main/java/com/example/main/grid/impl/SpacesItemDecoration.kt
VintLin
551,830,745
false
{"Kotlin": 29946, "Java": 6575}
package com.voter.adaptivegridview.impl import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView.ItemDecoration import androidx.recyclerview.widget.RecyclerView class SpacesItemDecoration(private val padding: Int, private val isHorizontal: Boolean) : ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { if (isHorizontal) outRect.right = padding else outRect.bottom = padding } }
0
Kotlin
0
0
c346f8aafee9b9d641137a9f8dcac5becb32bd9f
523
Jetpack-Seed
Apache License 2.0
src/main/kotlin/org/jetbrains/intellij/platform/gradle/tasks/PatchPluginXmlTask.kt
JetBrains
33,932,778
false
{"Kotlin": 830835, "Java": 6924}
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.platform.gradle.tasks import com.jetbrains.plugin.structure.intellij.utils.JDOMUtil import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.file.ProjectLayout import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.tasks.* import org.jdom2.CDATA import org.jdom2.Document import org.jdom2.Element import org.jetbrains.intellij.platform.gradle.Constants.Plugin import org.jetbrains.intellij.platform.gradle.Constants.Tasks import org.jetbrains.intellij.platform.gradle.extensions.IntelliJPlatformExtension import org.jetbrains.intellij.platform.gradle.models.transformXml import org.jetbrains.intellij.platform.gradle.tasks.aware.IntelliJPlatformVersionAware import org.jetbrains.intellij.platform.gradle.utils.Logger import org.jetbrains.intellij.platform.gradle.utils.asPath import org.jetbrains.intellij.platform.gradle.utils.extensionProvider import kotlin.io.path.inputStream import kotlin.io.path.name /** * Patches `plugin.xml` files with values provided with the [IntelliJPlatformExtension.PluginConfiguration] extension. * * @see <a href="https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html">Plugin Configuration File</a> */ @CacheableTask abstract class PatchPluginXmlTask : DefaultTask(), IntelliJPlatformVersionAware { /** * Specifies the input `plugin.xml`</path>` file, which by default is picked from the main resource location. * * Default value: `src/main/resources/META-INF/plugin.xml` */ @get:InputFile @get:SkipWhenEmpty @get:PathSensitive(PathSensitivity.RELATIVE) abstract val inputFile: RegularFileProperty /** * Specifies the patched output `plugin.xml` file, which by default is written to a temporary task-specific directory within the [ProjectLayout.getBuildDirectory] directory. * * Default value: [ProjectLayout.getBuildDirectory]/tmp/patchPluginXml/plugin.xml */ @get:OutputFile abstract val outputFile: RegularFileProperty /** * Specifies a unique plugin identifier, which should be a fully qualified name similar to Java packages and must not collide with the ID of existing plugins. * The ID is a technical value used to identify the plugin in the IDE and [JetBrains Marketplace](https://plugins.jetbrains.com/). * * The provided value will be assigned to the [`<id>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__id) element. * * Please use characters, numbers, and `.`/`-`/`_` symbols only and keep it reasonably short. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.id] */ @get:Input @get:Optional abstract val pluginId: Property<String> /** * Specifies the user-visible plugin name. * It should use Title Case. * The provided value will be assigned to the [`<name>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__name) element. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.name] */ @get:Input @get:Optional abstract val pluginName: Property<String> /** * Specifies the plugin version displayed in the <control>Plugins</control> settings dialog and on the [JetBrains Marketplace](https://plugins.jetbrains.com) plugin page. * Plugins uploaded to [JetBrains Marketplace](https://plugins.jetbrains.com) must follow [semantic versioning](https://plugins.jetbrains.com/docs/marketplace/semver.htm). * The provided value will be assigned to the [`<version>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__version) element. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.version] */ @get:Input @get:Optional abstract val pluginVersion: Property<String> /** * Specifies the plugin description displayed in the <control>Plugins</control> settings dialog and on the [JetBrains Marketplace](https://plugins.jetbrains.com) plugin page. * Simple HTML elements, like text formatting, paragraphs, lists, etc., are allowed. * * The description content is automatically wrapped in `<![CDATA[... ]]>`. * The provided value will be assigned to the [`<description>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__description) element. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.description] */ @get:Input @get:Optional abstract val pluginDescription: Property<String> /** * A short summary of new features, bugfixes, and changes provided in this plugin version. * Change notes are displayed on the [JetBrains Marketplace](https://plugins.jetbrains.com) plugin page and in the <control>Plugins</control> settings dialog. * Simple HTML elements, like text formatting, paragraphs, lists, etc., are allowed. * * The change notes content is automatically wrapped in `<![CDATA[... ]]>`. * The provided value will be assigned to the [`<change-notes>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__change-notes) element. * * To maintain and generate an up-to-date changelog, try using [Gradle Changelog Plugin](https://github.com/JetBrains/gradle-changelog-plugin). * * Default value: [IntelliJPlatformExtension.PluginConfiguration.changeNotes] */ @get:Input @get:Optional abstract val changeNotes: Property<String> /** * The plugin product code used in the JetBrains Sales System. * The code must be agreed with JetBrains in advance and follow [the requirements](https://plugins.jetbrains.com/docs/marketplace/obtain-a-product-code-from-jetbrains.html). * The provided value will be assigned to the [`<product-descriptor code="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__product-descriptor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.ProductDescriptor.code] */ @get:Input @get:Optional abstract val productDescriptorCode: Property<String> /** * Date of the major version release in the `YYYYMMDD` format. * The provided value will be assigned to the [`<product-descriptor release-date="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__product-descriptor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.ProductDescriptor.releaseDate] */ @get:Input @get:Optional abstract val productDescriptorReleaseDate: Property<String> /** * Specifies the major version of the plugin in a special number format used for paid plugins on [JetBrains Marketplace](https://plugins.jetbrains.com/docs/marketplace/add-required-parameters.html). * The provided value will be assigned to the [`<product-descriptor release-version="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__product-descriptor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.ProductDescriptor.releaseVersion] */ @get:Input @get:Optional abstract val productDescriptorReleaseVersion: Property<String> /** * Specifies the boolean value determining whether the plugin is a [Freemium](https://plugins.jetbrains.com/docs/marketplace/freemium.html) plugin. * The provided value will be assigned to the [`<product-descriptor optional="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__product-descriptor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.ProductDescriptor.optional] */ @get:Input @get:Optional abstract val productDescriptorOptional: Property<Boolean> /** * Specifies the boolean value determining whether the plugin is an EAP release. * The provided value will be assigned to the [`<product-descriptor eap="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__product-descriptor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.ProductDescriptor.eap] */ @get:Input @get:Optional abstract val productDescriptorEap: Property<Boolean> /** * Specifies the lowest IDE version compatible with the plugin. * The provided value will be assigned to the [`<idea-version since-build="..."/>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__idea-version) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.IdeaVersion.sinceBuild] */ @get:Input @get:Optional abstract val sinceBuild: Property<String> /** * The highest IDE version compatible with the plugin. * The `until-build` attribute can be unset by setting `provider { null }` as a value, and note that only passing `null` will make Gradle use the default value instead. * However, if `until-build` is undefined, compatibility with all the IDEs since the version specified by the `since-build` is assumed, which can cause incompatibility errors in future builds. * * The provided value will be assigned to the [`<idea-version until-build="..."/>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__idea-version) element attribute. * * The `until-build` attribute can be unset by setting `provider { null }` as a value. * Passing `null` will make Gradle use the default value instead. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.IdeaVersion.untilBuild] */ @get:Input @get:Optional abstract val untilBuild: Property<String> /** * Specifies the vendor name or organization ID (if created) in the <control>Plugins</control> settings dialog and on the [JetBrains Marketplace](https://plugins.jetbrains.com) plugin page. * The provided value will be assigned to the [`<vendor>`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__vendor) element. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.Vendor.name] */ @get:Input @get:Optional abstract val vendorName: Property<String> /** * Specifies the vendor's email address. * The provided value will be assigned to the [`<vendor email="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__vendor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.Vendor.email] */ @get:Input @get:Optional abstract val vendorEmail: Property<String> /** * Specifies the link to the vendor's homepage. * The provided value will be assigned to the [`<vendor url="">`](https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html#idea-plugin__vendor) element attribute. * * Default value: [IntelliJPlatformExtension.PluginConfiguration.Vendor.url] */ @get:Input @get:Optional abstract val vendorUrl: Property<String> private val log = Logger(javaClass) @TaskAction fun patchPluginXml() { inputFile.asPath.inputStream().use { inputStream -> val document = JDOMUtil.loadDocument(inputStream) with(document) { patch(pluginId, "id") patch(pluginName, "name") patch(pluginVersion.takeIf { it.get() != Project.DEFAULT_VERSION }, "version") patch(pluginDescription, "description", isCDATA = true) patch(changeNotes, "change-notes", isCDATA = true) patch(productDescriptorCode, "product-descriptor", "code") patch(productDescriptorReleaseDate, "product-descriptor", "release-date") patch(productDescriptorReleaseVersion, "product-descriptor", "release-version") patch(productDescriptorOptional.map { it.toString() }, "product-descriptor", "optional") patch(productDescriptorEap.map { it.toString() }, "product-descriptor", "eap") patch(sinceBuild, "idea-version", "since-build") patch(untilBuild, "idea-version", "until-build", acceptNull = true) patch(vendorName, "vendor") patch(vendorEmail, "vendor", "email") patch(vendorUrl, "vendor", "url") } transformXml(document, outputFile.asPath) } } /** * Sets the [provider] value for the given [tagName] or [attributeName] of [tagName]. */ private fun Document.patch( provider: Provider<String?>?, tagName: String, attributeName: String? = null, isCDATA: Boolean = false, acceptNull: Boolean = false, ) { val value = provider?.orNull when { value != null -> patch(value, tagName, attributeName, isCDATA) acceptNull -> remove(tagName, attributeName) } } /** * Sets the [value] for the given [tagName] or [attributeName] of [tagName]. * If [value] is `null` but the relevant attribute or element exists, unset it. */ private fun Document.patch(value: String, tagName: String, attributeName: String? = null, isCDATA: Boolean = false) { val pluginXml = rootElement.takeIf { it.name == "idea-plugin" } ?: return val element = pluginXml.getChild(tagName) ?: Element(tagName).apply { pluginXml.addContent(0, this) } when { attributeName == null -> { val existingValue = element.text if (existingValue.isNotEmpty() && existingValue != value) { log.warn("Patching plugin.xml: value of '$tagName[$existingValue]' tag will be set to '$value'") } when { isCDATA -> element.addContent(CDATA(value)) else -> element.text = value } } else -> { val existingValue = element.getAttribute(attributeName)?.value if (!existingValue.isNullOrEmpty() && existingValue != value) { log.warn("Patching plugin.xml: attribute '$attributeName=[$existingValue]' of '$tagName' tag will be set to '$value'") } element.setAttribute(attributeName, value) } } } private fun Document.remove(tagName: String, attributeName: String? = null) { val pluginXml = rootElement.takeIf { it.name == "idea-plugin" } ?: return when { attributeName == null -> rootElement.removeChild(tagName) else -> { val element = pluginXml.getChild(tagName) ?: return element.removeAttribute(attributeName) } } } init { group = Plugin.GROUP_NAME description = "Patches plugin.xml file with provided values." } companion object : Registrable { override fun register(project: Project) = project.registerTask<PatchPluginXmlTask>(Tasks.PATCH_PLUGIN_XML) { val pluginConfigurationProvider = project.extensionProvider.map { it.pluginConfiguration } val productDescriptorProvider = pluginConfigurationProvider.map { it.productDescriptor } val ideaVersionProvider = pluginConfigurationProvider.map { it.ideaVersion } val vendorProvider = pluginConfigurationProvider.map { it.vendor } inputFile.convention(project.layout.file(project.provider { val sourceSets = project.extensions.getByName("sourceSets") as SourceSetContainer sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME) .resources .srcDirs .map { it.resolve("META-INF/plugin.xml") } .firstOrNull { it.exists() } })) outputFile.convention(project.layout.file( inputFile.map { temporaryDir.resolve(it.asPath.name) } )) pluginId.convention(pluginConfigurationProvider.flatMap { it.id }) pluginName.convention(pluginConfigurationProvider.flatMap { it.name }) pluginVersion.convention(pluginConfigurationProvider.flatMap { it.version }) pluginDescription.convention(pluginConfigurationProvider.flatMap { it.description }) changeNotes.convention(pluginConfigurationProvider.flatMap { it.changeNotes }) productDescriptorCode.convention(productDescriptorProvider.flatMap { it.code }) productDescriptorReleaseDate.convention(productDescriptorProvider.flatMap { it.releaseDate }) productDescriptorReleaseVersion.convention(productDescriptorProvider.flatMap { it.releaseVersion }) productDescriptorOptional.convention(productDescriptorProvider.flatMap { it.optional }) productDescriptorEap.convention(productDescriptorProvider.flatMap { it.eap }) sinceBuild.convention(ideaVersionProvider.flatMap { it.sinceBuild }) untilBuild.convention(ideaVersionProvider.flatMap { it.untilBuild }) vendorName.convention(vendorProvider.flatMap { it.name }) vendorEmail.convention(vendorProvider.flatMap { it.email }) vendorUrl.convention(vendorProvider.flatMap { it.url }) } } }
58
Kotlin
270
1,420
4e58259843ceeb4314a8d53cd72404c2f8b62bb8
18,010
intellij-platform-gradle-plugin
Apache License 2.0
compiler/testData/codegen/box/delegatedProperty/provideDelegate/localCaptured.kt
JakeWharton
99,388,807
false
null
// WITH_STDLIB import kotlin.test.* var log: String = "" inline fun <T> runLogged(entry: String, action: () -> T): T { log += entry return action() } operator fun String.provideDelegate(host: Any?, p: Any): String = runLogged("tdf($this);") { this } operator fun String.getValue(receiver: Any?, p: Any): String = runLogged("get($this);") { this } class Test { val testO by runLogged("O;") { "O" } val testK by runLogged("K;") { "K" } val testOK = runLogged("OK;") { testO + testK } } fun box(): String { assertEquals("", log) val test = Test() assertEquals("O;tdf(O);K;tdf(K);OK;get(O);get(K);", log) return test.testOK }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
681
kotlin
Apache License 2.0
src/main/kotlin/redux/actions.kt
Sgoldik
244,194,433
false
{"Kotlin": 23727, "CSS": 397, "HTML": 272}
package redux import data.* class ChangePresent(val lessonID: Int, val studentID: Int): RAction class AddStudent(val student: Student): RAction class ChangeStudent(val id: Int, val newStudent: Student): RAction class RemoveStudent(val id: Int) : RAction class AddLesson(val lesson: Lesson): RAction class ChangeLesson(val id: Int, val newLesson: Lesson): RAction class RemoveLesson(val id: Int): RAction class SetVisibilityFilter(val filter: VisibilityFilter) : RAction
0
Kotlin
0
0
788428d336b1129cb4eaf4e823e038970c9cf0f8
478
kotlinjs
MIT License
domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/logger/LoggerFactory.kt
SeanShubin
129,466,612
false
null
package com.seanshubin.condorcet.logger import com.seanshubin.condorcet.contract.FilesContract import com.seanshubin.condorcet.contract.FilesDelegate import java.nio.file.Path import java.time.Clock import java.time.ZonedDateTime import java.time.format.DateTimeFormatter class LoggerFactory( private val clock: Clock, private val files: FilesContract, private val emit: (String) -> Unit ) { fun createLogger(path: Path, name: String): Logger { val now = clock.instant() val zone = clock.zone val zonedDateTime = ZonedDateTime.ofInstant(now, zone) val formattedDateTime = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zonedDateTime) val fileName = formattedDateTime.replace(':', '-').replace('.', '-') + "-$name" val logFile = path.resolve(fileName) val initialize: () -> Unit = { files.createDirectories(path) } return LineEmittingAndFileLogger(initialize, emit, files, logFile) } fun createLogGroup(baseDir: Path): LogGroup { val now = clock.instant() val zone = clock.zone val zonedDateTime = ZonedDateTime.ofInstant(now, zone) val formattedDateTime = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zonedDateTime) val logDir = baseDir.resolve(formattedDateTime.replace(':', '-').replace('.', '-')) return LogGroup(emit, files, logDir) } companion object { val instanceDefaultZone: LoggerFactory by lazy { val clock: Clock = Clock.systemDefaultZone() val files: FilesContract = FilesDelegate val emit: (String) -> Unit = ::println LoggerFactory(clock, files, emit) } } }
2
null
1
1
1803f204372d994130167749c22f825c51c6a434
1,720
kotlin-tryme
The Unlicense
include-build/roborazzi-core/src/commonJvmMain/kotlin/com/github/takahirom/roborazzi/roboOutputName.kt
takahirom
594,307,070
false
{"Kotlin": 440745, "HTML": 2244, "CSS": 408}
package com.github.takahirom.roborazzi /** * You can utilize this function to generate the file name of the image to be recorded. * You can change naming strategy by setting roborazzi.record.namingStrategy. */ @ExperimentalRoborazziApi fun roboOutputName(): String { val roborazziContext = provideRoborazziContext() val description = roborazziContext.description if (description != null) { return DefaultFileNameGenerator.generateOutputNameWithDescription(description) } return DefaultFileNameGenerator.generateOutputNameWithStackTrace() }
83
Kotlin
34
712
0f528a13d085a8d2e3d218639f986fbbc21ce400
557
roborazzi
Apache License 2.0
lightspark-sdk/src/commonMain/kotlin/com/lightspark/sdk/model/IncomingPaymentAttemptStatus.kt
lightsparkdev
590,703,408
false
{"Kotlin": 1602812, "Java": 34937, "Dockerfile": 1719, "Shell": 490}
// Copyright ©, 2023-present, Lightspark Group, Inc. - All Rights Reserved @file:Suppress("ktlint:standard:max-line-length") package com.lightspark.sdk.model import com.lightspark.sdk.core.util.EnumSerializer import kotlinx.serialization.Serializable /** This is an enum that enumerates all potential statuses for an incoming payment attempt. **/ @Serializable(with = IncomingPaymentAttemptStatusSerializer::class) enum class IncomingPaymentAttemptStatus(val rawValue: String) { ACCEPTED("ACCEPTED"), SETTLED("SETTLED"), CANCELED("CANCELED"), UNKNOWN("UNKNOWN"), /** * This is an enum value that represents values that could be added in the future. * Clients should support unknown values as more of them could be added without notice. */ FUTURE_VALUE("FUTURE_VALUE"), } object IncomingPaymentAttemptStatusSerializer : EnumSerializer<IncomingPaymentAttemptStatus>( IncomingPaymentAttemptStatus::class, { rawValue -> IncomingPaymentAttemptStatus.values().firstOrNull { it.rawValue == rawValue } ?: IncomingPaymentAttemptStatus.FUTURE_VALUE }, )
1
Kotlin
1
4
7d9733e82eadf871494fd82cf6431871f763013d
1,164
kotlin-sdk
Apache License 2.0
src/main/kotlin/smile/data/Description.kt
sabbatinif
418,445,072
true
null
package smile.data /** * Description of a DataFrame feature. * @property mean is the feature mean value. * @property stdDev is the feature standard deviation. * @property min is the feature min value. * @property max is the feature max value. */ data class Description( val mean: Double, val stdDev: Double, val min: Double, val max: Double )
0
Kotlin
0
0
4f6dabb09d7f478cc377bf0828c47e37f77e15c9
366
PSyKE
Apache License 2.0
app/src/androidTest/java/tech/dalapenko/kinosearch/OpenFilmDetailsBySearchTest.kt
dalapenko
739,864,810
false
{"Kotlin": 136155, "Dockerfile": 1314}
package tech.dalapenko.kinosearch import androidx.test.ext.junit.rules.ActivityScenarioRule import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import org.junit.Rule import org.junit.Test import tech.dalapenko.kinosearch.screen.FilmDetailsScreen import tech.dalapenko.kinosearch.screen.HomeScreen import tech.dalapenko.kinosearch.screen.SearchScreen class OpenFilmDetailsBySearchTest : TestCase() { @get:Rule val activityRule = ActivityScenarioRule(MainActivity::class.java) @Test fun openFilmDetailsBySearchE2ETest() = run( testName = "[E2E] Поиск фильма. Точно совпадение имени. Переход в карточку фильма" ) { step("Нажать на поисковую строку главного экрана") { HomeScreen.searchBar.click() } step("Ввести в поисковую строку название фильма: $FILM_NAME") { SearchScreen.searchField.replaceText(FILM_NAME) } step("Проверить именя в первой карточке поисковой выдачи") { SearchScreen.searchResult.firstChild<SearchScreen.SearchResultItem> { ruTitle.hasText(FILM_NAME) } } step("Провалиться в карточку фильма") { SearchScreen.searchResult.firstChild(SearchScreen.SearchResultItem::click) } step("Проверить имя фильма в карточке фильма") { FilmDetailsScreen.title.hasText(FILM_NAME) } } } private const val FILM_NAME = "Ла-Ла Ленд"
0
Kotlin
0
0
0225d35212e97a650b0752f89114a25bd254ad0f
1,449
kinosearch
Apache License 2.0
src/main/kotlin/service/typescript/AddGetter.kt
takaakit
164,598,033
false
{"Kotlin": 337824}
package main.kotlin.service.typescript // ˅ import com.change_vision.jude.api.inf.editor.ModelEditorFactory import com.change_vision.jude.api.inf.model.IAttribute import com.change_vision.jude.api.inf.model.IClass import com.change_vision.jude.api.inf.model.INamedElement import java.util.* import java.text.* import main.kotlin.service.IMyPluginActionDelegate import main.kotlin.util.collector.AttributeCollector // ˄ class AddGetter : IMyPluginActionDelegate { // ˅ // ˄ override fun collectSelectedElements(): List<INamedElement> { // ˅ return AttributeCollector().collectFromSelectedElements() // ˄ } override fun excludeSetElements(selectedElements: List<INamedElement>): List<INamedElement> { // ˅ val targetAttributes = mutableListOf<INamedElement>() loop@ for (selectedElement in selectedElements) { for (operation in (selectedElement.owner as IClass).operations) { if (operation.name == selectedElement.name && operation.hasStereotype("get")) { continue@loop } } targetAttributes.add(selectedElement) } return targetAttributes // ˄ } override fun editElements(elements: List<INamedElement>) { // ˅ elements.forEach { val basicModelEditor = ModelEditorFactory.getBasicModelEditor() val getter = basicModelEditor.createOperation((it as IAttribute).owner as IClass, it.name, "") getter.addStereotype("get") println("Added getter :".plus(getter.getFullName(".").plus("()"))) } // ˄ } // ˅ // ˄ } // ˅ // ˄
0
Kotlin
0
6
ccef783fc643264da0ad4aa25f82c770d0b5edc9
1,736
helper-for-m-plus
Creative Commons Zero v1.0 Universal
common/src/main/java/com/library/common/mvvm/BaseViewModel.kt
yangbangwei
287,162,841
false
null
package com.library.common.mvvm import android.view.View import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.blankj.utilcode.util.NetworkUtils import com.library.common.R import com.library.common.base.BaseApplication import com.library.common.config.AppConfig import com.library.common.em.RequestDisplay import com.library.common.http.exception.ReturnCodeException import com.library.common.http.exception.ReturnCodeNullException import com.library.common.http.interceptor.IReturnCodeErrorInterceptor import kotlinx.coroutines.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import java.lang.reflect.ParameterizedType /** * BaseViewModel封装 * * @author yangbw * @date 2020/8/31 */ @Suppress("UNCHECKED_CAST") abstract class BaseViewModel<API> : ViewModel(), LifecycleObserver { //接口类 private var apiService: API? = null //默认相关错误提示 protected val emptyMsg: String by lazy { BaseApplication.context.getString(R.string.no_data) } protected val errorMsg: String by lazy { BaseApplication.context.getString(R.string.network_error) } protected val codeNullMsg: String by lazy { BaseApplication.context.getString(R.string.no_suc_code) } protected val serverErrorMsg: String by lazy { BaseApplication.context.getString(R.string.network_error_please_refresh) } /** * 重试的监听 */ var listener: View.OnClickListener? = null /** * 视图变化 */ val viewState: ViewState by lazy { ViewState() } /** * 获取接口操作类 */ fun getApiService(): API { if (apiService == null) { apiService = AppConfig.getRetrofit().create( (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<API> ) } return apiService ?: throw RuntimeException("Api service is null") } /** * 开始执行方法 */ open fun onStart() {} /** * 所有网络请求都在 viewModelScope 域中启动,当页面销毁时会自动 * 调用ViewModel的 #onCleared 方法取消所有协程 */ protected fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch { block() } /** * 用流的方式进行网络请求 */ fun <T> launchFlow(block: suspend () -> T): Flow<T> { return flow { emit(block()) } } /** * 过滤请求结果,其他全抛异常 * @param block 请求体 * @param success 成功回调 * @param error 失败回调 * @param complete 完成回调(无论成功失败都会调用) * @param type RequestDisplay类型 NULL无交互 TOAST REPLACE 替换 * @param msg TOAST文字提醒 * **/ fun <T> launchOnlyResult( block: suspend CoroutineScope.() -> IRes<T>, //成功 success: (IRes<T>) -> Unit = {}, //错误 根据错误进行不同分类 error: (Throwable) -> Unit = {}, //完成 complete: () -> Unit = {}, //重试 reTry: () -> Unit = {}, //当前请求的CurrentDomainName,默认的DOMAIN_NAME,也可自行设置 currentDomainName: String = AppConfig.DOMAIN_NAME, //接口操作交互类型 type: RequestDisplay = RequestDisplay.REPLACE, //弹窗文字提醒 msg: String = "" ) { //开始请求接口前 when (type) { RequestDisplay.NULL -> { } RequestDisplay.TOAST -> { viewState.showDialogProgress.value = msg } RequestDisplay.REPLACE -> { viewState.showLoading.call() } } //正式请求接口 launchUI { //异常处理 handleException( //调用接口 { withContext(Dispatchers.IO) { block() } }, { res -> //接口成功返回 executeResponse(type, res, currentDomainName) { //自定义成功处理 success(it) } }, { //通用异常处理 if (!NetworkUtils.isConnected()) { //无网络情况 onError(type) { reTry() } } else { when (it) { //未设置成功码 is ReturnCodeNullException -> { onError(type, codeNullMsg) { reTry() } } //返回非成功码 is ReturnCodeException -> { isIntercepted(it) onError(type, it.message) { reTry() } } else -> { //服务异常 1:服务器地址错误;2:网络未连接 onError(type, serverErrorMsg) { reTry() } } } } //自定义异常处理 error(it) }, { //接口完成 complete() } ) } } /** * 异常统一处理 */ protected suspend fun <T> handleException( block: suspend CoroutineScope.() -> IRes<T>, success: suspend CoroutineScope.(IRes<T>) -> Unit, error: suspend CoroutineScope.(Throwable) -> Unit, complete: suspend CoroutineScope.() -> Unit ) { coroutineScope { try { success(block()) } catch (e: Throwable) { error(e) } finally { complete() } } } /** * 请求结果过滤 */ private suspend fun <T> executeResponse( type: RequestDisplay, response: IRes<T>, currentDomainName: String, success: suspend CoroutineScope.(IRes<T>) -> Unit ) { coroutineScope { //单一地址和多地址判断 if (AppConfig.getMoreBaseUrl() && currentDomainName != AppConfig.DOMAIN_NAME) { val retSuccessList = AppConfig.getRetSuccessMap()?.get(currentDomainName) if (retSuccessList == null || retSuccessList.isEmpty()) { ///抛出未设置状态码异常 throw ReturnCodeNullException(response.getBaseCode(), response.getBaseMsg()) } //判断状态码是否包含 if (!retSuccessList.contains(response.getBaseCode())) { //抛出状态码错误异常 throw ReturnCodeException(response.getBaseCode(), response.getBaseMsg()) } } else { val retSuccessList = AppConfig.getRetSuccess() ?: throw ReturnCodeNullException( response.getBaseCode(), response.getBaseMsg() ) //判断状态码是否包含 if (!retSuccessList.contains(response.getBaseCode())) { //抛出状态码错误异常 throw ReturnCodeException(response.getBaseCode(), response.getBaseMsg()) } } //无需判断数据是否为空,直接返回处理 success(response) //完成的回调页面效果处理 when (type) { RequestDisplay.NULL -> { } RequestDisplay.TOAST -> { viewState.dismissDialogProgress.call() } RequestDisplay.REPLACE -> { viewState.restore.call() } } } } /** * 网络异常,状态码异常,未设置成功状态码 */ private fun onError( type: RequestDisplay, msg: String? = errorMsg, reTry: () -> Unit = {} ) { when (type) { RequestDisplay.NULL -> { } RequestDisplay.TOAST -> { viewState.showToast.value = msg viewState.dismissDialogProgress.call() } RequestDisplay.REPLACE -> { this.listener = View.OnClickListener { reTry() } viewState.showError.value = msg } } } /** * 异常code拦截 */ protected fun isIntercepted(t: Throwable): Boolean { var isIntercepted = false for (interceptor: IReturnCodeErrorInterceptor in AppConfig.getRetCodeInterceptors()) { if (interceptor.intercept((t as ReturnCodeException).returnCode)) { isIntercepted = true interceptor.doWork(t.returnCode, t.message) break } } return isIntercepted } }
0
Kotlin
2
9
d3791cfa3586c7430b5fb8d9870fcb71fab9d8f1
8,450
MvvmLib
Apache License 2.0
notifications/notifications/src/main/kotlin/org/opensearch/notifications/NotificationPlugin.kt
opensearch-project
354,080,507
false
null
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.notifications import org.opensearch.action.ActionRequest import org.opensearch.action.ActionResponse import org.opensearch.client.Client import org.opensearch.cluster.metadata.IndexNameExpressionResolver import org.opensearch.cluster.node.DiscoveryNodes import org.opensearch.cluster.service.ClusterService import org.opensearch.common.settings.ClusterSettings import org.opensearch.common.settings.IndexScopedSettings import org.opensearch.common.settings.Setting import org.opensearch.common.settings.Settings import org.opensearch.common.settings.SettingsFilter import org.opensearch.commons.notifications.action.NotificationsActions import org.opensearch.commons.utils.logger import org.opensearch.core.common.io.stream.NamedWriteableRegistry import org.opensearch.core.xcontent.NamedXContentRegistry import org.opensearch.env.Environment import org.opensearch.env.NodeEnvironment import org.opensearch.notifications.action.CreateNotificationConfigAction import org.opensearch.notifications.action.DeleteNotificationConfigAction import org.opensearch.notifications.action.GetChannelListAction import org.opensearch.notifications.action.GetNotificationConfigAction import org.opensearch.notifications.action.GetPluginFeaturesAction import org.opensearch.notifications.action.PublishNotificationAction import org.opensearch.notifications.action.SendNotificationAction import org.opensearch.notifications.action.SendTestNotificationAction import org.opensearch.notifications.action.UpdateNotificationConfigAction import org.opensearch.notifications.index.ConfigIndexingActions import org.opensearch.notifications.index.NotificationConfigIndex import org.opensearch.notifications.resthandler.NotificationChannelListRestHandler import org.opensearch.notifications.resthandler.NotificationConfigRestHandler import org.opensearch.notifications.resthandler.NotificationFeaturesRestHandler import org.opensearch.notifications.resthandler.SendTestMessageRestHandler import org.opensearch.notifications.security.UserAccessManager import org.opensearch.notifications.send.SendMessageActionHelper import org.opensearch.notifications.settings.PluginSettings import org.opensearch.notifications.spi.NotificationCore import org.opensearch.notifications.spi.NotificationCoreExtension import org.opensearch.plugins.ActionPlugin import org.opensearch.plugins.Plugin import org.opensearch.repositories.RepositoriesService import org.opensearch.rest.RestController import org.opensearch.rest.RestHandler import org.opensearch.script.ScriptService import org.opensearch.threadpool.ThreadPool import org.opensearch.watcher.ResourceWatcherService import java.util.function.Supplier /** * Entry point of the OpenSearch Notifications plugin * This class initializes the rest handlers. */ class NotificationPlugin : ActionPlugin, Plugin(), NotificationCoreExtension { lateinit var clusterService: ClusterService // initialized in createComponents() internal companion object { private val log by logger(NotificationPlugin::class.java) // Plugin main global constants const val PLUGIN_NAME = "opensearch-notifications" const val LOG_PREFIX = "notifications" const val PLUGIN_BASE_URI = "/_plugins/_notifications" // Other global constants const val TEXT_QUERY_TAG = "text_query" } /** * {@inheritDoc} */ override fun getSettings(): List<Setting<*>> { log.debug("$LOG_PREFIX:getSettings") return PluginSettings.getAllSettings() } /** * {@inheritDoc} */ override fun createComponents( client: Client, clusterService: ClusterService, threadPool: ThreadPool, resourceWatcherService: ResourceWatcherService, scriptService: ScriptService, xContentRegistry: NamedXContentRegistry, environment: Environment, nodeEnvironment: NodeEnvironment, namedWriteableRegistry: NamedWriteableRegistry, indexNameExpressionResolver: IndexNameExpressionResolver, repositoriesServiceSupplier: Supplier<RepositoriesService> ): Collection<Any> { log.debug("$LOG_PREFIX:createComponents") this.clusterService = clusterService PluginSettings.addSettingsUpdateConsumer(clusterService) NotificationConfigIndex.initialize(client, clusterService) ConfigIndexingActions.initialize(NotificationConfigIndex, UserAccessManager) SendMessageActionHelper.initialize(NotificationConfigIndex, UserAccessManager) return listOf() } /** * {@inheritDoc} */ override fun getActions(): List<ActionPlugin.ActionHandler<out ActionRequest, out ActionResponse>> { log.debug("$LOG_PREFIX:getActions") return listOf( ActionPlugin.ActionHandler(SendTestNotificationAction.ACTION_TYPE, SendTestNotificationAction::class.java), ActionPlugin.ActionHandler( NotificationsActions.CREATE_NOTIFICATION_CONFIG_ACTION_TYPE, CreateNotificationConfigAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.UPDATE_NOTIFICATION_CONFIG_ACTION_TYPE, UpdateNotificationConfigAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.DELETE_NOTIFICATION_CONFIG_ACTION_TYPE, DeleteNotificationConfigAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.GET_NOTIFICATION_CONFIG_ACTION_TYPE, GetNotificationConfigAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.GET_CHANNEL_LIST_ACTION_TYPE, GetChannelListAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.GET_PLUGIN_FEATURES_ACTION_TYPE, GetPluginFeaturesAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.SEND_NOTIFICATION_ACTION_TYPE, SendNotificationAction::class.java ), ActionPlugin.ActionHandler( NotificationsActions.LEGACY_PUBLISH_NOTIFICATION_ACTION_TYPE, PublishNotificationAction::class.java ) ) } /** * {@inheritDoc} */ override fun getRestHandlers( settings: Settings, restController: RestController, clusterSettings: ClusterSettings, indexScopedSettings: IndexScopedSettings, settingsFilter: SettingsFilter, indexNameExpressionResolver: IndexNameExpressionResolver, nodesInCluster: Supplier<DiscoveryNodes> ): List<RestHandler> { log.debug("$LOG_PREFIX:getRestHandlers") return listOf( NotificationConfigRestHandler(), NotificationFeaturesRestHandler(), NotificationChannelListRestHandler(), SendTestMessageRestHandler() // NotificationStatsRestHandler() ) } override fun setNotificationCore(core: NotificationCore) { log.debug("$LOG_PREFIX:setNotificationCore") CoreProvider.initialize(core) } }
47
null
48
8
ded1a4ccc574e0042457d388a9d91d87be64228e
7,365
notifications
Apache License 2.0
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/services/AbstractQueueWorker.kt
djdylan2000
316,985,658
true
{"Kotlin": 27048, "Shell": 861, "Dockerfile": 249}
package io.pleo.antaeus.core.services import java.util.concurrent.Executor // Provides a template to poll, process and delete messages abstract class AbstractQueueWorker<MESSAGE>(val threadCount: Int, val pollWaitTimeSecs: Int, val executor: Executor) { abstract fun process(message: MESSAGE): Boolean abstract fun markDone(message: MESSAGE) abstract fun markFailed(message: MESSAGE) abstract fun poll(): MESSAGE? fun start() { for (thread in 1..threadCount) { executor.execute(Worker()) Thread.sleep(100) } } inner class Worker : Runnable { override fun run() { while(true) { val message: MESSAGE? = poll() if (message == null) { Thread.sleep(pollWaitTimeSecs * 1000L) continue } try { if (process(message)) { markDone(message) } else { markFailed(message) } } catch (e : Exception) { markFailed(message) } Thread.sleep(100) } } } }
0
Kotlin
0
0
fa3331548f2c556721c85c3c0bd5880a65a9d185
1,240
antaeus
Creative Commons Zero v1.0 Universal
tool/agent-upgrade-dist/src/main/kotlin/AgentUpdateMetadata.kt
JetBrains
261,739,564
false
{"Dockerfile": 199712, "C#": 194974, "Kotlin": 50785, "Batchfile": 18861, "Shell": 13946, "Python": 6106, "PowerShell": 5194}
data class AgentUpdateMetadata(val version: String, val hash: String)
6
Dockerfile
58
97
883ff049c2a47c0443c00b4c32425bd29efac01c
69
teamcity-docker-images
Apache License 2.0
src/main/kotlin/com/mark/netrune/endpoint/MessageEncoder.kt
Mark7625
641,050,293
false
{"Kotlin": 173330, "Java": 27801}
package com.mark.netrune.endpoint import io.netty.buffer.ByteBuf import org.openrs2.crypto.StreamCipher interface MessageEncoder<M : OutgoingMessage> { val opcode: Int fun encode(message: M, output: ByteBuf, cipher: StreamCipher) fun writeLengthPlaceholder(output: ByteBuf) fun setLength(output: ByteBuf, lengthWriterIndex: Int, length: Int) }
0
Kotlin
1
1
ec39a338cc30f7bb3d12f551f18285b5b3618cd3
366
Osrs-Data-packer
MIT License
strikt-jvm/src/test/kotlin/strikt/java/PathAssertions.kt
robfletcher
131,475,396
false
null
package strikt.assertions import dev.minutest.TestDescriptor import org.junit.jupiter.api.TestFactory import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir import strikt.api.expectThat import java.io.File import java.nio.file.Files import java.nio.file.LinkOption import java.nio.file.Path import java.nio.file.Paths import java.nio.file.attribute.PosixFilePermission import java.nio.file.attribute.PosixFilePermissions // TODO: improve how fixture Path's are generated since we leveraging @TempDir, which only gets created once for the entire minutest test context internal object PathAssertions { private fun TestDescriptor.joinFullName() = fullName().joinToString(separator = "_") @TestFactory internal fun endsWith() = assertionTests<Path> { fixture { expectThat(Paths.get("startsWith", "endsWith")) } context("passes when the subject ends with") { test("the String type path") { endsWith("endsWith") } test("the Path type path") { endsWith(Paths.get("endsWith")) } } context("fails when the subject does not end with") { test("the String type path") { assertThrows<AssertionError> { endsWith("doesNotEndsWith") } } test("the Path type path") { assertThrows<AssertionError> { endsWith(Paths.get("doesNotEndsWith")) } } } } @TestFactory internal fun fileName() = assertionTests<Path> { fixture { expectThat(Paths.get("some", "path", "with", "name")) } test("maps to a Path of the file name") { fileName .isEqualTo(Paths.get("name")) } } @TestFactory internal fun isAbsolute() = assertionTests<Path> { context("when subject is an absolute path") { fixture { expectThat(Paths.get("/tmp", "path").toAbsolutePath()) } test("then assertion passes") { isAbsolute() } } context("when subject is not an absolute path") { fixture { expectThat(Paths.get("relative", "path")) } test("then assertion fails") { assertThrows<AssertionError> { isAbsolute() } } } } @TestFactory internal fun parent() = assertionTests<Path> { context("when subject is the root Path") { fixture { expectThat(Paths.get("/").root) } test("then the mapped value is null") { parent.isNull() } } context("when subject has a parent") { fixture { expectThat(Paths.get("parent", "child")) } test("then the mapped value is that parent") { parent .isNotNull() .isEqualTo(Paths.get("parent")) } } } @TestFactory internal fun resolve() = assertionTests<Path> { fixture { expectThat(Paths.get("parent")) } context("when the resolve value type is a Path") { test("then the mapped assertion is the resolved path") { resolve(Paths.get("child")) .isEqualTo(Paths.get("parent", "child")) } } context("when the resolve value type is a String") { test("then the mapped assertion is the resolved path") { resolve("child") .isEqualTo(Paths.get("parent", "child")) } } } @TestFactory internal fun startsWith() = assertionTests<Path> { fixture { expectThat(Paths.get("startsWith", "endsWith")) } context("passes when the subject starts with") { test("the String type path") { startsWith("startsWith") } test("the Path type path") { startsWith(Paths.get("startsWith")) } } context("fails when the subject does not start with") { test("the String type path") { assertThrows<AssertionError> { startsWith("doesNotStartWith") } } test("the Path type path") { assertThrows<AssertionError> { startsWith(Paths.get("doesNotStartWith")) } } } } @TestFactory internal fun toFile() = assertionTests<Path> { fixture { expectThat(Paths.get("path", "of", "file")) } test("mapped value is a File") { toFile() .isA<File>() } } @TestFactory internal fun exists(@TempDir directory: Path) = assertionTests<Path> { context("assertion passes") { context("when Path points to an existing file") { fixture { expectThat(Files.createFile(directory.resolve(it.name))) } } context("when Path points to a symlink that resolves to an existing file") { fixture { expectThat( Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_symlink"), Files.createFile(directory.resolve("${it.joinFullName()}_target")) ) ) } test("and no link options are provided") { exists() } test("and the ${LinkOption.NOFOLLOW_LINKS} is provided") { exists(LinkOption.NOFOLLOW_LINKS) } } context("when Path points to a symlink that resolves to a nonexistent file") { fixture { val symlink = Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_symlink"), directory.resolve("${it.joinFullName()}_nonexistent-target") ) expectThat(symlink) } test("and the ${LinkOption.NOFOLLOW_LINKS} is provided") { exists(LinkOption.NOFOLLOW_LINKS) } } } context("assertion fails") { context("when Path points to a nonexistent file") { fixture { expectThat(directory.resolve(it.joinFullName())) } } context("when Path points to a symlink that resolves to an existing file") { fixture { val symlink = Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_symlink"), Files.createFile(directory.resolve("${it.joinFullName()}_target")) ) expectThat(symlink) } test("and no link options are provided") { exists() } test("and the ${LinkOption.NOFOLLOW_LINKS} is provided") { exists(LinkOption.NOFOLLOW_LINKS) } } context("when Path points to a symlink that resolves to a nonexistent file") { fixture { val symlink = Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_symlink"), directory.resolve("${it.joinFullName()}_nonexistent-target") ) expectThat(symlink) } test("and no link options are provided") { assertThrows<AssertionError> { exists() } } } } } @TestFactory internal fun isDirectory(@TempDir directory: Path) = assertionTests<Path> { context("when subject Path is a regular file") { fixture { expectThat(Files.createFile(directory.resolve(it.joinFullName()))) } test("assertion fails") { assertThrows<AssertionError> { isDirectory() } } } context("when subject Path is a directory") { fixture { expectThat(Files.createDirectory(directory.resolve(it.joinFullName()))) } test("assertion passes") { isDirectory() } } context("when subject Path is a symlink") { context("to a file") { fixture { expectThat( Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_link"), Files.createFile(directory.resolve("${it.joinFullName()}_target")) ) ) } test("assertion fails") { assertThrows<AssertionError> { isDirectory() } } } context("to a directory") { fixture { expectThat( Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_link"), Files.createDirectory(directory.resolve(it.joinFullName())) ) ) } test("succeeds when no link options are provided") { isDirectory() } test("fails when ${LinkOption.NOFOLLOW_LINKS} options is provided") { assertThrows<AssertionError> { isDirectory(LinkOption.NOFOLLOW_LINKS) } } } } } @TestFactory internal fun isExecutable(@TempDir directory: Path) = assertionTests<Path> { context("passes when") { fixture { expectThat( Files.createFile( directory.resolve(it.joinFullName()), PosixFilePermissions.asFileAttribute( setOf( PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_EXECUTE ) ) ) ) } test("path has executable permission") { isExecutable() } } context("fails when") { fixture { expectThat( Files.createFile( directory.resolve(it.joinFullName()), PosixFilePermissions.asFileAttribute(setOf(PosixFilePermission.OWNER_READ)) ) ) } test("path does not have executable permission") { assertThrows<AssertionError> { isExecutable() } } } } @TestFactory internal fun isReadable(@TempDir directory: Path) = assertionTests<Path> { fixture { expectThat(directory) } context("when subject is an existing directory") { test("then assertion passes") { isReadable() } } } @TestFactory internal fun isRegularFile(@TempDir directory: Path) = assertionTests<Path> { context("when subject is a regular file") { fixture { expectThat(Files.createFile(directory.resolve(it.joinFullName()))) } test("then assertion passes when no link options are provided") { isRegularFile() } test("then assertion passes when ${LinkOption.NOFOLLOW_LINKS} option is provide") { isRegularFile(LinkOption.NOFOLLOW_LINKS) } } context("subject is a directory") { fixture { expectThat(Files.createDirectory(directory.resolve(it.joinFullName()))) } test("then assertion fails") { assertThrows<AssertionError> { isRegularFile() } } } } @TestFactory internal fun isSymbolicLink(@TempDir directory: Path) = assertionTests<Path> { context("subject does not exist") { fixture { expectThat(directory.resolve(it.joinFullName())) } test("then assertion fails") { assertThrows<AssertionError> { isSymbolicLink() } } } context("subject is a regular file") { fixture { expectThat(Files.createFile(directory.resolve(it.joinFullName()))) } test("then assertion fails") { assertThrows<AssertionError> { isSymbolicLink() } } } context("subject is a symlink that resolves to an existing file") { context("that resolves to an existing file") { fixture { expectThat( Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_symlink"), Files.createFile(directory.resolve("${it.joinFullName()}_target")) ) ) } test("assertion passes") { isSymbolicLink() } } context("that resolves to a nonexistent file") { fixture { expectThat( Files.createSymbolicLink( directory.resolve("${it.joinFullName()}_symlink"), directory.resolve("${it.joinFullName()}_target") ) ) } test("assertion passes") { isSymbolicLink() } } } } @TestFactory internal fun allBytes(@TempDir directory: Path) = assertionTests<Path> { context("subject is an empty file") { fixture { expectThat(Files.createFile(directory.resolve(it.joinFullName()))) } test("then allBytes() maps to an empty byte array") { allBytes() .isEqualTo(byteArrayOf()) } } context("subject is a single line file") { fixture { expectThat( Files.write( directory.resolve(it.joinFullName()), byteArrayOf(1, 2, 3, 4) ) ) } test("then allLines() maps to a singleton list of the line") { allBytes() .isEqualTo(byteArrayOf(1, 2, 3, 4)) } } } @TestFactory internal fun allLines(@TempDir directory: Path) = assertionTests<Path> { context("subject is an empty file") { fixture { expectThat(Files.createFile(directory.resolve(it.joinFullName()))) } test("then allLines() maps to an empty list") { allLines() .isEmpty() } test("then allLines(${Charsets.UTF_8}) maps to an empty list") { allLines(Charsets.UTF_8) .isEmpty() } } context("subject is a single line file") { fixture { expectThat( Files.write( directory.resolve(it.joinFullName()), listOf("first line") ) ) } test("then allLines() maps to a singleton list of the line") { allLines() .containsExactly("first line") } test("then allLines(${Charsets.UTF_8}) maps to a singleton list of the line") { allLines(Charsets.UTF_8) .containsExactly("first line") } } } @TestFactory internal fun size(@TempDir directory: Path) = assertionTests<Path> { context("subject is an empty file") { fixture { expectThat( Files.createFile(directory.resolve(it.joinFullName())) ) } test("then size maps to a 0 ") { size .isEqualTo(0) } } context("subject is a 4-byte file") { fixture { expectThat( Files.write( Files.createFile(directory.resolve(it.joinFullName())), byteArrayOf(1, 2, 3, 4) ) ) } test("then size maps to a 4") { size .isEqualTo(4) } } } }
49
null
59
547
a245ed90bc9a1d4da005f2442b8fcc92e15d86c7
14,099
strikt
Apache License 2.0
src/test/kotlin/no/nav/helse/flex/ThrottleVarsleTest.kt
navikt
495,745,215
false
{"Kotlin": 273838, "Dockerfile": 267}
package no.nav.helse.flex import no.nav.helse.flex.varselutsending.CronJobStatus.* import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldHaveSize import org.junit.jupiter.api.MethodOrderer import org.junit.jupiter.api.Order import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestMethodOrder import java.time.Duration import java.time.Instant import java.time.OffsetDateTime @TestMethodOrder(MethodOrderer.OrderAnnotation::class) class ThrottleVarsleTest : FellesTestOppsett() { @Test @Order(1) fun `Vi sender inn 6 søknader som venter på arbeidsgiver`() { (0 until 6).forEach { index -> sendSoknaderSomVenterPaArbeidsgiver(index) } val perioderSomVenterPaaArbeidsgiver = vedtaksperiodeBehandlingRepository.finnPersonerMedPerioderSomVenterPaaArbeidsgiver(Instant.now()) perioderSomVenterPaaArbeidsgiver.shouldHaveSize(6) } @Test @Order(2) fun `Vi sender ut mangler inntektsmelding varsel etter 15 dager`() { val cronjobResultat = varselutsendingCronJob.runMedParameter(OffsetDateTime.now().plusDays(16)) cronjobResultat[SENDT_FØRSTE_VARSEL_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 4 cronjobResultat[FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL_DRY_RUN] shouldBeEqualTo 6 cronjobResultat[UNIKE_FNR_KANDIDATER_FØRSTE_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 6 cronjobResultat[THROTTLET_FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL] shouldBeEqualTo 2 varslingConsumer.ventPåRecords(4, duration = Duration.ofMinutes(1)) meldingKafkaConsumer.ventPåRecords(4, duration = Duration.ofMinutes(1)) } @Test @Order(3) fun `Vi sender ut de to siste inntektsmelding varsel etter 15 dager`() { val cronjobResultat = varselutsendingCronJob.runMedParameter(OffsetDateTime.now().plusDays(16)) cronjobResultat[SENDT_FØRSTE_VARSEL_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 2 cronjobResultat[FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL_DRY_RUN] shouldBeEqualTo 2 cronjobResultat[UNIKE_FNR_KANDIDATER_FØRSTE_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 2 cronjobResultat[THROTTLET_FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL].shouldBeNull() varslingConsumer.ventPåRecords(2, duration = Duration.ofMinutes(1)) meldingKafkaConsumer.ventPåRecords(2, duration = Duration.ofMinutes(1)) } @Test @Order(4) fun `Vi sender ut de andre inntektsmelding varsel etter 29 dager`() { val cronjobResultat = varselutsendingCronJob.runMedParameter(OffsetDateTime.now().plusDays(29)) cronjobResultat[SENDT_FØRSTE_VARSEL_MANGLER_INNTEKTSMELDING].shouldBeNull() cronjobResultat[FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL_DRY_RUN] shouldBeEqualTo 0 cronjobResultat[UNIKE_FNR_KANDIDATER_FØRSTE_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 0 cronjobResultat[THROTTLET_FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL].shouldBeNull() cronjobResultat[SENDT_ANDRE_VARSEL_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 4 cronjobResultat[ANDRE_MANGLER_INNTEKTSMELDING_VARSEL_DRY_RUN] shouldBeEqualTo 6 cronjobResultat[UNIKE_FNR_KANDIDATER_ANDRE_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 6 cronjobResultat[THROTTLET_ANDRE_MANGLER_INNTEKTSMELDING_VARSEL] shouldBeEqualTo 2 // Donner varslingConsumer.ventPåRecords(4, duration = Duration.ofMinutes(1)) meldingKafkaConsumer.ventPåRecords(4, duration = Duration.ofMinutes(1)) // Nye varsler varslingConsumer.ventPåRecords(4, duration = Duration.ofMinutes(1)) meldingKafkaConsumer.ventPåRecords(4, duration = Duration.ofMinutes(1)) } @Test @Order(5) fun `Vi sender ut de to siste andre inntektsmelding varsel etter 29 dager`() { val cronjobResultat = varselutsendingCronJob.runMedParameter(OffsetDateTime.now().plusDays(29)) cronjobResultat[SENDT_FØRSTE_VARSEL_MANGLER_INNTEKTSMELDING].shouldBeNull() cronjobResultat[FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL_DRY_RUN] shouldBeEqualTo 0 cronjobResultat[UNIKE_FNR_KANDIDATER_FØRSTE_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 0 cronjobResultat[THROTTLET_FØRSTE_MANGLER_INNTEKTSMELDING_VARSEL].shouldBeNull() cronjobResultat[SENDT_ANDRE_VARSEL_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 2 cronjobResultat[ANDRE_MANGLER_INNTEKTSMELDING_VARSEL_DRY_RUN] shouldBeEqualTo 2 cronjobResultat[UNIKE_FNR_KANDIDATER_ANDRE_MANGLER_INNTEKTSMELDING] shouldBeEqualTo 2 cronjobResultat[THROTTLET_ANDRE_MANGLER_INNTEKTSMELDING_VARSEL].shouldBeNull() // Donner varslingConsumer.ventPåRecords(2, duration = Duration.ofMinutes(1)) meldingKafkaConsumer.ventPåRecords(2, duration = Duration.ofMinutes(1)) // Nye varsler varslingConsumer.ventPåRecords(2, duration = Duration.ofMinutes(1)) meldingKafkaConsumer.ventPåRecords(2, duration = Duration.ofMinutes(1)) } }
3
Kotlin
0
0
c0f1601558195e689a99e2e551a853160882575c
4,961
flex-inntektsmelding-status
MIT License
DraggableTitleBarComponents/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.event.WindowEvent import javax.swing.* import javax.swing.event.MouseInputAdapter import javax.swing.plaf.LayerUI import javax.swing.plaf.basic.BasicComboBoxUI private const val GAP = 4 private val left = SideLabel(Side.W) private val right = SideLabel(Side.E) private val top = SideLabel(Side.N) private val bottom = SideLabel(Side.S) private val topLeft = SideLabel(Side.NW) private val topRight = SideLabel(Side.NE) private val bottomLeft = SideLabel(Side.SW) private val bottomRight = SideLabel(Side.SE) private val contentPanel = JPanel(BorderLayout()) private val resizePanel = object : JPanel(BorderLayout()) { private val borderColor = Color(0x64_64_64) override fun paintComponent(g: Graphics) { val g2 = g.create() as? Graphics2D ?: return val w = width val h = height g2.paint = Color.ORANGE g2.fillRect(0, 0, w, h) g2.paint = borderColor g2.drawRect(0, 0, w - 1, h - 1) g2.drawLine(0, 2, 2, 0) g2.drawLine(w - 3, 0, w - 1, 2) g2.clearRect(0, 0, 2, 1) g2.clearRect(0, 0, 1, 2) g2.clearRect(w - 2, 0, 2, 1) g2.clearRect(w - 1, 0, 1, 2) g2.dispose() } } val mainContentPane get() = contentPanel fun makeUI() = JPanel(BorderLayout()).also { it.add(JScrollPane(JTree())) it.preferredSize = Dimension(320, 240) } fun makeFrame(str: String): JFrame { val frame = object : JFrame(str) { override fun getContentPane() = mainContentPane } frame.isUndecorated = true frame.background = Color(0x0, true) val title = JPanel(BorderLayout(GAP, GAP)) title.isOpaque = false title.background = Color.ORANGE title.border = BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP) val check = JCheckBox("JCheckBox") check.isOpaque = false check.isFocusable = false val titleBox = Box.createHorizontalBox() titleBox.add(makeComboBox(str)) titleBox.add(Box.createHorizontalGlue()) titleBox.add(check) val button = makeTitleButton(ApplicationIcon()) button.addActionListener { Toolkit.getDefaultToolkit().beep() } title.add(button, BorderLayout.WEST) title.add(titleBox) val close = makeTitleButton(CloseIcon()) close.addActionListener { e -> val w = (e.source as? JComponent)?.topLevelAncestor if (w is Window) { w.dispatchEvent(WindowEvent(w, WindowEvent.WINDOW_CLOSING)) } } title.add(close, BorderLayout.EAST) val rwl = ResizeWindowListener() listOf(left, right, top, bottom, topLeft, topRight, bottomLeft, bottomRight).forEach { it.addMouseListener(rwl) it.addMouseMotionListener(rwl) } val titlePanel = JPanel(BorderLayout()) titlePanel.add(top, BorderLayout.NORTH) titlePanel.add(JLayer(title, TitleBarDragLayerUI()), BorderLayout.CENTER) val northPanel = JPanel(BorderLayout()) northPanel.add(topLeft, BorderLayout.WEST) northPanel.add(titlePanel, BorderLayout.CENTER) northPanel.add(topRight, BorderLayout.EAST) val southPanel = JPanel(BorderLayout()) southPanel.add(bottomLeft, BorderLayout.WEST) southPanel.add(bottom, BorderLayout.CENTER) southPanel.add(bottomRight, BorderLayout.EAST) resizePanel.add(left, BorderLayout.WEST) resizePanel.add(right, BorderLayout.EAST) resizePanel.add(northPanel, BorderLayout.NORTH) resizePanel.add(southPanel, BorderLayout.SOUTH) resizePanel.add(contentPanel, BorderLayout.CENTER) titlePanel.isOpaque = false northPanel.isOpaque = false southPanel.isOpaque = false contentPanel.isOpaque = false resizePanel.isOpaque = false frame.contentPane = resizePanel return frame } private fun makeTitleButton(icon: Icon): JButton { val button = JButton(icon) button.isContentAreaFilled = false button.isFocusPainted = false button.border = BorderFactory.createEmptyBorder() button.isOpaque = true button.background = Color.ORANGE return button } private fun makeComboBox(title: String): JComboBox<String> { val items = arrayOf(title, "$title (1)", "$title (2)", "$title (3)") val combo = object : JComboBox<String>(items) { override fun updateUI() { super.updateUI() val cui = object : BasicComboBoxUI() { override fun createArrowButton() = JButton().also { it.border = BorderFactory.createEmptyBorder() it.isVisible = false } } setUI(cui) isOpaque = true foreground = Color.BLACK background = Color.ORANGE border = BorderFactory.createEmptyBorder() isFocusable = false font = font.deriveFont(18f) } } val ml = object : MouseAdapter() { private fun getButtonModel(e: MouseEvent) = ((e.component as? JComboBox<*>)?.getComponent(0) as? JButton)?.model override fun mouseEntered(e: MouseEvent) { getButtonModel(e)?.isRollover = true e.component.background = Color.ORANGE.darker() } override fun mouseExited(e: MouseEvent) { getButtonModel(e)?.isRollover = false e.component.background = Color.ORANGE } override fun mousePressed(e: MouseEvent) { getButtonModel(e)?.isPressed = true combo.isPopupVisible = false } override fun mouseReleased(e: MouseEvent) { getButtonModel(e)?.isPressed = false } override fun mouseClicked(e: MouseEvent) { combo.isPopupVisible = true } } combo.addMouseListener(ml) return combo } private enum class Side(private val cursor: Int, private val width: Int, private val height: Int) { N(Cursor.N_RESIZE_CURSOR, 0, 4) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.y += delta.y rect.height -= delta.y return rect } }, W(Cursor.W_RESIZE_CURSOR, 4, 0) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.x += delta.x rect.width -= delta.x return rect } }, E(Cursor.E_RESIZE_CURSOR, 4, 0) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.width += delta.x return rect } }, S(Cursor.S_RESIZE_CURSOR, 0, 4) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.height += delta.y return rect } }, NW(Cursor.NW_RESIZE_CURSOR, 4, 4) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.y += delta.y rect.height -= delta.y rect.x += delta.x rect.width -= delta.x return rect } }, NE(Cursor.NE_RESIZE_CURSOR, 4, 4) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.y += delta.y rect.height -= delta.y rect.width += delta.x return rect } }, SW(Cursor.SW_RESIZE_CURSOR, 4, 4) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.height += delta.y rect.x += delta.x rect.width -= delta.x return rect } }, SE(Cursor.SE_RESIZE_CURSOR, 4, 4) { override fun getBounds(rect: Rectangle, delta: Point): Rectangle { rect.height += delta.y rect.width += delta.x return rect } }, ; val size get() = Dimension(width, height) fun getCursor(): Cursor = Cursor.getPredefinedCursor(cursor) abstract fun getBounds(rect: Rectangle, delta: Point): Rectangle } private class SideLabel(val side: Side) : JLabel() { init { cursor = side.getCursor() } override fun getPreferredSize() = side.size override fun getMinimumSize() = preferredSize override fun getMaximumSize() = preferredSize } private class ResizeWindowListener : MouseInputAdapter() { private val rect = Rectangle() override fun mousePressed(e: MouseEvent) { val p = SwingUtilities.getRoot(e.component) if (p is Window) { rect.bounds = p.getBounds() } } override fun mouseDragged(e: MouseEvent) { val c = e.component val p = SwingUtilities.getRoot(c) if (!rect.isEmpty && c is SideLabel && p is Window) { val side = c.side p.setBounds(side.getBounds(rect, e.point)) } } } private class TitleBarDragLayerUI : LayerUI<JComponent>() { private val startPt = Point() override fun installUI(c: JComponent) { super.installUI(c) if (c is JLayer<*>) { c.layerEventMask = AWTEvent.MOUSE_EVENT_MASK or AWTEvent.MOUSE_MOTION_EVENT_MASK } } override fun uninstallUI(c: JComponent) { (c as? JLayer<*>)?.layerEventMask = 0 super.uninstallUI(c) } override fun processMouseEvent( e: MouseEvent, l: JLayer<out JComponent>, ) { if (e.id == MouseEvent.MOUSE_PRESSED && SwingUtilities.isLeftMouseButton(e)) { startPt.location = e.point } } override fun processMouseMotionEvent( e: MouseEvent, l: JLayer<out JComponent>, ) { val c = SwingUtilities.getRoot(e.component) if (e.id == MouseEvent.MOUSE_DRAGGED && c is Window && SwingUtilities.isLeftMouseButton(e)) { val pt = c.getLocation() c.setLocation(pt.x - startPt.x + e.x, pt.y - startPt.y + e.y) } } } private class ApplicationIcon : Icon { override fun paintIcon( c: Component?, g: Graphics, x: Int, y: Int, ) { val g2 = g.create() as? Graphics2D ?: return g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.translate(x, y) g2.paint = Color.BLUE g2.fillOval(4, 4, 11, 11) g2.dispose() } override fun getIconWidth() = 16 override fun getIconHeight() = 16 } private class CloseIcon : Icon { override fun paintIcon( c: Component?, g: Graphics, x: Int, y: Int, ) { val g2 = g.create() as? Graphics2D ?: return g2.translate(x, y) g2.paint = Color.BLACK g2.drawLine(4, 4, 11, 11) g2.drawLine(4, 5, 10, 11) g2.drawLine(5, 4, 11, 10) g2.drawLine(11, 4, 4, 11) g2.drawLine(11, 5, 5, 11) g2.drawLine(10, 4, 4, 10) g2.dispose() } override fun getIconWidth() = 16 override fun getIconHeight() = 16 } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } makeFrame("title").apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) minimumSize = Dimension(100, 100) pack() setLocationRelativeTo(null) isVisible = true } } }
0
null
6
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
10,395
kotlin-swing-tips
MIT License
src/main/kotlin/io/unthrottled/doki/icons/jetbrains/config/IconSettings.kt
doki-theme
527,949,815
false
{"Kotlin": 92318, "Java": 6130, "Shell": 272, "Batchfile": 28}
package io.unthrottled.doki.icons.jetbrains.config import com.intellij.openapi.ui.ComboBox import io.unthrottled.doki.icons.jetbrains.themes.DokiTheme import io.unthrottled.doki.icons.jetbrains.themes.IconThemeManager import java.util.Vector import javax.swing.DefaultComboBoxModel class ThemeComboItem(private val dokiTheme: DokiTheme) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ThemeComboItem if (dokiTheme.id != other.dokiTheme.id) return false return true } override fun hashCode(): Int { return dokiTheme.id.hashCode() } val id: String get() = dokiTheme.id override fun toString(): String { return dokiTheme.listName } } data class IconSettingsModel( var isUIIcons: Boolean, var isNamedFileIcons: Boolean, var isGlyphIcons: Boolean, var isNamedFolderIcons: Boolean, var isMyIcons: Boolean, var currentThemeId: String, var syncWithDokiTheme: Boolean ) object IconSettings { const val SETTINGS_ID = "io.unthrottled.doki.icons.jetbrains.settings.ThemeSettings" const val ICON_SETTINGS_DISPLAY_NAME = "Doki Theme Icons Settings" @JvmStatic fun createSettingsModule(): IconSettingsModel = IconSettingsModel( isUIIcons = Config.instance.isUIIcons, isNamedFileIcons = Config.instance.isNamedFileIcons, isGlyphIcons = Config.instance.isGlyphIcon, isNamedFolderIcons = Config.instance.isNamedFolderIcons, isMyIcons = Config.instance.isMyIcons, currentThemeId = IconThemeManager.instance.getThemeById( Config.instance.currentThemeId ).orElseGet { IconThemeManager.instance.defaultTheme }.id, syncWithDokiTheme = Config.instance.syncWithDokiTheme ) fun createThemeComboBoxModel(settingsSupplier: () -> IconSettingsModel): ComboBox<ThemeComboItem> { val themeList = IconThemeManager.instance.allThemes .sortedBy { theme -> theme.listName } .map { ThemeComboItem(it) } val themeComboBox = ComboBox( DefaultComboBoxModel( Vector( themeList ) ) ) themeComboBox.model.selectedItem = themeList.find { it.id == settingsSupplier().currentThemeId } themeComboBox.addActionListener { settingsSupplier().currentThemeId = (themeComboBox.model.selectedItem as ThemeComboItem).id } return themeComboBox } }
18
Kotlin
3
44
5e66f9361e2ebec52f9ede5be9b1213bf2847c89
2,437
doki-theme-icons-jetbrains
MIT License
src/main/java/com/mallowigi/search/parsers/HexColorParser.kt
AtomMaterialUI
215,215,096
false
null
/* * The MIT License (MIT) * * Copyright (c) 2015-2022 <NAME>Mallowigi" Boukhobza * * 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.mallowigi.search.parsers import com.mallowigi.utils.ColorUtils import java.awt.Color /** * Parse a color in the hex format * * @param prefix - the prefix to offset with */ class HexColorParser internal constructor(prefix: String) : ColorParser { private val offset: Int init { offset = prefix.length } override fun parseColor(text: String): Color? = parseHex(text) /** * parse a color in the hex format */ private fun parseHex(text: String): Color? = when (text.length) { 3 + offset -> ColorUtils.getShortRGB(text.substring(offset)) // RGB 8 + offset -> ColorUtils.getRGBA(text.substring(offset)) // RRGGBBAA 6 + offset -> ColorUtils.getRGB(text.substring(offset)) // RRGGBB else -> null } }
5
null
24
41
7dd8fd0f0dfed3c60c7c6b1d024e5b389ae65550
1,937
color-highlighter
MIT License
core-data/src/main/java/com/stefang/dev/core/data/file/CryptoFileKeyStore.kt
stef-ang
652,432,695
false
null
package com.stefang.dev.core.data.file import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import android.util.Log import com.google.gson.Gson import java.nio.charset.Charset import java.security.KeyStore import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec import javax.inject.Inject class CryptoFileKeyStore @Inject constructor( private val gson: Gson ) : CryptoFile { private val TAG = "CryptoFile" companion object { private const val KEY_SIZE = 256 private const val ANDROID_KEYSTORE = "AndroidKeyStore" private const val ENCRYPTION_BLOCK_MODE = KeyProperties.BLOCK_MODE_GCM private const val ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_NONE private const val ENCRYPTION_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES private const val TLEN = 128 private const val CHAR_ENCODING = "UTF-8" private const val SECRET_KEY_NAME = "com.stefang.dev.core.data.file.key" } private fun getInitializedCipherForEncryption(): Cipher { val cipher = getCipher() val secretKey = getOrCreateSecretKey() cipher.init(Cipher.ENCRYPT_MODE, secretKey) return cipher } private fun getInitializedCipherForDecryption(initializationVector: ByteArray): Cipher { val cipher = getCipher() val secretKey = getOrCreateSecretKey() cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(TLEN, initializationVector)) return cipher } private fun getCipher(): Cipher { val transformation = "$ENCRYPTION_ALGORITHM/$ENCRYPTION_BLOCK_MODE/$ENCRYPTION_PADDING" return Cipher.getInstance(transformation) } private fun getOrCreateSecretKey(): SecretKey { val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE) // .load(null) to create an empty Keystore, Keystore must be loaded before it can be accessed keyStore.load(null) keyStore.getKey(SECRET_KEY_NAME, null)?.let { // If SecretKey was previously created for that KEY_NAME, then grab and return it. Log.d(TAG, "SecretKey: reusing KeyStore") return it as SecretKey } // if you reach here, then a new SecretKey must be generated for that keyName val paramsBuilder = KeyGenParameterSpec.Builder( SECRET_KEY_NAME, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT ) paramsBuilder.apply { setBlockModes(ENCRYPTION_BLOCK_MODE) setEncryptionPaddings(ENCRYPTION_PADDING) setKeySize(KEY_SIZE) setUserAuthenticationRequired(false) } val keyGenParams = paramsBuilder.build() val keyGenerator = KeyGenerator.getInstance( ENCRYPTION_ALGORITHM, ANDROID_KEYSTORE ) keyGenerator.init(keyGenParams) Log.d(TAG, "SecretKey: NEW KeyStore") return keyGenerator.generateKey() } override fun encryptData(data: String): String { val cipher = getInitializedCipherForEncryption() val encryptedText = cipher.doFinal(data.toByteArray(Charset.forName(CHAR_ENCODING))) return gson.toJson(CiphertextWrapper(encryptedText, cipher.iv)) } override fun decryptData(data: String): String { val ciphertextWrapper = gson.fromJson(data, CiphertextWrapper::class.java) val cipher = getInitializedCipherForDecryption(ciphertextWrapper.initializationVector) val plaintext = cipher.doFinal(ciphertextWrapper.ciphertext) return String(plaintext, Charset.forName(CHAR_ENCODING)) } }
0
Kotlin
0
0
e7b0dd4c071c3ec5c662d601672ff467b6b937df
3,744
ScanMeCalculator
Apache License 2.0
app/src/main/java/com/ctech/eaty/ui/login/viewmodel/LoginViewModel.kt
dbof10
116,687,959
false
null
package com.ctech.eaty.ui.login.viewmodel import com.ctech.eaty.entity.UserDetail import com.ctech.eaty.tracking.FirebaseTrackManager import com.ctech.eaty.ui.login.navigation.LoginNavigation import com.ctech.eaty.ui.login.state.LoginState import io.reactivex.Completable import io.reactivex.Observable class LoginViewModel(private val stateDispatcher: Observable<LoginState>, private val navigation: LoginNavigation, private val trackManager: FirebaseTrackManager) { fun loading(): Observable<LoginState> { return stateDispatcher .filter { it.loading } } fun loadError(): Observable<Throwable> { return stateDispatcher .filter { it.loadError != null && !it.loading } .map { it.loadError!! } .doOnNext { trackManager.trackLoginFail(it.message) } } fun tokenGrant(): Observable<LoginState> { return stateDispatcher .filter { it.tokenGrant && !it.firstTime } } fun configUser(): Completable { return stateDispatcher .filter { it.firstTime } .flatMapCompletable { navigation.toEdit() } } fun content(): Completable { return stateDispatcher .filter { !it.loading && it.loadError == null && it.content != UserDetail.GUEST } .doOnNext { trackManager.trackLoginSuccess(it.loginSource) } .map { it.content } .flatMapCompletable { navigation.toHome(it) } } fun loginWithFacebook() { navigation.toFacebook().subscribe() } fun loginWithTwitter() { navigation.toTwitter().subscribe() } }
2
Kotlin
11
49
2e3445debaedfea03f9b44ab62744046fe07f1cc
2,041
hunt-android
Apache License 2.0
game-plugins/src/main/kotlin/org/alter/plugins/service/worldlist/model/WorldLocation.kt
AlterRSPS
421,831,790
false
null
package org.alter.plugins.service.worldlist.model /** * @author <NAME> ("Dread") * * Represents the various world locations * * @param id The flag id */ enum class WorldLocation(val id: Int) { UNITED_STATES(0), UNITED_KINGDOM(1), CANADA(2), AUSTRALIA(3), NETHERLANDS(4), SWEDEN(5), FINLAND(6), GERMANY(7) }
8
Kotlin
33
23
9dbd62d67de547cfedc43b902797306c5db8fb55
348
Alter
Apache License 2.0
src/commonMain/kotlin/com/soywiz/korau/format/atrac3plus/ChannelUnit.kt
kpspemu
108,654,928
false
null
package com.soywiz.korau.format.atrac3plus import com.soywiz.kmem.arraycopy import com.soywiz.kmem.fill import com.soywiz.kmem.signExtend import com.soywiz.korau.format.atrac3plus.Atrac3plusData1.atrac3p_spectra_tabs import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_ct_restricted_to_full import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_qu_num_to_seg import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_qu_to_subband import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_sf_shapes import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_subband_to_num_powgrps import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_wl_shapes import com.soywiz.korau.format.atrac3plus.Atrac3plusData2.atrac3p_wl_weights import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.AT3P_ERROR import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.ATRAC3P_FRAME_SAMPLES import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.ATRAC3P_POWER_COMP_OFF import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.ATRAC3P_SUBBANDS import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.ATRAC3P_SUBBAND_SAMPLES import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.CH_UNIT_STEREO import com.soywiz.korau.format.atrac3plus.Atrac3plusDsp.Companion.ff_atrac3p_mant_tab import com.soywiz.korau.format.atrac3plus.Atrac3plusDsp.Companion.ff_atrac3p_qu_to_spec_pos import com.soywiz.korau.format.atrac3plus.Atrac3plusDsp.Companion.ff_atrac3p_sf_tab import com.soywiz.korau.format.util.* import com.soywiz.korau.format.util.CodecUtils.avLog2 import com.soywiz.korio.lang.format import kotlin.math.abs /* * Based on the FFmpeg version from <NAME>. * All credits go to him. * C to Java conversion by gid15 for the jpcsp project. * Java to Kotlin for kpspemu */ class ChannelUnit { var ctx = ChannelUnitContext() private lateinit var br: BitReader private var dsp: Atrac3plusDsp? = null private var numChannels: Int = 0 /** * Decode number of code table values. * * @return result code: 0 = OK, otherwise - error code */ private val numCtValues: Int get() { if (!br.readBool()) { return ctx.usedQuantUnits } val numCodedVals = br.read(5) if (numCodedVals > ctx.usedQuantUnits) { log.error { "Invalid number of code table indexes: %d".format(numCodedVals) } return AT3P_ERROR } return numCodedVals } fun setBitReader(br: BitReader) { this.br = br } fun setDsp(dsp: Atrac3plusDsp) { this.dsp = dsp } fun setNumChannels(numChannels: Int) { this.numChannels = numChannels } fun decode(): Int { var ret: Int ctx.numQuantUnits = br.read(5) + 1 if (ctx.numQuantUnits > 28 && ctx.numQuantUnits < 32) { log.error("Invalid number of quantization units: %d".format(ctx.numQuantUnits)) return AT3P_ERROR } ctx.muteFlag = br.readBool() ret = decodeQuantWordlen() if (ret < 0) { return ret } ctx.numSubbands = atrac3p_qu_to_subband[ctx.numQuantUnits - 1] + 1 ctx.numCodedSubbands = if (ctx.usedQuantUnits > 0) atrac3p_qu_to_subband[ctx.usedQuantUnits - 1] + 1 else 0 ret = decodeScaleFactors() if (ret < 0) { return ret } ret = decodeCodeTableIndexes() if (ret < 0) { return ret } decodeSpectrum() if (numChannels == 2) { getSubbandFlags(ctx.swapChannels, ctx.numCodedSubbands) getSubbandFlags(ctx.negateCoeffs, ctx.numCodedSubbands) } decodeWindowShape() ret = decodeGaincData() if (ret < 0) { return ret } ret = decodeTonesInfo() if (ret < 0) { return ret } ctx.noisePresent = br.readBool() if (ctx.noisePresent) { ctx.noiseLevelIndex = br.read(4) ctx.noiseTableIndex = br.read(4) } return 0 } /** * Decode number of coded quantization units. * * @param[in,out] chan ptr to the channel parameters * @return result code: 0 = OK, otherwise - error code */ private fun numCodedUnits(chan: Channel): Int { chan.fillMode = br.read(2) if (chan.fillMode == 0) { chan.numCodedVals = ctx.numQuantUnits } else { chan.numCodedVals = br.read(5) if (chan.numCodedVals > ctx.numQuantUnits) { log.error { "Invalid number of transmitted units" } return AT3P_ERROR } if (chan.fillMode == 3) { chan.splitPoint = br.read(2) + (chan.chNum shl 1) + 1 } } return 0 } private fun getDelta(deltaBits: Int): Int { return if (deltaBits <= 0) 0 else br.read(deltaBits) } /** * Unpack vector quantization tables. * * @param startVal start value for the unpacked table * @param shapeVec ptr to table to unpack * @param dst ptr to output array * @param numValues number of values to unpack */ private fun unpackVqShape(startVal: Int, shapeVec: IntArray, dst: IntArray, numValues: Int) { if (numValues > 0) { dst[0] = startVal dst[1] = startVal dst[2] = startVal for (i in 3 until numValues) { dst[i] = startVal - shapeVec[atrac3p_qu_num_to_seg[i] - 1] } } } private fun unpackSfVqShape(dst: IntArray, numValues: Int) { val startVal = br.read(6) unpackVqShape(startVal, atrac3p_sf_shapes[br.read(6)], dst, numValues) } /** * Add weighting coefficients to the decoded word-length information. * * @param[in,out] chan ptr to the channel parameters * @param[in] wtab_idx index of the table of weights * @return result code: 0 = OK, otherwise - error code */ private fun addWordlenWeights(chan: Channel, weightIdx: Int): Int { val weigthsTab = atrac3p_wl_weights[chan.chNum * 3 + weightIdx - 1] for (i in 0 until ctx.numQuantUnits) { chan.quWordlen[i] += weigthsTab[i] if (chan.quWordlen[i] < 0 || chan.quWordlen[i] > 7) { log.error { "WL index out of range pos=%d, val=%d".format(i, chan.quWordlen[i]) } return AT3P_ERROR } } return 0 } /** * Decode word length for each quantization unit of a channel. * * @param[in] chNum channel to process * @return result code: 0 = OK, otherwise - error code */ private fun decodeChannelWordlen(chNum: Int): Int { val ret: Int val chan = ctx.channels[chNum] val refChan = ctx.channels[0] var weightIdx = 0 chan.fillMode = 0 when (br.read(2)) { // switch according to coding mode 0 // coded using constant number of bits -> for (i in 0 until ctx.numQuantUnits) { chan.quWordlen[i] = br.read(3) } 1 -> if (chNum > 0) { ret = numCodedUnits(chan) if (ret < 0) { return ret } if (chan.numCodedVals > 0) { val vlcTab = wl_vlc_tabs[br.read(2)] for (i in 0 until chan.numCodedVals) { val delta = vlcTab.getVLC2(br) chan.quWordlen[i] = refChan.quWordlen[i] + delta and 7 } } } else { weightIdx = br.read(2) ret = numCodedUnits(chan) if (ret < 0) { return ret } if (chan.numCodedVals > 0) { val pos = br.read(5) if (pos > chan.numCodedVals) { log.error { "WL mode 1: invalid position %d".format(pos) } return AT3P_ERROR } val deltaBits = br.read(2) val minVal = br.read(3) for (i in 0 until pos) { chan.quWordlen[i] = br.read(3) } for (i in pos until chan.numCodedVals) { chan.quWordlen[i] = minVal + getDelta(deltaBits) and 7 } } } 2 -> { ret = numCodedUnits(chan) if (ret < 0) { return ret } if (chNum > 0 && chan.numCodedVals > 0) { val vlcTab = wl_vlc_tabs[br.read(2)]!! var delta = vlcTab.getVLC2(br) chan.quWordlen[0] = refChan.quWordlen[0] + delta and 7 for (i in 1 until chan.numCodedVals) { val diff = refChan.quWordlen[i] - refChan.quWordlen[i - 1] delta = vlcTab.getVLC2(br) chan.quWordlen[i] = chan.quWordlen[i - 1] + diff + delta and 7 } } else if (chan.numCodedVals > 0) { val flag = br.readBool() val vlcTab = wl_vlc_tabs[br.read(1)]!! val startVal = br.read(3) unpackVqShape(startVal, atrac3p_wl_shapes[startVal][br.read(4)], chan.quWordlen, chan.numCodedVals) if (!flag) { for (i in 0 until chan.numCodedVals) { val delta = vlcTab.getVLC2(br) chan.quWordlen[i] = chan.quWordlen[i] + delta and 7 } } else { var i: Int i = 0 while (i < chan.numCodedVals and -2) { if (!br.readBool()) { chan.quWordlen[i] = chan.quWordlen[i] + vlcTab.getVLC2(br) and 7 chan.quWordlen[i + 1] = chan.quWordlen[i + 1] + vlcTab.getVLC2(br) and 7 } i += 2 } if (chan.numCodedVals and 1 != 0) { chan.quWordlen[i] = chan.quWordlen[i] + vlcTab.getVLC2(br) and 7 } } } } 3 -> { weightIdx = br.read(2) ret = numCodedUnits(chan) if (ret < 0) { return ret } if (chan.numCodedVals > 0) { val vlcTab = wl_vlc_tabs[br.read(2)]!! // first coefficient is coded directly chan.quWordlen[0] = br.read(3) for (i in 1 until chan.numCodedVals) { val delta = vlcTab.getVLC2(br) chan.quWordlen[i] = chan.quWordlen[i - 1] + delta and 7 } } } } if (chan.fillMode == 2) { for (i in chan.numCodedVals until ctx.numQuantUnits) { chan.quWordlen[i] = if (chNum > 0) br.read1() else 1 } } else if (chan.fillMode == 3) { val pos = if (chNum > 0) chan.numCodedVals + chan.splitPoint else ctx.numQuantUnits - chan.splitPoint for (i in chan.numCodedVals until pos) { chan.quWordlen[i] = 1 } } return if (weightIdx != 0) { addWordlenWeights(chan, weightIdx) } else 0 } /** * Subtract weighting coefficients from decoded scalefactors. * * @param[in,out] chan ptr to the channel parameters * @param[in] wtab_idx index of table of weights * @return result code: 0 = OK, otherwise - error code */ private fun substractSfWeights(chan: Channel, wtabIdx: Int): Int { val weigthsTab = Atrac3plusData2.atrac3p_sf_weights[wtabIdx - 1] for (i in 0 until ctx.usedQuantUnits) { chan.quSfIdx[i] -= weigthsTab[i] if (chan.quSfIdx[i] < 0 || chan.quSfIdx[i] > 63) { log.error { "SF index out of range pos=%d, val=%d".format(i, chan.quSfIdx[i]) } return AT3P_ERROR } } return 0 } /** * Decode scale factor indexes for each quant unit of a channel. * * @param[in] chNum channel to process * @return result code: 0 = OK, otherwise - error code */ private fun decodeChannelSfIdx(chNum: Int): Int { val chan = ctx.channels[chNum] val refChan = ctx.channels[0] var weightIdx = 0 chan.fillMode = 0 when (br.read(2)) { // switch according to coding mode 0 // coded using constant number of bits -> for (i in 0 until ctx.usedQuantUnits) { chan.quSfIdx[i] = br.read(6) } 1 -> if (chNum > 0) { val vlcTab = sf_vlc_tabs[br.read(2)]!! for (i in 0 until ctx.usedQuantUnits) { val delta = vlcTab.getVLC2(br) chan.quSfIdx[i] = refChan.quSfIdx[i] + delta and 0x3F } } else { weightIdx = br.read(2) if (weightIdx == 3) { unpackSfVqShape(chan.quSfIdx, ctx.usedQuantUnits) val numLongVals = br.read(5) val deltaBits = br.read(2) val minVal = br.read(4) - 7 for (i in 0 until numLongVals) { chan.quSfIdx[i] = chan.quSfIdx[i] + br.read(4) - 7 and 0x3F } // All others are: minVal + delta for (i in numLongVals until ctx.usedQuantUnits) { chan.quSfIdx[i] = chan.quSfIdx[i] + minVal + getDelta(deltaBits) and 0x3F } } else { val numLongVals = br.read(5) val deltaBits = br.read(3) val minVal = br.read(6) if (numLongVals > ctx.usedQuantUnits || deltaBits == 7) { log.error("SF mode 1: invalid parameters".format()) return AT3P_ERROR } // Read full-precision SF indexes for (i in 0 until numLongVals) { chan.quSfIdx[i] = br.read(6) } // All others are: minVal + delta for (i in numLongVals until ctx.usedQuantUnits) { chan.quSfIdx[i] = minVal + getDelta(deltaBits) and 0x3F } } } 2 -> if (chNum > 0) { val vlcTab = sf_vlc_tabs[br.read(2)]!! var delta = vlcTab.getVLC2(br) chan.quSfIdx[0] = refChan.quSfIdx[0] + delta and 0x3F for (i in 1 until ctx.usedQuantUnits) { val diff = refChan.quSfIdx[i] - refChan.quSfIdx[i - 1] delta = vlcTab.getVLC2(br) chan.quSfIdx[i] = chan.quSfIdx[i - 1] + diff + delta and 0x3F } } else if (chan.numCodedVals > 0) { val vlcTab = sf_vlc_tabs[br.read(2) + 4] unpackSfVqShape(chan.quSfIdx, ctx.usedQuantUnits) for (i in 0 until ctx.usedQuantUnits) { val delta = vlcTab!!.getVLC2(br) chan.quSfIdx[i] = chan.quSfIdx[i] + delta.signExtend(4) and 0x3F } } 3 -> if (chNum > 0) { // Copy coefficients from reference channel for (i in 0 until ctx.usedQuantUnits) { chan.quSfIdx[i] = refChan.quSfIdx[i] } } else { weightIdx = br.read(2) val vlcSel = br.read(2) var vlcTab = sf_vlc_tabs[vlcSel]!! if (weightIdx == 3) { vlcTab = sf_vlc_tabs[vlcSel + 4]!! unpackSfVqShape(chan.quSfIdx, ctx.usedQuantUnits) var diff = br.read(4) + 56 and 0x3F chan.quSfIdx[0] = chan.quSfIdx[0] + diff and 0x3F for (i in 1 until ctx.usedQuantUnits) { val delta = vlcTab.getVLC2(br) diff = diff + delta.signExtend(4) and 0x3F chan.quSfIdx[i] = diff + chan.quSfIdx[i] and 0x3F } } else { // 1st coefficient is coded directly chan.quSfIdx[0] = br.read(6) for (i in 1 until ctx.usedQuantUnits) { val delta = vlcTab.getVLC2(br) chan.quSfIdx[i] = chan.quSfIdx[i - 1] + delta and 0x3F } } } } return if (weightIdx != 0 && weightIdx < 3) { substractSfWeights(chan, weightIdx) } else 0 } /** * Decode word length information for each channel. * * @return result code: 0 = OK, otherwise - error code */ private fun decodeQuantWordlen(): Int { for (chNum in 0 until numChannels) { ctx.channels[chNum].quWordlen.fill(0) val ret = decodeChannelWordlen(chNum) if (ret < 0) { return ret } } /* scan for last non-zero coeff in both channels and * set number of quant units having coded spectrum */ var i: Int i = ctx.numQuantUnits - 1 while (i >= 0) { if (ctx.channels[0].quWordlen[i] != 0 || numChannels == 2 && ctx.channels[1].quWordlen[i] != 0) { break } i-- } ctx.usedQuantUnits = i + 1 return 0 } private fun decodeScaleFactors(): Int { if (ctx.usedQuantUnits == 0) { return 0 } for (chNum in 0 until numChannels) { ctx.channels[chNum].quSfIdx.fill(0) val ret = decodeChannelSfIdx(chNum) if (ret < 0) { return ret } } return 0 } /** * Decode code table indexes for each quant unit of a channel. * * @param[in] chNum channel to process * @return result code: 0 = OK, otherwise - error code */ private fun decodeChannelCodeTab(chNum: Int): Int { val vlcTab: VLC val numVals: Int val mask = if (ctx.useFullTable) 7 else 3 // mask for modular arithmetic val chan = ctx.channels[chNum] val refChan = ctx.channels[0] chan.tableType = br.read(1) when (br.read(2)) { // switch according to coding mode 0 // directly coded -> { val numBits = if (ctx.useFullTable) 3 else 2 numVals = numCtValues if (numVals < 0) { return numVals } for (i in 0 until numVals) { if (chan.quWordlen[i] != 0) { chan.quTabIdx[i] = br.read(numBits) } else if (chNum > 0 && refChan.quWordlen[i] != 0) { // get clone master flag chan.quTabIdx[i] = br.read1() } } } 1 // entropy-coded -> { vlcTab = if (ctx.useFullTable) ct_vlc_tabs[1]!! else ct_vlc_tabs[0]!! numVals = numCtValues if (numVals < 0) { return numVals } for (i in 0 until numVals) { if (chan.quWordlen[i] != 0) { chan.quTabIdx[i] = vlcTab.getVLC2(br) } else if (chNum > 0 && refChan.quWordlen[i] != 0) { // get clone master flag chan.quTabIdx[i] = br.read1() } } } 2 // entropy-coded delta -> { val deltaVlc: VLC if (ctx.useFullTable) { vlcTab = ct_vlc_tabs[1]!! deltaVlc = ct_vlc_tabs[2]!! } else { vlcTab = ct_vlc_tabs[0]!! deltaVlc = ct_vlc_tabs[0]!! } var pred = 0 numVals = numCtValues if (numVals < 0) { return numVals } for (i in 0 until numVals) { if (chan.quWordlen[i] != 0) { chan.quTabIdx[i] = if (i == 0) vlcTab.getVLC2(br) else pred + deltaVlc.getVLC2(br) and mask pred = chan.quTabIdx[i] } else if (chNum > 0 && refChan.quWordlen[i] != 0) { // get clone master flag chan.quTabIdx[i] = br.read1() } } } 3 // entropy-coded difference to master -> if (chNum > 0) { vlcTab = if (ctx.useFullTable) ct_vlc_tabs[3] else ct_vlc_tabs[0] numVals = numCtValues if (numVals < 0) { return numVals } for (i in 0 until numVals) { if (chan.quWordlen[i] != 0) { chan.quTabIdx[i] = refChan.quTabIdx[i] + vlcTab.getVLC2(br) and mask } else if (chNum > 0 && refChan.quWordlen[i] != 0) { // get clone master flag chan.quTabIdx[i] = br.read1() } } } } return 0 } /** * Decode code table indexes for each channel. * * @return result code: 0 = OK, otherwise - error code */ private fun decodeCodeTableIndexes(): Int { if (ctx.usedQuantUnits == 0) { return 0 } ctx.useFullTable = br.readBool() for (chNum in 0 until numChannels) { ctx.channels[chNum].quTabIdx.fill(0) val ret = decodeChannelCodeTab(chNum) if (ret < 0) { return ret } } return 0 } private fun decodeQuSpectra(tab: Atrac3plusData1.Atrac3pSpecCodeTab, vlcTab: VLC, out: IntArray, outOffset: Int, numSpecs: Int) { val groupSize = tab.groupSize val numCoeffs = tab.numCoeffs val bits = tab.bits val isSigned = tab.isSigned val mask = (1 shl bits) - 1 var pos = 0 while (pos < numSpecs) { if (groupSize == 1 || br.readBool()) { for (j in 0 until groupSize) { var `val` = vlcTab.getVLC2(br) for (i in 0 until numCoeffs) { var cf = `val` and mask if (isSigned) { cf = cf.signExtend(bits) } else if (cf != 0 && br.readBool()) { cf = -cf } out[outOffset + pos] = cf pos++ `val` = `val` shr bits } } } else { // Group skipped pos += groupSize * numCoeffs } } } private fun decodeSpectrum() { for (chNum in 0 until numChannels) { val chan = ctx.channels[chNum] chan.spectrum.fill(0) chan.powerLevs.fill(ATRAC3P_POWER_COMP_OFF) for (qu in 0 until ctx.usedQuantUnits) { val numSpecs = ff_atrac3p_qu_to_spec_pos[qu + 1] - ff_atrac3p_qu_to_spec_pos[qu] val wordlen = chan.quWordlen[qu] var codetab = chan.quTabIdx[qu] if (wordlen > 0) { if (!ctx.useFullTable) { codetab = atrac3p_ct_restricted_to_full[chan.tableType][wordlen - 1][codetab] } var tabIndex = (chan.tableType * 8 + codetab) * 7 + wordlen - 1 val tab = atrac3p_spectra_tabs[tabIndex] if (tab.redirect >= 0) { tabIndex = tab.redirect } decodeQuSpectra(tab, spec_vlc_tabs[tabIndex]!!, chan.spectrum, ff_atrac3p_qu_to_spec_pos[qu], numSpecs) } else if (chNum > 0 && ctx.channels[0].quWordlen[qu] != 0 && codetab == 0) { // Copy coefficients from master arraycopy(ctx.channels[0].spectrum, ff_atrac3p_qu_to_spec_pos[qu], chan.spectrum, ff_atrac3p_qu_to_spec_pos[qu], numSpecs) chan.quWordlen[qu] = ctx.channels[0].quWordlen[qu] } } /* Power compensation levels only present in the bitstream * if there are more than 2 quant units. The lowest two units * correspond to the frequencies 0...351 Hz, whose shouldn't * be affected by the power compensation. */ if (ctx.usedQuantUnits > 2) { val numSpecs = atrac3p_subband_to_num_powgrps[ctx.numCodedSubbands - 1] for (i in 0 until numSpecs) { chan.powerLevs[i] = br.read(4) } } } } private fun getSubbandFlags(out: BooleanArray, numFlags: Int): Boolean { val result = br.readBool() if (result) { if (br.readBool()) { for (i in 0 until numFlags) { out[i] = br.readBool() } } else { for (i in 0 until numFlags) { out[i] = true } } } else { for (i in 0 until numFlags) { out[i] = false } } return result } /** * Decode mdct window shape flags for all channels. * */ private fun decodeWindowShape() { for (i in 0 until numChannels) { getSubbandFlags(ctx.channels[i].wndShape, ctx.numSubbands) } } private fun decodeGaincNPoints(chNum: Int, codedSubbands: Int): Int { val chan = ctx.channels[chNum] val refChan = ctx.channels[0] when (br.read(2)) { // switch according to coding mode 0 // fixed-length coding -> for (i in 0 until codedSubbands) { chan.gainData[i].numPoints = br.read(3) } 1 // variable-length coding -> for (i in 0 until codedSubbands) { chan.gainData[i].numPoints = gain_vlc_tabs[0].getVLC2(br) } 2 -> if (chNum > 0) { // VLC modulo delta to master channel for (i in 0 until codedSubbands) { val delta = gain_vlc_tabs[1].getVLC2(br) chan.gainData[i].numPoints = refChan.gainData[i].numPoints + delta and 7 } } else { // VLC modulo delta to previous chan.gainData[0].numPoints = gain_vlc_tabs[0].getVLC2(br) for (i in 1 until codedSubbands) { val delta = gain_vlc_tabs[1].getVLC2(br) chan.gainData[i].numPoints = chan.gainData[i - 1].numPoints + delta and 7 } } 3 -> if (chNum > 0) { // copy data from master channel for (i in 0 until codedSubbands) { chan.gainData[i].numPoints = refChan.gainData[i].numPoints } } else { // shorter delta to min val deltaBits = br.read(2) val minVal = br.read(3) for (i in 0 until codedSubbands) { chan.gainData[i].numPoints = minVal + getDelta(deltaBits) if (chan.gainData[i].numPoints > 7) { return AT3P_ERROR } } } } return 0 } /** * Implements coding mode 1 (master) for gain compensation levels. * * @param[out] dst ptr to the output array */ private fun gaincLevelMode1m(dst: AtracGainInfo) { if (dst.numPoints > 0) { dst.levCode[0] = gain_vlc_tabs[2].getVLC2(br) } for (i in 1 until dst.numPoints) { val delta = gain_vlc_tabs[3].getVLC2(br) dst.levCode[i] = dst.levCode[i - 1] + delta and 0xF } } /** * Implements coding mode 3 (slave) for gain compensation levels. * * @param[out] dst ptr to the output array * @param[in] ref ptr to the reference channel */ private fun gaincLevelMode3s(dst: AtracGainInfo, ref: AtracGainInfo) { for (i in 0 until dst.numPoints) { dst.levCode[i] = if (i >= ref.numPoints) 7 else ref.levCode[i] } } /** * Decode level code for each gain control point. * * @param[in] ch_num channel to process * @param[in] coded_subbands number of subbands to process * @return result code: 0 = OK, otherwise - error code */ private fun decodeGaincLevels(chNum: Int, codedSubbands: Int): Int { val chan = ctx.channels[chNum] val refChan = ctx.channels[0] when (br.read(2)) { // switch according to coding mode 0 // fixed-length coding -> for (sb in 0 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { chan.gainData[sb].levCode[i] = br.read(4) } } 1 -> if (chNum > 0) { // VLC module delta to master channel for (sb in 0 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { val delta = gain_vlc_tabs[5].getVLC2(br) val pred = if (i >= refChan.gainData[sb].numPoints) 7 else refChan.gainData[sb].levCode[i] chan.gainData[sb].levCode[i] = pred + delta and 0xF } } } else { // VLC module delta to previous for (sb in 0 until codedSubbands) { gaincLevelMode1m(chan.gainData[sb]) } } 2 -> if (chNum > 0) { // VLC modulo delta to previous or clone master for (sb in 0 until codedSubbands) { if (chan.gainData[sb].numPoints > 0) { if (br.readBool()) { gaincLevelMode1m(chan.gainData[sb]) } else { gaincLevelMode3s(chan.gainData[sb], refChan.gainData[sb]) } } } } else { // VLC modulo delta to lev_codes of previous subband if (chan.gainData[0].numPoints > 0) { gaincLevelMode1m(chan.gainData[0]) } for (sb in 1 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { val delta = gain_vlc_tabs[4].getVLC2(br) val pred = if (i >= chan.gainData[sb - 1].numPoints) 7 else chan.gainData[sb - 1].levCode[i] chan.gainData[sb].levCode[i] = pred + delta and 0xF } } } 3 -> if (chNum > 0) { // clone master for (sb in 0 until codedSubbands) { gaincLevelMode3s(chan.gainData[sb], refChan.gainData[sb]) } } else { // shorter delta to min val deltaBits = br.read(2) val minVal = br.read(4) for (sb in 0 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { chan.gainData[sb].levCode[i] = minVal + getDelta(deltaBits) if (chan.gainData[sb].levCode[i] > 15) { return AT3P_ERROR } } } } } return 0 } /** * Implements coding mode 0 for gain compensation locations. * * @param[out] dst ptr to the output array * @param[in] pos position of the value to be processed */ private fun gaincLocMode0(dst: AtracGainInfo, pos: Int) { if (pos == 0 || dst.locCode[pos - 1] < 15) { dst.locCode[pos] = br.read(5) } else if (dst.locCode[pos - 1] >= 30) { dst.locCode[pos] = 31 } else { val deltaBits = avLog2(30 - dst.locCode[pos - 1]) + 1 dst.locCode[pos] = dst.locCode[pos - 1] + br.read(deltaBits) + 1 } } /** * Implements coding mode 1 for gain compensation locations. * * @param[out] dst ptr to the output array */ private fun gaincLocMode1(dst: AtracGainInfo) { if (dst.numPoints > 0) { // 1st coefficient is stored directly dst.locCode[0] = br.read(5) for (i in 1 until dst.numPoints) { // Switch VLC according to the curve direction // (ascending/descending) val tab = if (dst.levCode[i] <= dst.levCode[i - 1]) gain_vlc_tabs[7] else gain_vlc_tabs[9] dst.locCode[i] = dst.locCode[i - 1] + tab.getVLC2(br) } } } /** * Decode location code for each gain control point. * * @param[in] chNum channel to process * @param[in] codedSubbands number of subbands to process * @return result code: 0 = OK, otherwise - error code */ private fun decodeGaincLocCodes(chNum: Int, codedSubbands: Int): Int { val chan = ctx.channels[chNum] val refChan = ctx.channels[0] val codingMode = br.read(2) when (codingMode) { // switch according to coding mode 0 // sequence of numbers in ascending order -> for (sb in 0 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { gaincLocMode0(chan.gainData[sb], i) } } 1 -> if (chNum > 0) { for (sb in 0 until codedSubbands) { if (chan.gainData[sb].numPoints <= 0) { continue } val dst = chan.gainData[sb] val ref = refChan.gainData[sb] // 1st value is vlc-coded modulo delta to master var delta = gain_vlc_tabs[10].getVLC2(br) val pred = if (ref.numPoints > 0) ref.locCode[0] else 0 dst.locCode[0] = pred + delta and 0x1F for (i in 1 until dst.numPoints) { val moreThanRef = i >= ref.numPoints if (dst.levCode[i] > dst.levCode[i - 1]) { // ascending curve if (moreThanRef) { delta = gain_vlc_tabs[9].getVLC2(br) dst.locCode[i] = dst.locCode[i - 1] + delta } else { if (br.readBool()) { gaincLocMode0(dst, i) // direct coding } else { dst.locCode[i] = ref.locCode[i] // clone master } } } else { // descending curve val tab = if (moreThanRef) gain_vlc_tabs[7]!! else gain_vlc_tabs[10]!! delta = tab.getVLC2(br) if (moreThanRef) { dst.locCode[i] = dst.locCode[i - 1] + delta } else { dst.locCode[i] = ref.locCode[i] + delta and 0x1F } } } } } else { // VLC delta to previous for (sb in 0 until codedSubbands) { gaincLocMode1(chan.gainData[sb]) } } 2 -> if (chNum > 0) { for (sb in 0 until codedSubbands) { if (chan.gainData[sb].numPoints <= 0) { continue } val dst = chan.gainData[sb] val ref = refChan.gainData[sb] if (dst.numPoints > ref.numPoints || br.readBool()) { gaincLocMode1(dst) } else { // clone master for the whole subband for (i in 0 until chan.gainData[sb].numPoints) { dst.locCode[i] = ref.locCode[i] } } } } else { // data for the first subband is coded directly for (i in 0 until chan.gainData[0].numPoints) { gaincLocMode0(chan.gainData[0], i) } for (sb in 1 until codedSubbands) { if (chan.gainData[sb].numPoints <= 0) { continue } val dst = chan.gainData[sb] // 1st value is vlc-coded modulo delta to the corresponding // value of the previous subband if any or zero var delta = gain_vlc_tabs[6].getVLC2(br) val pred = if (chan.gainData[sb - 1].numPoints > 0) chan.gainData[sb - 1].locCode[0] else 0 dst.locCode[0] = pred + delta and 0x1F for (i in 1 until dst.numPoints) { val moreThanRef = i >= chan.gainData[sb - 1].numPoints // Select VLC table according to curve direction and // presence of prediction val tab = gain_vlc_tabs[(if (dst.levCode[i] > dst.levCode[i - 1]) 2 else 0) + (if (moreThanRef) 1 else 0) + 6]!! delta = tab.getVLC2(br) if (moreThanRef) { dst.locCode[i] = dst.locCode[i - 1] + delta } else { dst.locCode[i] = chan.gainData[sb - 1].locCode[i] + delta and 0x1F } } } } 3 -> if (chNum > 0) { // clone master or direct or direct coding for (sb in 0 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { if (i >= refChan.gainData[sb].numPoints) { gaincLocMode0(chan.gainData[sb], i) } else { chan.gainData[sb].locCode[i] = refChan.gainData[sb].locCode[i] } } } } else { // shorter delta to min val deltaBits = br.read(2) + 1 val minVal = br.read(5) for (sb in 0 until codedSubbands) { for (i in 0 until chan.gainData[sb].numPoints) { chan.gainData[sb].locCode[i] = minVal + i + br.read(deltaBits) } } } } // Validate decoded information for (sb in 0 until codedSubbands) { val dst = chan.gainData[sb] for (i in 0 until chan.gainData[sb].numPoints) { if (dst.locCode[i] < 0 || dst.locCode[i] > 31 || i > 0 && dst.locCode[i] <= dst.locCode[i - 1]) { log.error("Invalid gain location: ch=%d, sb=%d, pos=%d, val=%d".format(chNum, sb, i, dst.locCode[i])) return AT3P_ERROR } } } return 0 } /** * Decode gain control data for all channels. * * @return result code: 0 = OK, otherwise - error code */ private fun decodeGaincData(): Int { var ret: Int for (chNum in 0 until numChannels) { for (i in 0 until ATRAC3P_SUBBANDS) { ctx.channels[chNum].gainData[i].clear() } if (br.readBool()) { // gain control data present? val codedSubbands = br.read(4) + 1 if (br.readBool()) { // is high band gain data replication on? ctx.channels[chNum].numGainSubbands = br.read(4) + 1 } else { ctx.channels[chNum].numGainSubbands = codedSubbands } ret = decodeGaincNPoints(chNum, codedSubbands) if (ret < 0) { return ret } ret = decodeGaincLevels(chNum, codedSubbands) if (ret < 0) { return ret } ret = decodeGaincLocCodes(chNum, codedSubbands) if (ret < 0) { return ret } if (codedSubbands > 0) { // propagate gain data if requested for (sb in codedSubbands until ctx.channels[chNum].numGainSubbands) { ctx.channels[chNum].gainData[sb].copy(ctx.channels[chNum].gainData[sb - 1]) } } } else { ctx.channels[chNum].numGainSubbands = 0 } } return 0 } /** * Decode envelope for all tones of a channel. * * @param[in] chNum channel to process * @param[in] bandHasTones ptr to an array of per-band-flags: * 1 - tone data present */ private fun decodeTonesEnvelope(chNum: Int, bandHasTones: BooleanArray) { val dst = ctx.channels[chNum].tonesInfo val ref = ctx.channels[0].tonesInfo if (chNum == 0 || !br.readBool()) { // mode 0: fixed-length coding for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb]) { continue } dst[sb].pendEnv.hasStartPoint = br.readBool() dst[sb].pendEnv.startPos = if (dst[sb].pendEnv.hasStartPoint) br.read(5) else -1 dst[sb].pendEnv.hasStopPoint = br.readBool() dst[sb].pendEnv.stopPos = if (dst[sb].pendEnv.hasStopPoint) br.read(5) else 32 } } else { // mode 1(slave only): copy master for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb]) { continue } dst[sb].pendEnv.copy(ref[sb].pendEnv) } } } /** * Decode number of tones for each subband of a channel. * * @param[in] chNum channel to process * @param[in] bandHasTones ptr to an array of per-band-flags: * 1 - tone data present * @return result code: 0 = OK, otherwise - error code */ private fun decodeBandNumwavs(chNum: Int, bandHasTones: BooleanArray): Int { val dst = ctx.channels[chNum].tonesInfo val ref = ctx.channels[0].tonesInfo val mode = br.read(chNum + 1) when (mode) { 0 // fixed-length coding -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (bandHasTones[sb]) { dst[sb].numWavs = br.read(4) } } 1 // variable-length coding -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (bandHasTones[sb]) { dst[sb].numWavs = tone_vlc_tabs[1].getVLC2(br) } } 2 // VLC modulo delta to master (slave only) -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (bandHasTones[sb]) { var delta = tone_vlc_tabs[2].getVLC2(br) delta = delta.signExtend(3) dst[sb].numWavs = ref[sb].numWavs + delta and 0xF } } 3 // copy master (slave only) -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (bandHasTones[sb]) { dst[sb].numWavs = ref[sb].numWavs } } } // initialize start tone index for each subband for (sb in 0 until ctx.wavesInfo.numToneBands) { if (bandHasTones[sb]) { if (ctx.wavesInfo.tonesIndex + dst[sb].numWavs > 48) { log.error("Too many tones: %d (max. 48)".format(ctx.wavesInfo.tonesIndex + dst[sb].numWavs)) return AT3P_ERROR } dst[sb].startIndex = ctx.wavesInfo.tonesIndex ctx.wavesInfo.tonesIndex += dst[sb].numWavs } } return 0 } /** * Decode frequency information for each subband of a channel. * * @param[in] chNum channel to process * @param[in] bandHasTones ptr to an array of per-band-flags: * 1 - tone data present */ private fun decodeTonesFrequency(chNum: Int, bandHasTones: BooleanArray) { val dst = ctx.channels[chNum].tonesInfo val ref = ctx.channels[0].tonesInfo if (chNum == 0 || !br.readBool()) { // mode 0: fixed-length coding for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb] || dst[sb].numWavs == 0) { continue } val iwav = dst[sb].startIndex val direction = if (dst[sb].numWavs > 1) br.readBool() else false if (direction) { // packed numbers in descending order if (dst[sb].numWavs > 0) { ctx.wavesInfo.waves[iwav + dst[sb].numWavs - 1]!!.freqIndex = br.read(10) } for (i in dst[sb].numWavs - 2 downTo 0) { val nbits = avLog2(ctx.wavesInfo.waves[iwav + i + 1]!!.freqIndex) + 1 ctx.wavesInfo.waves[iwav + i]!!.freqIndex = br.read(nbits) } } else { // packed numbers in ascending order for (i in 0 until dst[sb].numWavs) { if (i == 0 || ctx.wavesInfo.waves[iwav + i - 1]!!.freqIndex < 512) { ctx.wavesInfo.waves[iwav + i]!!.freqIndex = br.read(10) } else { val nbits = avLog2(1023 - ctx.wavesInfo.waves[iwav + i - 1]!!.freqIndex) + 1 ctx.wavesInfo.waves[iwav + i]!!.freqIndex = br.read(nbits) + 1024 - (1 shl nbits) } } } } } else { // mode 1: VLC module delta to master (slave only) for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb] || dst[sb].numWavs == 0) { continue } val iwav = ref[sb].startIndex val owav = dst[sb].startIndex for (i in 0 until dst[sb].numWavs) { var delta = tone_vlc_tabs[6]!!.getVLC2(br) delta = delta.signExtend(8) val pred = if (i < ref[sb].numWavs) ctx.wavesInfo.waves[iwav + i]!!.freqIndex else if (ref[sb].numWavs > 0) ctx.wavesInfo.waves[iwav + ref[sb].numWavs - 1]!!.freqIndex else 0 ctx.wavesInfo.waves[owav + i]!!.freqIndex = pred + delta and 0x3FF } } } } /** * Decode amplitude information for each subband of a channel. * * @param[in] chNum channel to process * @param[in] bandHasTones ptr to an array of per-band-flags: * 1 - tone data present */ private fun decodeTonesAmplitude(chNum: Int, bandHasTones: BooleanArray) { val dst = ctx.channels[chNum].tonesInfo val ref = ctx.channels[0].tonesInfo val refwaves = IntArray(48) if (chNum > 0) { for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb] || dst[sb].numWavs == 0) { continue } val wsrc = dst[sb].startIndex val wref = ref[sb].startIndex for (j in 0 until dst[sb].numWavs) { var fi = 0 var maxdiff = 1024 for (i in 0 until ref[sb].numWavs) { val diff = abs(ctx.wavesInfo.waves[wsrc + j]!!.freqIndex - ctx.wavesInfo.waves[wref + i]!!.freqIndex) if (diff < maxdiff) { maxdiff = diff fi = i } } if (maxdiff < 8) { refwaves[dst[sb].startIndex + j] = fi + ref[sb].startIndex } else if (j < ref[sb].numWavs) { refwaves[dst[sb].startIndex + j] = j + ref[sb].startIndex } else { refwaves[dst[sb].startIndex + j] = -1 } } } } val mode = br.read(chNum + 1) when (mode) { 0 // fixed-length coding -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb] || dst[sb].numWavs == 0) { continue } if (ctx.wavesInfo.amplitudeMode != 0) { for (i in 0 until dst[sb].numWavs) { ctx.wavesInfo.waves[dst[sb].startIndex + i]!!.ampSf = br.read(6) } } else { ctx.wavesInfo.waves[dst[sb].startIndex]!!.ampSf = br.read(6) } } 1 // min + VLC delta -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb] || dst[sb].numWavs == 0) { continue } if (ctx.wavesInfo.amplitudeMode != 0) { for (i in 0 until dst[sb].numWavs) { ctx.wavesInfo.waves[dst[sb].startIndex + i]!!.ampSf = tone_vlc_tabs[3]!!.getVLC2(br) + 20 } } else { ctx.wavesInfo.waves[dst[sb].startIndex]!!.ampSf = tone_vlc_tabs[4]!!.getVLC2(br) + 24 } } 2 // VLC module delta to master (slave only) -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb] || dst[sb].numWavs == 0) { continue } for (i in 0 until dst[sb].numWavs) { var delta = tone_vlc_tabs[5]!!.getVLC2(br) delta = delta.signExtend(5) val pred = if (refwaves[dst[sb].startIndex + i] >= 0) ctx.wavesInfo.waves[refwaves[dst[sb].startIndex + i]]!!.ampSf else 34 ctx.wavesInfo.waves[dst[sb].startIndex + i]!!.ampSf = pred + delta and 0x3F } } 3 // clone master (slave only) -> for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb]) { continue } for (i in 0 until dst[sb].numWavs) { ctx.wavesInfo.waves[dst[sb].startIndex + i]!!.ampSf = if (refwaves[dst[sb].startIndex + i] >= 0) ctx.wavesInfo.waves[refwaves[dst[sb].startIndex + i]]!!.ampSf else 32 } } } } /** * Decode phase information for each subband of a channel. * * @param chNnum channel to process * @param bandHasTones ptr to an array of per-band-flags: * 1 - tone data present */ private fun decodeTonesPhase(chNum: Int, bandHasTones: BooleanArray) { val dst = ctx.channels[chNum].tonesInfo for (sb in 0 until ctx.wavesInfo.numToneBands) { if (!bandHasTones[sb]) { continue } val wparam = dst[sb].startIndex for (i in 0 until dst[sb].numWavs) { ctx.wavesInfo.waves[wparam + i]!!.phaseIndex = br.read(5) } } } /** * Decode tones info for all channels. * * @return result code: 0 = OK, otherwise - error code */ private fun decodeTonesInfo(): Int { for (chNum in 0 until numChannels) { for (i in 0 until ATRAC3P_SUBBANDS) { ctx.channels[chNum].tonesInfo[i].clear() } } ctx.wavesInfo.tonesPresent = br.readBool() if (!ctx.wavesInfo.tonesPresent) { return 0 } for (i in ctx.wavesInfo.waves.indices) { ctx.wavesInfo.waves[i]!!.clear() } ctx.wavesInfo.amplitudeMode = br.read1() if (ctx.wavesInfo.amplitudeMode == 0) { log.error("GHA amplitude mode 0") return AT3P_ERROR } ctx.wavesInfo.numToneBands = tone_vlc_tabs[0].getVLC2(br) + 1 if (numChannels == 2) { getSubbandFlags(ctx.wavesInfo.toneSharing, ctx.wavesInfo.numToneBands) getSubbandFlags(ctx.wavesInfo.toneMaster, ctx.wavesInfo.numToneBands) if (getSubbandFlags(ctx.wavesInfo.phaseShift, ctx.wavesInfo.numToneBands)) { log.warn("GHA Phase shifting") } } ctx.wavesInfo.tonesIndex = 0 for (chNum in 0 until numChannels) { val bandHasTones = BooleanArray(16) for (i in 0 until ctx.wavesInfo.numToneBands) { bandHasTones[i] = if (chNum == 0) true else !ctx.wavesInfo.toneSharing[i] } decodeTonesEnvelope(chNum, bandHasTones) val ret = decodeBandNumwavs(chNum, bandHasTones) if (ret < 0) { return ret } decodeTonesFrequency(chNum, bandHasTones) decodeTonesAmplitude(chNum, bandHasTones) decodeTonesPhase(chNum, bandHasTones) } if (numChannels == 2) { for (i in 0 until ctx.wavesInfo.numToneBands) { if (ctx.wavesInfo.toneSharing[i]) { ctx.channels[1].tonesInfo[i].copy(ctx.channels[0].tonesInfo[i]) } if (ctx.wavesInfo.toneMaster[i]) { // Swap channels 0 and 1 val tmp = WavesData() tmp.copy(ctx.channels[0].tonesInfo[i]) ctx.channels[0].tonesInfo[i].copy(ctx.channels[1].tonesInfo[i]) ctx.channels[1].tonesInfo[i].copy(tmp) } } } return 0 } fun decodeResidualSpectrum(out: Array<FloatArray>) { val sbRNGindex = IntArray(ATRAC3P_SUBBANDS) if (ctx.muteFlag) { for (ch in 0 until numChannels) { out[ch].fill(0f) } return } var RNGindex = 0 for (qu in 0 until ctx.usedQuantUnits) { RNGindex += ctx.channels[0].quSfIdx[qu] + ctx.channels[1].quSfIdx[qu] } run { var sb = 0 while (sb < ctx.numCodedSubbands) { sbRNGindex[sb] = RNGindex and 0x3FC sb++ RNGindex += 128 } } // inverse quant and power compensation for (ch in 0 until numChannels) { // clear channel's residual spectrum out[ch].fill(0f, 0, ATRAC3P_FRAME_SAMPLES) for (qu in 0 until ctx.usedQuantUnits) { val src = ff_atrac3p_qu_to_spec_pos[qu] val dst = ff_atrac3p_qu_to_spec_pos[qu] val nspeclines = ff_atrac3p_qu_to_spec_pos[qu + 1] - ff_atrac3p_qu_to_spec_pos[qu] if (ctx.channels[ch].quWordlen[qu] > 0) { val q = ff_atrac3p_sf_tab[ctx.channels[ch].quSfIdx[qu]] * ff_atrac3p_mant_tab[ctx.channels[ch].quWordlen[qu]] for (i in 0 until nspeclines) { out[ch][dst + i] = ctx.channels[ch].spectrum[src + i] * q } } } for (sb in 0 until ctx.numCodedSubbands) { dsp!!.powerCompensation(ctx, ch, out[ch], sbRNGindex[sb], sb) } } if (ctx.unitType == CH_UNIT_STEREO) { val tmp = FloatArray(ATRAC3P_SUBBAND_SAMPLES) for (sb in 0 until ctx.numCodedSubbands) { if (ctx.swapChannels[sb]) { // Swap both channels arraycopy(out[0], sb * ATRAC3P_SUBBAND_SAMPLES, tmp, 0, ATRAC3P_SUBBAND_SAMPLES) arraycopy(out[1], sb * ATRAC3P_SUBBAND_SAMPLES, out[0], sb * ATRAC3P_SUBBAND_SAMPLES, ATRAC3P_SUBBAND_SAMPLES) arraycopy(tmp, 0, out[1], sb * ATRAC3P_SUBBAND_SAMPLES, ATRAC3P_SUBBAND_SAMPLES) } // flip coefficients' sign if requested if (ctx.negateCoeffs[sb]) { for (i in 0 until ATRAC3P_SUBBAND_SAMPLES) { out[1][sb * ATRAC3P_SUBBAND_SAMPLES + i] = -out[1][sb * ATRAC3P_SUBBAND_SAMPLES + i] } } } } } fun reconstructFrame(at3pContext: Context) { for (ch in 0 until numChannels) { for (sb in 0 until ctx.numSubbands) { // inverse transform and windowing dsp!!.imdct(at3pContext.mdctCtx!!, at3pContext.samples[ch], sb * ATRAC3P_SUBBAND_SAMPLES, at3pContext.mdctBuf[ch], sb * ATRAC3P_SUBBAND_SAMPLES, (if (ctx.channels[ch].wndShapePrev[sb]) 2 else 0) + if (ctx.channels[ch].wndShape[sb]) 1 else 0, sb) // gain compensation and overlapping at3pContext.gaincCtx!!.gainCompensation(at3pContext.mdctBuf[ch], sb * ATRAC3P_SUBBAND_SAMPLES, ctx.prevBuf[ch], sb * ATRAC3P_SUBBAND_SAMPLES, ctx.channels[ch].gainDataPrev[sb], ctx.channels[ch].gainData[sb], ATRAC3P_SUBBAND_SAMPLES, at3pContext.timeBuf[ch], sb * ATRAC3P_SUBBAND_SAMPLES) } // zero unused subbands in both output and overlapping buffers ctx.prevBuf[ch].fill(0f, ctx.numSubbands * ATRAC3P_SUBBAND_SAMPLES, ctx.prevBuf[ch].size) at3pContext.timeBuf[ch].fill(0f, ctx.numSubbands * ATRAC3P_SUBBAND_SAMPLES, at3pContext.timeBuf[ch].size) // resynthesize and add tonal signal if (ctx.wavesInfo.tonesPresent || ctx.wavesInfoPrev.tonesPresent) { for (sb in 0 until ctx.numSubbands) { if (ctx.channels[ch].tonesInfo[sb].numWavs > 0 || ctx.channels[ch].tonesInfoPrev[sb].numWavs > 0) { dsp!!.generateTones(ctx, ch, sb, at3pContext.timeBuf[ch], sb * 128) } } } // subband synthesis and acoustic signal output dsp!!.ipqf(at3pContext.ipqfDctCtx!!, ctx.ipqfCtx[ch], at3pContext.timeBuf[ch], at3pContext.outpBuf[ch]) } // swap window shape and gain control buffers for (ch in 0 until numChannels) { val tmp1 = ctx.channels[ch].wndShape ctx.channels[ch].wndShape = ctx.channels[ch].wndShapePrev ctx.channels[ch].wndShapePrev = tmp1 val tmp2 = ctx.channels[ch].gainData ctx.channels[ch].gainData = ctx.channels[ch].gainDataPrev ctx.channels[ch].gainDataPrev = tmp2 val tmp3 = ctx.channels[ch].tonesInfo ctx.channels[ch].tonesInfo = ctx.channels[ch].tonesInfoPrev ctx.channels[ch].tonesInfoPrev = tmp3 } val tmp = ctx.wavesInfo ctx.wavesInfo = ctx.wavesInfoPrev ctx.wavesInfoPrev = tmp } companion object { private val log = Atrac3plusDecoder.log /* build huffman tables for gain data decoding */ private val gain_cbs = arrayOf<IntArray>(Atrac3plusData2.atrac3p_huff_gain_npoints1_cb, Atrac3plusData2.atrac3p_huff_gain_npoints1_cb, Atrac3plusData2.atrac3p_huff_gain_lev1_cb, Atrac3plusData2.atrac3p_huff_gain_lev2_cb, Atrac3plusData2.atrac3p_huff_gain_lev3_cb, Atrac3plusData2.atrac3p_huff_gain_lev4_cb, Atrac3plusData2.atrac3p_huff_gain_loc3_cb, Atrac3plusData2.atrac3p_huff_gain_loc1_cb, Atrac3plusData2.atrac3p_huff_gain_loc4_cb, Atrac3plusData2.atrac3p_huff_gain_loc2_cb, Atrac3plusData2.atrac3p_huff_gain_loc5_cb) private val gain_xlats = arrayOf<IntArray?>(null, Atrac3plusData2.atrac3p_huff_gain_npoints2_xlat, Atrac3plusData2.atrac3p_huff_gain_lev1_xlat, Atrac3plusData2.atrac3p_huff_gain_lev2_xlat, Atrac3plusData2.atrac3p_huff_gain_lev3_xlat, Atrac3plusData2.atrac3p_huff_gain_lev4_xlat, Atrac3plusData2.atrac3p_huff_gain_loc3_xlat, Atrac3plusData2.atrac3p_huff_gain_loc1_xlat, Atrac3plusData2.atrac3p_huff_gain_loc4_xlat, Atrac3plusData2.atrac3p_huff_gain_loc2_xlat, Atrac3plusData2.atrac3p_huff_gain_loc5_xlat) private val gain_vlc_tabs = Array<VLC>(11) { i -> val vlc = VLC() buildCanonicalHuff(gain_cbs[i], gain_xlats[i], vlc) vlc } /* build huffman tables for tone decoding */ private val tone_cbs = arrayOf<IntArray>(Atrac3plusData2.atrac3p_huff_tonebands_cb, Atrac3plusData2.atrac3p_huff_numwavs1_cb, Atrac3plusData2.atrac3p_huff_numwavs2_cb, Atrac3plusData2.atrac3p_huff_wav_ampsf1_cb, Atrac3plusData2.atrac3p_huff_wav_ampsf2_cb, Atrac3plusData2.atrac3p_huff_wav_ampsf3_cb, Atrac3plusData2.atrac3p_huff_freq_cb) private val tone_xlats = arrayOf<IntArray?>(null, null, Atrac3plusData2.atrac3p_huff_numwavs2_xlat, Atrac3plusData2.atrac3p_huff_wav_ampsf1_xlat, Atrac3plusData2.atrac3p_huff_wav_ampsf2_xlat, Atrac3plusData2.atrac3p_huff_wav_ampsf3_xlat, Atrac3plusData2.atrac3p_huff_freq_xlat) private val tone_vlc_tabs = Array<VLC>(7) { i-> val vlc = VLC() buildCanonicalHuff(tone_cbs[i], tone_xlats[i], vlc) vlc } private val wl_nb_bits = intArrayOf(2, 3, 5, 5) private val wl_nb_codes = intArrayOf(3, 5, 8, 8) private val wl_bits = arrayOf<IntArray>(Atrac3plusData2.atrac3p_wl_huff_bits1, Atrac3plusData2.atrac3p_wl_huff_bits2, Atrac3plusData2.atrac3p_wl_huff_bits3, Atrac3plusData2.atrac3p_wl_huff_bits4) private val wl_codes = arrayOf<IntArray>(Atrac3plusData2.atrac3p_wl_huff_code1, Atrac3plusData2.atrac3p_wl_huff_code2, Atrac3plusData2.atrac3p_wl_huff_code3, Atrac3plusData2.atrac3p_wl_huff_code4) private val wl_xlats = arrayOf<IntArray?>(Atrac3plusData2.atrac3p_wl_huff_xlat1, Atrac3plusData2.atrac3p_wl_huff_xlat2, null, null) private val ct_nb_bits = intArrayOf(3, 4, 4, 4) private val ct_nb_codes = intArrayOf(4, 8, 8, 8) private val ct_bits = arrayOf<IntArray>(Atrac3plusData2.atrac3p_ct_huff_bits1, Atrac3plusData2.atrac3p_ct_huff_bits2, Atrac3plusData2.atrac3p_ct_huff_bits2, Atrac3plusData2.atrac3p_ct_huff_bits3) private val ct_codes = arrayOf<IntArray>(Atrac3plusData2.atrac3p_ct_huff_code1, Atrac3plusData2.atrac3p_ct_huff_code2, Atrac3plusData2.atrac3p_ct_huff_code2, Atrac3plusData2.atrac3p_ct_huff_code3) private val ct_xlats = arrayOf<IntArray?>(null, null, Atrac3plusData2.atrac3p_ct_huff_xlat1, null) private val sf_nb_bits = intArrayOf(9, 9, 9, 9, 6, 6, 7, 7) private val sf_nb_codes = intArrayOf(64, 64, 64, 64, 16, 16, 16, 16) private val sf_bits = arrayOf<IntArray>(Atrac3plusData2.atrac3p_sf_huff_bits1, Atrac3plusData2.atrac3p_sf_huff_bits1, Atrac3plusData2.atrac3p_sf_huff_bits2, Atrac3plusData2.atrac3p_sf_huff_bits3, Atrac3plusData2.atrac3p_sf_huff_bits4, Atrac3plusData2.atrac3p_sf_huff_bits4, Atrac3plusData2.atrac3p_sf_huff_bits5, Atrac3plusData2.atrac3p_sf_huff_bits6) private val sf_codes = arrayOf<IntArray>(Atrac3plusData2.atrac3p_sf_huff_code1, Atrac3plusData2.atrac3p_sf_huff_code1, Atrac3plusData2.atrac3p_sf_huff_code2, Atrac3plusData2.atrac3p_sf_huff_code3, Atrac3plusData2.atrac3p_sf_huff_code4, Atrac3plusData2.atrac3p_sf_huff_code4, Atrac3plusData2.atrac3p_sf_huff_code5, Atrac3plusData2.atrac3p_sf_huff_code6) private val sf_xlats = arrayOf<IntArray?>(Atrac3plusData2.atrac3p_sf_huff_xlat1, Atrac3plusData2.atrac3p_sf_huff_xlat2, null, null, Atrac3plusData2.atrac3p_sf_huff_xlat4, Atrac3plusData2.atrac3p_sf_huff_xlat5, null, null) private val wl_vlc_tabs = Array<VLC>(4) { i -> VLC().apply { initVLCSparse(wl_nb_bits[i], wl_nb_codes[i], wl_bits[i], wl_codes[i], wl_xlats[i]) } } private val sf_vlc_tabs = Array<VLC>(8) { i -> VLC().apply { initVLCSparse(sf_nb_bits[i], sf_nb_codes[i], sf_bits[i], sf_codes[i], sf_xlats[i]) } } private val ct_vlc_tabs = Array<VLC>(4) { i-> VLC().apply { initVLCSparse(ct_nb_bits[i], ct_nb_codes[i], ct_bits[i], ct_codes[i], ct_xlats[i]) } } /* build huffman tables for spectrum decoding */ private val spec_vlc_tabs = Array<VLC?>(112) { i -> val atrac3pSpecCodeTab = atrac3p_spectra_tabs[i] if (atrac3pSpecCodeTab.cb != null) { val vlc = VLC() buildCanonicalHuff(atrac3pSpecCodeTab.cb!!, atrac3pSpecCodeTab.xlat, vlc) vlc } else { null } } private fun buildCanonicalHuff(cb: IntArray, xlat: IntArray?, vlc: VLC): Int { val codes = IntArray(256) val bits = IntArray(256) var cbIndex = 0 var index = 0 var code = 0 val minLen = cb[cbIndex++] // get shortest codeword length val maxLen = cb[cbIndex++] // get longest codeword length for (b in minLen..maxLen) { for (i in cb[cbIndex++] downTo 1) { bits[index] = b codes[index] = code++ index++ } code = code shl 1 } return vlc.initVLCSparse(maxLen, index, bits, codes, xlat) } } }
16
null
9
72
5ad15d161bef8baa40961ee508643306d933a50a
52,528
kpspemu
MIT License
jdroid-android-google-maps/src/main/java/com/jdroid/android/google/maps/MapUtils.kt
fwonly123
198,339,170
false
null
package com.jdroid.android.google.maps import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.graphics.drawable.DrawableCompat import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import com.google.android.gms.maps.model.BitmapDescriptor import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.LatLng import com.jdroid.android.application.AbstractApplication import com.jdroid.android.domain.GeoLocation object MapUtils { fun safeVectorToBitmap(@DrawableRes drawableRes: Int, @ColorRes colorRes: Int): BitmapDescriptor? { try { return vectorToBitmap(drawableRes, colorRes) } catch (e: Exception) { AbstractApplication.get().exceptionHandler.logHandledException(e) } return null } /** * Convert a [Drawable] to a [BitmapDescriptor], for use as a marker icon. */ fun vectorToBitmap(@DrawableRes drawableRes: Int, @ColorRes colorRes: Int): BitmapDescriptor { val vectorDrawable = VectorDrawableCompat.create(AbstractApplication.get().resources, drawableRes, null)!! val bitmap = Bitmap.createBitmap(vectorDrawable.intrinsicWidth, vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) vectorDrawable.setBounds(0, 0, canvas.width, canvas.height) DrawableCompat.setTint(vectorDrawable, AbstractApplication.get().resources.getColor(colorRes)) vectorDrawable.draw(canvas) return BitmapDescriptorFactory.fromBitmap(bitmap) } fun createLatLng(geoLocation: GeoLocation?): LatLng? { return if (geoLocation != null) LatLng(geoLocation.latitude, geoLocation.longitude) else null } }
1
null
1
1
578194586fc7d7e71d3742756651d658cb498bd0
1,875
jdroid-android
Apache License 2.0
app/src/main/java/com/droidafricana/moveery/di/modules/WorkerBindingModule.kt
Fbada006
240,091,360
false
null
package com.droidafricana.moveery.di.modules import com.droidafricana.moveery.di.keys.WorkerKey import com.droidafricana.moveery.di.workerfactory.ChildWorkerFactory import com.droidafricana.moveery.work.RefreshMovieWork import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap /**Handles creation of the different types of [Worker]*/ @Module interface WorkerBindingModule { /**Create the [RefreshMovieWork]*/ @Binds @IntoMap @WorkerKey(RefreshMovieWork::class) fun bindHelloWorldWorker(factory: RefreshMovieWork.Factory): ChildWorkerFactory }
0
Kotlin
0
2
92b175690eac0333ecbe0d87c9f07084f6099459
585
Moveery
Apache License 2.0
src/data/src/main/java/com/exemplo/astroimagemdodia/data/calladapter/CallAdapterFactory.kt
daniloabranches
245,878,517
false
{"Kotlin": 17339}
package com.exemplo.retrofitcalladapterfactory.calladapter import retrofit2.CallAdapter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class CallAdapterFactory private constructor() : CallAdapter.Factory() { override fun get( returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit ): CallAdapter<*, *>? { return try { val parameterizedType = (returnType as ParameterizedType) return if (parameterizedType.rawType == Observable::class.java) { val type = parameterizedType.actualTypeArguments[0] CallAdapter<Any>(type) } else null } catch (ex: ClassCastException) { null } } companion object { fun create() = CallAdapterFactory() } }
0
Kotlin
0
1
4b3b6327e66de88df0a2fa489d826d305b33fc47
868
astronomia-imagem-dia-mvc
MIT License
src/data/src/main/java/com/exemplo/astroimagemdodia/data/calladapter/CallAdapterFactory.kt
daniloabranches
245,878,517
false
{"Kotlin": 17339}
package com.exemplo.retrofitcalladapterfactory.calladapter import retrofit2.CallAdapter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class CallAdapterFactory private constructor() : CallAdapter.Factory() { override fun get( returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit ): CallAdapter<*, *>? { return try { val parameterizedType = (returnType as ParameterizedType) return if (parameterizedType.rawType == Observable::class.java) { val type = parameterizedType.actualTypeArguments[0] CallAdapter<Any>(type) } else null } catch (ex: ClassCastException) { null } } companion object { fun create() = CallAdapterFactory() } }
0
Kotlin
0
1
4b3b6327e66de88df0a2fa489d826d305b33fc47
868
astronomia-imagem-dia-mvc
MIT License
picker-media/src/main/java/chooongg/box/picker/media/MediaPickerAdapter.kt
Chooongg
298,511,826
false
null
package chooongg.box.picker.media import android.provider.MediaStore import chooongg.box.core.adapter.BindingAdapter import chooongg.box.core.adapter.BindingHolder import chooongg.box.ext.gone import chooongg.box.ext.visible import chooongg.box.picker.media.databinding.BoxItemPickerMediaBinding import chooongg.box.picker.media.model.MediaItem import chooongg.box.utils.TimeConstants import chooongg.box.utils.TimeUtils import coil.load import coil.util.CoilUtils class MediaPickerAdapter : BindingAdapter<MediaItem, BoxItemPickerMediaBinding>() { init { addChildClickViewIds(R.id.checkbox_layout) } override fun convert(holder: BindingHolder<BoxItemPickerMediaBinding>, item: MediaItem) { if (item.id == -1000L) { holder.binding.ivImage.load(R.drawable.layer_picker_camera) holder.binding.viewVideoMask.gone() holder.binding.tvDuration.gone() holder.binding.checkboxLayout.gone() return } holder.binding.ivImage.load(item.uri) if (item.mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) { holder.binding.viewVideoMask.visible() holder.binding.tvDuration.visible() holder.binding.tvDuration.text = when { item.duration >= TimeConstants.HOUR -> TimeUtils.millis2String( item.duration, "H:m:s" ) item.duration >= 1000 -> TimeUtils.millis2String(item.duration, "m:s") else -> "0:1" } } else { holder.binding.viewVideoMask.gone() holder.binding.tvDuration.gone() } if (!MediaPickerConstant.isSingle) { holder.binding.checkboxLayout.visible() item.isCheck = MediaPickerConstant.selectedMedia.contains(item) if (item.isCheck) { holder.binding.checkbox.text = (MediaPickerConstant.selectedMedia.indexOf(item) + 1).toString() holder.binding.checkbox.setBackgroundResource(R.drawable.shape_media_picker_checkbox_checked) holder.binding.viewCheckMask.alpha = 1f } else { holder.binding.checkbox.text = null holder.binding.checkbox.setBackgroundResource(R.drawable.shape_media_picker_checkbox_unchecked) holder.binding.viewCheckMask.alpha = 0f } } else { holder.binding.checkboxLayout.gone() } } override fun convert( holder: BindingHolder<BoxItemPickerMediaBinding>, item: MediaItem, payloads: List<Any> ) { if (!MediaPickerConstant.isSingle) { holder.binding.checkboxLayout.visible() item.isCheck = MediaPickerConstant.selectedMedia.contains(item) if (item.isCheck) { holder.binding.checkbox.text = (MediaPickerConstant.selectedMedia.indexOf(item) + 1).toString() holder.binding.checkbox.setBackgroundResource(R.drawable.shape_media_picker_checkbox_checked) holder.binding.viewCheckMask.animate().alpha(1f) } else { holder.binding.checkbox.text = null holder.binding.checkbox.setBackgroundResource(R.drawable.shape_media_picker_checkbox_unchecked) holder.binding.viewCheckMask.animate().alpha(0f) } } else { holder.binding.checkboxLayout.gone() } } override fun onViewRecycled(holder: BindingHolder<BoxItemPickerMediaBinding>) { CoilUtils.clear(holder.binding.ivImage) } }
0
Kotlin
1
2
f2b4adac448036ef2e48ec2a3ac030c7f8d0fe2e
3,643
ChooonggBox
Apache License 2.0
rpk-core/src/main/kotlin/com/rpkit/core/database/TableVersion.kt
Nyrheim
269,929,653
true
{"Kotlin": 2944589, "Java": 1237516, "HTML": 94789, "JavaScript": 640, "CSS": 607}
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.core.database /** * Represents the version of a table. * * @property id The ID of the table version, defaults to 0. Set automatically when inserted into a table. * @property table The name of the table * @property version The version of the table */ class TableVersion( override var id: Int = 0, val table: String, var version: String ): Entity
0
null
0
0
f2196a76e0822b2c60e4a551de317ed717bbdc7e
984
RPKit
Apache License 2.0
app/src/main/java/com/techbeloved/hymnbook/hymndetail/DetailPagerFragment.kt
techbeloved
133,724,406
false
null
package com.techbeloved.hymnbook.hymndetail import android.annotation.SuppressLint import android.app.ProgressDialog import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.core.app.ShareCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.viewpager.widget.PagerAdapter import com.google.android.material.snackbar.Snackbar import com.techbeloved.hymnbook.R import com.techbeloved.hymnbook.sheetmusic.SheetMusicDetailFragment import com.techbeloved.hymnbook.usecases.Lce import com.techbeloved.hymnbook.utils.* import dagger.hilt.android.AndroidEntryPoint import timber.log.Timber import kotlin.properties.Delegates.observable @AndroidEntryPoint class DetailPagerFragment : BaseDetailPagerFragment() { private val viewModel: HymnPagerViewModel by viewModels() private lateinit var detailPagerAdapter: DetailPagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Restore current index if (savedInstanceState != null) { currentHymnId = savedInstanceState.getInt(EXTRA_CURRENT_ITEM_ID, 1) currentCategoryUri = savedInstanceState.getString(EXTRA_CURRENT_CATEGORY_URI, DEFAULT_CATEGORY_URI) } else { val args = requireArguments().let { DetailPagerFragmentArgs.fromBundle(it) } val inComingItemUri = args.navUri currentHymnId = inComingItemUri.hymnId()?.toInt() ?: 1 currentCategoryUri = inComingItemUri.parentCategoryUri() ?: DEFAULT_CATEGORY_URI } // Set the category uri. This would be used by the viewModel requireArguments().putString(HymnPagerViewModel.CATEGORY_URI_ARG, currentCategoryUri) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) detailPagerAdapter = DetailPagerAdapter(childFragmentManager).also { adapter -> viewModel.preferSheetMusic.observe(viewLifecycleOwner) { adapter.preferSheetMusic = it } } binding.viewpagerHymnDetail.adapter = detailPagerAdapter binding.viewpagerHymnDetail.setPageTransformer(true, DepthPageTransformer()) viewModel.hymnIndicesLiveData.observe(viewLifecycleOwner, Observer { indicesLce -> val indexToLoad = currentHymnId when (indicesLce) { is Lce.Loading -> showProgressLoading(indicesLce.loading) is Lce.Content -> { initializeViewPager(indicesLce.content, indexToLoad) updateCurrentItemId(indexToLoad) updateHymnItems(indicesLce.content.map { it.index }) } is Lce.Error -> showContentError(indicesLce.error) } }) viewModel.header.observe(viewLifecycleOwner, Observer { title -> binding.toolbarDetail.title = title }) viewModel.shareLinkStatus.observe(viewLifecycleOwner, Observer { shareStatus -> when (shareStatus) { ShareStatus.Loading -> showShareLoadingDialog() is ShareStatus.Success -> showShareOptionsChooser(shareStatus.shareLink) is ShareStatus.Error -> { showShareError(shareStatus.error) } ShareStatus.None -> { cancelProgressDialog() } } }) } private fun showShareError(error: Throwable) { Timber.w(error) Snackbar.make(requireView().rootView, "Failure creating share content", Snackbar.LENGTH_SHORT).show() } private fun showShareOptionsChooser(shareLink: String) { ShareCompat.IntentBuilder.from(requireActivity()).apply { setChooserTitle(getString(R.string.share_hymn)) setType("text/plain") setText(shareLink) }.startChooser() } private var progressDialog: ProgressDialog? = null private fun showShareLoadingDialog() { progressDialog = ProgressDialog.show(requireContext(), "Share hymn", "Working") progressDialog?.setCancelable(true) } private fun cancelProgressDialog() { progressDialog?.cancel() } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(EXTRA_CURRENT_ITEM_ID, currentHymnId) outState.putString(EXTRA_CURRENT_CATEGORY_URI, currentCategoryUri) super.onSaveInstanceState(outState) } private fun initializeViewPager(hymnIndices: List<HymnNumber>, initialIndex: Int) { Timber.i("Initializing viewPager with index: $initialIndex") //showProgressLoading(false) detailPagerAdapter.submitList(hymnIndices) // initialIndex represents the hymn number, where as the adapter uses a zero based index // Which implies that when the indices is sorted by titles, the correct detail won't be shown. // So we just need to find the index from the list of hymn indices val indexToLoad = hymnIndices.indexOfFirst { it.index == initialIndex } binding.viewpagerHymnDetail.currentItem = indexToLoad } override fun initiateContentSharing() { viewModel.requestShareLink(currentHymnId, getString(R.string.about_app), MINIMUM_VERSION_FOR_SHARE_LINK, WCCRM_LOGO_URL) } @SuppressLint("WrongConstant") inner class DetailPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { private val hymnIndices = mutableListOf<HymnNumber>() var preferSheetMusic: Boolean by observable(false) { property, oldValue, newValue -> if (oldValue != newValue) notifyDataSetChanged() } override fun getItem(position: Int): Fragment { val item = hymnIndices[position] val hymnToShow = if (position < hymnIndices.size) item.index else 1 return if (preferSheetMusic && item.hasSheetMusic) { SheetMusicDetailFragment().apply { init(hymnToShow) } } else { DetailFragment().apply { init(hymnToShow) } } } override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) { super.setPrimaryItem(container, position, `object`) updateCurrentItemId(hymnIndices[position].index) } override fun getItemPosition(`object`: Any): Int { return PagerAdapter.POSITION_NONE } override fun getCount(): Int { return hymnIndices.size } fun submitList(hymnIndices: List<HymnNumber>) { this.hymnIndices.clear() this.hymnIndices.addAll(hymnIndices) notifyDataSetChanged() } } }
2
Kotlin
6
7
19451208eb3d0ca3060e388bc4a41cf487a3ca63
7,009
hymnbook
MIT License
modules/modules_contact/src/main/java/com/cl/modules_contact/request/Extend.kt
aaaaaaaazmx
528,318,389
false
{"Kotlin": 3779032, "Java": 1498865}
package com.cl.modules_contact.request class Extend
0
Kotlin
0
0
49a74a32c320a273dbe04c785af49f874f1d711b
52
abby
Apache License 2.0
app/src/main/java/edu/rosehulman/condrak/roseschedule/Day.kt
keith-cr
164,172,313
false
null
package edu.rosehulman.condrak.roseschedule import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Day (var name: String = "", var periods: MutableList<ClassPeriod> = ArrayList()) : Parcelable
0
Kotlin
0
0
1c371a063edb6ba014bc34e7195ee5d5aae7b10d
230
rose-schedule
MIT License
app/src/main/java/com/wave/audiorecording/app/AppRecorderCallback.kt
SimformSolutionsPvtLtd
359,396,860
false
null
package com.wave.audiorecording.app import com.wave.audiorecording.data.database.Record import com.wave.audiorecording.exception.AppException import java.io.File interface AppRecorderCallback { fun onRecordingStarted(file: File?) fun onRecordingPaused() fun onRecordProcessing() fun onRecordFinishProcessing() fun onRecordingStopped(file: File?, record: Record?) fun onRecordingProgress(mills: Long, amp: Int) fun onError(throwable: AppException?) }
0
Kotlin
5
9
4b3ffa7bfc8c4718085bfc3c146863c659f8e09f
479
SSAudioRecorderWithWaveForm
Apache License 2.0
økonomi/infrastructure/src/main/kotlin/økonomi/infrastructure/kvittering/consumer/UtbetalingKvitteringIbmMqConsumer.kt
navikt
227,366,088
false
null
package økonomi.infrastructure.kvittering.consumer import no.nav.su.se.bakover.common.infrastructure.correlation.withCorrelationId import no.nav.su.se.bakover.common.sikkerLogg import org.slf4j.LoggerFactory import java.lang.RuntimeException import javax.jms.JMSContext import javax.jms.Session /** * TODO jah: Denne slettes når vi tar i bruk UtbetalingKvitteringIbmMqConsumerV2 */ class UtbetalingKvitteringIbmMqConsumer( kvitteringQueueName: String, globalJmsContext: JMSContext, private val kvitteringConsumer: UtbetalingKvitteringConsumer, ) { private val log = LoggerFactory.getLogger(this::class.java) private val jmsContext = globalJmsContext.createContext(Session.AUTO_ACKNOWLEDGE) private val consumer = jmsContext.createConsumer(jmsContext.createQueue(kvitteringQueueName)) // TODO: Vurder å gjøre om dette til en jobb som poller med receive, i stedet for asynkron messageListener // Da slipper vi sannsynligvis exceptionListeneren og vi har litt mer kontroll på når/hvordan tråden kjører init { consumer.setMessageListener { message -> try { withCorrelationId { log.info("Mottok kvittering fra køen: $kvitteringQueueName. Se sikkerlogg for meldingsinnhold.") message.getBody(String::class.java).let { sikkerLogg.info("Kvittering lest fra $kvitteringQueueName, innhold:$it") kvitteringConsumer.onMessage(it) } } } catch (ex: Exception) { log.error("Feil ved prosessering av melding fra: $kvitteringQueueName", ex) throw RuntimeException("Feil ved prosessering av melding fra: $kvitteringQueueName. Vi må kaste for å nacke meldingen. Se tilhørende errorlogg.") } } jmsContext.setExceptionListener { exception -> log.error("Feil mot $kvitteringQueueName", exception) } jmsContext.start() } }
6
Kotlin
1
1
d7157394e11b5b3c714a420a96211abb0a53ea45
1,989
su-se-bakover
MIT License
src/main/java/com/pako2k/banknotescatalog/app/tables/TotalStatsTable.kt
Pako2K
857,481,593
false
{"Kotlin": 672402}
package com.pako2k.banknotescatalog.app.tables typealias StatsTableSubColumn = List<Int> class TotalStatsTable( columns : List<String>, private val totalColumn : String? = null, val subColumns : List<String> ){ data class Record( val name : String, val columns : List<StatsTableSubColumn> ) val columns : List<String> = totalColumn?.let { total -> columns.toMutableList().also { it.add(total) } }?:columns private val _records : MutableList<Record> = mutableListOf() val dataRecords : List<Record> get() = this._records.toList() var totalRecord : List<StatsTableSubColumn> = listOf() private set fun addRecords(records: List<Record>){ records.forEach { addToRecords(it) } if(records.size>1) totalRecord = sumRecords() } fun addRecord(record: Record){ addToRecords(record) if(_records.size>1) totalRecord = sumRecords() } private fun addToRecords(record: Record){ // validate if( (totalColumn == null && (record.columns.size != columns.size)) || (totalColumn != null && (record.columns.size != columns.size - 1)) ) throw Exception("Data does not match number of columns") record.columns.forEach { subCol -> if(subCol.size != subColumns.size) throw Exception("Data does not match number of subColumns") } if(columns.size>1 && totalColumn != null){ // Add total Column val columnTotal = MutableList(subColumns.size) { 0 } record.columns.forEach { col -> col.forEachIndexed { indexSubCol, subCol -> columnTotal[indexSubCol] += subCol } } val allCols = record.columns.toMutableList() allCols.add(columnTotal) _records.add(Record(record.name, allCols)) } else _records.add(record) } private fun sumRecords() : List<StatsTableSubColumn> { val total = MutableList(columns.size){ MutableList(subColumns.size) { 0 } } _records.forEach { rec -> rec.columns.forEachIndexed { indexCol, col -> col.forEachIndexed { indexSubCol, subCol -> total[indexCol][indexSubCol] += subCol } } } return total } fun clear() { _records.clear() totalRecord = listOf() } }
0
Kotlin
0
0
3f7486c1a9544213a108dd17c4d78aeb50204bd4
2,483
BanknotesCatalog
MIT License
app/src/main/java/com/danchoo/sample/gallery/data/datasource/GalleryDataSourceImpl.kt
danchoo21
447,993,828
false
null
package com.danchoo.sample.gallery.data.datasource import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.MediaStore import com.danchoo.sample.gallery.domain.model.GalleryItemModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class GalleryDataSourceImpl @Inject constructor( @ApplicationContext private val context: Context ) : GalleryDataSource { override fun getDefaultCursor(): Cursor { return getCursor(getMediaDefaultProjection()) } override fun getGalleryItemList(count: Int): Flow<List<GalleryItemModel>> { return flow { val mediaItemList = mutableListOf<GalleryItemModel>() val projection = getMediaDefaultProjection() val cursor = getCursor(projection) while (cursor.moveToNext()) { val mediaItemModel = getMediaItemModel(cursor, projection) mediaItemList.add(mediaItemModel) if (mediaItemList.size == count) { emit(mediaItemList.toList()) mediaItemList.clear() } } if (mediaItemList.isNotEmpty()) { emit(mediaItemList.toList()) } cursor.close() } } override fun getGalleryItemList(start: Int, count: Int): List<GalleryItemModel> { val mediaItemList = mutableListOf<GalleryItemModel>() val projection = getMediaDefaultProjection() val cursor = getCursor(projection) cursor.moveToPosition(start - 1) while (cursor.moveToNext()) { val mediaItemModel = getMediaItemModel(cursor, projection) mediaItemList.add(mediaItemModel) if (mediaItemList.size == count) { break } } cursor.close() return mediaItemList } override fun getGalleryItemList( cursor: Cursor, start: Int, count: Int ): List<GalleryItemModel> { val mediaItemList = mutableListOf<GalleryItemModel>() val projection = getMediaDefaultProjection() cursor.moveToPosition(start - 1) while (cursor.moveToNext()) { val mediaItemModel = getMediaItemModel(cursor, projection) mediaItemList.add(mediaItemModel) if (mediaItemList.size == count) { break } } return mediaItemList } private fun getCursor(projection: Array<String>): Cursor { val selection = getAllMediaSelection() val resolver = context.contentResolver return resolver.query( MediaStore.Files.getContentUri("external"), projection, selection, null, MediaStore.Images.Media.DATE_MODIFIED + " desc" ) ?: throw Exception() } private fun getMediaItemModel(cursor: Cursor, projection: Array<String>): GalleryItemModel { val id = cursor.getInt(cursor.getColumnIndexOrThrow(projection[0])) val name = cursor.getString(cursor.getColumnIndexOrThrow(projection[1])) ?: "" val addedDate = cursor.getString(cursor.getColumnIndexOrThrow(projection[2])) ?: "" val modifiedDate = cursor.getString(cursor.getColumnIndexOrThrow(projection[3])) ?: "" val size = cursor.getLong(cursor.getColumnIndexOrThrow(projection[4])) val createDate = cursor.getLong(cursor.getColumnIndexOrThrow(projection[5])) val mediaType = cursor.getInt(cursor.getColumnIndexOrThrow(projection[6])) val mineType = cursor.getString(cursor.getColumnIndexOrThrow(projection[7])) ?: "" val columnIndexId = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID) val uri = when (mediaType) { MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO -> { Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cursor.getLong(columnIndexId).toString() ) } MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE -> { Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cursor.getLong(columnIndexId).toString() ) } else -> null } return GalleryItemModel( id = id, uri = uri, name = name, addedDate = addedDate, modifiedDate = modifiedDate, size = size, createDate = createDate, mediaType = mediaType, mineType = mineType ) } private fun getMediaDefaultProjection(): Array<String> { return arrayOf( MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.DATE_ADDED, MediaStore.MediaColumns.DATE_MODIFIED, MediaStore.MediaColumns.SIZE, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Files.FileColumns.MEDIA_TYPE, MediaStore.Files.FileColumns.MIME_TYPE ) } private fun getAllMediaSelection(): String { return StringBuilder() .append(MediaStore.Files.FileColumns.MEDIA_TYPE) .append("=") .append(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) .append(" OR ") .append(MediaStore.Files.FileColumns.MEDIA_TYPE) .append("=") .append(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) .toString() } }
0
Kotlin
0
1
9bacbf01f40e76571d368a4ec9cc4d8e464e6d64
5,709
compose-glide-image
Apache License 2.0
compose/desktop/desktop/src/jvmMain/kotlin/androidx/compose/ui/window/WindowDraggableArea.jvm.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import androidx.compose.desktop.AppWindow import androidx.compose.desktop.LocalAppWindow import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.drag import androidx.compose.foundation.gestures.forEachGesture import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.IntOffset import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.event.MouseMotionAdapter import java.awt.MouseInfo import java.awt.Point /** * WindowDraggableArea is a component that allows you to drag the window using the mouse. * * @param modifier The modifier to be applied to the layout. */ @Deprecated( "Use another variant of WindowDraggableArea for the new Composable Window API (https://github" + ".com/JetBrains/compose-jb/tree/master/tutorials/Window_API_new)", replaceWith = ReplaceWith( "WindowDraggableArea(modifier, content)", "androidx.compose.foundation.window.WindowDraggableArea" ) ) @Suppress("DEPRECATION") @Composable fun WindowDraggableArea( modifier: Modifier = Modifier, content: @Composable() () -> Unit = {} ) { val window = LocalAppWindow.current val handler = remember { DragHandler(window) } Box( modifier = modifier.pointerInput(Unit) { forEachGesture { awaitPointerEventScope { awaitFirstDown() handler.register() } } } ) { content() } } @Suppress("DEPRECATION") private class DragHandler(private val window: AppWindow) { private var location = window.window.location.toComposeOffset() private var pointStart = MouseInfo.getPointerInfo().location.toComposeOffset() private val dragListener = object : MouseMotionAdapter() { override fun mouseDragged(event: MouseEvent) = drag() } private val removeListener = object : MouseAdapter() { override fun mouseReleased(event: MouseEvent) { window.removeMouseMotionListener(dragListener) window.removeMouseListener(this) } } fun register() { location = window.window.location.toComposeOffset() pointStart = MouseInfo.getPointerInfo().location.toComposeOffset() window.addMouseListener(removeListener) window.addMouseMotionListener(dragListener) } private fun drag() { val point = MouseInfo.getPointerInfo().location.toComposeOffset() val location = location + (point - pointStart) window.setLocation(location.x, location.y) } private fun Point.toComposeOffset() = IntOffset(x, y) }
30
null
950
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,489
androidx
Apache License 2.0
tests/engine/src/commonTest/kotlin/WebSocketEngineTest.kt
apollographql
69,469,299
false
null
import com.apollographql.apollo3.api.http.HttpHeader import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.exception.ApolloNetworkException import com.apollographql.apollo3.exception.ApolloWebSocketClosedException import com.apollographql.apollo3.mpp.Platform import com.apollographql.apollo3.mpp.platform import com.apollographql.apollo3.testing.internal.runTest import com.apollographql.mockserver.CloseFrame import com.apollographql.mockserver.DataMessage import com.apollographql.mockserver.MockServer import com.apollographql.mockserver.TextMessage import com.apollographql.mockserver.awaitWebSocketRequest import com.apollographql.mockserver.enqueueWebSocket import kotlinx.coroutines.delay import okio.ByteString.Companion.encodeUtf8 import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertIs import kotlin.test.assertTrue class WebSocketEngineTest { /** * NSURLSession has a bug that sometimes skips the close frame * See https://developer.apple.com/forums/thread/679446 */ private fun maySkipCloseFrame(): Boolean { return platform() == Platform.Native } @Test fun textFrames() = runTest { val webSocketEngine = webSocketEngine() val webSocketServer = MockServer() val responseBody = webSocketServer.enqueueWebSocket() val connection = webSocketEngine.open(webSocketServer.url()) val request = webSocketServer.awaitWebSocketRequest() connection.send("client->server") request.awaitMessage().apply { assertIs<TextMessage>(this) assertEquals("client->server", text) } responseBody.enqueueMessage(TextMessage("server->client")) assertEquals("server->client", connection.receive()) connection.close() if (!maySkipCloseFrame()) { request.awaitMessage().apply { assertIs<CloseFrame>(this) } } webSocketServer.close() } @Test fun binaryFrames() = runTest { if (platform() == Platform.Js) return@runTest // Binary frames are not supported by the JS WebSocketEngine val webSocketEngine = webSocketEngine() val webSocketServer = MockServer() val responseBody = webSocketServer.enqueueWebSocket() val connection = webSocketEngine.open(webSocketServer.url()) val request = webSocketServer.awaitWebSocketRequest() connection.send("client->server".encodeUtf8()) request.awaitMessage().apply { assertIs<DataMessage>(this) assertEquals("client->server", data.decodeToString()) } responseBody.enqueueMessage(DataMessage("server->client".encodeToByteArray())) assertEquals("server->client", connection.receive()) connection.close() if (!maySkipCloseFrame()) { request.awaitMessage().apply { assertIs<CloseFrame>(this) } } webSocketServer.close() } @Test fun serverCloseNicely() = runTest { if (platform() == Platform.Js) return@runTest // It's not clear how termination works on JS val webSocketEngine = webSocketEngine() val webSocketServer = MockServer() val responseBody = webSocketServer.enqueueWebSocket() val connection = webSocketEngine.open(webSocketServer.url()) // See https://youtrack.jetbrains.com/issue/KTOR-7099/Race-condition-in-darwin-websockets-client-runIncomingProcessor delay(1000) responseBody.enqueueMessage(CloseFrame(4200, "Bye now")) val e = assertFailsWith<ApolloException> { connection.receive() } // On Apple, the close code and reason are not available - https://youtrack.jetbrains.com/issue/KTOR-6198 if (!isKtor || platform() != Platform.Native) { assertTrue(e is ApolloWebSocketClosedException) assertEquals(4200, e.code) assertEquals("Bye now", e.reason) } connection.close() webSocketServer.close() } @Test fun serverCloseAbruptly() = runTest { if (platform() == Platform.Js) return@runTest // It's not clear how termination works on JS if (platform() == Platform.Native) return@runTest // https://youtrack.jetbrains.com/issue/KTOR-6406 val webSocketEngine = webSocketEngine() val webSocketServer = MockServer() webSocketServer.enqueueWebSocket() val connection = webSocketEngine.open(webSocketServer.url()) webSocketServer.close() assertFailsWith<ApolloNetworkException> { connection.receive() } connection.close() } @Test fun headers() = runTest { val webSocketEngine = webSocketEngine() val webSocketServer = MockServer() webSocketServer.enqueueWebSocket() webSocketEngine.open(webSocketServer.url(), listOf( HttpHeader("Sec-WebSocket-Protocol", "graphql-ws"), HttpHeader("header1", "value1"), HttpHeader("header2", "value2"), )) val request = webSocketServer.awaitWebSocketRequest() assertEquals("graphql-ws", request.headers["Sec-WebSocket-Protocol"]) assertEquals("value1", request.headers["header1"]) assertEquals("value2", request.headers["header2"]) webSocketServer.close() } }
188
null
646
3,684
720d01d5cb61a178309f4edc37ae92c2a7d57c77
5,083
apollo-kotlin
MIT License
core/src/main/java/de/quantummaid/testmaid/SkipDecider.kt
quantummaid
373,873,853
false
null
/* * Copyright (c) 2021 <NAME> - https://quantummaid.de/. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 de.quantummaid.testmaid import de.quantummaid.injectmaid.api.Injector import de.quantummaid.testmaid.model.testcase.TestCaseData import de.quantummaid.testmaid.model.testclass.TestClassData data class ExecutionDecision(val execute: Boolean, val reason: String) interface SkipDecider { companion object { fun alwaysExecute(): SkipDecider { return AlwaysExecute() } } fun skipTestClass(testClassData: TestClassData, testSuiteScopedInjector: Injector): ExecutionDecision fun skipTestCase(testCaseData: TestCaseData, testSuiteScopedInjector: Injector): ExecutionDecision } private class AlwaysExecute : SkipDecider { override fun skipTestClass(testClassData: TestClassData, testSuiteScopedInjector: Injector): ExecutionDecision { return ExecutionDecision(true, "Test classes are executed by default") } override fun skipTestCase(testCaseData: TestCaseData, testSuiteScopedInjector: Injector): ExecutionDecision { return ExecutionDecision(true, "Test cases are executed by default") } }
0
Kotlin
0
0
651ca9678af542c57e9e0987cbcb7bd26d952a42
1,941
testmaid
Apache License 2.0
src/main/kotlin/me/steven/indrev/registry/IRModelManagers.kt
GabrielOlvH
265,247,813
false
null
package me.steven.indrev.registry import me.steven.indrev.api.machines.Tier import me.steven.indrev.blocks.machine.DrillHeadModel import me.steven.indrev.blocks.models.PumpPipeBakedModel import me.steven.indrev.blocks.models.pipes.CableModel import me.steven.indrev.blocks.models.pipes.FluidPipeModel import me.steven.indrev.blocks.models.pipes.ItemPipeModel import me.steven.indrev.items.models.TankItemBakedModel import me.steven.indrev.utils.identifier import net.fabricmc.fabric.api.client.model.ExtraModelProvider import net.fabricmc.fabric.api.client.model.ModelProviderContext import net.fabricmc.fabric.api.client.model.ModelVariantProvider import net.minecraft.client.render.model.UnbakedModel import net.minecraft.client.util.ModelIdentifier import net.minecraft.resource.ResourceManager import net.minecraft.util.Identifier import java.util.function.Consumer object IRModelManagers : ModelVariantProvider, ExtraModelProvider { private val CABLE_MODELS = arrayOf( CableModel(Tier.MK1), CableModel(Tier.MK2), CableModel(Tier.MK3), CableModel(Tier.MK4) ) private val ITEM_PIPE_MODELS = arrayOf( ItemPipeModel(Tier.MK1), ItemPipeModel(Tier.MK2), ItemPipeModel(Tier.MK3), ItemPipeModel(Tier.MK4) ) private val FLUID_PIPE_MODELS = arrayOf( FluidPipeModel(Tier.MK1), FluidPipeModel(Tier.MK2), FluidPipeModel(Tier.MK3), FluidPipeModel(Tier.MK4) ) override fun loadModelVariant(resourceId: ModelIdentifier, ctx: ModelProviderContext?): UnbakedModel? { if (resourceId.namespace != "indrev") return null val path = resourceId.path val variant = resourceId.variant val id = Identifier(resourceId.namespace, resourceId.path) return when { path == "drill_head" -> DrillHeadModel(resourceId.variant) path == "pump_pipe" -> PumpPipeBakedModel() path == "tank" && variant == "inventory" -> TankItemBakedModel path.startsWith("cable_mk") -> CABLE_MODELS[path.last().toString().toInt() - 1] path.startsWith("item_pipe_mk") -> ITEM_PIPE_MODELS[path.last().toString().toInt() - 1] path.startsWith("fluid_pipe_mk") -> FLUID_PIPE_MODELS[path.last().toString().toInt() - 1] MachineRegistry.MAP.containsKey(id) -> MachineRegistry.MAP[id]?.modelProvider?.get(Tier.values()[(path.last().toString().toIntOrNull() ?: 4) - 1])?.invoke(id.path.replace("_creative", "_mk4")) else -> return null } } override fun provideExtraModels(manager: ResourceManager?, out: Consumer<Identifier>) { out.accept(ModelIdentifier(identifier("drill_head"), "stone")) out.accept(ModelIdentifier(identifier("drill_head"), "iron")) out.accept(ModelIdentifier(identifier("drill_head"), "diamond")) out.accept(ModelIdentifier(identifier("drill_head"), "netherite")) out.accept(ModelIdentifier(identifier("pump_pipe"), "")) } }
51
null
56
192
012a1b83f39ab50a10d03ef3c1a8e2651e517053
2,939
Industrial-Revolution
Apache License 2.0
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/QueueTest.kt
tanelso2
100,993,157
false
null
/* * Copyright 2017 Netflix, 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.netflix.spinnaker.orca.q import com.netflix.spinnaker.orca.pipeline.model.Pipeline import com.netflix.spinnaker.orca.q.Queue.Companion.maxRetries import com.netflix.spinnaker.orca.time.MutableClock import com.netflix.spinnaker.spek.and import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import java.io.Closeable import java.time.Clock import java.time.Duration abstract class QueueSpec<out Q : Queue>( createQueue: (Clock, DeadMessageCallback) -> Q, shutdownCallback: (() -> Unit)? = null ) : Spek({ var queue: Q? = null val callback: QueueCallback = mock() val deadLetterCallback: DeadMessageCallback = mock() val clock = MutableClock() fun resetMocks() = reset(callback, deadLetterCallback) fun stopQueue() { queue?.let { q -> if (q is Closeable) { q.close() } } shutdownCallback?.invoke() } describe("polling the queue") { given("there are no messages") { beforeGroup { queue = createQueue(clock, deadLetterCallback) } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue") { queue!!.poll(callback) } it("does not invoke the callback") { verifyZeroInteractions(callback) } } given("there is a single message") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.push(message) } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue") { queue!!.poll(callback) } it("passes the queued message to the callback") { verify(callback).invoke(eq(message), any()) } } given("there are multiple messages") { val message1 = StartExecution(Pipeline::class.java, "1", "foo") val message2 = StartExecution(Pipeline::class.java, "2", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message1) clock.incrementBy(Duration.ofSeconds(1)) push(message2) } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue twice") { queue!!.apply { poll(callback) poll(callback) } } it("passes the messages to the callback in the order they were queued") { verify(callback).invoke(eq(message1), any()) verify(callback).invoke(eq(message2), any()) } } given("there is a delayed message") { val delay = Duration.ofHours(1) and("its delay has not expired") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.push(message, delay) } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue") { queue!!.poll(callback) } it("does not invoke the callback") { verifyZeroInteractions(callback) } } and("its delay has expired") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.push(message, delay) clock.incrementBy(delay) } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue") { queue!!.poll(callback) } it("passes the message to the callback") { verify(callback).invoke(eq(message), any()) } } } } describe("message redelivery") { given("a message was acknowledged") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.apply { push(message) poll { _, ack -> ack() } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue after the message acknowledgment has timed out") { queue!!.apply { clock.incrementBy(ackTimeout) retry() poll(callback) } } it("does not retry the message") { verifyZeroInteractions(callback) } } given("a message was not acknowledged") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.apply { push(message) poll { _, _ -> } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue after the message acknowledgment has timed out") { queue!!.apply { clock.incrementBy(ackTimeout) retry() poll(callback) } } it("retries the message") { verify(callback).invoke(eq(message), any()) } } given("a message was not acknowledged more than once") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.apply { push(message) repeat(2) { poll { _, _ -> } clock.incrementBy(ackTimeout) retry() } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue again") { queue!!.apply { poll(callback) } } it("retries the message") { verify(callback).invoke(eq(message), any()) } } given("a message was not acknowledged more than $maxRetries times") { val message = StartExecution(Pipeline::class.java, "1", "foo") beforeGroup { queue = createQueue(clock, deadLetterCallback) queue!!.apply { push(message) repeat(maxRetries) { poll { _, _ -> } clock.incrementBy(ackTimeout) retry() } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue again") { queue!!.apply { poll(callback) } } it("stops retrying the message") { verifyZeroInteractions(callback) } it("passes the failed message to the dead letter handler") { verify(deadLetterCallback).invoke(queue!!, message) } and("the message has been dead-lettered") { on("the next time retry checks happen") { queue!!.apply { retry() poll(callback) } } it("it does not get redelivered again") { verifyZeroInteractions(callback) } it("no longer gets sent to the dead letter handler") { verify(deadLetterCallback).invoke(queue!!, message) } } } } describe("message hashing") { given("a message was pushed") { val message = StartExecution(Pipeline::class.java, "1", "foo") and("a different message is pushed before acknowledging the first") { val newMessage = message.copy(executionId = "2") beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message) push(newMessage) } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue more than once") { queue!!.poll(callback) queue!!.poll(callback) } it("enqueued the new message") { verify(callback).invoke(eq(message), any()) verify(callback).invoke(eq(newMessage), any()) } } and("another identical message is pushed before acknowledging the first") { beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message) push(message.copy()) poll { _, ack -> ack() } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue again") { queue!!.poll(callback) } it("did not enqueue the duplicate message") { verifyZeroInteractions(callback) } } and("another identical message is pushed after reading but before acknowledging the first") { beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message) poll { _, ack -> push(message.copy()) ack() } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue again") { queue!!.poll(callback) } it("enqueued the second message") { verify(callback).invoke(eq(message), any()) } } and("another identical message is pushed after acknowledging the first") { beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message) poll { _, ack -> ack() } push(message.copy()) } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("polling the queue again") { queue!!.poll(callback) } it("enqueued the second message") { verify(callback).invoke(eq(message), any()) } } and("another identical message is pushed and the first is never acknowledged") { beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message) poll { _, _ -> push(message.copy()) } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("after the first message's acknowledgment times out") { with(queue!!) { clock.incrementBy(ackTimeout) retry() poll(callback) poll(callback) } } it("does not re-deliver the first message") { verify(callback).invoke(eq(message), any()) verifyNoMoreInteractions(callback) } } and("the first message is never acknowledged, gets re-delivered then another identical message is pushed") { beforeGroup { queue = createQueue(clock, deadLetterCallback).apply { push(message) poll { _, _ -> } } } afterGroup(::stopQueue) afterGroup(::resetMocks) on("after the first message's acknowledgment times out") { with(queue!!) { clock.incrementBy(ackTimeout) retry() push(message.copy()) poll(callback) poll(callback) } } it("did not enqueue the new duplicate message") { verify(callback).invoke(eq(message), any()) verifyNoMoreInteractions(callback) } } } } })
1
null
1
1
b641c49bbf9d887a9613944bdb67dc310cfd1ec9
11,839
orca
Apache License 2.0
app/src/main/java/com/optiontrade/br/base/BaseFragment.kt
DanSumtsov
587,860,108
false
null
package com.optiontrade.br.base import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil.inflate import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import com.optiontrade.br.MyApp open class BaseFragment<BindingType : ViewDataBinding, ParentType : BaseActivity<*>>() : Fragment() { lateinit var binding: BindingType lateinit var parentActivity: ParentType private var viewRoot: View? = null lateinit var preferences: SharedPreferences lateinit var app: MyApp private var layout_id: Int = 0 constructor(id : Int) : this(){ layout_id = id } open fun init() {} override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { parentActivity = activity as ParentType app = parentActivity.app preferences = parentActivity.preferences return if (viewRoot != null) { viewRoot!! } else { binding = inflate(inflater, layout_id, container, false) viewRoot = binding.root viewRoot!! } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) init() } fun replaceFrag(fragment: Fragment, backStack: Boolean) { parentActivity.openFrag(fragment, backStack) } }
0
Kotlin
0
0
546cce0bd4948bb51ec21b9359dfb001d1b49555
1,564
TradeStudyProject
Apache License 2.0
components/src/main/java/emperorfin/android/components/ui/screens/authentication/uicomponents/AuthenticationTitle.kt
emperorfin
611,222,954
false
null
/* * Copyright 2023 <NAME> (emperorfin) * * 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 emperorfin.android.components.ui.screens.authentication.uicomponents import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import emperorfin.android.components.R import emperorfin.android.components.ui.screens.authentication.enums.AuthenticationMode import emperorfin.android.components.ui.screens.authentication.enums.AuthenticationMode.SIGN_IN import emperorfin.android.components.ui.res.theme.ComposeEmailAuthenticationTheme import emperorfin.android.components.ui.screens.authentication.uicomponents.tags.Tags.TAG_AUTHENTICATION_AUTHENTICATION_TITLE /** * @Author: <NAME> (emperorfin) * @Date: November, 2022. */ @Composable fun AuthenticationTitle( modifier: Modifier = Modifier, authenticationMode: AuthenticationMode ) { Text( modifier = Modifier .testTag(tag = TAG_AUTHENTICATION_AUTHENTICATION_TITLE), text = stringResource( id = if (authenticationMode == SIGN_IN) { R.string.label_sign_in_to_account } else { R.string.label_sign_up_for_account } ), fontSize = FONT_SIZE_SP_24, fontWeight = FontWeight.Black ) } @Composable @Preview(showBackground = true) private fun AuthenticationTitlePreview() { ComposeEmailAuthenticationTheme { AuthenticationTitle( authenticationMode = SIGN_IN ) } } private val FONT_SIZE_SP_24: TextUnit = 24.sp
0
null
0
28
58cf34eea5c1c3f26e99b3ed3c8647885cc497d2
2,365
MilitaryJet
Apache License 2.0
app/src/main/java/com/iafs/sadagithubbrowser/data/network/github/model/LicenseSchema.kt
iafsilva
650,237,222
false
null
package com.iafs.sadagithubbrowser.data.network.github.model import com.google.gson.annotations.SerializedName /** * Entity [LicenseSchema] retrieved from Github on api.github.com/search/repositories */ data class LicenseSchema( @SerializedName("key") val key: String, @SerializedName("name") val name: String, @SerializedName("spdx_id") val spdxId: String, @SerializedName("url") val url: String?, @SerializedName("node_id") val nodeId: String )
1
Kotlin
0
0
df88bb48affdbe436a1689f86f71be249ba5a423
491
sada-github-browser
Apache License 2.0
app/src/main/java/com/black_dragon74/mujbuddy/SettingsActivity.kt
black-dragon74
170,815,529
false
{"Kotlin": 117240}
package com.black_dragon74.mujbuddy import android.content.SharedPreferences import android.os.Bundle import androidx.annotation.Nullable import com.black_dragon74.mujbuddy.utils.HelperFunctions import com.black_dragon74.mujbuddy.utils.SEMESTER_DATA import com.codevscolor.materialpreference.activity.MaterialPreferenceActivity import com.codevscolor.materialpreference.callback.MaterialPreferenceCallback import com.codevscolor.materialpreference.util.MaterialPrefUtil class SettingsActivity : MaterialPreferenceActivity(), MaterialPreferenceCallback { override fun init(@Nullable savedInstanceState: Bundle?) { setPreferenceChangedListener(this) useDarkTheme(true) setToolbarTitle("Settings") setPrimaryColor(MaterialPrefUtil.COLOR_RED) setDefaultSecondaryColor(this, MaterialPrefUtil.COLOR_AMBER) setAppPackageName("com.black_dragon74.mujbuddy") setXmlResourceName("pref_general") } override fun onPreferenceSettingsChanged(sharedPreferences: SharedPreferences, name: String) { // Init the helper val helper = HelperFunctions(this) // Get the semester value val currSem = sharedPreferences.getString(SEMESTER_DATA, "1")!!.toInt() helper.setCurrentSemester(currSem) } }
0
Kotlin
0
0
b530df85ed0e8bf78c6e918b209d87c7763ac53f
1,296
MUJ-Buddy-Android
MIT License
components/ledger/ledger-utxo-flow/src/main/kotlin/net/corda/ledger/utxo/flow/impl/UtxoLedgerServiceImpl.kt
corda
346,070,752
false
null
package net.corda.ledger.utxo.flow.impl import net.corda.flow.external.events.executor.ExternalEventExecutor import net.corda.flow.persistence.query.ResultSetFactory import net.corda.flow.pipeline.sessions.protocol.FlowProtocolStore import net.corda.ledger.common.data.transaction.TransactionStatus import net.corda.ledger.utxo.flow.impl.flows.finality.UtxoFinalityFlow import net.corda.ledger.utxo.flow.impl.flows.finality.UtxoReceiveFinalityFlow import net.corda.ledger.utxo.flow.impl.flows.transactionbuilder.ReceiveAndUpdateTransactionBuilderFlow import net.corda.ledger.utxo.flow.impl.flows.transactionbuilder.SendTransactionBuilderDiffFlow import net.corda.ledger.utxo.flow.impl.flows.transactiontransmission.ReceiveTransactionFlow import net.corda.ledger.utxo.flow.impl.flows.transactiontransmission.SendTransactionFlow import net.corda.ledger.utxo.flow.impl.persistence.UtxoLedgerPersistenceService import net.corda.ledger.utxo.flow.impl.persistence.UtxoLedgerStateQueryService import net.corda.ledger.utxo.flow.impl.persistence.VaultNamedParameterizedQueryImpl import net.corda.ledger.utxo.flow.impl.transaction.UtxoBaselinedTransactionBuilder import net.corda.ledger.utxo.flow.impl.transaction.UtxoSignedTransactionInternal import net.corda.ledger.utxo.flow.impl.transaction.UtxoTransactionBuilderImpl import net.corda.ledger.utxo.flow.impl.transaction.UtxoTransactionBuilderInternal import net.corda.ledger.utxo.flow.impl.transaction.factory.UtxoSignedTransactionFactory import net.corda.ledger.utxo.flow.impl.transaction.filtered.UtxoFilteredTransactionBuilderImpl import net.corda.ledger.utxo.flow.impl.transaction.filtered.factory.UtxoFilteredTransactionFactory import net.corda.ledger.utxo.flow.impl.transaction.verifier.UtxoLedgerTransactionVerificationService import net.corda.sandbox.type.UsedByFlow import net.corda.sandboxgroupcontext.CurrentSandboxGroupContext import net.corda.sandboxgroupcontext.getObjectByKey import net.corda.utilities.time.UTCClock import net.corda.v5.application.flows.FlowEngine import net.corda.v5.application.messaging.FlowSession import net.corda.v5.application.persistence.PagedQuery import net.corda.v5.base.annotations.Suspendable import net.corda.v5.base.annotations.VisibleForTesting import net.corda.v5.base.exceptions.CordaRuntimeException import net.corda.v5.base.types.MemberX500Name import net.corda.v5.crypto.SecureHash import net.corda.v5.ledger.common.NotaryLookup import net.corda.v5.ledger.notary.plugin.api.PluggableNotaryClientFlow import net.corda.v5.ledger.utxo.ContractState import net.corda.v5.ledger.utxo.FinalizationResult import net.corda.v5.ledger.utxo.StateAndRef import net.corda.v5.ledger.utxo.StateRef import net.corda.v5.ledger.utxo.UtxoLedgerService import net.corda.v5.ledger.utxo.query.VaultNamedParameterizedQuery import net.corda.v5.ledger.utxo.transaction.UtxoLedgerTransaction import net.corda.v5.ledger.utxo.transaction.UtxoSignedTransaction import net.corda.v5.ledger.utxo.transaction.UtxoTransactionBuilder import net.corda.v5.ledger.utxo.transaction.UtxoTransactionValidator import net.corda.v5.ledger.utxo.transaction.filtered.UtxoFilteredTransactionBuilder import net.corda.v5.serialization.SingletonSerializeAsToken import org.osgi.service.component.annotations.Activate import org.osgi.service.component.annotations.Component import org.osgi.service.component.annotations.Reference import org.osgi.service.component.annotations.ServiceScope.PROTOTYPE import java.security.PrivilegedActionException import java.security.PrivilegedExceptionAction import java.time.Instant @Suppress("LongParameterList", "TooManyFunctions") @Component(service = [UtxoLedgerService::class, UsedByFlow::class], scope = PROTOTYPE) class UtxoLedgerServiceImpl @Activate constructor( @Reference(service = UtxoFilteredTransactionFactory::class) private val utxoFilteredTransactionFactory: UtxoFilteredTransactionFactory, @Reference(service = UtxoSignedTransactionFactory::class) private val utxoSignedTransactionFactory: UtxoSignedTransactionFactory, @Reference(service = FlowEngine::class) private val flowEngine: FlowEngine, @Reference(service = UtxoLedgerPersistenceService::class) private val utxoLedgerPersistenceService: UtxoLedgerPersistenceService, @Reference(service = UtxoLedgerStateQueryService::class) private val utxoLedgerStateQueryService: UtxoLedgerStateQueryService, @Reference(service = CurrentSandboxGroupContext::class) private val currentSandboxGroupContext: CurrentSandboxGroupContext, @Reference(service = NotaryLookup::class) private val notaryLookup: NotaryLookup, @Reference(service = ExternalEventExecutor::class) private val externalEventExecutor: ExternalEventExecutor, @Reference(service = ResultSetFactory::class) private val resultSetFactory: ResultSetFactory, @Reference(service = UtxoLedgerTransactionVerificationService::class) private val transactionVerificationService: UtxoLedgerTransactionVerificationService ) : UtxoLedgerService, UsedByFlow, SingletonSerializeAsToken { private companion object { const val FIND_UNCONSUMED_STATES_BY_EXACT_TYPE = "CORDA_FIND_UNCONSUMED_STATES_BY_EXACT_TYPE" val clock = UTCClock() } @Suspendable override fun createTransactionBuilder() = UtxoTransactionBuilderImpl(utxoSignedTransactionFactory, notaryLookup) @Suspendable override fun verify(ledgerTransaction: UtxoLedgerTransaction) { transactionVerificationService.verify(ledgerTransaction) } @Suppress("UNCHECKED_CAST") @Suspendable override fun <T : ContractState> resolve(stateRefs: Iterable<StateRef>): List<StateAndRef<T>> { return utxoLedgerStateQueryService.resolveStateRefs(stateRefs) as List<StateAndRef<T>> } @Suspendable override fun <T : ContractState> resolve(stateRef: StateRef): StateAndRef<T> { return resolve<T>(listOf(stateRef)).first() } @Suspendable override fun findSignedTransaction(id: SecureHash): UtxoSignedTransaction? { return utxoLedgerPersistenceService.findSignedTransaction(id, TransactionStatus.VERIFIED) } @Suspendable override fun findLedgerTransaction(id: SecureHash): UtxoLedgerTransaction? { return utxoLedgerPersistenceService.findSignedLedgerTransaction(id)?.ledgerTransaction } @Suspendable override fun filterSignedTransaction(signedTransaction: UtxoSignedTransaction): UtxoFilteredTransactionBuilder { return UtxoFilteredTransactionBuilderImpl( utxoFilteredTransactionFactory, signedTransaction as UtxoSignedTransactionInternal ) } @Suspendable @Deprecated("Deprecated in inherited API") @Suppress("deprecation", "removal") override fun <T : ContractState> findUnconsumedStatesByType(type: Class<T>): List<StateAndRef<T>> { return utxoLedgerStateQueryService.findUnconsumedStatesByType(type) } @Suspendable override fun <T : ContractState> findUnconsumedStatesByExactType( type: Class<T>, limit: Int, createdTimestampLimit: Instant ): PagedQuery.ResultSet<StateAndRef<T>> { @Suppress("UNCHECKED_CAST") return query(FIND_UNCONSUMED_STATES_BY_EXACT_TYPE, StateAndRef::class.java) .setParameter("type", type.name) .setCreatedTimestampLimit(createdTimestampLimit) .setLimit(limit) .execute() as PagedQuery.ResultSet<StateAndRef<T>> } @Suspendable override fun finalize( signedTransaction: UtxoSignedTransaction, sessions: List<FlowSession> ): FinalizationResult { /* Need [doPrivileged] due to [contextLogger] being used in the flow's constructor. Creating the executing the SubFlow must be independent otherwise the security manager causes issues with Quasar. */ val utxoFinalityFlow = try { @Suppress("deprecation", "removal") java.security.AccessController.doPrivileged( PrivilegedExceptionAction { UtxoFinalityFlow( signedTransaction as UtxoSignedTransactionInternal, sessions, getPluggableNotaryDetails(signedTransaction.notaryName) ) } ) } catch (e: PrivilegedActionException) { throw e.exception } return FinalizationResultImpl(flowEngine.subFlow(utxoFinalityFlow)) } @Suspendable override fun receiveFinality( session: FlowSession, validator: UtxoTransactionValidator ): FinalizationResult { val utxoReceiveFinalityFlow = try { @Suppress("deprecation", "removal") java.security.AccessController.doPrivileged( PrivilegedExceptionAction { UtxoReceiveFinalityFlow(session, validator) } ) } catch (e: PrivilegedActionException) { throw e.exception } return FinalizationResultImpl(flowEngine.subFlow(utxoReceiveFinalityFlow)) } @Suspendable override fun <R> query(queryName: String, resultClass: Class<R>): VaultNamedParameterizedQuery<R> { return VaultNamedParameterizedQueryImpl( queryName, externalEventExecutor, currentSandboxGroupContext, resultSetFactory, parameters = mutableMapOf(), limit = Int.MAX_VALUE, offset = 0, resultClass, clock ) } @Suspendable override fun persistDraftSignedTransaction(utxoSignedTransaction: UtxoSignedTransaction) { // Verifications need to be at least as strong as what // net.corda.ledger.utxo.flow.impl.flows.finality.v1.UtxoFinalityFlowV1.call // does before the initial persist() utxoSignedTransaction as UtxoSignedTransactionInternal // verifyExistingSignatures check(utxoSignedTransaction.signatures.isNotEmpty()) { "Received draft transaction without signatures." } utxoSignedTransaction.signatures.forEach { utxoSignedTransaction.verifySignatorySignature(it) } // verifyTransaction transactionVerificationService.verify(utxoSignedTransaction.toLedgerTransaction()) // Initial verifications passed, the transaction can be saved in the database. utxoLedgerPersistenceService.persist(utxoSignedTransaction, TransactionStatus.DRAFT) } @Suspendable override fun findDraftSignedTransaction(id: SecureHash): UtxoSignedTransaction? { return utxoLedgerPersistenceService.findSignedTransaction(id, TransactionStatus.DRAFT) } // Retrieve notary client plugin class for specified notary service identity. This is done in // a non-suspendable function to avoid trying (and failing) to serialize the objects used // internally. @VisibleForTesting @Suppress("ThrowsCount") internal fun getPluggableNotaryDetails(notary: MemberX500Name): PluggableNotaryDetails { val notaryInfo = notaryLookup.notaryServices.firstOrNull { it.name == notary } ?: throw CordaRuntimeException( "Notary service $notary has not been registered on the network." ) val sandboxGroupContext = currentSandboxGroupContext.get() val protocolStore = sandboxGroupContext.getObjectByKey<FlowProtocolStore>("FLOW_PROTOCOL_STORE") ?: throw CordaRuntimeException( "Cannot get flow protocol store for current sandbox group context" ) val flowName = protocolStore.initiatorForProtocol(notaryInfo.protocol, notaryInfo.protocolVersions) val flowClass = sandboxGroupContext.sandboxGroup.loadClassFromMainBundles(flowName) if (!PluggableNotaryClientFlow::class.java.isAssignableFrom(flowClass)) { throw CordaRuntimeException( "Notary client flow class $flowName is invalid because " + "it does not inherit from ${PluggableNotaryClientFlow::class.simpleName}." ) } @Suppress("UNCHECKED_CAST") return PluggableNotaryDetails( flowClass as Class<PluggableNotaryClientFlow>, notaryInfo.isBackchainRequired ) } @Suspendable override fun receiveTransactionBuilder(session: FlowSession): UtxoTransactionBuilder { val receivedTransactionBuilder = flowEngine.subFlow( ReceiveAndUpdateTransactionBuilderFlow( session, createTransactionBuilder() ) ) return UtxoBaselinedTransactionBuilder( receivedTransactionBuilder as UtxoTransactionBuilderInternal ) } @Suspendable override fun receiveTransaction(session: FlowSession): UtxoSignedTransaction { return flowEngine.subFlow(ReceiveTransactionFlow(session)) } @Suspendable override fun sendTransaction(signedTransaction: UtxoSignedTransaction, sessions: List<FlowSession>) { flowEngine.subFlow(SendTransactionFlow(signedTransaction, sessions)) } @Suspendable override fun sendUpdatedTransactionBuilder( transactionBuilder: UtxoTransactionBuilder, session: FlowSession, ) { if (transactionBuilder !is UtxoBaselinedTransactionBuilder) { throw UnsupportedOperationException("Only received transaction builder proposals can be used in replies.") } flowEngine.subFlow( SendTransactionBuilderDiffFlow( transactionBuilder, session ) ) } @Suspendable override fun sendAndReceiveTransactionBuilder( transactionBuilder: UtxoTransactionBuilder, session: FlowSession ): UtxoTransactionBuilder { flowEngine.subFlow( SendTransactionBuilderDiffFlow( transactionBuilder as UtxoTransactionBuilderInternal, session ) ) return flowEngine.subFlow( ReceiveAndUpdateTransactionBuilderFlow( session, transactionBuilder ) ) } }
96
null
9
56
dd139d8da25a3c52ae17ca8d0debc3da4067f158
14,247
corda-runtime-os
Apache License 2.0
components/ledger/ledger-utxo-flow/src/main/kotlin/net/corda/ledger/utxo/flow/impl/UtxoLedgerServiceImpl.kt
corda
346,070,752
false
null
package net.corda.ledger.utxo.flow.impl import net.corda.flow.external.events.executor.ExternalEventExecutor import net.corda.flow.persistence.query.ResultSetFactory import net.corda.flow.pipeline.sessions.protocol.FlowProtocolStore import net.corda.ledger.common.data.transaction.TransactionStatus import net.corda.ledger.utxo.flow.impl.flows.finality.UtxoFinalityFlow import net.corda.ledger.utxo.flow.impl.flows.finality.UtxoReceiveFinalityFlow import net.corda.ledger.utxo.flow.impl.flows.transactionbuilder.ReceiveAndUpdateTransactionBuilderFlow import net.corda.ledger.utxo.flow.impl.flows.transactionbuilder.SendTransactionBuilderDiffFlow import net.corda.ledger.utxo.flow.impl.flows.transactiontransmission.ReceiveTransactionFlow import net.corda.ledger.utxo.flow.impl.flows.transactiontransmission.SendTransactionFlow import net.corda.ledger.utxo.flow.impl.persistence.UtxoLedgerPersistenceService import net.corda.ledger.utxo.flow.impl.persistence.UtxoLedgerStateQueryService import net.corda.ledger.utxo.flow.impl.persistence.VaultNamedParameterizedQueryImpl import net.corda.ledger.utxo.flow.impl.transaction.UtxoBaselinedTransactionBuilder import net.corda.ledger.utxo.flow.impl.transaction.UtxoSignedTransactionInternal import net.corda.ledger.utxo.flow.impl.transaction.UtxoTransactionBuilderImpl import net.corda.ledger.utxo.flow.impl.transaction.UtxoTransactionBuilderInternal import net.corda.ledger.utxo.flow.impl.transaction.factory.UtxoSignedTransactionFactory import net.corda.ledger.utxo.flow.impl.transaction.filtered.UtxoFilteredTransactionBuilderImpl import net.corda.ledger.utxo.flow.impl.transaction.filtered.factory.UtxoFilteredTransactionFactory import net.corda.ledger.utxo.flow.impl.transaction.verifier.UtxoLedgerTransactionVerificationService import net.corda.sandbox.type.UsedByFlow import net.corda.sandboxgroupcontext.CurrentSandboxGroupContext import net.corda.sandboxgroupcontext.getObjectByKey import net.corda.utilities.time.UTCClock import net.corda.v5.application.flows.FlowEngine import net.corda.v5.application.messaging.FlowSession import net.corda.v5.application.persistence.PagedQuery import net.corda.v5.base.annotations.Suspendable import net.corda.v5.base.annotations.VisibleForTesting import net.corda.v5.base.exceptions.CordaRuntimeException import net.corda.v5.base.types.MemberX500Name import net.corda.v5.crypto.SecureHash import net.corda.v5.ledger.common.NotaryLookup import net.corda.v5.ledger.notary.plugin.api.PluggableNotaryClientFlow import net.corda.v5.ledger.utxo.ContractState import net.corda.v5.ledger.utxo.FinalizationResult import net.corda.v5.ledger.utxo.StateAndRef import net.corda.v5.ledger.utxo.StateRef import net.corda.v5.ledger.utxo.UtxoLedgerService import net.corda.v5.ledger.utxo.query.VaultNamedParameterizedQuery import net.corda.v5.ledger.utxo.transaction.UtxoLedgerTransaction import net.corda.v5.ledger.utxo.transaction.UtxoSignedTransaction import net.corda.v5.ledger.utxo.transaction.UtxoTransactionBuilder import net.corda.v5.ledger.utxo.transaction.UtxoTransactionValidator import net.corda.v5.ledger.utxo.transaction.filtered.UtxoFilteredTransactionBuilder import net.corda.v5.serialization.SingletonSerializeAsToken import org.osgi.service.component.annotations.Activate import org.osgi.service.component.annotations.Component import org.osgi.service.component.annotations.Reference import org.osgi.service.component.annotations.ServiceScope.PROTOTYPE import java.security.PrivilegedActionException import java.security.PrivilegedExceptionAction import java.time.Instant @Suppress("LongParameterList", "TooManyFunctions") @Component(service = [UtxoLedgerService::class, UsedByFlow::class], scope = PROTOTYPE) class UtxoLedgerServiceImpl @Activate constructor( @Reference(service = UtxoFilteredTransactionFactory::class) private val utxoFilteredTransactionFactory: UtxoFilteredTransactionFactory, @Reference(service = UtxoSignedTransactionFactory::class) private val utxoSignedTransactionFactory: UtxoSignedTransactionFactory, @Reference(service = FlowEngine::class) private val flowEngine: FlowEngine, @Reference(service = UtxoLedgerPersistenceService::class) private val utxoLedgerPersistenceService: UtxoLedgerPersistenceService, @Reference(service = UtxoLedgerStateQueryService::class) private val utxoLedgerStateQueryService: UtxoLedgerStateQueryService, @Reference(service = CurrentSandboxGroupContext::class) private val currentSandboxGroupContext: CurrentSandboxGroupContext, @Reference(service = NotaryLookup::class) private val notaryLookup: NotaryLookup, @Reference(service = ExternalEventExecutor::class) private val externalEventExecutor: ExternalEventExecutor, @Reference(service = ResultSetFactory::class) private val resultSetFactory: ResultSetFactory, @Reference(service = UtxoLedgerTransactionVerificationService::class) private val transactionVerificationService: UtxoLedgerTransactionVerificationService ) : UtxoLedgerService, UsedByFlow, SingletonSerializeAsToken { private companion object { const val FIND_UNCONSUMED_STATES_BY_EXACT_TYPE = "CORDA_FIND_UNCONSUMED_STATES_BY_EXACT_TYPE" val clock = UTCClock() } @Suspendable override fun createTransactionBuilder() = UtxoTransactionBuilderImpl(utxoSignedTransactionFactory, notaryLookup) @Suspendable override fun verify(ledgerTransaction: UtxoLedgerTransaction) { transactionVerificationService.verify(ledgerTransaction) } @Suppress("UNCHECKED_CAST") @Suspendable override fun <T : ContractState> resolve(stateRefs: Iterable<StateRef>): List<StateAndRef<T>> { return utxoLedgerStateQueryService.resolveStateRefs(stateRefs) as List<StateAndRef<T>> } @Suspendable override fun <T : ContractState> resolve(stateRef: StateRef): StateAndRef<T> { return resolve<T>(listOf(stateRef)).first() } @Suspendable override fun findSignedTransaction(id: SecureHash): UtxoSignedTransaction? { return utxoLedgerPersistenceService.findSignedTransaction(id, TransactionStatus.VERIFIED) } @Suspendable override fun findLedgerTransaction(id: SecureHash): UtxoLedgerTransaction? { return utxoLedgerPersistenceService.findSignedLedgerTransaction(id)?.ledgerTransaction } @Suspendable override fun filterSignedTransaction(signedTransaction: UtxoSignedTransaction): UtxoFilteredTransactionBuilder { return UtxoFilteredTransactionBuilderImpl( utxoFilteredTransactionFactory, signedTransaction as UtxoSignedTransactionInternal ) } @Suspendable @Deprecated("Deprecated in inherited API") @Suppress("deprecation", "removal") override fun <T : ContractState> findUnconsumedStatesByType(type: Class<T>): List<StateAndRef<T>> { return utxoLedgerStateQueryService.findUnconsumedStatesByType(type) } @Suspendable override fun <T : ContractState> findUnconsumedStatesByExactType( type: Class<T>, limit: Int, createdTimestampLimit: Instant ): PagedQuery.ResultSet<StateAndRef<T>> { @Suppress("UNCHECKED_CAST") return query(FIND_UNCONSUMED_STATES_BY_EXACT_TYPE, StateAndRef::class.java) .setParameter("type", type.name) .setCreatedTimestampLimit(createdTimestampLimit) .setLimit(limit) .execute() as PagedQuery.ResultSet<StateAndRef<T>> } @Suspendable override fun finalize( signedTransaction: UtxoSignedTransaction, sessions: List<FlowSession> ): FinalizationResult { /* Need [doPrivileged] due to [contextLogger] being used in the flow's constructor. Creating the executing the SubFlow must be independent otherwise the security manager causes issues with Quasar. */ val utxoFinalityFlow = try { @Suppress("deprecation", "removal") java.security.AccessController.doPrivileged( PrivilegedExceptionAction { UtxoFinalityFlow( signedTransaction as UtxoSignedTransactionInternal, sessions, getPluggableNotaryDetails(signedTransaction.notaryName) ) } ) } catch (e: PrivilegedActionException) { throw e.exception } return FinalizationResultImpl(flowEngine.subFlow(utxoFinalityFlow)) } @Suspendable override fun receiveFinality( session: FlowSession, validator: UtxoTransactionValidator ): FinalizationResult { val utxoReceiveFinalityFlow = try { @Suppress("deprecation", "removal") java.security.AccessController.doPrivileged( PrivilegedExceptionAction { UtxoReceiveFinalityFlow(session, validator) } ) } catch (e: PrivilegedActionException) { throw e.exception } return FinalizationResultImpl(flowEngine.subFlow(utxoReceiveFinalityFlow)) } @Suspendable override fun <R> query(queryName: String, resultClass: Class<R>): VaultNamedParameterizedQuery<R> { return VaultNamedParameterizedQueryImpl( queryName, externalEventExecutor, currentSandboxGroupContext, resultSetFactory, parameters = mutableMapOf(), limit = Int.MAX_VALUE, offset = 0, resultClass, clock ) } @Suspendable override fun persistDraftSignedTransaction(utxoSignedTransaction: UtxoSignedTransaction) { // Verifications need to be at least as strong as what // net.corda.ledger.utxo.flow.impl.flows.finality.v1.UtxoFinalityFlowV1.call // does before the initial persist() utxoSignedTransaction as UtxoSignedTransactionInternal // verifyExistingSignatures check(utxoSignedTransaction.signatures.isNotEmpty()) { "Received draft transaction without signatures." } utxoSignedTransaction.signatures.forEach { utxoSignedTransaction.verifySignatorySignature(it) } // verifyTransaction transactionVerificationService.verify(utxoSignedTransaction.toLedgerTransaction()) // Initial verifications passed, the transaction can be saved in the database. utxoLedgerPersistenceService.persist(utxoSignedTransaction, TransactionStatus.DRAFT) } @Suspendable override fun findDraftSignedTransaction(id: SecureHash): UtxoSignedTransaction? { return utxoLedgerPersistenceService.findSignedTransaction(id, TransactionStatus.DRAFT) } // Retrieve notary client plugin class for specified notary service identity. This is done in // a non-suspendable function to avoid trying (and failing) to serialize the objects used // internally. @VisibleForTesting @Suppress("ThrowsCount") internal fun getPluggableNotaryDetails(notary: MemberX500Name): PluggableNotaryDetails { val notaryInfo = notaryLookup.notaryServices.firstOrNull { it.name == notary } ?: throw CordaRuntimeException( "Notary service $notary has not been registered on the network." ) val sandboxGroupContext = currentSandboxGroupContext.get() val protocolStore = sandboxGroupContext.getObjectByKey<FlowProtocolStore>("FLOW_PROTOCOL_STORE") ?: throw CordaRuntimeException( "Cannot get flow protocol store for current sandbox group context" ) val flowName = protocolStore.initiatorForProtocol(notaryInfo.protocol, notaryInfo.protocolVersions) val flowClass = sandboxGroupContext.sandboxGroup.loadClassFromMainBundles(flowName) if (!PluggableNotaryClientFlow::class.java.isAssignableFrom(flowClass)) { throw CordaRuntimeException( "Notary client flow class $flowName is invalid because " + "it does not inherit from ${PluggableNotaryClientFlow::class.simpleName}." ) } @Suppress("UNCHECKED_CAST") return PluggableNotaryDetails( flowClass as Class<PluggableNotaryClientFlow>, notaryInfo.isBackchainRequired ) } @Suspendable override fun receiveTransactionBuilder(session: FlowSession): UtxoTransactionBuilder { val receivedTransactionBuilder = flowEngine.subFlow( ReceiveAndUpdateTransactionBuilderFlow( session, createTransactionBuilder() ) ) return UtxoBaselinedTransactionBuilder( receivedTransactionBuilder as UtxoTransactionBuilderInternal ) } @Suspendable override fun receiveTransaction(session: FlowSession): UtxoSignedTransaction { return flowEngine.subFlow(ReceiveTransactionFlow(session)) } @Suspendable override fun sendTransaction(signedTransaction: UtxoSignedTransaction, sessions: List<FlowSession>) { flowEngine.subFlow(SendTransactionFlow(signedTransaction, sessions)) } @Suspendable override fun sendUpdatedTransactionBuilder( transactionBuilder: UtxoTransactionBuilder, session: FlowSession, ) { if (transactionBuilder !is UtxoBaselinedTransactionBuilder) { throw UnsupportedOperationException("Only received transaction builder proposals can be used in replies.") } flowEngine.subFlow( SendTransactionBuilderDiffFlow( transactionBuilder, session ) ) } @Suspendable override fun sendAndReceiveTransactionBuilder( transactionBuilder: UtxoTransactionBuilder, session: FlowSession ): UtxoTransactionBuilder { flowEngine.subFlow( SendTransactionBuilderDiffFlow( transactionBuilder as UtxoTransactionBuilderInternal, session ) ) return flowEngine.subFlow( ReceiveAndUpdateTransactionBuilderFlow( session, transactionBuilder ) ) } }
96
null
9
56
dd139d8da25a3c52ae17ca8d0debc3da4067f158
14,247
corda-runtime-os
Apache License 2.0
src/main/kotlin/hr/fer/zemris/renderer/dsl/LightDSL.kt
lukamijic
244,489,376
false
null
package hr.fer.zemris.renderer.dsl import hr.fer.zemris.math.vector.Vector import hr.fer.zemris.renderer.lightning.Intensity import hr.fer.zemris.renderer.lightning.Light fun light(block: LightBuilder.() -> Unit) : Light = LightBuilder().apply(block).build() class LightBuilder { var id: String? = null var position: Vector? = null var ambientIntensity: Intensity? = null var intensity: Intensity? = null fun build(): Light = Light( id!!, position!!, ambientIntensity!!, intensity!! ) }
0
Kotlin
0
0
26f18a2d6caf1648a78ed61c2f18a9114ecff87e
575
feRenderer
MIT License
src/main/kotlin/view/UiResources.kt
vladcudoidem
791,799,477
false
{"Kotlin": 64984}
package view import androidx.compose.foundation.defaultScrollbarStyle import androidx.compose.foundation.shape.RoundedCornerShape import shared.Colors.scrollbarHoverColor import shared.Colors.scrollbarUnhoverColor import shared.Dimensions.scrollbarThickness val CustomScrollbarStyle = defaultScrollbarStyle().copy( shape = RoundedCornerShape(50), hoverColor = scrollbarHoverColor, unhoverColor = scrollbarUnhoverColor, thickness = scrollbarThickness )
11
Kotlin
0
0
ea4b8edd3ef87c9b2761513b7e749b8d160406d3
469
Schaumamal
MIT License
compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrImplicitCastInserter.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.backend import org.jetbrains.kotlin.fir.FirElement import org.jetbrains.kotlin.fir.declarations.FirTypeAlias import org.jetbrains.kotlin.fir.expressions.* import org.jetbrains.kotlin.fir.expressions.impl.FirStubStatement import org.jetbrains.kotlin.fir.expressions.impl.FirUnitExpression import org.jetbrains.kotlin.fir.references.FirReference import org.jetbrains.kotlin.fir.render import org.jetbrains.kotlin.fir.resolvedSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol import org.jetbrains.kotlin.fir.types.* import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitor import org.jetbrains.kotlin.ir.IrBuiltIns import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.classId import org.jetbrains.kotlin.ir.util.parentAsClass import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.types.AbstractTypeChecker class Fir2IrImplicitCastInserter( private val components: Fir2IrComponents ) : Fir2IrComponents by components, FirDefaultVisitor<IrElement, IrElement>() { private fun FirTypeRef.toIrType(): IrType = with(typeConverter) { toIrType() } private fun ConeKotlinType.toIrType(): IrType = with(typeConverter) { toIrType() } override fun visitElement(element: FirElement, data: IrElement): IrElement { TODO("Should not be here: ${element::class}: ${element.render()}") } override fun visitAnnotation(annotation: FirAnnotation, data: IrElement): IrElement = data override fun visitAnnotationCall(annotationCall: FirAnnotationCall, data: IrElement): IrElement = data override fun visitAnonymousObjectExpression(anonymousObjectExpression: FirAnonymousObjectExpression, data: IrElement): IrElement = data override fun visitAnonymousFunctionExpression(anonymousFunctionExpression: FirAnonymousFunctionExpression, data: IrElement): IrElement { return data } override fun visitBinaryLogicExpression(binaryLogicExpression: FirBinaryLogicExpression, data: IrElement): IrElement = data // TODO: maybe a place to do coerceIntToAnotherIntegerType? override fun visitComparisonExpression(comparisonExpression: FirComparisonExpression, data: IrElement): IrElement = data override fun visitTypeOperatorCall(typeOperatorCall: FirTypeOperatorCall, data: IrElement): IrElement = data override fun visitEqualityOperatorCall(equalityOperatorCall: FirEqualityOperatorCall, data: IrElement): IrElement = data override fun <T> visitConstExpression(constExpression: FirConstExpression<T>, data: IrElement): IrElement = data override fun visitThisReceiverExpression(thisReceiverExpression: FirThisReceiverExpression, data: IrElement): IrElement = data override fun visitQualifiedAccessExpression(qualifiedAccessExpression: FirQualifiedAccessExpression, data: IrElement): IrElement = data override fun visitPropertyAccessExpression(propertyAccessExpression: FirPropertyAccessExpression, data: IrElement): IrElement = data override fun visitResolvedQualifier(resolvedQualifier: FirResolvedQualifier, data: IrElement): IrElement = data override fun visitGetClassCall(getClassCall: FirGetClassCall, data: IrElement): IrElement = data override fun visitFunctionCall(functionCall: FirFunctionCall, data: IrElement): IrElement = data override fun visitCheckNotNullCall(checkNotNullCall: FirCheckNotNullCall, data: IrElement): IrElement = data override fun visitCheckedSafeCallSubject(checkedSafeCallSubject: FirCheckedSafeCallSubject, data: IrElement): IrElement = data override fun visitSafeCallExpression(safeCallExpression: FirSafeCallExpression, data: IrElement): IrElement = data override fun visitStringConcatenationCall(stringConcatenationCall: FirStringConcatenationCall, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitArrayOfCall(arrayOfCall: FirArrayOfCall, data: IrElement): IrElement = data // TODO: something to do w.r.t. SAM? override fun visitLambdaArgumentExpression(lambdaArgumentExpression: FirLambdaArgumentExpression, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitNamedArgumentExpression(namedArgumentExpression: FirNamedArgumentExpression, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitVarargArgumentsExpression(varargArgumentsExpression: FirVarargArgumentsExpression, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitSpreadArgumentExpression(spreadArgumentExpression: FirSpreadArgumentExpression, data: IrElement): IrElement = data // ================================================================================== override fun visitExpression(expression: FirExpression, data: IrElement): IrElement { return when (expression) { is FirBlock -> (data as IrContainerExpression).insertImplicitCasts() is FirUnitExpression -> (data as IrExpression).let { coerceToUnitIfNeeded(it, irBuiltIns) } else -> data } } override fun visitStatement(statement: FirStatement, data: IrElement): IrElement { return when (statement) { is FirTypeAlias -> data FirStubStatement -> data is FirUnitExpression -> (data as IrExpression).let { coerceToUnitIfNeeded(it, irBuiltIns) } is FirBlock -> (data as IrContainerExpression).insertImplicitCasts() else -> statement.accept(this, data) } } // ================================================================================== override fun visitWhenExpression(whenExpression: FirWhenExpression, data: IrElement): IrElement { if (data is IrBlock) { return data.insertImplicitCasts() } val irWhen = data as IrWhen if (irWhen.branches.size != whenExpression.branches.size) { return data } val firBranchMap = irWhen.branches.zip(whenExpression.branches).toMap() irWhen.branches.replaceAll { visitWhenBranch(firBranchMap.getValue(it), it) } return data } override fun visitWhenSubjectExpression(whenSubjectExpression: FirWhenSubjectExpression, data: IrElement): IrElement = data // TODO: cast `condition` expression to boolean? override fun visitWhenBranch(whenBranch: FirWhenBranch, data: IrElement): IrBranch { val irBranch = data as IrBranch (irBranch.result as? IrContainerExpression)?.let { irBranch.result = it.insertImplicitCasts() } return data } // TODO: Need to visit lhs/rhs branches? override fun visitElvisExpression(elvisExpression: FirElvisExpression, data: IrElement): IrElement = data // ================================================================================== // TODO: cast `condition` expression to boolean? override fun visitDoWhileLoop(doWhileLoop: FirDoWhileLoop, data: IrElement): IrElement { val loop = data as IrDoWhileLoop (loop.body as? IrContainerExpression)?.let { loop.body = it.insertImplicitCasts() } return data } // TODO: cast `condition` expression to boolean? override fun visitWhileLoop(whileLoop: FirWhileLoop, data: IrElement): IrElement { val loop = data as IrWhileLoop (loop.body as? IrContainerExpression)?.let { loop.body = it.insertImplicitCasts() } return data } override fun visitBreakExpression(breakExpression: FirBreakExpression, data: IrElement): IrElement = data override fun visitContinueExpression(continueExpression: FirContinueExpression, data: IrElement): IrElement = data // ================================================================================== override fun visitTryExpression(tryExpression: FirTryExpression, data: IrElement): IrElement { val irTry = data as IrTry (irTry.finallyExpression as? IrContainerExpression)?.let { irTry.finallyExpression = it.insertImplicitCasts() } return data } override fun visitThrowExpression(throwExpression: FirThrowExpression, data: IrElement): IrElement = (data as IrThrow).cast(throwExpression, throwExpression.exception.typeRef, throwExpression.typeRef) override fun visitBlock(block: FirBlock, data: IrElement): IrElement = (data as? IrContainerExpression)?.insertImplicitCasts() ?: data override fun visitReturnExpression(returnExpression: FirReturnExpression, data: IrElement): IrElement { val irReturn = data as IrReturn val expectedType = returnExpression.target.labeledElement.returnTypeRef irReturn.value = irReturn.value.cast(returnExpression.result, returnExpression.result.typeRef, expectedType) return data } // ================================================================================== internal fun IrExpression.cast(expression: FirExpression, valueType: FirTypeRef, expectedType: FirTypeRef): IrExpression { if (this is IrTypeOperatorCall) { return this } return when { this is IrContainerExpression -> { insertImplicitCasts() } expectedType.isUnit -> { coerceToUnitIfNeeded(this, irBuiltIns) } typeCanBeEnhancedOrFlexibleNullable(valueType) && !expectedType.acceptsNullValues() -> { insertImplicitNotNullCastIfNeeded(expression) } // TODO: coerceIntToAnotherIntegerType // TODO: even implicitCast call can be here? else -> this } } private fun FirTypeRef.acceptsNullValues(): Boolean = canBeNull || hasEnhancedNullability() private fun IrExpression.insertImplicitNotNullCastIfNeeded(expression: FirExpression): IrExpression { if (this is IrGetEnumValue) return this // [TypeOperatorLowering] will retrieve the source (from start offset to end offset) as an assertion message. // Avoid type casting if we can't determine the source for some reasons, e.g., implicit `this` receiver. if (expression.source == null) return this return implicitNotNullCast(this) } private fun IrContainerExpression.insertImplicitCasts(): IrContainerExpression { if (statements.isEmpty()) return this val lastIndex = statements.lastIndex statements.forEachIndexed { i, irStatement -> if (irStatement !is IrErrorCallExpression && irStatement is IrExpression) { if (i != lastIndex) { statements[i] = coerceToUnitIfNeeded(irStatement, irBuiltIns) } // TODO: for the last statement, need to cast to the return type if mismatched } } return this } internal fun IrBlockBody.insertImplicitCasts(): IrBlockBody { if (statements.isEmpty()) return this statements.forEachIndexed { i, irStatement -> if (irStatement !is IrErrorCallExpression && irStatement is IrExpression) { statements[i] = coerceToUnitIfNeeded(irStatement, irBuiltIns) } } return this } override fun visitExpressionWithSmartcast(expressionWithSmartcast: FirExpressionWithSmartcast, data: IrElement): IrExpression { return if (expressionWithSmartcast.isStable) { implicitCastOrExpression(data as IrExpression, expressionWithSmartcast.typeRef) } else { data as IrExpression } } override fun visitExpressionWithSmartcastToNull( expressionWithSmartcastToNull: FirExpressionWithSmartcastToNull, data: IrElement ): IrElement { // We don't want an implicit cast to Nothing?. This expression just encompasses nullability after null check. return data } override fun visitWhenSubjectExpressionWithSmartcast( whenSubjectExpressionWithSmartcast: FirWhenSubjectExpressionWithSmartcast, data: IrElement ): IrElement { return if (whenSubjectExpressionWithSmartcast.isStable) { implicitCastOrExpression(data as IrExpression, whenSubjectExpressionWithSmartcast.typeRef) } else { data as IrExpression } } override fun visitWhenSubjectExpressionWithSmartcastToNull( whenSubjectExpressionWithSmartcastToNull: FirWhenSubjectExpressionWithSmartcastToNull, data: IrElement ): IrElement { // We don't want an implicit cast to Nothing?. This expression just encompasses nullability after null check. return data } internal fun implicitCastFromDispatchReceiver( original: IrExpression, originalTypeRef: FirTypeRef, calleeReference: FirReference, ): IrExpression { val referencedDeclaration = (calleeReference.resolvedSymbol as? FirCallableSymbol<*>)?.unwrapCallRepresentative()?.fir val dispatchReceiverType = referencedDeclaration?.dispatchReceiverType as? ConeClassLikeType ?: return implicitCastOrExpression(original, originalTypeRef) val starProjectedDispatchReceiver = dispatchReceiverType.replaceArgumentsWithStarProjections() val castType = originalTypeRef.coneTypeSafe<ConeIntersectionType>() castType?.intersectedTypes?.forEach { componentType -> if (AbstractTypeChecker.isSubtypeOf(session.typeContext, componentType, starProjectedDispatchReceiver)) { return implicitCastOrExpression(original, componentType) } } return implicitCastOrExpression(original, originalTypeRef) } private fun implicitCastOrExpression(original: IrExpression, castType: ConeKotlinType): IrExpression { return implicitCastOrExpression(original, castType.toIrType()) } private fun implicitCastOrExpression(original: IrExpression, castType: FirTypeRef): IrExpression { return implicitCastOrExpression(original, castType.toIrType()) } internal fun implicitCastOrExpression(original: IrExpression, castType: IrType): IrExpression { val originalNotNull = original.type.makeNotNull() if (originalNotNull == castType.makeNotNull()) return original return implicitCast(original, castType) } companion object { private fun implicitCast(original: IrExpression, castType: IrType): IrExpression { return IrTypeOperatorCallImpl( original.startOffset, original.endOffset, castType, IrTypeOperator.IMPLICIT_CAST, castType, original ) } private fun coerceToUnitIfNeeded(original: IrExpression, irBuiltIns: IrBuiltIns): IrExpression { val valueType = original.type return if (valueType.isUnit() || valueType.isNothing()) original else IrTypeOperatorCallImpl( original.startOffset, original.endOffset, irBuiltIns.unitType, IrTypeOperator.IMPLICIT_COERCION_TO_UNIT, irBuiltIns.unitType, original ) } internal fun implicitNotNullCast(original: IrExpression): IrTypeOperatorCall { // Cast type massage 1. Remove @EnhancedNullability // Cast type massage 2. Convert it to a non-null variant (in case of @FlexibleNullability) val castType = original.type.removeAnnotations { val classId = it.symbol.owner.parentAsClass.classId classId == StandardClassIds.Annotations.EnhancedNullability || classId == StandardClassIds.Annotations.FlexibleNullability }.makeNotNull() return IrTypeOperatorCallImpl( original.startOffset, original.endOffset, castType, IrTypeOperator.IMPLICIT_NOTNULL, castType, original ) } internal fun typeCanBeEnhancedOrFlexibleNullable(typeRef: FirTypeRef): Boolean { return when { typeRef.hasEnhancedNullability() -> true typeRef.isNullabilityFlexible() && typeRef.canBeNull -> true else -> false } } private fun FirTypeRef.isNullabilityFlexible(): Boolean { val flexibility = coneTypeSafe<ConeFlexibleType>() ?: return false return flexibility.lowerBound.isMarkedNullable != flexibility.upperBound.isMarkedNullable } } }
5
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
17,126
kotlin
Apache License 2.0
compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrImplicitCastInserter.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.backend import org.jetbrains.kotlin.fir.FirElement import org.jetbrains.kotlin.fir.declarations.FirTypeAlias import org.jetbrains.kotlin.fir.expressions.* import org.jetbrains.kotlin.fir.expressions.impl.FirStubStatement import org.jetbrains.kotlin.fir.expressions.impl.FirUnitExpression import org.jetbrains.kotlin.fir.references.FirReference import org.jetbrains.kotlin.fir.render import org.jetbrains.kotlin.fir.resolvedSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol import org.jetbrains.kotlin.fir.types.* import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitor import org.jetbrains.kotlin.ir.IrBuiltIns import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.classId import org.jetbrains.kotlin.ir.util.parentAsClass import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.types.AbstractTypeChecker class Fir2IrImplicitCastInserter( private val components: Fir2IrComponents ) : Fir2IrComponents by components, FirDefaultVisitor<IrElement, IrElement>() { private fun FirTypeRef.toIrType(): IrType = with(typeConverter) { toIrType() } private fun ConeKotlinType.toIrType(): IrType = with(typeConverter) { toIrType() } override fun visitElement(element: FirElement, data: IrElement): IrElement { TODO("Should not be here: ${element::class}: ${element.render()}") } override fun visitAnnotation(annotation: FirAnnotation, data: IrElement): IrElement = data override fun visitAnnotationCall(annotationCall: FirAnnotationCall, data: IrElement): IrElement = data override fun visitAnonymousObjectExpression(anonymousObjectExpression: FirAnonymousObjectExpression, data: IrElement): IrElement = data override fun visitAnonymousFunctionExpression(anonymousFunctionExpression: FirAnonymousFunctionExpression, data: IrElement): IrElement { return data } override fun visitBinaryLogicExpression(binaryLogicExpression: FirBinaryLogicExpression, data: IrElement): IrElement = data // TODO: maybe a place to do coerceIntToAnotherIntegerType? override fun visitComparisonExpression(comparisonExpression: FirComparisonExpression, data: IrElement): IrElement = data override fun visitTypeOperatorCall(typeOperatorCall: FirTypeOperatorCall, data: IrElement): IrElement = data override fun visitEqualityOperatorCall(equalityOperatorCall: FirEqualityOperatorCall, data: IrElement): IrElement = data override fun <T> visitConstExpression(constExpression: FirConstExpression<T>, data: IrElement): IrElement = data override fun visitThisReceiverExpression(thisReceiverExpression: FirThisReceiverExpression, data: IrElement): IrElement = data override fun visitQualifiedAccessExpression(qualifiedAccessExpression: FirQualifiedAccessExpression, data: IrElement): IrElement = data override fun visitPropertyAccessExpression(propertyAccessExpression: FirPropertyAccessExpression, data: IrElement): IrElement = data override fun visitResolvedQualifier(resolvedQualifier: FirResolvedQualifier, data: IrElement): IrElement = data override fun visitGetClassCall(getClassCall: FirGetClassCall, data: IrElement): IrElement = data override fun visitFunctionCall(functionCall: FirFunctionCall, data: IrElement): IrElement = data override fun visitCheckNotNullCall(checkNotNullCall: FirCheckNotNullCall, data: IrElement): IrElement = data override fun visitCheckedSafeCallSubject(checkedSafeCallSubject: FirCheckedSafeCallSubject, data: IrElement): IrElement = data override fun visitSafeCallExpression(safeCallExpression: FirSafeCallExpression, data: IrElement): IrElement = data override fun visitStringConcatenationCall(stringConcatenationCall: FirStringConcatenationCall, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitArrayOfCall(arrayOfCall: FirArrayOfCall, data: IrElement): IrElement = data // TODO: something to do w.r.t. SAM? override fun visitLambdaArgumentExpression(lambdaArgumentExpression: FirLambdaArgumentExpression, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitNamedArgumentExpression(namedArgumentExpression: FirNamedArgumentExpression, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitVarargArgumentsExpression(varargArgumentsExpression: FirVarargArgumentsExpression, data: IrElement): IrElement = data // TODO: element-wise cast? override fun visitSpreadArgumentExpression(spreadArgumentExpression: FirSpreadArgumentExpression, data: IrElement): IrElement = data // ================================================================================== override fun visitExpression(expression: FirExpression, data: IrElement): IrElement { return when (expression) { is FirBlock -> (data as IrContainerExpression).insertImplicitCasts() is FirUnitExpression -> (data as IrExpression).let { coerceToUnitIfNeeded(it, irBuiltIns) } else -> data } } override fun visitStatement(statement: FirStatement, data: IrElement): IrElement { return when (statement) { is FirTypeAlias -> data FirStubStatement -> data is FirUnitExpression -> (data as IrExpression).let { coerceToUnitIfNeeded(it, irBuiltIns) } is FirBlock -> (data as IrContainerExpression).insertImplicitCasts() else -> statement.accept(this, data) } } // ================================================================================== override fun visitWhenExpression(whenExpression: FirWhenExpression, data: IrElement): IrElement { if (data is IrBlock) { return data.insertImplicitCasts() } val irWhen = data as IrWhen if (irWhen.branches.size != whenExpression.branches.size) { return data } val firBranchMap = irWhen.branches.zip(whenExpression.branches).toMap() irWhen.branches.replaceAll { visitWhenBranch(firBranchMap.getValue(it), it) } return data } override fun visitWhenSubjectExpression(whenSubjectExpression: FirWhenSubjectExpression, data: IrElement): IrElement = data // TODO: cast `condition` expression to boolean? override fun visitWhenBranch(whenBranch: FirWhenBranch, data: IrElement): IrBranch { val irBranch = data as IrBranch (irBranch.result as? IrContainerExpression)?.let { irBranch.result = it.insertImplicitCasts() } return data } // TODO: Need to visit lhs/rhs branches? override fun visitElvisExpression(elvisExpression: FirElvisExpression, data: IrElement): IrElement = data // ================================================================================== // TODO: cast `condition` expression to boolean? override fun visitDoWhileLoop(doWhileLoop: FirDoWhileLoop, data: IrElement): IrElement { val loop = data as IrDoWhileLoop (loop.body as? IrContainerExpression)?.let { loop.body = it.insertImplicitCasts() } return data } // TODO: cast `condition` expression to boolean? override fun visitWhileLoop(whileLoop: FirWhileLoop, data: IrElement): IrElement { val loop = data as IrWhileLoop (loop.body as? IrContainerExpression)?.let { loop.body = it.insertImplicitCasts() } return data } override fun visitBreakExpression(breakExpression: FirBreakExpression, data: IrElement): IrElement = data override fun visitContinueExpression(continueExpression: FirContinueExpression, data: IrElement): IrElement = data // ================================================================================== override fun visitTryExpression(tryExpression: FirTryExpression, data: IrElement): IrElement { val irTry = data as IrTry (irTry.finallyExpression as? IrContainerExpression)?.let { irTry.finallyExpression = it.insertImplicitCasts() } return data } override fun visitThrowExpression(throwExpression: FirThrowExpression, data: IrElement): IrElement = (data as IrThrow).cast(throwExpression, throwExpression.exception.typeRef, throwExpression.typeRef) override fun visitBlock(block: FirBlock, data: IrElement): IrElement = (data as? IrContainerExpression)?.insertImplicitCasts() ?: data override fun visitReturnExpression(returnExpression: FirReturnExpression, data: IrElement): IrElement { val irReturn = data as IrReturn val expectedType = returnExpression.target.labeledElement.returnTypeRef irReturn.value = irReturn.value.cast(returnExpression.result, returnExpression.result.typeRef, expectedType) return data } // ================================================================================== internal fun IrExpression.cast(expression: FirExpression, valueType: FirTypeRef, expectedType: FirTypeRef): IrExpression { if (this is IrTypeOperatorCall) { return this } return when { this is IrContainerExpression -> { insertImplicitCasts() } expectedType.isUnit -> { coerceToUnitIfNeeded(this, irBuiltIns) } typeCanBeEnhancedOrFlexibleNullable(valueType) && !expectedType.acceptsNullValues() -> { insertImplicitNotNullCastIfNeeded(expression) } // TODO: coerceIntToAnotherIntegerType // TODO: even implicitCast call can be here? else -> this } } private fun FirTypeRef.acceptsNullValues(): Boolean = canBeNull || hasEnhancedNullability() private fun IrExpression.insertImplicitNotNullCastIfNeeded(expression: FirExpression): IrExpression { if (this is IrGetEnumValue) return this // [TypeOperatorLowering] will retrieve the source (from start offset to end offset) as an assertion message. // Avoid type casting if we can't determine the source for some reasons, e.g., implicit `this` receiver. if (expression.source == null) return this return implicitNotNullCast(this) } private fun IrContainerExpression.insertImplicitCasts(): IrContainerExpression { if (statements.isEmpty()) return this val lastIndex = statements.lastIndex statements.forEachIndexed { i, irStatement -> if (irStatement !is IrErrorCallExpression && irStatement is IrExpression) { if (i != lastIndex) { statements[i] = coerceToUnitIfNeeded(irStatement, irBuiltIns) } // TODO: for the last statement, need to cast to the return type if mismatched } } return this } internal fun IrBlockBody.insertImplicitCasts(): IrBlockBody { if (statements.isEmpty()) return this statements.forEachIndexed { i, irStatement -> if (irStatement !is IrErrorCallExpression && irStatement is IrExpression) { statements[i] = coerceToUnitIfNeeded(irStatement, irBuiltIns) } } return this } override fun visitExpressionWithSmartcast(expressionWithSmartcast: FirExpressionWithSmartcast, data: IrElement): IrExpression { return if (expressionWithSmartcast.isStable) { implicitCastOrExpression(data as IrExpression, expressionWithSmartcast.typeRef) } else { data as IrExpression } } override fun visitExpressionWithSmartcastToNull( expressionWithSmartcastToNull: FirExpressionWithSmartcastToNull, data: IrElement ): IrElement { // We don't want an implicit cast to Nothing?. This expression just encompasses nullability after null check. return data } override fun visitWhenSubjectExpressionWithSmartcast( whenSubjectExpressionWithSmartcast: FirWhenSubjectExpressionWithSmartcast, data: IrElement ): IrElement { return if (whenSubjectExpressionWithSmartcast.isStable) { implicitCastOrExpression(data as IrExpression, whenSubjectExpressionWithSmartcast.typeRef) } else { data as IrExpression } } override fun visitWhenSubjectExpressionWithSmartcastToNull( whenSubjectExpressionWithSmartcastToNull: FirWhenSubjectExpressionWithSmartcastToNull, data: IrElement ): IrElement { // We don't want an implicit cast to Nothing?. This expression just encompasses nullability after null check. return data } internal fun implicitCastFromDispatchReceiver( original: IrExpression, originalTypeRef: FirTypeRef, calleeReference: FirReference, ): IrExpression { val referencedDeclaration = (calleeReference.resolvedSymbol as? FirCallableSymbol<*>)?.unwrapCallRepresentative()?.fir val dispatchReceiverType = referencedDeclaration?.dispatchReceiverType as? ConeClassLikeType ?: return implicitCastOrExpression(original, originalTypeRef) val starProjectedDispatchReceiver = dispatchReceiverType.replaceArgumentsWithStarProjections() val castType = originalTypeRef.coneTypeSafe<ConeIntersectionType>() castType?.intersectedTypes?.forEach { componentType -> if (AbstractTypeChecker.isSubtypeOf(session.typeContext, componentType, starProjectedDispatchReceiver)) { return implicitCastOrExpression(original, componentType) } } return implicitCastOrExpression(original, originalTypeRef) } private fun implicitCastOrExpression(original: IrExpression, castType: ConeKotlinType): IrExpression { return implicitCastOrExpression(original, castType.toIrType()) } private fun implicitCastOrExpression(original: IrExpression, castType: FirTypeRef): IrExpression { return implicitCastOrExpression(original, castType.toIrType()) } internal fun implicitCastOrExpression(original: IrExpression, castType: IrType): IrExpression { val originalNotNull = original.type.makeNotNull() if (originalNotNull == castType.makeNotNull()) return original return implicitCast(original, castType) } companion object { private fun implicitCast(original: IrExpression, castType: IrType): IrExpression { return IrTypeOperatorCallImpl( original.startOffset, original.endOffset, castType, IrTypeOperator.IMPLICIT_CAST, castType, original ) } private fun coerceToUnitIfNeeded(original: IrExpression, irBuiltIns: IrBuiltIns): IrExpression { val valueType = original.type return if (valueType.isUnit() || valueType.isNothing()) original else IrTypeOperatorCallImpl( original.startOffset, original.endOffset, irBuiltIns.unitType, IrTypeOperator.IMPLICIT_COERCION_TO_UNIT, irBuiltIns.unitType, original ) } internal fun implicitNotNullCast(original: IrExpression): IrTypeOperatorCall { // Cast type massage 1. Remove @EnhancedNullability // Cast type massage 2. Convert it to a non-null variant (in case of @FlexibleNullability) val castType = original.type.removeAnnotations { val classId = it.symbol.owner.parentAsClass.classId classId == StandardClassIds.Annotations.EnhancedNullability || classId == StandardClassIds.Annotations.FlexibleNullability }.makeNotNull() return IrTypeOperatorCallImpl( original.startOffset, original.endOffset, castType, IrTypeOperator.IMPLICIT_NOTNULL, castType, original ) } internal fun typeCanBeEnhancedOrFlexibleNullable(typeRef: FirTypeRef): Boolean { return when { typeRef.hasEnhancedNullability() -> true typeRef.isNullabilityFlexible() && typeRef.canBeNull -> true else -> false } } private fun FirTypeRef.isNullabilityFlexible(): Boolean { val flexibility = coneTypeSafe<ConeFlexibleType>() ?: return false return flexibility.lowerBound.isMarkedNullable != flexibility.upperBound.isMarkedNullable } } }
5
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
17,126
kotlin
Apache License 2.0
client_end_user/shared/src/androidMain/kotlin/presentation/map/CommonGPSLocationService.android.kt
SantiagoFlynnUTN
770,562,894
false
{"Kotlin": 2180936, "Swift": 6073, "HTML": 3900, "Ruby": 2543, "Dockerfile": 1994, "Shell": 912}
package presentation.map import _androidIntentFlow import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.location.LocationManager import android.os.Looper import androidx.compose.runtime.NoLiveLiterals import androidx.core.app.ActivityCompat import appContext import com.google.android.gms.location.LocationAvailability import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicReference import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine // Implement the LocationService in Android @SuppressLint("MissingPermission") // Assuming location permission check is already handled @NoLiveLiterals actual class CommonGPSLocationService { // Define an atomic reference to store the latest location private val latestLocation = AtomicReference<Location?>(null) // Initialize the FusedLocationProviderClient source of location data private val fusedLocationClient by lazy { LocationServices.getFusedLocationProviderClient( appContext, ) } private var errorCallback: ((String) -> Unit)? = null private var locationUpdateCallback: ((Location?) -> Unit)? = null private var internalLocationCallback: LocationCallback? = null private val locationRequest = LocationRequest.Builder(kUpdateInterval) .setIntervalMillis(kUpdateInterval) .setPriority(Priority.PRIORITY_LOW_POWER) .setMinUpdateDistanceMeters(1.0f) .setWaitForAccurateLocation(false) .build() // Gets location 1 time only. (useful for testing) // WARNING: Should NOT be used for continuous location updates or in conjunction with currentLocation() @SuppressLint("MissingPermission") // Assuming location permission check is already handled actual suspend fun getCurrentGPSLocationOneTime(): Location = suspendCoroutine { continuation -> fusedLocationClient.lastLocation.addOnSuccessListener { location -> location?.let { androidOsLocation -> val updatedLocation = Location(androidOsLocation.latitude, androidOsLocation.longitude) latestLocation.set(updatedLocation) continuation.resume(updatedLocation) } ?: run { continuation.resumeWithException(Exception("Unable to get current location")) } }.addOnFailureListener { e -> continuation.resumeWithException(e) } } @SuppressLint("MissingPermission") // suppress missing permission check warning, we are checking permissions in the method. // actual suspend fun onUpdatedGPSLocation(callback: (Location?) -> Flow<Location>) { // LEAVE FOR REFERENCE - emits a flow of locations actual suspend fun onUpdatedGPSLocation( errorCallback: (errorMessage: String) -> Unit, locationCallback: (newLocation: Location?) -> Unit, ) { startGPSLocationUpdates(errorCallback, locationCallback) // keeps requesting location updates } @SuppressLint("MissingPermission") // suppress missing permission check warning, we are checking permissions in the method. private fun startGPSLocationUpdates( errorCallback: ((String) -> Unit)? = null, locationCallback: ((Location?) -> Unit)? = null, ) { if (!checkLocationPermissions()) return if (locationCallback == [email protected]) return // already using same callback [email protected] = locationCallback [email protected] = errorCallback // Check if GPS and Network location is enabled val locationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) val isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) if (!isGpsEnabled) { errorCallback?.let { errorCallback("GPS is disabled") } println("GPS is disabled") return } if (!isNetworkEnabled) { errorCallback?.let { errorCallback("Network is disabled") } println("Network is disabled") return } // Setup the location callback internalLocationCallback?.let { fusedLocationClient.removeLocationUpdates(it) } internalLocationCallback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) { super.onLocationResult(result) result.locations.lastOrNull()?.let { androidOsLocation: android.location.Location -> // launch { // For flow - leave for reference // send(androidOsLocation) // emits the androidOsLocation into the flow // } val updatedLocation = Location(androidOsLocation.latitude, androidOsLocation.longitude) latestLocation.set(updatedLocation) locationCallback?.let { locationCallback(updatedLocation) } } } override fun onLocationAvailability(availability: LocationAvailability) { super.onLocationAvailability(availability) } } fusedLocationClient.requestLocationUpdates( locationRequest, internalLocationCallback!!, Looper.getMainLooper(), ) } private fun checkLocationPermissions(): Boolean { return ActivityCompat.checkSelfPermission( appContext, Manifest.permission.ACCESS_FINE_LOCATION, ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( appContext, Manifest.permission.ACCESS_COARSE_LOCATION, ) == PackageManager.PERMISSION_GRANTED } actual suspend fun currentHeading(callback: (Heading?) -> Unit) { } actual fun getLatestGPSLocation(): Location? { return latestLocation.get() } actual fun allowBackgroundLocationUpdates() { CoroutineScope(Dispatchers.Main).launch { _androidIntentFlow.emit(Intent(CommonGPSLocationService.ACTION_START_BACKGROUND_UPDATES)) } } actual fun preventBackgroundLocationUpdates() { CoroutineScope(Dispatchers.Main).launch { _androidIntentFlow.emit(Intent(CommonGPSLocationService.ACTION_STOP_BACKGROUND_UPDATES)) } } companion object { const val ACTION_START_BACKGROUND_UPDATES = "ACTION_START_BACKGROUND_UPDATES" const val ACTION_STOP_BACKGROUND_UPDATES = "ACTION_STOP_BACKGROUND_UPDATES" const val kUpdateInterval = 1000L } }
0
Kotlin
0
0
a2ab62649ae89c83c3621756cc89d335656f8f30
7,314
AngusBrotherKMP
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/synthetics/CronOptionsDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5279682}
package com.faendir.awscdkkt.generated.services.synthetics import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.synthetics.CronOptions @Generated public fun buildCronOptions(initializer: @AwsCdkDsl CronOptions.Builder.() -> Unit = {}): CronOptions = CronOptions.Builder().apply(initializer).build()
1
Kotlin
0
4
e6850aac225a29dfaf94807a5bc4da07175c4682
384
aws-cdk-kt
Apache License 2.0
src/main/kotlin/no/nav/k9/los/nyoppgavestyring/query/dto/felter/Oppgavefelt.kt
navikt
238,874,021
false
{"Kotlin": 1849311, "Shell": 899, "JavaScript": 741, "Dockerfile": 447, "PLpgSQL": 167}
package no.nav.k9.los.nyoppgavestyring.query.dto.felter class Oppgavefelt( val område: String?, val kode: String, val visningsnavn: String, val tolkes_som: String, val kokriterie: Boolean, val verdiforklaringerErUttømmende: Boolean = false, val verdiforklaringer: List<Verdiforklaring>? )
9
Kotlin
0
0
d8fea1f1bd954c249c8638d8dd9c51c2267fbe06
317
k9-los-api
MIT License
SoftwareDesign/02-mock/src/main/kotlin/Tweets.kt
ShuffleZZZ
128,576,289
false
null
import java.time.LocalDateTime interface Tweet { fun getDate(): LocalDateTime } interface TweetProvider { fun getTweetsByHashtag(hashtag: String): List<Tweet> fun getHoursArray(hashtag: String, hours: Int): Array<Int> fun makeHoursArray(hours: List<Int>, forHours: Int): Array<Int> }
0
Jupyter Notebook
3
9
29db54d96afef0558550471c58f695c962e1f747
302
ITMO
MIT License
app/gradle/build-logic/src/main/kotlin/build/wallet/gradle/logic/rust/util/RustToolchainProvider.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.gradle.logic.rust.util import org.gradle.api.file.Directory import org.gradle.api.file.RegularFileProperty import org.gradle.api.services.BuildService import org.gradle.api.services.BuildServiceParameters import org.gradle.process.ExecOperations import java.io.File import javax.inject.Inject internal abstract class RustToolchainProvider : BuildService<RustToolchainProvider.Parameters> { interface Parameters : BuildServiceParameters { val cargoPath: RegularFileProperty } companion object { const val SERVICE = "rust" } private val toolchains = mutableMapOf<File, RustToolchain>() @get:Inject protected abstract val execOperations: ExecOperations @Synchronized fun getToolchain(workdir: Directory): RustToolchain { val workdirFile = workdir.asFile return toolchains.getOrPut(workdirFile) { RustToolchain( rootProjectExecOperations = execOperations, cargoPath = parameters.cargoPath.get().asFile, workdir = workdirFile ) } } }
3
C
16
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
1,032
bitkey
MIT License
cinescout/database/src/commonMain/kotlin/cinescout/database/testutil/TestAdapters.kt
4face-studi0
280,630,732
false
null
package cinescout.database.testutil import cinescout.database.Movie import cinescout.database.MovieRating import cinescout.database.TmdbCredentials import cinescout.database.TraktTokens import cinescout.database.Watchlist import cinescout.database.adapter.DateAdapter import cinescout.database.adapter.RatingAdapter import cinescout.database.adapter.TmdbAccessTokenAdapter import cinescout.database.adapter.TmdbAccountIdAdapter import cinescout.database.adapter.TmdbIdAdapter import cinescout.database.adapter.TmdbSessionIdAdapter import cinescout.database.adapter.TraktAccessTokenAdapter import cinescout.database.adapter.TraktRefreshTokenAdapter object TestAdapters { val MovieAdapter = Movie.Adapter(releaseDateAdapter = DateAdapter, tmdbIdAdapter = TmdbIdAdapter) val MovieRatingAdapter = MovieRating.Adapter(tmdbIdAdapter = TmdbIdAdapter, ratingAdapter = RatingAdapter) val TmdbCredentialsAdapter = TmdbCredentials.Adapter( accessTokenAdapter = TmdbAccessTokenAdapter, accountIdAdapter = TmdbAccountIdAdapter, sessionIdAdapter = TmdbSessionIdAdapter ) val TraktTokensAdapter = TraktTokens.Adapter( accessTokenAdapter = TraktAccessTokenAdapter, refreshTokenAdapter = TraktRefreshTokenAdapter ) val WatchlistAdapter = Watchlist.Adapter(tmdbIdAdapter = TmdbIdAdapter) }
24
Kotlin
1
3
dabd9284655ead17314e871530a9664aa6965953
1,343
CineScout
Apache License 2.0
me-api/src/main/kotlin/shop/hyeonme/domain/inventory/service/impl/InventoryCommandServiceImpl.kt
TEAM-hyeonme
776,784,109
false
{"Kotlin": 120635, "Dockerfile": 204}
package shop.hyeonme.domain.inventory.service.impl import shop.hyeonme.common.annotation.CommandService import shop.hyeonme.domain.inventory.model.Inventory import shop.hyeonme.domain.inventory.service.InventoryCommandService import shop.hyeonme.domain.inventory.spi.InventoryPort @CommandService class InventoryCommandServiceImpl( private val inventoryPort: InventoryPort ) : InventoryCommandService { override fun saveInventories(inventories: List<Inventory>): List<Inventory> = inventoryPort.saveInventories(inventories) }
0
Kotlin
0
0
646621f5577418523de44ed3a229d19879ee7193
543
ME-server
MIT License
compiler/testData/debug/stepping/assertion.kt
JetBrains
3,432,266
false
{"Kotlin": 73968610, "Java": 6672141, "Swift": 4257498, "C": 2622360, "C++": 1898765, "Objective-C": 641056, "Objective-C++": 167134, "JavaScript": 135706, "Python": 48402, "Shell": 31423, "TypeScript": 22754, "Lex": 18369, "Groovy": 17265, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FILE: test.kt public val MASSERTIONS_ENABLED: Boolean = true public inline fun massert(value: Boolean, lazyMessage: () -> String) { if (MASSERTIONS_ENABLED) { if (!value) { val message = lazyMessage() throw AssertionError(message) } } } public inline fun massert(value: Boolean, message: Any = "Assertion failed") { if (MASSERTIONS_ENABLED) { if (!value) { throw AssertionError(message) } } } fun box(): String { massert(true) massert(true) { "test" } return "OK" } // EXPECTATIONS JVM JVM_IR // test.kt:25 box // test.kt:16 box // test.kt:17 box // test.kt:4 getMASSERTIONS_ENABLED // test.kt:17 box // test.kt:18 box // test.kt:22 box // test.kt:26 box // test.kt:7 box // test.kt:4 getMASSERTIONS_ENABLED // test.kt:7 box // test.kt:8 box // test.kt:13 box // test.kt:30 box // EXPECTATIONS JS_IR // test.kt:17 box // test.kt:7 box // test.kt:30 box
162
Kotlin
5729
46,436
c902e5f56504e8572f9bc13f424de8bfb7f86d39
973
kotlin
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/s3outposts/CfnBucketFilterTagPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 63959868}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.s3outposts import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.s3outposts.CfnBucket /** * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.s3outposts.*; * FilterTagProperty filterTagProperty = FilterTagProperty.builder() * .key("key") * .value("value") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3outposts-bucket-filtertag.html) */ @CdkDslMarker public class CfnBucketFilterTagPropertyDsl { private val cdkBuilder: CfnBucket.FilterTagProperty.Builder = CfnBucket.FilterTagProperty.builder() /** * @param key the value to be set. */ public fun key(key: String) { cdkBuilder.key(key) } /** * @param value the value to be set. */ public fun `value`(`value`: String) { cdkBuilder.`value`(`value`) } public fun build(): CfnBucket.FilterTagProperty = cdkBuilder.build() }
4
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,302
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/example/digitalminimalism/Focus/FocusModeFragment.kt
knowhrishi
717,086,143
false
{"Kotlin": 237977}
import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.digitalminimalism.Focus.BottomNavigation.Active.ActiveNavFragment import com.example.digitalminimalism.Focus.BottomNavigation.History.HistoryNavFragment import com.example.digitalminimalism.Focus.BottomNavigation.HomeNavFragment import com.example.digitalminimalism.Focus.BottomNavigation.Schedule.ScheduleNavFragment import com.example.digitalminimalism.Focus.BottomNavigation.Timer.TimerNavFragment import com.example.digitalminimalism.R import com.google.android.material.bottomnavigation.BottomNavigationView class FocusModeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate(R.layout.fragment_focus_mode, container, false) val bottomNavView: BottomNavigationView = view.findViewById(R.id.focus_bottom_nav) bottomNavView.setOnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.nav_active_focus -> loadSubFragment(ActiveNavFragment()) R.id.nav_home_focus -> loadSubFragment(HomeNavFragment()) R.id.nav_schedule_focus -> loadSubFragment(ScheduleNavFragment()) R.id.nav_timer_focus -> loadSubFragment(TimerNavFragment()) R.id.nav_history_focus -> loadSubFragment(HistoryNavFragment()) } true } // Load the default fragment on creation if (savedInstanceState == null) { loadSubFragment(ActiveNavFragment()) } return view } private fun loadSubFragment(fragment: Fragment) { childFragmentManager.beginTransaction() .replace(R.id.focus_fragment_container, fragment) .commit() } }
0
Kotlin
0
0
cacb1c208336c84580343395b9f52e96dfe475b5
1,945
digital-minmalism-app
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonregister/model/PrisonRepository.kt
ministryofjustice
337,466,567
false
{"Kotlin": 321410, "Dockerfile": 1443, "Shell": 238}
package uk.gov.justice.digital.hmpps.prisonregister.model import org.springframework.data.jpa.domain.Specification import org.springframework.data.jpa.repository.EntityGraph import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.JpaSpecificationExecutor import org.springframework.data.jpa.repository.Query import org.springframework.stereotype.Repository import java.util.* @Repository interface PrisonRepository : JpaRepository<Prison, String>, JpaSpecificationExecutor<Prison> { @Query("FROM Prison p where (:active is null or p.active = :active) order by p.name") fun findByActiveOrderByPrisonName(active: Boolean?): List<Prison> fun findOneByGpPractice(gpPractice: String): Prison? @EntityGraph(value = "prison-entity-graph", type = EntityGraph.EntityGraphType.LOAD) fun findAllByPrisonIdIsIn(ids: List<String>): List<Prison> @EntityGraph(value = "prison-entity-graph", type = EntityGraph.EntityGraphType.LOAD) override fun findById(id: String): Optional<Prison> @EntityGraph(value = "prison-entity-graph", type = EntityGraph.EntityGraphType.LOAD) override fun findAll(spec: Specification<Prison>?): List<Prison> @EntityGraph(value = "prison-entity-graph", type = EntityGraph.EntityGraphType.LOAD) override fun findAll(): List<Prison> }
2
Kotlin
1
2
23ad6fd7c134253c7830d43a4cf090c6bef3e9b3
1,325
prison-register
MIT License
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/CollapsibleTitledSeparatorImpl.kt
ingokegel
72,937,917
true
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.observable.properties.AtomicBooleanProperty import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.NlsContexts import com.intellij.ui.TitledSeparator import com.intellij.util.ui.IndentedIcon import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import java.awt.Cursor import java.awt.Insets import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import kotlin.math.max // todo move to components package, rename into CollapsibleTitledSeparator, make internal @ApiStatus.Internal class CollapsibleTitledSeparatorImpl(@NlsContexts.Separator title: String) : TitledSeparator(title) { val expandedProperty: AtomicBooleanProperty = AtomicBooleanProperty(true) var expanded: Boolean by expandedProperty init { updateIcon() expandedProperty.afterChange { updateIcon() } cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) addMouseListener(object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) { expanded = !expanded } }) } fun onAction(listener: (Boolean) -> Unit) { expandedProperty.afterChange(listener) } private fun updateIcon() { val treeExpandedIcon = UIUtil.getTreeExpandedIcon() val treeCollapsedIcon = UIUtil.getTreeCollapsedIcon() val width = max(treeExpandedIcon.iconWidth, treeCollapsedIcon.iconWidth) var icon = if (expanded) treeExpandedIcon else treeCollapsedIcon val extraSpace = width - icon.iconWidth if (extraSpace > 0) { val left = extraSpace / 2 icon = IndentedIcon(icon, Insets(0, left, 0, extraSpace - left)) } label.icon = icon label.disabledIcon = IconLoader.getTransparentIcon(icon, 0.5f) } }
214
null
4829
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
1,929
intellij-community
Apache License 2.0
Project_Manager_App/app/src/main/java/com/example/projectmanager/activities/CreateBoardActivity.kt
Maver1ck123
834,721,199
false
{"Kotlin": 93262}
package com.example.projectmanager.activities import android.net.Uri import android.os.Bundle import android.webkit.MimeTypeMap import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.example.projectmanager.Firebase.Firestore import com.example.projectmanager.R import com.example.projectmanager.databinding.ActivityCreateBoardBinding import com.example.projectmanager.models.Board import com.example.projectmanager.utils.Constants import com.google.firebase.storage.FirebaseStorage import kotlinx.coroutines.launch class CreateBoardActivity : BaseActivity() { private var fboardLink: String? = "" private lateinit var binding: ActivityCreateBoardBinding private var galleryUri: Uri? = null private var muserName: String? = "" val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { try { galleryUri = it lifecycleScope.launch { Glide.with(this@CreateBoardActivity).load(galleryUri).centerCrop() .placeholder(R.drawable.ic_board_place_holder) .into(binding.ivBoardImage) } } catch (e: Exception) { e.printStackTrace() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCreateBoardBinding.inflate(layoutInflater) setContentView(binding.root) setUpActionBar() binding.btnCreate.setOnClickListener { if (galleryUri != null) { uploadBoardImage() } else { showProgressDialog(getString(R.string.please_wait)) createBoard() } } binding.ivBoardImage.setOnClickListener { Constants.requestPermission(this) } if (intent.hasExtra(Constants.name)) { muserName = intent.getStringExtra(Constants.name) } } private fun setUpActionBar() { setSupportActionBar(binding.toolbarCreateBoardActivity) binding.toolbarCreateBoardActivity.setNavigationIcon(R.drawable.baseline_menu_24) binding.toolbarCreateBoardActivity.setNavigationOnClickListener { onBackPressed() } binding.toolbarCreateBoardActivity.title = resources.getString(R.string.create_board_title) supportActionBar?.setDisplayHomeAsUpEnabled(true) } private fun uploadBoardImage() { showProgressDialog(resources.getString(R.string.please_wait)) val sRef = FirebaseStorage.getInstance().reference.child( "USER_IMAGE" + System.currentTimeMillis() + "." + getFileExtension(galleryUri) ) sRef.putFile(galleryUri!!).addOnSuccessListener { it.metadata!!.reference!!.downloadUrl.addOnSuccessListener { uri -> fboardLink = uri.toString() createBoard() } }.addOnFailureListener { showErrorSnackBar(it.message.toString()) dismissDialog() } } private fun createBoard() { val assignedUsersArrayList: ArrayList<String> = ArrayList() assignedUsersArrayList.add(getCurrentUserId()) val board = Board( binding.etBoardName.text.toString(), fboardLink!!, muserName!!, assignedUsersArrayList ) Firestore().createBoard(this@CreateBoardActivity, board) } private fun getFileExtension(uri: Uri?): String? { return MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri!!)) } fun boardCreatedSuccessfully() { dismissDialog() setResult(RESULT_OK) Toast.makeText(this@CreateBoardActivity,"Board created successfully",Toast.LENGTH_SHORT).show() finish() } }
0
Kotlin
0
0
904be14cac8ede1ba96d71f3ffa5e6b5a4c7d50c
3,936
Project-Manager-App
MIT License
kotlin-moment/src/main/kotlin/moment/Moment.kt
oxiadenine
206,398,615
false
null
@file:JsModule("moment") @file:JsNonModule package moment import kotlin.js.Date import kotlin.js.RegExp external interface Locale { fun calendar( key: CalendarKey? = definedExternally, m: Moment? = definedExternally, now: Moment? = definedExternally ): String fun longDateFormat(key: LongDateFormatKey): String fun invalidDate(): String fun ordinal(n: Number): String fun preparse(inp: String): String fun postformat(inp: String): String fun relativeTime( n: Number, withoutSuffix: Boolean, key: RelativeTimeKey, isFuture: Boolean ): String fun pastFuture(diff: Number, absRelTime: String): String fun set(config: Any) fun months(): Array<String> fun months(m: Moment, format: String? = definedExternally): String fun monthsShort(): Array<String> fun monthsShort(m: Moment, format: String? = definedExternally): String fun monthsParse(monthName: String, format: String, strict: Boolean): Number fun monthsRegex(strict: Boolean): RegExp fun monthsShortRegex(strict: Boolean): RegExp fun week(m: Moment): Number fun firstDayOfYear(): Number fun firstDayOfWeek(): Number fun weekdays(): Array<String> fun weekdays(m: Moment, format: String? = definedExternally): String fun weekdaysMin(): Array<String> fun weekdaysMin(m: Moment): String fun weekdaysShort(): Array<String> fun weekdaysShort(m: Moment): String fun weekdaysParse(weekdayName: String, format: String, strict: Boolean): Number fun weekdaysRegex(strict: Boolean): RegExp fun weekdaysShortRegex(strict: Boolean): RegExp fun weekdaysMinRegex(strict: Boolean): RegExp fun isPM(input: String): Boolean fun meridiem(hour: Number, minute: Number, isLower: Boolean): String } external interface StandaloneFormatSpec { var format: Array<String> var standalone: Array<String> var isFormat: RegExp? } external interface WeekSpec { var dow: Number var doy: Number? } external interface CalendarSpec { var sameDay: CalendarSpecVal? var nextDay: CalendarSpecVal? var lastDay: CalendarSpecVal? var nextWeek: CalendarSpecVal? var lastWeek: CalendarSpecVal? var sameElse: CalendarSpecVal? // any additional properties might be used with moment.calendarFormat /* [x: String]: CalendarSpecVal | Unit // undefined */ } external interface RelativeTimeSpec { var future: RelativeTimeFuturePastVal? var past: RelativeTimeFuturePastVal? var s: RelativeTimeSpecVal? var ss: RelativeTimeSpecVal? var m: RelativeTimeSpecVal? var mm: RelativeTimeSpecVal? var h: RelativeTimeSpecVal? var hh: RelativeTimeSpecVal? var d: RelativeTimeSpecVal? var dd: RelativeTimeSpecVal? var w: RelativeTimeFuturePastVal? var M: RelativeTimeSpecVal? var MM: RelativeTimeSpecVal? var y: RelativeTimeSpecVal? var yy: RelativeTimeSpecVal? } external interface LongDateFormatSpec { var LTS: String var LT: String var L: String var LL: String var LLL: String var LLLL: String // lets forget for a sec that any upper/lower permutation will also work var lts: String? var lt: String? var l: String? var ll: String? var lll: String? var llll: String? } external interface EraSpec { var since: Any /* String | Number */ var until: Any /* String | Number */ var offset: Number var name: String var narrow: String var abbr: String } external interface LocaleSpecification { var months: Any? /* Array<String> | StandaloneFormatSpec | MonthWeekdayFn */ var monthsShort: Any? /* Array<String>| StandaloneFormatSpec | MonthWeekdayFn */ var weekdays: Any? /* Array<String> | StandaloneFormatSpec | MonthWeekdayFn */ var weekdaysShort: Any? /* Array<String> | StandaloneFormatSpec | WeekdaySimpleFn */ var weekdaysMin: Any? /* Array<String> | StandaloneFormatSpec | WeekdaySimpleFn */ var meridiemParse: RegExp? var meridiem: ((hour: Number, minute: Number, isLower: Boolean) -> String)? var isPM: ((input: String) -> Boolean)? var longDateFormat: LongDateFormatSpec? var calendar: CalendarSpec? var relativeTime: RelativeTimeSpec? var invalidDate: String? var ordinal: ((n: Number) -> String)? var ordinalParse: RegExp? var week: WeekSpec? var eras: Array<EraSpec>? // Allow anything: in general any property that is passed as locale spec is // put in the locale object so it can be used by locale functions /* [x: String]: Any */ } external interface MomentObjectOutput { var years: Number /* One digit */ var months: Number /* Day of the month */ var date: Number var hours: Number var minutes: Number var seconds: Number var milliseconds: Number } external interface ArgThresholdOpts { var ss: Number? var s: Number? var m: Number? var h: Number? var d: Number? var w: Any? /* Number | Unit */ var M: Number? } external interface Duration { fun clone(): Duration fun humanize(withSuffix: Boolean? = definedExternally, argThresholds: ArgThresholdOpts? = definedExternally): String fun abs(): Duration fun `as`(units: Base): Number fun get(units: Base): Number fun milliseconds(): Number fun asMilliseconds(): Number fun seconds(): Number fun asSeconds(): Number fun minutes(): Number fun asMinutes(): Number fun hours(): Number fun asHours(): Number fun days(): Number fun asDays(): Number fun weeks(): Number fun asWeeks(): Number fun months(): Number fun asMonths(): Number fun years(): Number fun asYears(): Number fun add(inp: DurationInputArg1? = definedExternally, unit: DurationInputArg2? = definedExternally): Duration fun subtract(inp: DurationInputArg1? = definedExternally, unit: DurationInputArg2? = definedExternally): Duration fun locale(): String fun locale(locale: LocaleSpecifier): Duration fun localeData(): Locale fun toISOString(): String fun toJSON(): String fun isValid(): Boolean /** * @deprecated since version 2.8.0 */ fun lang(locale: LocaleSpecifier): Moment /** * @deprecated since version 2.8.0 */ fun lang(): Locale /** * @deprecated */ fun toIsoString(): String } external interface MomentRelativeTime { var future: Any var past: Any var s: Any var ss: Any var m: Any var mm: Any var h: Any var hh: Any var d: Any var dd: Any var M: Any var MM: Any var y: Any var yy: Any } external interface MomentLongDateFormat { var L: String var LL: String var LLL: String var LLLL: String var LT: String var LTS: String var l: String? var ll: String? var lll: String? var llll: String? var lt: String? var lts: String? } external interface MomentParsingFlags { var empty: Boolean var unusedTokens: Array<String> var unusedInput: Array<String> var overflow: Number var charsLeftOver: Number var nullInput: Boolean var invalidMonth: Any /* String | Unit // null */ var invalidFormat: Boolean var userInvalidated: Boolean var iso: Boolean var parsedDateParts: Array<Any> var meridiem: Any? /* String | Unit */ } external interface MomentParsingFlagsOpt { var empty: Boolean? var unusedTokens: Array<String>? var unusedInput: Array<String>? var overflow: Number? var charsLeftOver: Number? var nullInput: Boolean? var invalidMonth: String? var invalidFormat: Boolean? var userInvalidated: Boolean? var iso: Boolean? var parsedDateParts: Array<Any>? var meridiem: String? } external interface MomentBuiltinFormat { var __momentBuiltinFormatBrand: Any } external interface MomentInputObject { var years: NumberLike? var year: NumberLike? var y: NumberLike? var months: NumberLike? var month: NumberLike? var M: NumberLike? var days: NumberLike? var day: NumberLike? var d: NumberLike? var dates: NumberLike? var date: NumberLike? var D: NumberLike? var hours: NumberLike? var hour: NumberLike? var h: NumberLike? var minutes: NumberLike? var minute: NumberLike? var m: NumberLike? var seconds: NumberLike? var second: NumberLike? var s: NumberLike? var milliseconds: NumberLike? var millisecond: NumberLike? var ms: NumberLike? } external interface DurationInputObject : MomentInputObject { var quarters: NumberLike? var quarter: NumberLike? var Q: NumberLike? var weeks: NumberLike? var week: NumberLike? var w: NumberLike? } external interface MomentSetObject : MomentInputObject { var weekYears: NumberLike? var weekYear: NumberLike? var gg: NumberLike? var isoWeekYears: NumberLike? var isoWeekYear: NumberLike? var GG: NumberLike? var quarters: NumberLike? var quarter: NumberLike? var Q: NumberLike? var weeks: NumberLike? var week: NumberLike? var w: NumberLike? var isoWeeks: NumberLike? var isoWeek: NumberLike? var W: NumberLike? var dayOfYears: NumberLike? var dayOfYear: NumberLike? var DDD: NumberLike? var weekdays: NumberLike? var weekday: NumberLike? var e: NumberLike? var isoWeekdays: NumberLike? var isoWeekday: NumberLike? var E: NumberLike? } external interface FromTo { var from: MomentInput var to: MomentInput } external interface MomentCreationData { var input: MomentInput var format: MomentFormatSpecification? var locale: Locale var isUTC: Boolean var strict: Boolean? } external interface Moment { fun format(format: String? = definedExternally): String fun startOf(unitOfTime: StartOf): Moment fun endOf(unitOfTime: StartOf): Moment fun add(amount: DurationInputArg1? = definedExternally, unit: DurationInputArg2? = definedExternally): Moment /** * @deprecated reverse syntax */ fun add(unit: DurationConstructor, amount: Any /* Number | String */): Moment fun subtract(amount: DurationInputArg1? = definedExternally, unit: DurationInputArg2? = definedExternally): Moment /** * @deprecated reverse syntax */ fun subtract(unit: DurationConstructor, amount: Any /* Number | String */): Moment fun calendar(): String fun calendar(formats: CalendarSpec): String fun calendar(time: MomentInput, formats: CalendarSpec? = definedExternally): String fun clone(): Moment /** * @return Unix timestamp in milliseconds */ fun valueOf(): Number // current date/time in local mode fun local(keepLocalTime: Boolean? = definedExternally): Moment fun isLocal(): Boolean // current date/time in UTC mode fun utc(keepLocalTime: Boolean? = definedExternally): Moment fun isUTC(): Boolean /** * @deprecated use isUTC */ fun isUtc(): Boolean fun parseZone(): Moment fun isValid(): Boolean fun invalidAt(): Number fun hasAlignedHourOffset(other: MomentInput? = definedExternally): Boolean fun creationData(): MomentCreationData fun parsingFlags(): MomentParsingFlags fun year(y: Number): Moment fun year(): Number /** * @deprecated use year(y) */ fun years(y: Number): Moment /** * @deprecated use year() */ fun years(): Number fun quarter(): Number fun quarter(q: Number): Moment fun quarters(): Number fun quarters(q: Number): Moment fun month(M: Any /* Number | String */): Moment fun month(): Number /** * @deprecated use month(M) */ fun months(M: Any /* Number | String */): Moment /** * @deprecated use month() */ fun months(): Number fun day(d: Any /* Number | String */): Moment fun day(): Number fun days(d: Any /* Number | String */): Moment fun days(): Number fun date(d: Number): Moment fun date(): Number /** * @deprecated use date(d) */ fun dates(d: Number): Moment /** * @deprecated use date() */ fun dates(): Number fun hour(h: Number): Moment fun hour(): Number fun hours(h: Number): Moment fun hours(): Number fun minute(m: Number): Moment fun minute(): Number fun minutes(m: Number): Moment fun minutes(): Number fun second(s: Number): Moment fun second(): Number fun seconds(s: Number): Moment fun seconds(): Number fun millisecond(ms: Number): Moment fun millisecond(): Number fun milliseconds(ms: Number): Moment fun milliseconds(): Number fun weekday(): Number fun weekday(d: Number): Moment fun isoWeekday(): Number fun isoWeekday(d: Any /* Number | String */): Moment fun weekYear(): Number fun weekYear(d: Number): Moment fun isoWeekYear(): Number fun isoWeekYear(d: Number): Moment fun week(): Number fun week(d: Number): Moment fun weeks(): Number fun weeks(d: Number): Moment fun isoWeek(): Number fun isoWeek(d: Number): Moment fun isoWeeks(): Number fun isoWeeks(d: Number): Moment fun weeksInYear(): Number fun weeksInWeekYear(): Number fun isoWeeksInYear(): Number fun isoWeeksInISOWeekYear(): Number fun dayOfYear(): Number fun dayOfYear(d: Number): Moment fun from(inp: MomentInput, suffix: Boolean? = definedExternally): String fun to(inp: MomentInput, suffix: Boolean? = definedExternally): String fun fromNow(withoutSuffix: Boolean? = definedExternally): String fun toNow(withoutPrefix: Boolean? = definedExternally): String fun diff(b: MomentInput, unitOfTime: Diff? = definedExternally, precise: Boolean? = definedExternally): Number fun toArray(): Array<Number> fun toDate(): Date fun toISOString(keepOffset: Boolean? = definedExternally): String fun inspect(): String fun toJSON(): String fun unix(): Number fun isLeapYear(): Boolean /** * @deprecated in favor of utcOffset */ fun zone(): Number fun zone(b: Any /* Number | String */): Moment fun utcOffset(): Number fun utcOffset(b: Any /* Number | String */, keepLocalTime: Boolean? = definedExternally): Moment fun isUtcOffset(): Boolean fun daysInMonth(): Number fun isDST(): Boolean fun zoneAbbr(): String fun zoneName(): String fun isBefore(inp: MomentInput? = definedExternally, granularity: StartOf? = definedExternally): Boolean fun isAfter(inp: MomentInput? = definedExternally, granularity: StartOf? = definedExternally): Boolean fun isSame(inp: MomentInput? = definedExternally, granularity: StartOf? = definedExternally): Boolean fun isSameOrAfter(inp: MomentInput? = definedExternally, granularity: StartOf? = definedExternally): Boolean fun isSameOrBefore(inp: MomentInput? = definedExternally, granularity: StartOf? = definedExternally): Boolean fun isBetween( a: MomentInput, b: MomentInput, granularity: StartOf? = definedExternally, inclusivity: String? = definedExternally /* "()" | "[)" | "(]" | "[]" */ ): Boolean /** * @deprecated as of 2.8.0, use locale */ fun lang(language: LocaleSpecifier): Moment /** * @deprecated as of 2.8.0, use locale */ fun lang(): Locale fun locale(): String fun locale(locale: LocaleSpecifier): Moment fun localeData(): Locale /** * @deprecated no reliable implementation */ fun isDSTShifted(): Boolean // NOTE(constructor): Same as moment constructor /** * @deprecated as of 2.7.0, use moment.min/max */ fun max( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, strict: Boolean? = definedExternally ): Moment /** * @deprecated as of 2.7.0, use moment.min/max */ fun max( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, language: String? = definedExternally, strict: Boolean? = definedExternally ): Moment // NOTE(constructor): Same as moment constructor /** * @deprecated as of 2.7.0, use moment.min/max */ fun min( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, strict: Boolean? = definedExternally ): Moment /** * @deprecated as of 2.7.0, use moment.min/max */ fun min( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, language: String? = definedExternally, strict: Boolean? = definedExternally ): Moment fun get(unit: All): Number fun set(unit: All, value: Number): Moment fun set(objectLiteral: MomentSetObject): Moment fun toObject(): MomentObjectOutput } external var version: String external var fn: Moment // NOTE(constructor): Same as moment constructor external fun utc( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, strict: Boolean? = definedExternally ): Moment external fun utc( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, language: String? = definedExternally, strict: Boolean? = definedExternally ): Moment external fun unix(timestamp: Number): Moment external fun invalid(flags: MomentParsingFlagsOpt? = definedExternally): Moment external fun isMoment(m: Any): Boolean external fun isDate(m: Any): Boolean external fun isDuration(d: Any): Boolean /** * @deprecated in 2.8.0 */ external fun lang(language: String? = definedExternally): String /** * @deprecated in 2.8.0 */ external fun lang(language: String? = definedExternally, definition: Locale? = definedExternally): String external fun locale(language: String? = definedExternally): String external fun locale(language: Array<String>? = definedExternally): String external fun locale( language: String? = definedExternally, definition: Any? = definedExternally /* LocaleSpecification | Unit */ ): String external fun localeData(key: Any? = definedExternally /* String | Array<String> */): Locale external fun duration( inp: DurationInputArg1? = definedExternally, unit: DurationInputArg2? = definedExternally ): Duration // NOTE(constructor): Same as moment constructor external fun parseZone( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, strict: Boolean? = definedExternally ): Moment external fun parseZone( inp: MomentInput? = definedExternally, format: MomentFormatSpecification? = definedExternally, language: String? = definedExternally, strict: Boolean? = definedExternally ): Moment external fun months(): Array<String> external fun months(index: Number): String external fun months(format: String): Array<String> external fun months(format: String, index: Number): String external fun monthsShort(): Array<String> external fun monthsShort(index: Number): String external fun monthsShort(format: String): Array<String> external fun monthsShort(format: String, index: Number): String external fun weekdays(): Array<String> external fun weekdays(index: Number): String external fun weekdays(format: String): Array<String> external fun weekdays(format: String, index: Number): String external fun weekdays(localeSorted: Boolean): Array<String> external fun weekdays(localeSorted: Boolean, index: Number): String external fun weekdays(localeSorted: Boolean, format: String): Array<String> external fun weekdays(localeSorted: Boolean, format: String, index: Number): String external fun weekdaysShort(): Array<String> external fun weekdaysShort(index: Number): String external fun weekdaysShort(format: String): Array<String> external fun weekdaysShort(format: String, index: Number): String external fun weekdaysShort(localeSorted: Boolean): Array<String> external fun weekdaysShort(localeSorted: Boolean, index: Number): String external fun weekdaysShort(localeSorted: Boolean, format: String): Array<String> external fun weekdaysShort(localeSorted: Boolean, format: String, index: Number): String external fun weekdaysMin(): Array<String> external fun weekdaysMin(index: Number): String external fun weekdaysMin(format: String): Array<String> external fun weekdaysMin(format: String, index: Number): String external fun weekdaysMin(localeSorted: Boolean): Array<String> external fun weekdaysMin(localeSorted: Boolean, index: Number): String external fun weekdaysMin(localeSorted: Boolean, format: String): Array<String> external fun weekdaysMin(localeSorted: Boolean, format: String, index: Number): String external fun min(moments: Array<Moment>): Moment external fun min(vararg moments: Moment): Moment external fun max(moments: Array<Moment>): Moment external fun max(vararg moments: Moment): Moment /** * Returns unix time in milliseconds. Overwrite for profit. */ external fun now(): Number external fun defineLocale(language: String, localeSpec: Any /* LocaleSpecification | Unit */): Locale // null external fun updateLocale(language: String, localeSpec: Any /* LocaleSpecification | Unit */): Locale // null external fun locales(): Array<String> external fun normalizeUnits(unit: All): String external fun relativeTimeThreshold(threshold: String): Any /* Number | Boolean */ external fun relativeTimeThreshold(threshold: String, limit: Number): Boolean external fun relativeTimeRounding(fn: (num: Number) -> Number): Boolean external fun relativeTimeRounding(): (num: Number) -> Number external fun calendarFormat(m: Moment, now: Moment): String external fun parseTwoDigitYear(input: String): Number /** * Constant used to enable explicit ISO_8601 format parsing. */ external var ISO_8601: MomentBuiltinFormat external var RFC_2822: MomentBuiltinFormat external var defaultFormat: String external var defaultFormatUtc: String external object HTML5_FMT { var DATETIME_LOCAL: String var DATETIME_LOCAL_SECONDS: String var DATETIME_LOCAL_MS: String var DATE: String var TIME: String var TIME_SECONDS: String var TIME_MS: String var WEEK: String var MONTH: String }
1
null
8
50
e0017a108b36025630c354c7663256347e867251
22,457
kotlin-js-wrappers
Apache License 2.0
common/src/commonMain/kotlin/dev/zwander/common/pages/WifiConfigPage.kt
zacharee
641,202,797
false
null
@file:OptIn(ExperimentalObjCRefinement::class) package dev.zwander.common.pages import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState 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.compositeOver import androidx.compose.ui.unit.dp import dev.icerock.moko.mvvm.flow.compose.collectAsMutableState import dev.icerock.moko.resources.StringResource import dev.icerock.moko.resources.compose.stringResource import dev.zwander.common.components.BandConfigLayout import dev.zwander.common.components.ChannelConfigLayout import dev.zwander.common.components.PageGrid import dev.zwander.common.components.SSIDListLayout import dev.zwander.common.components.dialog.AlertDialogDef import dev.zwander.common.model.GlobalModel import dev.zwander.common.model.MainModel import dev.zwander.resources.common.MR import kotlinx.coroutines.launch import kotlin.experimental.ExperimentalObjCRefinement import kotlin.native.HiddenFromObjC private data class ItemData( val title: StringResource, val render: @Composable (Modifier) -> Unit, val description: (@Composable () -> Unit)? = null, val visible: Boolean = true, ) @Composable @HiddenFromObjC fun WifiConfigPage( modifier: Modifier = Modifier, ) { val scope = rememberCoroutineScope() val data by MainModel.currentWifiData.collectAsState() var tempState by MainModel.tempWifiState.collectAsMutableState() var showingRadioWarning by remember { mutableStateOf(false) } fun save() { scope.launch { tempState?.let { GlobalModel.httpClient.value?.setWifiData(it) } MainModel.currentWifiData.value = GlobalModel.httpClient.value?.getWifiData() } } LaunchedEffect(data) { tempState = data } val items = remember(tempState) { listOf( ItemData( title = MR.strings.band_mgmnt, render = { BandConfigLayout(it) }, description = { Text( text = stringResource(MR.strings.radio_warning), color = MaterialTheme.colorScheme.error, ) Text( text = stringResource(MR.strings.radio_advice), ) }, ), ItemData( title = MR.strings.channel_mgmnt, render = { ChannelConfigLayout(it) }, visible = tempState?.twoGig?.channel != null && tempState?.fiveGig?.channel != null, ), ItemData( title = MR.strings.ssids, render = { SSIDListLayout(it) }, ), ) } PageGrid( items = items.filter { it.visible }, modifier = modifier, renderItemTitle = { Text( text = stringResource(it.title), ) }, renderItem = { it.render(Modifier.fillMaxWidth()) }, renderItemDescription = { it.description?.invoke() }, bottomBarContents = { Button( onClick = { if ((tempState?.twoGig?.isRadioEnabled == false && tempState?.twoGig?.isRadioEnabled != data?.twoGig?.isRadioEnabled) || (tempState?.fiveGig?.isRadioEnabled == false && tempState?.fiveGig?.isRadioEnabled != data?.fiveGig?.isRadioEnabled) ) { showingRadioWarning = true } else { save() } }, enabled = tempState != data && tempState != null, modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), colors = ButtonDefaults.buttonColors( disabledContainerColor = MaterialTheme.colorScheme.onSurface .copy(alpha = 0.12f) .compositeOver(MaterialTheme.colorScheme.background), ), ) { Text( text = stringResource(MR.strings.save) ) } }, showBottomBarExpander = false, itemIsSelectable = { false }, ) AlertDialogDef( showing = showingRadioWarning, title = { Text(text = stringResource(MR.strings.save)) }, text = { Text(text = stringResource(MR.strings.radio_disable_confirm)) }, onDismissRequest = { showingRadioWarning = false }, buttons = { TextButton( onClick = { showingRadioWarning = false }, ) { Text(text = stringResource(MR.strings.no)) } TextButton( onClick = { showingRadioWarning = false save() }, colors = ButtonDefaults.textButtonColors( contentColor = MaterialTheme.colorScheme.error, ), ) { Text(text = stringResource(MR.strings.yes)) } }, ) }
8
null
7
91
3d958ae0b2581815d4e496b0fef69186cc3a8c4f
5,980
ArcadyanKVD21Control
MIT License
src/main/java/com/sayzen/campfiresdk/screens/fandoms/rubrics/SRubricPosts.kt
HorsePower68
230,018,763
true
{"Kotlin": 1489208}
package com.sayzen.campfiresdk.screens.fandoms.rubrics import com.dzen.campfire.api.models.fandoms.Rubric import com.dzen.campfire.api.models.publications.Publication import com.dzen.campfire.api.requests.post.RPostGetAllByRubric import com.dzen.campfire.api.requests.rubrics.RRubricGet import com.sayzen.campfiresdk.R import com.sayzen.campfiresdk.controllers.ControllerRubrics import com.sayzen.campfiresdk.controllers.api import com.sayzen.campfiresdk.models.cards.CardPublication import com.sayzen.campfiresdk.models.events.rubrics.EventRubricChangeName import com.sayzen.campfiresdk.models.events.rubrics.EventRubricChangeOwner import com.sayzen.campfiresdk.models.events.rubrics.EventRubricRemove import com.sayzen.campfiresdk.tools.ApiRequestsSupporter import com.sup.dev.android.libs.screens.navigator.NavigationAction import com.sup.dev.android.libs.screens.navigator.Navigator import com.sup.dev.android.tools.ToolsResources import com.sup.dev.android.views.screens.SLoadingRecycler import com.sup.dev.android.views.support.adapters.recycler_view.RecyclerCardAdapterLoading import com.sup.dev.java.libs.eventBus.EventBus class SRubricPosts( val rubric: Rubric ) : SLoadingRecycler<CardPublication, Publication>() { companion object{ fun instance(rubricId:Long, action: NavigationAction){ ApiRequestsSupporter.executeInterstitial(action, RRubricGet(rubricId)) { r -> SRubricPosts(r.rubric) } } } val eventBus = EventBus .subscribe(EventRubricChangeName::class){ if(rubric.id == it.rubricId){ rubric.name = it.rubricName } } .subscribe(EventRubricChangeOwner::class){ if(rubric.id == it.rubricId){ rubric.ownerId = it.ownerId rubric.ownerImageId = it.ownerImageId rubric.ownerName = it.ownerName rubric.ownerLevel = it.ownerLevel rubric.ownerKarma30 = it.ownerKarma30 rubric.ownerLastOnlineTime = it.ownerLastOnlineTime } } .subscribe(EventRubricChangeName::class){ if(rubric.id == it.rubricId){ rubric.name = it.rubricName setTitle(rubric.name) } } .subscribe(EventRubricRemove::class){ if(rubric.id == it.rubricId){ Navigator.remove(this) } } init { vScreenRoot!!.setBackgroundColor(ToolsResources.getBackgroundColor(context)) setTitle(rubric.name) setTextEmpty(R.string.rubric_posts_empty) addToolbarIcon(R.drawable.ic_more_vert_white_24dp){ ControllerRubrics.instanceMenu(rubric).asSheetShow() } } override fun instanceAdapter(): RecyclerCardAdapterLoading<CardPublication, Publication> { return RecyclerCardAdapterLoading<CardPublication, Publication>(CardPublication::class) { publication -> CardPublication.instance(publication, vRecycler) } .setBottomLoader { onLoad, cards -> RPostGetAllByRubric(rubric.id, cards.size.toLong()) .onComplete { r -> onLoad.invoke(r.publications) } .onNetworkError { onLoad.invoke(null) } .send(api) } } }
0
null
0
0
214a4ee9262e185eb33a0ddcfc3a6803f22d54fd
3,473
CampfireSDK
Apache License 2.0
coinkit/src/main/java/io/horizontalsystems/coinkit/models/Coin.kt
horizontalsystems
342,791,847
false
null
package io.vextabit.coinkit.models import android.content.Context import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.eclipsesource.json.Json import kotlinx.android.parcel.Parcelize import java.io.InputStreamReader import java.util.* @Parcelize @Entity data class Coin( @PrimaryKey @ColumnInfo(name = "id") val type: CoinType, val code: String, val title: String, val decimal: Int): Parcelable { val id: String get() = type.ID override fun equals(other: Any?): Boolean { if (other is Coin) { return type == other.type } return super.equals(other) } override fun hashCode(): Int { return Objects.hash(type.ID) } } sealed class CoinType: Parcelable { @Parcelize object Bitcoin : CoinType() @Parcelize object Litecoin : CoinType() @Parcelize object BitcoinCash : CoinType() @Parcelize object Dash : CoinType() @Parcelize object Ethereum : CoinType() @Parcelize object BinanceSmartChain : CoinType() @Parcelize object DigestSwarmChain : CoinType() @Parcelize object Zcash : CoinType() @Parcelize class Erc20(val address: String) : CoinType() @Parcelize class Bep2(val symbol: String) : CoinType() @Parcelize class Bep20(val address: String) : CoinType() @Parcelize class Unsupported(val id: String) : CoinType() val ID: String get() = getCoinId() override fun equals(other: Any?): Boolean { if (other is CoinType) { return ID == other.ID } return super.equals(other) } override fun hashCode(): Int { return Objects.hashCode(ID) } fun getCoinId(): String { return when (this) { is Bitcoin -> "bitcoin" is Litecoin -> "litecoin" is BitcoinCash -> "bitcoinCash" is Dash -> "dash" is Ethereum -> "ethereum" is Zcash -> "zcash" is BinanceSmartChain -> "binanceSmartChain" is DigestSwarmChain -> "digestSwarmChain" is Erc20 -> "erc20|${this.address}" is Bep2 -> "bep2|${this.symbol}" is Bep20 -> "bep20|${this.address}" is Unsupported -> "unsupported|${this.id}" } } companion object { fun fromString(id: String): CoinType { val chunks = id.split("|") if (chunks.size == 1) { return when (chunks[0]) { "bitcoin" -> Bitcoin "litecoin" -> Litecoin "bitcoinCash" -> BitcoinCash "dash" -> Dash "ethereum" -> Ethereum "zcash" -> Zcash "binanceSmartChain" -> BinanceSmartChain "digestSwarmChain" -> DigestSwarmChain else -> Unsupported(chunks[0]) } } else { return when (chunks[0]) { "erc20" -> Erc20(chunks[1]) "bep2" -> Bep2(chunks[1]) "bep20" -> Bep20(chunks[1]) "unsupported" -> Unsupported(chunks.drop(1).joinToString("|")) else -> Unsupported(chunks.joinToString("|")) } } } } } @Entity class ResourceInfo( @PrimaryKey @ColumnInfo(name = "id") val resourceType: ResourceType, val version: Int) enum class ResourceType{ DEFAULT_COINS; } data class CoinResponse(val version: Int, val coins: List<Coin>){ companion object{ fun parseFile(context: Context, fileName: String): CoinResponse{ val inputStream = context.assets.open(fileName) val jsonObject = Json.parse(InputStreamReader(inputStream)) val coins = mutableListOf<Coin>() val version = jsonObject.asObject().get("version").asInt() jsonObject.asObject().get("coins").asArray().forEach { category -> val code = category.asObject().get("code").asString() val title = category.asObject().get("title").asString() val decimal = category.asObject().get("decimal").asInt() var typeString = category.asObject().get("type").asString() if(category.asObject().get("address") != null){ if(!category.asObject().get("address").isNull) { typeString = "${typeString.trim()}|${category.asObject().get("address").asString().trim()}" if(typeString.contains("erc20|") || typeString.contains("bep20|") ) typeString = typeString.toLowerCase(Locale.ROOT) } } else if(category.asObject().get("symbol") != null){ if(!category.asObject().get("symbol").isNull) typeString = "${typeString.trim()}|${category.asObject().get("symbol").asString().trim()}" } coins.add(Coin(CoinType.fromString(typeString), code, title, decimal)) } return CoinResponse(version, coins) } } }
1
null
12
4
670a130caef66bef9c9f9e464a5da5884b56bf21
5,263
coin-kit-android
MIT License
unity/BIDUnityBanner.kt
bidapphub
708,849,825
false
null
package io.bidapp.networks.unity import android.app.Activity import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import com.unity3d.services.banners.BannerErrorInfo import com.unity3d.services.banners.BannerView import com.unity3d.services.banners.UnityBannerSize import io.bidapp.sdk.AdFormat import io.bidapp.sdk.BIDLog import io.bidapp.sdk.protocols.BIDBannerAdapterDelegateProtocol import io.bidapp.sdk.protocols.BIDBannerAdapterProtocol import java.lang.ref.WeakReference @PublishedApi internal class BIDUnityBanner( var adapter: BIDBannerAdapterProtocol?, var adTag: String?, format: AdFormat? ) : BIDBannerAdapterDelegateProtocol, BannerView.IListener { val TAG = "Banner Unity" val bannerFormat = if (format?.isbanner_320x50 == true) UnityBannerSize(320, 50) else if (format?.isbanner_300x250 == true) UnityBannerSize(300, 250) else { BIDLog.d(TAG, "Unsuported banner format: $format") null } var adView: WeakReference<BannerView>? = null var cachedAd: BannerView? = null override fun nativeAdView(): WeakReference<View>? { return WeakReference(adView?.get() as View) } override fun isAdReady(): Boolean { return cachedAd != null } override fun load(activity: Activity) { cachedAd = null val load = runCatching { if (adView == null) { adView = WeakReference(BannerView(activity, adTag!!, bannerFormat)) adView?.get()?.listener = this } adView?.get()?.load() } if (load.isFailure) adapter?.onFailedToLoad(Error("Unity banner loading error")) } override fun prepareForDealloc() { // prepareForDealloc } override fun showOnView(view: WeakReference<View>, activity: Activity): Boolean { return try { val density = activity.resources.displayMetrics.density val weightAndHeight = if (bannerFormat?.height == 50 && bannerFormat.width == 320) arrayOf( 320, 50 ) else if (bannerFormat?.height == 250 && bannerFormat.width == 300) arrayOf( 300, 250 ) else arrayOf(0, 0) (view.get() as FrameLayout).addView( adView?.get(),0, ViewGroup.LayoutParams( (weightAndHeight[0]*density).toInt(), (weightAndHeight[1]*density).toInt()) ) true } catch (e: Exception) { BIDLog.d(TAG, "Show on view is failed ${e.message}") false } } override fun waitForAdToShow(): Boolean { return true } override fun onBannerLoaded(ad: BannerView?) { cachedAd = ad adapter?.onLoad() BIDLog.d(TAG, "load") } override fun onBannerShown(bannerAdView: BannerView?) { BIDLog.d(TAG, "show") adapter?.onDisplay() } override fun onBannerClick(bannerAdView: BannerView?) { BIDLog.d(TAG, "click") adapter?.onClick() } override fun onBannerFailedToLoad(bannerAdView: BannerView?, errorInfo: BannerErrorInfo?) { BIDLog.d(TAG, "failed to load ad. Error: ${errorInfo?.errorCode}") adapter?.onFailedToLoad(Error(errorInfo?.errorCode.toString())) } override fun onBannerLeftApplication(bannerView: BannerView?) { BIDLog.d(TAG, "banner left application") adapter?.onHide() } }
0
null
1
2
927356cc82d347ee3699dbeb167e007b97e65354
3,529
bidapp-ads-android
Apache License 2.0
z2-kotlin-plugin/testData/box/schematic/generic.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1768633, "CSS": 171914, "Java": 18941, "JavaScript": 1950, "HTML": 1854}
package foo.bar import hu.simplexion.z2.schematic.Schematic class Test<T> : Schematic<Test<T>>() { var genericField by generic<T>() var genericFieldOrNull by generic<T?>() } fun box(): String { val test = Test<Int>() test.genericField = 12 if (test.genericField != 12) return "Fail: genericField != 12" test.genericFieldOrNull = 23 if (test.genericFieldOrNull != 23) return "Fail: genericFieldOrNull != 23" test.genericFieldOrNull = null if (test.genericFieldOrNull != null) return "Fail: genericFieldOrNull != null" return "OK" }
5
Kotlin
0
1
cc13a72fb54d89dffb91e3edf499ae5152bca0d9
580
z2
Apache License 2.0
plugins/amazonq/codetransform/jetbrains-community/src/software/aws/toolkits/jetbrains/services/codemodernizer/controller/CodeTransformChatController.kt
aws
91,485,909
false
null
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.codemodernizer.controller import com.intellij.ide.BrowserUtil import com.intellij.openapi.application.runInEdt import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.vfs.VirtualFile import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import software.aws.toolkits.core.utils.debug import software.aws.toolkits.core.utils.getLogger import software.aws.toolkits.jetbrains.services.amazonq.apps.AmazonQAppInitContext import software.aws.toolkits.jetbrains.services.amazonq.auth.AuthController import software.aws.toolkits.jetbrains.services.codemodernizer.ArtifactHandler import software.aws.toolkits.jetbrains.services.codemodernizer.CodeModernizerManager import software.aws.toolkits.jetbrains.services.codemodernizer.CodeTransformTelemetryManager import software.aws.toolkits.jetbrains.services.codemodernizer.InboundAppMessagesHandler import software.aws.toolkits.jetbrains.services.codemodernizer.client.GumbyClient import software.aws.toolkits.jetbrains.services.codemodernizer.commands.CodeTransformActionMessage import software.aws.toolkits.jetbrains.services.codemodernizer.commands.CodeTransformCommand import software.aws.toolkits.jetbrains.services.codemodernizer.constants.FEATURE_NAME import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildCheckingValidProjectChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildCompileLocalFailedChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildCompileLocalInProgressChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildCompileLocalSuccessChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildProjectInvalidChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildProjectValidChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildStartNewTransformFollowup import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildTransformInProgressChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildTransformResultChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildTransformResumingChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildTransformStoppedChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildTransformStoppingChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildUserCancelledChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildUserInputChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildUserSelectionSummaryChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.constants.buildUserStopTransformChatContent import software.aws.toolkits.jetbrains.services.codemodernizer.getModuleOrProjectNameForFile import software.aws.toolkits.jetbrains.services.codemodernizer.messages.AuthenticationNeededExceptionMessage import software.aws.toolkits.jetbrains.services.codemodernizer.messages.CodeTransformChatMessage import software.aws.toolkits.jetbrains.services.codemodernizer.messages.CodeTransformCommandMessage import software.aws.toolkits.jetbrains.services.codemodernizer.messages.IncomingCodeTransformMessage import software.aws.toolkits.jetbrains.services.codemodernizer.model.CodeModernizerJobCompletedResult import software.aws.toolkits.jetbrains.services.codemodernizer.model.CustomerSelection import software.aws.toolkits.jetbrains.services.codemodernizer.model.JobId import software.aws.toolkits.jetbrains.services.codemodernizer.model.MavenCopyCommandsResult import software.aws.toolkits.jetbrains.services.codemodernizer.session.ChatSessionStorage import software.aws.toolkits.jetbrains.services.codemodernizer.session.Session import software.aws.toolkits.jetbrains.services.codemodernizer.state.CodeModernizerSessionState import software.aws.toolkits.jetbrains.services.codemodernizer.toVirtualFile import software.aws.toolkits.jetbrains.services.cwc.messages.ChatMessageType import software.aws.toolkits.resources.message import software.aws.toolkits.telemetry.CodeTransformStartSrcComponents class CodeTransformChatController( private val context: AmazonQAppInitContext, private val chatSessionStorage: ChatSessionStorage ) : InboundAppMessagesHandler { private val authController = AuthController() private val messagePublisher = context.messagesFromAppToUi private val telemetry = CodeTransformTelemetryManager.getInstance(context.project) private val codeModernizerManager = CodeModernizerManager.getInstance(context.project) private val codeTransformChatHelper = CodeTransformChatHelper(context.messagesFromAppToUi, chatSessionStorage) private val artifactHandler = ArtifactHandler(context.project, GumbyClient.getInstance(context.project)) override suspend fun processTransformQuickAction(message: IncomingCodeTransformMessage.Transform) { if (!checkForAuth(message.tabId)) { return } CodeTransformTelemetryManager.getInstance(context.project).jobIsStartedFromChatPrompt() telemetry.sendUserClickedTelemetry(CodeTransformStartSrcComponents.ChatPrompt) codeTransformChatHelper.setActiveCodeTransformTabId(message.tabId) if (!message.startNewTransform) { if (tryRestoreChatProgress()) { return } } codeTransformChatHelper.addNewMessage( buildCheckingValidProjectChatContent() ) delay(3000) val validationResult = codeModernizerManager.validate(context.project) if (!validationResult.valid) { codeModernizerManager.warnUnsupportedProject(validationResult.invalidReason) codeTransformChatHelper.updateLastPendingMessage( buildProjectInvalidChatContent(validationResult) ) codeTransformChatHelper.addNewMessage( buildStartNewTransformFollowup() ) return } codeTransformChatHelper.updateLastPendingMessage( buildProjectValidChatContent(validationResult) ) delay(500) codeTransformChatHelper.addNewMessage( buildUserInputChatContent(context.project, validationResult) ) } suspend fun tryRestoreChatProgress(): Boolean { val isTransformOngoing = codeModernizerManager.isModernizationJobActive() val isMvnRunning = codeModernizerManager.isRunningMvn() val isTransformationResuming = codeModernizerManager.isModernizationJobResuming() while (isTransformationResuming) { delay(50) } if (isMvnRunning) { codeTransformChatHelper.addNewMessage(buildCompileLocalInProgressChatContent()) return true } if (isTransformOngoing) { if (codeModernizerManager.isJobSuccessfullyResumed()) { codeTransformChatHelper.addNewMessage(buildTransformResumingChatContent()) } else { codeTransformChatHelper.addNewMessage(buildTransformInProgressChatContent()) } return true } val lastTransformResult = codeModernizerManager.getLastTransformResult() if (lastTransformResult != null) { codeTransformChatHelper.addNewMessage(buildTransformResumingChatContent()) handleCodeTransformResult(lastTransformResult) return true } val lastMvnBuildResult = codeModernizerManager.getLastMvnBuildResult() if (lastMvnBuildResult != null) { codeTransformChatHelper.addNewMessage(buildCompileLocalInProgressChatContent()) handleMavenBuildResult(lastMvnBuildResult) return true } return false } override suspend fun processCodeTransformCancelAction(message: IncomingCodeTransformMessage.CodeTransformCancel) { if (!checkForAuth(message.tabId)) { return } codeTransformChatHelper.run { addNewMessage(buildUserCancelledChatContent()) addNewMessage(buildStartNewTransformFollowup()) } } override suspend fun processCodeTransformStartAction(message: IncomingCodeTransformMessage.CodeTransformStart) { if (!checkForAuth(message.tabId)) { return } val (tabId, modulePath, targetVersion) = message val moduleVirtualFile: VirtualFile = modulePath.toVirtualFile() as VirtualFile val moduleName = context.project.getModuleOrProjectNameForFile(moduleVirtualFile) codeTransformChatHelper.run { addNewMessage(buildUserSelectionSummaryChatContent(moduleName)) addNewMessage(buildCompileLocalInProgressChatContent()) } val selection = CustomerSelection( moduleVirtualFile, JavaSdkVersion.JDK_1_8, JavaSdkVersion.JDK_17 ) codeModernizerManager.runLocalMavenBuild(context.project, selection) } suspend fun handleMavenBuildResult(mavenBuildResult: MavenCopyCommandsResult) { if (mavenBuildResult == MavenCopyCommandsResult.Cancelled) { codeTransformChatHelper.updateLastPendingMessage(buildUserCancelledChatContent()) codeTransformChatHelper.addNewMessage(buildStartNewTransformFollowup()) return } else if (mavenBuildResult == MavenCopyCommandsResult.Failure) { codeTransformChatHelper.updateLastPendingMessage(buildCompileLocalFailedChatContent()) codeTransformChatHelper.addNewMessage(buildStartNewTransformFollowup()) return } codeTransformChatHelper.run { updateLastPendingMessage(buildCompileLocalSuccessChatContent()) addNewMessage(buildTransformInProgressChatContent()) } runInEdt { codeModernizerManager.runModernize(mavenBuildResult) } } override suspend fun processCodeTransformStopAction(tabId: String) { if (!checkForAuth(tabId)) { return } codeTransformChatHelper.run { addNewMessage(buildUserStopTransformChatContent()) addNewMessage(buildTransformStoppingChatContent()) } runBlocking { codeModernizerManager.stopModernize() } } override suspend fun processCodeTransformOpenTransformHub(message: IncomingCodeTransformMessage.CodeTransformOpenTransformHub) { runInEdt { codeModernizerManager.getBottomToolWindow().show() } } override suspend fun processCodeTransformOpenMvnBuild(message: IncomingCodeTransformMessage.CodeTransformOpenMvnBuild) { runInEdt { codeModernizerManager.getMvnBuildWindow().show() } } override suspend fun processCodeTransformViewDiff(message: IncomingCodeTransformMessage.CodeTransformViewDiff) { artifactHandler.displayDiffAction(CodeModernizerSessionState.getInstance(context.project).currentJobId as JobId) } override suspend fun processCodeTransformViewSummary(message: IncomingCodeTransformMessage.CodeTransformViewSummary) { artifactHandler.showTransformationSummary(CodeModernizerSessionState.getInstance(context.project).currentJobId as JobId) } override suspend fun processCodeTransformNewAction(message: IncomingCodeTransformMessage.CodeTransformNew) { processTransformQuickAction(IncomingCodeTransformMessage.Transform(tabId = message.tabId, startNewTransform = true)) } override suspend fun processCodeTransformCommand(message: CodeTransformActionMessage) { val activeTabId = codeTransformChatHelper.getActiveCodeTransformTabId() ?: return when (message.command) { CodeTransformCommand.StopClicked -> { messagePublisher.publish(CodeTransformCommandMessage(command = "stop")) processCodeTransformStopAction(activeTabId) } CodeTransformCommand.MavenBuildComplete -> { val result = message.mavenBuildResult if (result != null) { handleMavenBuildResult(result) } } CodeTransformCommand.TransformComplete -> { val result = message.transformResult if (result != null) { handleCodeTransformResult(result) } } CodeTransformCommand.TransformStopped -> { handleCodeTransformStoppedByUser() } CodeTransformCommand.TransformResuming -> { handleCodeTransformJobResume() } else -> { processTransformQuickAction(IncomingCodeTransformMessage.Transform(tabId = activeTabId)) } } } override suspend fun processTabCreated(message: IncomingCodeTransformMessage.TabCreated) { logger.debug { "$FEATURE_NAME: New tab created: $message" } } private suspend fun checkForAuth(tabId: String): Boolean { var session: Session? = null try { session = chatSessionStorage.getSession(tabId) logger.debug { "$FEATURE_NAME: Session created with id: ${session.tabId}" } val credentialState = authController.getAuthNeededStates(context.project).amazonQ if (credentialState != null) { messagePublisher.publish( AuthenticationNeededExceptionMessage( tabId = session.tabId, authType = credentialState.authType, message = credentialState.message ) ) session.isAuthenticating = true return false } } catch (err: Exception) { messagePublisher.publish( CodeTransformChatMessage( tabId = tabId, messageType = ChatMessageType.Answer, message = message("codemodernizer.chat.message.error_request") ) ) return false } return true } override suspend fun processTabRemoved(message: IncomingCodeTransformMessage.TabRemoved) { chatSessionStorage.deleteSession(message.tabId) } override suspend fun processAuthFollowUpClick(message: IncomingCodeTransformMessage.AuthFollowUpWasClicked) { authController.handleAuth(context.project, message.authType) messagePublisher.publish( CodeTransformChatMessage( tabId = message.tabId, messageType = ChatMessageType.Answer, message = message("codemodernizer.chat.message.auth_prompt") ) ) } override suspend fun processBodyLinkClicked(message: IncomingCodeTransformMessage.BodyLinkClicked) { BrowserUtil.browse(message.link) } private suspend fun handleCodeTransformJobResume() { codeTransformChatHelper.addNewMessage(buildTransformResumingChatContent()) } private suspend fun handleCodeTransformStoppedByUser() { codeTransformChatHelper.updateLastPendingMessage(buildTransformStoppedChatContent()) codeTransformChatHelper.addNewMessage(buildStartNewTransformFollowup()) } private suspend fun handleCodeTransformResult(result: CodeModernizerJobCompletedResult) { when (result) { is CodeModernizerJobCompletedResult.Stopped, CodeModernizerJobCompletedResult.JobAbortedBeforeStarting -> handleCodeTransformStoppedByUser() else -> { codeTransformChatHelper.updateLastPendingMessage( buildTransformResultChatContent(result) ) codeTransformChatHelper.addNewMessage(buildStartNewTransformFollowup()) } } } companion object { private val logger = getLogger<CodeTransformChatController>() } }
439
null
190
725
a26137f3db9a93deaf2d83e60b071d439431106a
16,397
aws-toolkit-jetbrains
Apache License 2.0
backend/data/src/main/kotlin/io/tolgee/model/batch/params/SetTranslationStateJobParams.kt
tolgee
303,766,501
false
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.model.batch.params import io.tolgee.model.enums.TranslationState class SetTranslationStateJobParams { var languageIds: List<Long> = listOf() var state: TranslationState? = null }
170
TypeScript
188
1,837
6e01eec3a19c151a6e0aca49e187e2d0deef3082
203
tolgee-platform
Apache License 2.0
src/test/java/com/andres_k/lib/test/document/CreatePdfTest.kt
Draym
319,586,872
false
null
package com.andres_k.lib.test.document import com.andres_k.lib.extension.template.BaseTestTemplate import com.andres_k.lib.library.core.component.PdfComponent import com.andres_k.lib.library.core.component.container.PdfCol import com.andres_k.lib.library.core.component.container.PdfRow import com.andres_k.lib.library.core.component.custom.PdfTextLine import com.andres_k.lib.library.core.component.element.PdfParagraph import com.andres_k.lib.library.core.component.element.PdfText import com.andres_k.lib.library.core.property.BodyAlign import com.andres_k.lib.library.core.property.SizeAttr import com.andres_k.lib.library.core.property.Spacing import com.andres_k.lib.library.factory.FConf import com.andres_k.lib.library.factory.conf import com.andres_k.lib.library.output.OutputBuilder import com.andres_k.lib.library.output.PdfToFile import com.andres_k.lib.library.utils.BaseFont import com.andres_k.lib.parser.PdfParser import com.andres_k.lib.test.PdfFlexBase import com.andres_k.lib.wrapper.PDFGeneratedWrapper import org.apache.pdfbox.pdmodel.PDDocument import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.awt.Color import java.nio.file.InvalidPathException import java.nio.file.Path import kotlin.io.path.exists import kotlin.test.assertEquals import kotlin.test.assertNotNull /** * Created on 2021/06/28. * * @author Kevin Andres */ internal class CreatePdfTest : PdfFlexBase() { @TempDir lateinit var tempDir: Path private lateinit var createPdfTestFile: Path @BeforeEach fun setUp() { try { createPdfTestFile = tempDir.resolve("CreatePdfTest.pdf") } catch (ipe: InvalidPathException) { System.err.println("[CreatePdfTest] error creating temporary test file in " + this.javaClass.simpleName) } } @AfterEach fun tearDown() { } @Test fun createPDFInMemory() { val components = createComponents() val template = BaseTestTemplate(components) val pdf = template.use { builder -> OutputBuilder.asByteArray().use { output -> // build the PDF in memory // explorer will contains information on what has been actually created val explorer = builder.build(output) // write the PDF into a byte array val pdfAsBytes = output.get() // return the generated result data PDFGeneratedWrapper( pdf = pdfAsBytes, explorer = explorer ) } } } @Test fun createPDFIntoFile() { val components = createComponents() val template = BaseTestTemplate(components) val fileOutput = PdfToFile(createPdfTestFile.toFile()) val explorer = template.use { builder -> fileOutput.use { output -> // build the PDF in memory and save it to a file builder.build(output) } } assertTrue(createPdfTestFile.exists()); PDDocument.load(createPdfTestFile.toFile()).use { pdf -> val parser = PdfParser(pdf) val drawnTitle = explorer.searchText("Hello world").firstOrNull() assertNotNull(drawnTitle) val resultTitle = parser.search("Hello world") println("result title: $resultTitle") assertNotNull(resultTitle) assertEquals((resultTitle.pageWidth / 2) - (drawnTitle.width / 2), resultTitle.getPositionFromTop().x) assertEquals(Color(90, 43, 129), resultTitle.color) } } private fun createComponents(): List<PdfComponent> { val fontB = BaseFont.BOLD.code /** Title **/ val rtTxt = FConf(font = fontB, bodyAlign = BodyAlign.CENTER_CENTER, color = Color(90, 43, 129)) val rowTitle = PdfRow( elements = listOf(PdfText("Hello world", fontSize = 17f).conf(rtTxt)), margin = Spacing(top = 20f) ) /** Paragraph **/ val messages = listOf("Test Line1.", "Test Line2.\nTest Line3.") val paragraph1 = PdfParagraph( lines = messages .map { text -> text.lines().map { PdfTextLine(PdfText(text = it, bodyAlign = BodyAlign.LEFT, font = BaseFont.DEFAULT.code, color = Color.BLACK)) } }.flatten(), bodyAlign = BodyAlign.TOP_LEFT ) val flatMessage = "Test Line1.\n Test Line2.\nTest Line3." val paragraph2 = PdfParagraph( text = flatMessage, textAlign = BodyAlign.LEFT, textFont = BaseFont.DEFAULT.code, color = Color.BLACK, bodyAlign = BodyAlign.TOP_LEFT ) val rowParagraph = PdfRow( elements = listOf( PdfCol(paragraph1, maxWidth = SizeAttr.percent(50f)), PdfCol(paragraph2, maxWidth = SizeAttr.percent(50f)) ), margin = Spacing(top = 20f) ) return listOf(rowTitle, rowParagraph) } }
0
Kotlin
0
1
5084ca91cf25328afa3238abc19d1f0e3c095fe1
5,229
PDF-Flex
MIT License
src/main/kotlin/com/ibrahimharoon/gitautocommit/rest/dtos/DefaultLlmResponseDto.kt
Ibrahim-Haroon
837,470,568
false
{"Kotlin": 63154, "PowerShell": 3057, "Shell": 1646}
package com.ibrahimharoon.gitautocommit.rest.dtos /** * Represents the default response structure from an LLM API. * * @property choices A list of Choice objects representing possible responses. */ data class DefaultLlmResponseDto( val choices: List<Choice> ) { /** * Represents a single choice in the LLM response. * * @property message The Message object containing the response content. */ data class Choice( val message: Message ) { /** * Represents the message content of a choice. * * @property content The actual text content of the response. */ data class Message( val content: String ) } }
0
Kotlin
2
5
eae9bebd7caf88a90a944d9dbf581cfaf8cbe54f
724
git-autocommit-cli
MIT License
design/components/src/main/java/com/choice/compose/Row.kt
choicedev
474,815,875
false
{"Kotlin": 139368}
package com.choice.compose import androidx.compose.foundation.layout.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.choice.theme.MonkeyTheme @Composable inline fun MonkeyRow( modifier: Modifier = Modifier, horizontalArrangement: Arrangement.Horizontal = Arrangement.Start, verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, content: @Composable RowScope.() -> Unit ) { Row( modifier = modifier .fillMaxWidth() .padding(vertical = MonkeyTheme.spacing.small), horizontalArrangement = horizontalArrangement, verticalAlignment = verticalAlignment, content = content ) } @Composable inline fun MonkeyDefaultRow( modifier: Modifier = Modifier, horizontalArrangement: Arrangement.Horizontal = Arrangement.Start, verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, content: @Composable RowScope.() -> Unit ) { Row( modifier = modifier, horizontalArrangement = horizontalArrangement, verticalAlignment = verticalAlignment, content = content ) }
0
Kotlin
0
1
7b1b382da31021e186b40bd173a68071454d2655
1,189
MonkeyFoodFork
Apache License 2.0
features/roomdetails/impl/src/main/kotlin/io/element/android/features/roomdetails/impl/RoomDetailsView.kt
vector-im
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.roomdetails.impl import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.consumeWindowInsets 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.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.outlined.Add import androidx.compose.material.icons.outlined.Lock import androidx.compose.material.icons.outlined.Person import androidx.compose.material.icons.outlined.PersonAddAlt import androidx.compose.material.icons.outlined.Share import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import io.element.android.features.leaveroom.api.LeaveRoomView import io.element.android.features.roomdetails.impl.blockuser.BlockUserDialogs import io.element.android.features.roomdetails.impl.blockuser.BlockUserSection import io.element.android.features.roomdetails.impl.members.details.RoomMemberHeaderSection import io.element.android.features.roomdetails.impl.members.details.RoomMemberMainActionsSection import io.element.android.libraries.designsystem.ElementTextStyles import io.element.android.libraries.designsystem.components.avatar.Avatar import io.element.android.libraries.designsystem.components.avatar.AvatarData import io.element.android.libraries.designsystem.components.avatar.AvatarSize import io.element.android.libraries.designsystem.components.button.BackButton import io.element.android.libraries.designsystem.components.button.MainActionButton import io.element.android.libraries.designsystem.components.preferences.PreferenceCategory import io.element.android.libraries.designsystem.components.preferences.PreferenceText import io.element.android.libraries.designsystem.preview.ElementPreviewDark import io.element.android.libraries.designsystem.preview.ElementPreviewLight import io.element.android.libraries.designsystem.preview.LargeHeightPreview import io.element.android.libraries.designsystem.theme.LocalColors import io.element.android.libraries.designsystem.theme.components.Icon import io.element.android.libraries.designsystem.theme.components.IconButton import io.element.android.libraries.designsystem.theme.components.Scaffold import io.element.android.libraries.designsystem.theme.components.Text import io.element.android.libraries.designsystem.theme.components.TopAppBar import io.element.android.libraries.matrix.api.room.RoomMember import io.element.android.libraries.ui.strings.R as StringR @OptIn(ExperimentalLayoutApi::class) @Composable fun RoomDetailsView( state: RoomDetailsState, goBack: () -> Unit, onActionClicked: (RoomDetailsAction) -> Unit, onShareRoom: () -> Unit, onShareMember: (RoomMember) -> Unit, openRoomMemberList: () -> Unit, invitePeople: () -> Unit, modifier: Modifier = Modifier, ) { fun onShareMember() { onShareMember((state.roomType as RoomDetailsType.Dm).roomMember) } Scaffold( modifier = modifier, topBar = { RoomDetailsTopBar( goBack = goBack, showEdit = state.canEdit, onActionClicked = onActionClicked ) }, ) { padding -> Column( modifier = Modifier .padding(padding) .verticalScroll(rememberScrollState()) .consumeWindowInsets(padding) ) { LeaveRoomView(state = state.leaveRoomState) when (state.roomType) { RoomDetailsType.Room -> { RoomHeaderSection( avatarUrl = state.roomAvatarUrl, roomId = state.roomId, roomName = state.roomName, roomAlias = state.roomAlias ) MainActionsSection(onShareRoom = onShareRoom) } is RoomDetailsType.Dm -> { val member = state.roomType.roomMember RoomMemberHeaderSection( avatarUrl = state.roomAvatarUrl ?: member.avatarUrl, userId = member.userId.value, userName = state.roomName ) RoomMemberMainActionsSection(onShareUser = ::onShareMember) } } Spacer(Modifier.height(26.dp)) if (state.roomTopic !is RoomTopicState.Hidden) { TopicSection( roomTopic = state.roomTopic, onActionClicked = onActionClicked, ) } if (state.roomType is RoomDetailsType.Room) { MembersSection( memberCount = state.memberCount, openRoomMemberList = openRoomMemberList, ) if (state.canInvite) { InviteSection( invitePeople = invitePeople ) } } if (state.isEncrypted) { SecuritySection() } if (state.roomType is RoomDetailsType.Dm && state.roomMemberDetailsState != null) { val roomMemberState = state.roomMemberDetailsState BlockUserSection(roomMemberState) BlockUserDialogs(roomMemberState) } OtherActionsSection(onLeaveRoom = { state.eventSink(RoomDetailsEvent.LeaveRoom) }) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun RoomDetailsTopBar( goBack: () -> Unit, onActionClicked: (RoomDetailsAction) -> Unit, showEdit: Boolean, modifier: Modifier = Modifier, ) { var showMenu by remember { mutableStateOf(false) } TopAppBar( modifier = modifier, title = { }, navigationIcon = { BackButton(onClick = goBack) }, actions = { if (showEdit) { IconButton(onClick = { showMenu = !showMenu }) { Icon(Icons.Default.MoreVert, "") } DropdownMenu( modifier = Modifier.widthIn(200.dp), expanded = showMenu, onDismissRequest = { showMenu = false }, ) { DropdownMenuItem( text = { Text(stringResource(id = StringR.string.action_edit)) }, onClick = { // Explicitly close the menu before handling the action, as otherwise it stays open during the // transition and renders really badly. showMenu = false onActionClicked(RoomDetailsAction.Edit) }, ) } } }, ) } @Composable internal fun MainActionsSection(onShareRoom: () -> Unit, modifier: Modifier = Modifier) { Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { MainActionButton(title = stringResource(R.string.screen_room_details_share_room_title), icon = Icons.Outlined.Share, onClick = onShareRoom) } } @Composable internal fun RoomHeaderSection( avatarUrl: String?, roomId: String, roomName: String, roomAlias: String?, modifier: Modifier = Modifier ) { Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Box(modifier = Modifier.size(70.dp)) { Avatar( avatarData = AvatarData(roomId, roomName, avatarUrl, AvatarSize.HUGE), modifier = Modifier.fillMaxSize() ) } Spacer(modifier = Modifier.height(24.dp)) Text(roomName, style = ElementTextStyles.Bold.title1) if (roomAlias != null) { Spacer(modifier = Modifier.height(6.dp)) Text(roomAlias, style = ElementTextStyles.Regular.body, color = MaterialTheme.colorScheme.secondary) } Spacer(Modifier.height(32.dp)) } } @Composable internal fun TopicSection( roomTopic: RoomTopicState, onActionClicked: (RoomDetailsAction) -> Unit, modifier: Modifier = Modifier ) { PreferenceCategory(title = stringResource(StringR.string.common_topic), modifier = modifier) { if (roomTopic is RoomTopicState.CanAddTopic) { PreferenceText( title = stringResource(R.string.screen_room_details_add_topic_title), icon = Icons.Outlined.Add, onClick = { onActionClicked(RoomDetailsAction.AddTopic) }, ) } else if (roomTopic is RoomTopicState.ExistingTopic) { Text( roomTopic.topic, modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 12.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.tertiary ) } } } @Composable internal fun MembersSection( memberCount: Long, openRoomMemberList: () -> Unit, modifier: Modifier = Modifier, ) { PreferenceCategory(modifier = modifier) { PreferenceText( title = stringResource(R.string.screen_room_details_people_title), icon = Icons.Outlined.Person, currentValue = memberCount.toString(), onClick = openRoomMemberList, ) } } @Composable internal fun InviteSection( invitePeople: () -> Unit, modifier: Modifier = Modifier, ) { PreferenceCategory(modifier = modifier) { PreferenceText( title = stringResource(R.string.screen_room_details_invite_people_title), icon = Icons.Outlined.PersonAddAlt, onClick = invitePeople, ) } } @Composable internal fun SecuritySection(modifier: Modifier = Modifier) { PreferenceCategory(title = stringResource(R.string.screen_room_details_security_title), modifier = modifier) { PreferenceText( title = stringResource(R.string.screen_room_details_encryption_enabled_title), subtitle = stringResource(R.string.screen_room_details_encryption_enabled_subtitle), icon = Icons.Outlined.Lock, ) } } @Composable internal fun OtherActionsSection(onLeaveRoom: () -> Unit, modifier: Modifier = Modifier) { PreferenceCategory(showDivider = false, modifier = modifier) { PreferenceText( title = stringResource(R.string.screen_room_details_leave_room_title), icon = ImageVector.vectorResource(R.drawable.ic_door_open), tintColor = LocalColors.current.textActionCritical, onClick = onLeaveRoom, ) } } @LargeHeightPreview @Composable fun RoomDetailsLightPreview(@PreviewParameter(RoomDetailsStateProvider::class) state: RoomDetailsState) = ElementPreviewLight { ContentToPreview(state) } @LargeHeightPreview @Composable fun RoomDetailsDarkPreview(@PreviewParameter(RoomDetailsStateProvider::class) state: RoomDetailsState) = ElementPreviewDark { ContentToPreview(state) } @Composable private fun ContentToPreview(state: RoomDetailsState) { RoomDetailsView( state = state, goBack = {}, onActionClicked = {}, onShareRoom = {}, onShareMember = {}, openRoomMemberList = {}, invitePeople = {}, ) }
91
null
32
287
4587b51bd33e8b5a2e2c81c79f3aa70a3ac52923
13,313
element-x-android
Apache License 2.0
app/android/src/main/java/UpdateAwareAppScope.kt
DRSchlaubi
641,131,010
false
{"Kotlin": 211716, "Rust": 4226, "Swift": 2736, "Ruby": 2733, "HTML": 705, "JavaScript": 645, "PowerShell": 617, "Dockerfile": 255}
package dev.schlaubi.tonbrett.app.android import android.app.Activity import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.OpenInNew import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.google.android.play.core.appupdate.AppUpdateManagerFactory import com.google.android.play.core.install.model.InstallStatus import com.google.android.play.core.ktx.AppUpdateResult import com.google.android.play.core.ktx.bytesDownloaded import com.google.android.play.core.ktx.installStatus import com.google.android.play.core.ktx.requestCompleteUpdate import com.google.android.play.core.ktx.requestUpdateFlow import com.google.android.play.core.ktx.totalBytesToDownload import dev.schlaubi.tonbrett.app.ColorScheme import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import java.text.NumberFormat @Composable fun UpdateAwareAppScope(activity: Activity, content: @Composable () -> Unit) { val context = LocalContext.current.applicationContext val scope = rememberCoroutineScope() val appUpdateManager = remember(context) { AppUpdateManagerFactory.create(context.applicationContext) } val progressFlow = remember(appUpdateManager) { appUpdateManager.requestUpdateFlow() .catch { emit(AppUpdateResult.NotAvailable) } } val progress: AppUpdateResult? by progressFlow.collectAsState(initial = null) var failed by remember(appUpdateManager) { mutableStateOf(false) } Box(Modifier.fillMaxSize()) { content() if (failed) return Column( verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding(vertical = 10.dp) .zIndex(10f) ) { Row( modifier = Modifier .padding(vertical = 7.dp) .background( MaterialTheme.colorScheme.primary, RoundedCornerShape(50.dp) ) ) { @Composable fun Info(text: String) { Text( text, style = MaterialTheme.typography.headlineSmall.copy(color = ColorScheme.current.textColor), modifier = Modifier.padding(horizontal = 15.dp, vertical = 10.dp) ) } when (val currentProgress = progress) { is AppUpdateResult.InProgress -> { val installState = currentProgress.installState when (installState.installStatus) { InstallStatus.CANCELED, InstallStatus.INSTALLED, InstallStatus.FAILED -> { failed = true } InstallStatus.DOWNLOADING -> { val ratio = installState.bytesDownloaded.toDouble() / installState.totalBytesToDownload.toDouble() .coerceAtLeast(1.0) // avoid division by zero val percentage = NumberFormat.getPercentInstance().format(ratio) Info(stringResource(R.string.update_downloading, percentage)) } InstallStatus.PENDING -> { Info(stringResource(R.string.update_pending)) } else -> {} // ignore } } is AppUpdateResult.Available -> Button(onClick = { currentProgress.startFlexibleUpdate(activity, 12548) }) { Info(stringResource(R.string.update_available)) } is AppUpdateResult.Downloaded -> Button(onClick = { scope.launch { appUpdateManager.requestCompleteUpdate() } }) { Icon(Icons.Default.OpenInNew, null) Info(stringResource(R.string.update_download_done)) } else -> {} // ignore } } } } }
0
Kotlin
1
8
e73c478cb8e613f90d2813a81672a508ad3ad536
5,533
tonbrett
MIT License
lib/src/main/kotlin/com/github/xingray/kotlinjavafxbase/page/BaseStage.kt
XingRay
870,533,727
false
{"Kotlin": 53262}
package com.github.xingray.kotlinjavafxbase.page import javafx.event.EventHandler import javafx.stage.Stage import javafx.stage.StageStyle import javafx.stage.WindowEvent open class BaseStage : Stage { private val onCloseEventHandlers: MutableList<EventHandler<WindowEvent>> = mutableListOf() constructor() { initOnCloseEventHandler() } constructor(style: StageStyle?) : super(style) { initOnCloseEventHandler() } fun addOnCloseEventHandler(eventEventHandler: EventHandler<WindowEvent>) { onCloseEventHandlers.add(eventEventHandler) } private fun initOnCloseEventHandler() { super.setOnCloseRequest(object : EventHandler<WindowEvent?> { override fun handle(event: WindowEvent?) { val handlers: List<EventHandler<WindowEvent>> = onCloseEventHandlers if (handlers.isEmpty()) { return } for (eventHandler in handlers) { eventHandler.handle(event) } } }) } }
0
Kotlin
0
0
4579746bb97f26958e825dcad6263e7530a2d54c
1,080
kotlin-javafx-base
Apache License 2.0
serverless-simulator/opendc/opendc-workflows/src/main/kotlin/com/atlarge/opendc/workflows/service/WorkflowEvent.kt
atlarge-research
297,702,102
false
null
/* * Copyright (c) 2020 AtLarge Research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opendc.workflows.service import org.opendc.workflows.workload.Job /** * An event emitted by the [WorkflowService]. */ public sealed class WorkflowEvent { /** * The [WorkflowService] that emitted the event. */ public abstract val service: WorkflowService /** * This event is emitted when a job has been submitted to the scheduler. */ public data class JobSubmitted( override val service: WorkflowService, public val jobState: JobState, public val time: Long ) : WorkflowEvent() /** * This event is emitted when a job has become active. */ public data class JobStarted( override val service: WorkflowService, public val jobState: JobState, public val time: Long ) : WorkflowEvent() /** * This event is emitted when a job has finished processing. */ public data class JobFinished( override val service: WorkflowService, public val job: Job, public val time: Long ) : WorkflowEvent() /** * This event is emitted when a task of a job has been submitted for execution. */ public data class TaskSubmitted( override val service: WorkflowService, public val job: Job, public val task: TaskState, public val time: Long ) : WorkflowEvent() /** * This event is emitted when a task of a job has started processing. */ public data class TaskStarted( override val service: WorkflowService, public val job: Job, public val task: TaskState, public val time: Long ) : WorkflowEvent() /** * This event is emitted when a task of a job has started processing. */ public data class TaskFinished( override val service: WorkflowService, public val job: Job, public val task: TaskState, public val time: Long ) : WorkflowEvent() }
0
null
1
2
11c772bcb3fc7a7c2590d6ed6ab979b78cb9fec9
3,068
opendc-serverless
MIT License
connectors/jdbc-connector/src/main/java/com/orbitalhq/connectors/jdbc/drivers/snowflake/SnowflakeJdbcUrlBuilder.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.connectors.jdbc.drivers.snowflake import com.orbitalhq.connectors.ConnectionDriverParam import com.orbitalhq.connectors.ConnectionParameterName import com.orbitalhq.connectors.ConnectorUtils import com.orbitalhq.connectors.IConnectionParameter import com.orbitalhq.connectors.SimpleDataType import com.orbitalhq.connectors.config.jdbc.JdbcUrlBuilder import com.orbitalhq.connectors.connectionParams import com.orbitalhq.connectors.config.jdbc.JdbcUrlAndCredentials import com.orbitalhq.connectors.jdbc.drivers.postgres.remove import com.orbitalhq.utils.substitute class SnowflakeJdbcUrlBuilder : JdbcUrlBuilder { enum class Parameters(override val param: ConnectionDriverParam) : IConnectionParameter { ACCOUNT(ConnectionDriverParam("account", SimpleDataType.STRING)), DATABASE(ConnectionDriverParam("db", SimpleDataType.STRING)), SCHEMA_NAME(ConnectionDriverParam("schema", SimpleDataType.STRING)), WAREHOUSE_NAME(ConnectionDriverParam("warehouse", SimpleDataType.STRING)), USERNAME(ConnectionDriverParam("username", SimpleDataType.STRING)), PASSWORD(ConnectionDriverParam("password", SimpleDataType.STRING, sensitive = true)), ROLE(ConnectionDriverParam("role", SimpleDataType.STRING)) } override val displayName: String = "Snowflake" override val driverName: String = "net.snowflake.client.jdbc.SnowflakeDriver" override val parameters: List<ConnectionDriverParam> = Parameters.values().connectionParams() override fun build(inputs: Map<ConnectionParameterName, Any?>): JdbcUrlAndCredentials { val inputsWithDefaults = ConnectorUtils.assertAllParametersPresent(parameters, inputs) val connectionString = "jdbc:snowflake://{account}.snowflakecomputing.com/".substitute(inputsWithDefaults) val remainingInputs = inputsWithDefaults.remove(listOf("account", "host", "username", "password", "user")) .entries.joinToString(separator = "&") { (key, value) -> "$key=$value" } val builtConnectionString = if (remainingInputs.isNullOrEmpty()) { connectionString } else { "$connectionString?$remainingInputs" } return JdbcUrlAndCredentials( builtConnectionString, inputsWithDefaults["username"]?.toString(), inputsWithDefaults["password"]?.toString() ) } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
2,342
orbital
Apache License 2.0