
Datasets:
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinDebuggerCaches.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.debugger.evaluate
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.containers.MultiMap
import org.apache.log4j.Logger
import org.jetbrains.annotations.TestOnly
import org.jetbrains.eval4j.Value
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.debugger.BinaryCacheKey
import org.jetbrains.kotlin.idea.debugger.BytecodeDebugInfo
import org.jetbrains.kotlin.idea.debugger.createWeakBytecodeDebugInfoStorage
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad
import org.jetbrains.kotlin.idea.runInReadActionWithWriteActionPriorityWithPCE
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.types.KotlinType
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class KotlinDebuggerCaches(project: Project) {
private val cachedCompiledData = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MultiMap<String, CompiledDataDescriptor>>(
MultiMap.create(), PsiModificationTracker.MODIFICATION_COUNT)
}, false)
private val cachedClassNames = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MutableMap<PsiElement, List<String>>>(
ConcurrentHashMap<PsiElement, List<String>>(),
PsiModificationTracker.MODIFICATION_COUNT)
}, false)
private val cachedTypeMappers = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MutableMap<PsiElement, KotlinTypeMapper>>(
ConcurrentHashMap<PsiElement, KotlinTypeMapper>(),
PsiModificationTracker.MODIFICATION_COUNT)
}, false)
private val debugInfoCache = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result(
createWeakBytecodeDebugInfoStorage(),
PsiModificationTracker.MODIFICATION_COUNT)
}, false)
companion object {
private val LOG = Logger.getLogger(KotlinDebuggerCaches::class.java)!!
fun getInstance(project: Project) = ServiceManager.getService(project, KotlinDebuggerCaches::class.java)!!
fun getOrCreateCompiledData(
codeFragment: KtCodeFragment,
sourcePosition: SourcePosition,
evaluationContext: EvaluationContextImpl,
create: (KtCodeFragment, SourcePosition) -> CompiledDataDescriptor
): CompiledDataDescriptor {
val evaluateExpressionCache = getInstance(codeFragment.project)
val text = "${codeFragment.importsToString()}\n${codeFragment.text}"
val cached = synchronized<Collection<CompiledDataDescriptor>>(evaluateExpressionCache.cachedCompiledData) {
val cache = evaluateExpressionCache.cachedCompiledData.value!!
cache[text]
}
val answer = cached.firstOrNull {
it.sourcePosition == sourcePosition || evaluateExpressionCache.canBeEvaluatedInThisContext(it, evaluationContext)
}
if (answer != null) {
return answer
}
val newCompiledData = create(codeFragment, sourcePosition)
LOG.debug("Compile bytecode for ${codeFragment.text}")
synchronized(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value.putValue(text, newCompiledData)
}
return newCompiledData
}
fun <T : PsiElement> getOrComputeClassNames(psiElement: T?, create: (T) -> ComputedClassNames): List<String> {
if (psiElement == null) return Collections.emptyList()
val cache = getInstance(runReadAction { psiElement.project })
val classNamesCache = cache.cachedClassNames.value
val cachedValue = classNamesCache[psiElement]
if (cachedValue != null) return cachedValue
val computedClassNames = create(psiElement)
if (computedClassNames.shouldBeCached) {
classNamesCache[psiElement] = computedClassNames.classNames
}
return computedClassNames.classNames
}
fun getOrCreateTypeMapper(psiElement: PsiElement): KotlinTypeMapper {
val cache = getInstance(runReadAction { psiElement.project })
val file = runReadAction { psiElement.containingFile as KtFile }
val isInLibrary = runReadAction { LibraryUtil.findLibraryEntry(file.virtualFile, file.project) } != null
val key = if (!isInLibrary) file else psiElement
val typeMappersCache = cache.cachedTypeMappers.value
val cachedValue = typeMappersCache[key]
if (cachedValue != null) return cachedValue
val newValue = if (!isInLibrary) {
createTypeMapperForSourceFile(file)
}
else {
val element = getElementToCreateTypeMapperForLibraryFile(psiElement)
createTypeMapperForLibraryFile(element, file)
}
typeMappersCache[key] = newValue
return newValue
}
fun getOrReadDebugInfoFromBytecode(
project: Project,
jvmName: JvmClassName,
file: VirtualFile): BytecodeDebugInfo? {
val cache = getInstance(project)
return cache.debugInfoCache.value[BinaryCacheKey(project, jvmName, file)]
}
private fun getElementToCreateTypeMapperForLibraryFile(element: PsiElement?) =
runReadAction { element as? KtElement ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java)!! }
private fun createTypeMapperForLibraryFile(element: KtElement, file: KtFile): KotlinTypeMapper =
runInReadActionWithWriteActionPriorityWithPCE {
createTypeMapper(file, element.analyzeAndGetResult())
}
private fun createTypeMapperForSourceFile(file: KtFile): KotlinTypeMapper =
runInReadActionWithWriteActionPriorityWithPCE {
createTypeMapper(file, file.analyzeWithAllCompilerChecks().apply(AnalysisResult::throwIfError))
}
private fun createTypeMapper(file: KtFile, analysisResult: AnalysisResult): KotlinTypeMapper {
val state = GenerationState.Builder(
file.project,
ClassBuilderFactories.THROW_EXCEPTION,
analysisResult.moduleDescriptor,
analysisResult.bindingContext,
listOf(file),
CompilerConfiguration.EMPTY
).build()
state.beforeCompile()
return state.typeMapper
}
@TestOnly fun addTypeMapper(file: KtFile, typeMapper: KotlinTypeMapper) {
getInstance(file.project).cachedTypeMappers.value[file] = typeMapper
}
}
private fun canBeEvaluatedInThisContext(compiledData: CompiledDataDescriptor, context: EvaluationContextImpl): Boolean {
val frameVisitor = FrameVisitor(context)
return compiledData.parameters.all { p ->
val (name, jetType) = p
val value = frameVisitor.findValue(name, asmType = null, checkType = false, failIfNotFound = false)
if (value == null) return@all false
val thisDescriptor = value.asmType.getClassDescriptor(context.debugProcess.searchScope)
val superClassDescriptor = jetType.constructor.declarationDescriptor as? ClassDescriptor
return@all thisDescriptor != null && superClassDescriptor != null && runReadAction { DescriptorUtils.isSubclass(thisDescriptor, superClassDescriptor) }
}
}
data class CompiledDataDescriptor(
val classes: List<ClassToLoad>,
val sourcePosition: SourcePosition,
val parameters: ParametersDescriptor
)
class ParametersDescriptor : Iterable<Parameter> {
private val list = ArrayList<Parameter>()
fun add(name: String, jetType: KotlinType, value: Value? = null) {
list.add(Parameter(name, jetType, value))
}
override fun iterator() = list.iterator()
}
data class Parameter(val callText: String, val type: KotlinType, val value: Value? = null)
class ComputedClassNames(val classNames: List<String>, val shouldBeCached: Boolean) {
companion object {
val EMPTY = ComputedClassNames.Cached(emptyList())
fun Cached(classNames: List<String>) = ComputedClassNames(classNames, true)
fun Cached(className: String) = ComputedClassNames(Collections.singletonList(className), true)
fun NonCached(classNames: List<String>) = ComputedClassNames(classNames, false)
}
fun distinct() = ComputedClassNames(classNames.distinct(), shouldBeCached)
operator fun plus(other: ComputedClassNames) = ComputedClassNames(
classNames + other.classNames, shouldBeCached && other.shouldBeCached)
}
}
private fun String?.toList() = if (this == null) emptyList() else listOf(this) | 12 | null | 4 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 11,169 | kotlin | Apache License 2.0 |
src/main/kotlin/com/salesforce/revoman/output/report/failure/ResponseFailure.kt | salesforce-misc | 677,000,343 | false | null | /**
* ************************************************************************************************
* Copyright (c) 2023, Salesforce, Inc. All rights reserved. SPDX-License-Identifier: Apache License
* Version 2.0 For full license text, see the LICENSE file in the repo root or
* http://www.apache.org/licenses/LICENSE-2.0
* ************************************************************************************************
*/
package com.salesforce.revoman.output.report.failure
import com.salesforce.revoman.output.ExeType.TESTS_JS
import com.salesforce.revoman.output.ExeType.UNMARSHALL_RESPONSE
import com.salesforce.revoman.output.report.TxnInfo
import org.http4k.core.Request
import org.http4k.core.Response
sealed class ResponseFailure : ExeFailure() {
abstract val requestInfo: TxnInfo<Request>
abstract val responseInfo: TxnInfo<Response>
data class TestsJSFailure(
override val failure: Throwable,
override val requestInfo: TxnInfo<Request>,
override val responseInfo: TxnInfo<Response>,
) : ResponseFailure() {
override val exeType = TESTS_JS
}
data class UnmarshallResponseFailure(
override val failure: Throwable,
override val requestInfo: TxnInfo<Request>,
override val responseInfo: TxnInfo<Response>
) : ResponseFailure() {
override val exeType = UNMARSHALL_RESPONSE
}
}
| 9 | null | 5 | 6 | 1c4aa93c77a28d1d1482da14a4afbdabf3991f14 | 1,346 | ReVoman | Apache License 2.0 |
ui/src/test/java/ru/tinkoff/acquiring/sdk/redesign/cards/list/CardsDeleteViewModelTest.kt | itlogic | 293,802,517 | true | {"Kotlin": 1162428, "Java": 29422} | package ru.tinkoff.acquiring.sdk.redesign.cards.list
import androidx.lifecycle.SavedStateHandle
import app.cash.turbine.test
import common.MutableCollector
import common.assertByClassName
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import ru.tinkoff.acquiring.sdk.AcquiringSdk
import ru.tinkoff.acquiring.sdk.models.options.screen.SavedCardsOptions
import ru.tinkoff.acquiring.sdk.redesign.cards.list.models.CardItemUiModel
import ru.tinkoff.acquiring.sdk.redesign.cards.list.presentation.CardsListViewModel
import ru.tinkoff.acquiring.sdk.redesign.cards.list.ui.CardListEvent
import ru.tinkoff.acquiring.sdk.redesign.cards.list.ui.CardListMode
import ru.tinkoff.acquiring.sdk.redesign.cards.list.ui.CardsListState
import ru.tinkoff.acquiring.sdk.requests.RemoveCardRequest
import ru.tinkoff.acquiring.sdk.responses.RemoveCardResponse
import ru.tinkoff.acquiring.sdk.utils.*
import java.lang.Exception
import java.util.concurrent.Executors
/**
* Created by <NAME>
*/
internal class CardsDeleteViewModelTest {
val defaultContent = CardsListState.Content(
CardListMode.ADD, false, listOf(createCard("1"), createCard("2")),
)
val extendsContent = CardsListState.Content(
CardListMode.ADD, false, listOf(createCard("1"), createCard("2"), createCard("3")),
)
@Test
fun `when card delete complete`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Success(RemoveCardResponse(1)))
val card = createCard("1")
vm.deleteCard(card, "")
eventCollector.joinWithTimeout()
eventCollector.flow.test {
assertByClassName(CardListEvent.RemoveCardProgress(mock()), awaitItem())
assertByClassName(CardListEvent.RemoveCardSuccess(card, null), awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete throw error`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Failure(Exception()))
vm.deleteCard(createCard("1"), "")
eventCollector.joinWithTimeout()
eventCollector.flow.test {
assertByClassName(CardListEvent.RemoveCardProgress(mock()), awaitItem())
assertByClassName(CardListEvent.ShowCardDeleteError(mock()), awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete without key`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Failure(Exception()))
vm.deleteCard(createCard("1"), null)
eventCollector.joinWithTimeout()
eventCollector.flow.test {
awaitItem()
assertByClassName(CardListEvent.ShowError, awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete is offline`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Failure(Exception()))
setOnline(false)
vm.deleteCard(createCard("1"), "")
eventCollector.joinWithTimeout()
eventCollector.flow.test {
awaitItem()
assertByClassName(CardListEvent.ShowError, awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete multiply show last card`() = runBlocking {
with(Environment(initState = extendsContent)) {
stateCollector.takeValues(2)
setResponse(RequestResult.Success(RemoveCardResponse(1)))
vm.deleteCard(createCard("1"), "")
setResponse(RequestResult.Success(RemoveCardResponse(2)))
vm.deleteCard(createCard("2"), "")
stateCollector.joinWithTimeout()
stateCollector.flow.test {
assertByClassName(CardsListState.Content::class.java, awaitItem().javaClass)
assertByClassName(CardsListState.Content::class.java, awaitItem().javaClass)
awaitComplete()
}
}
}
class Environment(
initState: CardsListState,
val connectionMock: ConnectionChecker = mock { on { isOnline() } doReturn true },
val asdk: AcquiringSdk = mock { },
val savedStateHandler: SavedStateHandle = mock { on { get<SavedCardsOptions>(any()) } doReturn SavedCardsOptions() }
) {
val dispatcher: CoroutineDispatcher =
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val vm = CardsListViewModel(
savedStateHandle = savedStateHandler,
asdk,
connectionMock,
BankCaptionProvider { "Tinkoff" },
CoroutineManager(dispatcher, dispatcher)
).apply {
stateFlow.value = initState
}
val eventCollector = MutableCollector<CardListEvent>(vm.eventFlow)
val stateCollector = MutableCollector<CardsListState>(vm.stateFlow)
fun setState(initState: CardsListState) {
vm.stateFlow.value = initState
}
fun setOnline(isOnline: Boolean) {
whenever(connectionMock.isOnline()).doReturn(isOnline)
}
fun setResponse(response: RequestResult<out RemoveCardResponse>) {
val request: RemoveCardRequest =
mock { on { executeFlow() } doReturn MutableStateFlow(response) }
whenever(asdk.removeCard(any())).doReturn(request)
}
}
private fun createCard(idMock: String): CardItemUiModel = mock { on { id } doReturn idMock }
} | 0 | Kotlin | 0 | 0 | 8de009c2ae6ca40843c74799429346fcfa74820c | 6,040 | AcquiringSdkAndroid | Apache License 2.0 |
src/test/kotlin/com/github/mpe85/grampa/rule/ConditionalRuleTests.kt | mpe85 | 138,511,038 | false | {"Kotlin": 270203, "Java": 1073} | package com.github.mpe85.grampa.rule
import com.github.mpe85.grampa.context.ParserContext
import com.github.mpe85.grampa.context.RuleContext
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.mockk.every
import io.mockk.mockk
import java.util.function.Predicate
class ConditionalRuleTests : StringSpec({
"equals/hashCode/ToString" {
val predicate = Predicate<RuleContext<String>> { true }
val empty = EmptyRule<String>()
val never = NeverRule<String>()
val rule1 = ConditionalRule(predicate::test, empty, never)
val rule2 = ConditionalRule(predicate::test, EmptyRule(), NeverRule())
val rule3 = ConditionalRule(predicate::test, empty)
rule1 shouldBe rule2
rule1 shouldNotBe rule3
rule1 shouldNotBe Any()
rule1.hashCode() shouldBe rule2.hashCode()
rule1.hashCode() shouldNotBe rule3.hashCode()
rule1.toString() shouldBe "ConditionalRule(condition=" +
"fun java.util.function.Predicate<T>.test(T): kotlin.Boolean, thenRule=EmptyRule, elseRule=NeverRule)"
rule2.toString() shouldBe "ConditionalRule(condition=" +
"fun java.util.function.Predicate<T>.test(T): kotlin.Boolean, thenRule=EmptyRule, elseRule=NeverRule)"
rule3.toString() shouldBe "ConditionalRule(condition=" +
"fun java.util.function.Predicate<T>.test(T): kotlin.Boolean, thenRule=EmptyRule, elseRule=null)"
}
"Rule match" {
val ctx = mockk<ParserContext<String>>().apply {
every { atEndOfInput } returns false
every { currentChar } returns 'a'
every { advanceIndex(1) } returns true
}
ConditionalRule<String>({ true }, CharPredicateRule('a')).match(ctx) shouldBe true
ConditionalRule<String>({ false }, CharPredicateRule('b')).match(ctx) shouldBe true
ConditionalRule<String>({ true }, CharPredicateRule('a'), CharPredicateRule('b')).match(ctx) shouldBe true
ConditionalRule<String>({ false }, CharPredicateRule('a'), CharPredicateRule('b')).match(ctx) shouldBe false
}
})
| 7 | Kotlin | 1 | 13 | 5a59969dd2c6b464f28b513579b2ea3cae182ab8 | 2,160 | grampa | MIT License |
mybatis-plus-spring/src/test/kotlin/com/baomidou/mybatisplus/test/kotlin/User.kt | baomidou | 65,987,043 | false | {"Java": 2664861, "Kotlin": 34733, "FreeMarker": 15242} | package com.baomidou.mybatisplus.test.kotlin
import com.baomidou.mybatisplus.annotation.TableField
import com.baomidou.mybatisplus.annotation.TableName
@TableName("sys_user")
class User {
var id: Int? = null
@TableField("username")
var name: String? = null
var roleId: Int? = null
}
| 74 | Java | 4308 | 16,378 | bbf2b671b5ad2492033a2b03a4c99b56c02d7701 | 304 | mybatis-plus | Apache License 2.0 |
api/common/src/main/kotlin/uk/co/baconi/oauth/api/common/authorisation/AuthorisationCodeRepository.kt | beercan1989 | 345,334,044 | false | null | package uk.co.baconi.oauth.api.common.authorisation
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import uk.co.baconi.oauth.api.common.client.ClientId
import uk.co.baconi.oauth.api.common.scope.ScopesSerializer
import uk.co.baconi.oauth.api.common.authentication.AuthenticatedUsername
import java.time.Instant
import java.util.*
class AuthorisationCodeRepository(private val database: Database) {
// TODO - Consider automatic expiration of token records.
companion object {
private const val BASIC = "basic"
private const val PKCE = "pkce"
}
fun insert(new: AuthorisationCode) {
transaction(database) {
AuthorisationCodeTable.insertAndGetId {
it[id] = new.value
when (new) {
is AuthorisationCode.Basic -> {
it[type] = BASIC
}
is AuthorisationCode.PKCE -> {
it[type] = PKCE
it[codeChallenge] = new.codeChallenge.value
it[codeChallengeMethod] = new.codeChallengeMethod.name
}
}
it[username] = new.username.value
it[clientId] = new.clientId.value
it[issuedAt] = new.issuedAt
it[expiresAt] = new.expiresAt
it[scopes] = new.scopes.let(ScopesSerializer::serialize)
it[redirectUri] = new.redirectUri
it[state] = new.state
}
}
}
fun findById(id: UUID): AuthorisationCode? {
return transaction(database) {
AuthorisationCodeTable
.select { AuthorisationCodeTable.id eq id }
.firstOrNull()
?.let(::toAuthorisationCode)
}
}
fun deleteById(id: UUID) {
transaction(database) {
AuthorisationCodeTable.deleteWhere { AuthorisationCodeTable.id eq id }
}
}
fun deleteExpired() {
transaction(database) {
AuthorisationCodeTable.deleteWhere { AuthorisationCodeTable.expiresAt lessEq Instant.now() }
}
}
private fun toAuthorisationCode(it: ResultRow): AuthorisationCode {
return when (val type = it[AuthorisationCodeTable.type]) {
BASIC -> AuthorisationCode.Basic(
value = it[AuthorisationCodeTable.id].value,
username = it[AuthorisationCodeTable.username].let(::AuthenticatedUsername),
clientId = it[AuthorisationCodeTable.clientId].let(::ClientId),
issuedAt = it[AuthorisationCodeTable.issuedAt],
expiresAt = it[AuthorisationCodeTable.expiresAt],
scopes = it[AuthorisationCodeTable.scopes].let(ScopesSerializer::deserialize),
redirectUri = it[AuthorisationCodeTable.redirectUri],
state = it[AuthorisationCodeTable.state],
)
PKCE -> AuthorisationCode.PKCE(
value = it[AuthorisationCodeTable.id].value,
username = it[AuthorisationCodeTable.username].let(::AuthenticatedUsername),
clientId = it[AuthorisationCodeTable.clientId].let(::ClientId),
issuedAt = it[AuthorisationCodeTable.issuedAt],
expiresAt = it[AuthorisationCodeTable.expiresAt],
scopes = it[AuthorisationCodeTable.scopes].let(ScopesSerializer::deserialize),
redirectUri = it[AuthorisationCodeTable.redirectUri],
state = it[AuthorisationCodeTable.state],
codeChallenge = CodeChallenge(checkNotNull(it[AuthorisationCodeTable.codeChallenge])),
codeChallengeMethod = enumValueOf(checkNotNull(it[AuthorisationCodeTable.codeChallengeMethod])),
)
else -> throw IllegalStateException("Unknown authorisation code type: $type")
}
}
} | 0 | Kotlin | 0 | 0 | e6377891fe624b9bc15abde0de4a31660584b00a | 3,959 | oauth-api | Apache License 2.0 |
ci/docker/image-builder/src/main/kotlin/ru/avito/image_builder/Main.kt | avito-tech | 230,265,582 | false | null | package ru.avito.image_builder
import kotlinx.cli.ArgParser
import kotlinx.cli.ExperimentalCli
import ru.avito.image_builder.internal.cli.BuildImage
import ru.avito.image_builder.internal.cli.PublishEmceeImage
import ru.avito.image_builder.internal.cli.PublishEmceeWorker
import ru.avito.image_builder.internal.cli.PublishEmulator
import ru.avito.image_builder.internal.cli.PublishImage
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
import java.util.logging.SimpleFormatter
public object Main {
@OptIn(ExperimentalCli::class)
@JvmStatic
public fun main(args: Array<String>) {
Logger.getLogger("").apply {
level = Level.INFO
for (handler in handlers) {
level = Level.INFO
// Sets up logging format similar to Emcee queue
handler.formatter = object : SimpleFormatter() {
// 2022-11-28 16:05:30.500
val dateFormatter = SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ROOT)
override fun format(record: LogRecord): String {
// [INFO] 2022-11-25 16:05:30.500: Message
return "[${record.level}] ${dateFormatter.format(Date(record.millis))}: ${record.message}\n"
}
}
}
}
val parser = ArgParser(
programName = "image-builder",
)
parser.subcommands(
BuildImage("build", "Build image"),
PublishImage("publish", "Build and publish image"),
PublishEmulator("publishEmulator", "Build and publish Android emulator image"),
PublishEmceeImage("publishEmceeImage", "Build and publish Emcee queue image"),
PublishEmceeWorker("publishEmceeWorker", "Build and publish Emcee worker image")
)
parser.parse(sanitizeEmptyArgs(args))
}
private fun sanitizeEmptyArgs(args: Array<String>): Array<String> {
return if (args.isEmpty()) {
arrayOf("--help")
} else {
args
}
}
}
| 7 | null | 50 | 414 | bc94abf5cbac32ac249a653457644a83b4b715bb | 2,215 | avito-android | MIT License |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/jvm/KotlinJvmCompilation.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch") // Old package for compatibility
package org.jetbrains.kotlin.gradle.plugin.mpp
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle.Stage.AfterFinaliseDsl
import org.jetbrains.kotlin.gradle.plugin.internal.JavaSourceSetsAccessor
import org.jetbrains.kotlin.gradle.plugin.mpp.compilationImpl.KotlinCompilationImpl
import org.jetbrains.kotlin.gradle.plugin.variantImplementationFactory
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask
import org.jetbrains.kotlin.gradle.utils.CompletableFuture
import org.jetbrains.kotlin.gradle.utils.Future
import org.jetbrains.kotlin.gradle.utils.lenient
import javax.inject.Inject
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION")
open class KotlinJvmCompilation @Inject internal constructor(
compilation: KotlinCompilationImpl,
) : DeprecatedAbstractKotlinCompilationToRunnableFiles<KotlinJvmOptions>(compilation),
DeprecatedKotlinCompilationWithResources<KotlinJvmOptions> {
final override val target: KotlinJvmTarget = compilation.target as KotlinJvmTarget
@Suppress("DEPRECATION")
@Deprecated(
"To configure compilation compiler options use 'compileTaskProvider':\ncompilation.compileTaskProvider.configure{\n" +
" compilerOptions {}\n}"
)
override val compilerOptions: DeprecatedHasCompilerOptions<KotlinJvmCompilerOptions> =
compilation.compilerOptions.castCompilerOptionsType()
@Deprecated("Replaced with compileTaskProvider", replaceWith = ReplaceWith("compileTaskProvider"))
@Suppress("UNCHECKED_CAST", "DEPRECATION")
override val compileKotlinTaskProvider: TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
get() = compilation.compileKotlinTaskProvider as TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
@Suppress("DEPRECATION")
@Deprecated("Accessing task instance directly is deprecated", replaceWith = ReplaceWith("compileTaskProvider"))
override val compileKotlinTask: org.jetbrains.kotlin.gradle.tasks.KotlinCompile
get() = compilation.compileKotlinTask as org.jetbrains.kotlin.gradle.tasks.KotlinCompile
@Suppress("UNCHECKED_CAST")
override val compileTaskProvider: TaskProvider<out KotlinCompilationTask<KotlinJvmCompilerOptions>>
get() = compilation.compileTaskProvider as TaskProvider<KotlinCompilationTask<KotlinJvmCompilerOptions>>
/**
* **Note**: requesting this too early (right after target creation and before any target configuration) may falsely return `null`
* value, but later target will be configured to run with Java enabled. If possible, please use [compileJavaTaskProviderSafe].
*/
val compileJavaTaskProvider: TaskProvider<out JavaCompile>?
get() = if (target.withJavaEnabled) {
val project = target.project
val javaSourceSets = project.variantImplementationFactory<JavaSourceSetsAccessor.JavaSourceSetsAccessorVariantFactory>()
.getInstance(project)
.sourceSets
val javaSourceSet = javaSourceSets.getByName(compilationName)
project.tasks.withType(JavaCompile::class.java).named(javaSourceSet.compileJavaTaskName)
} else null
/**
* Alternative to [compileJavaTaskProvider] to safely receive [JavaCompile] task provider when [KotlinJvmTarget.withJavaEnabled]
* will be enabled after call to this method.
*/
internal val compileJavaTaskProviderSafe: Provider<JavaCompile> = target.project.providers
.provider { javaSourceSet.lenient.getOrNull() }
.flatMap { javaSourceSet ->
checkNotNull(javaSourceSet)
project.tasks.named(javaSourceSet.compileJavaTaskName, JavaCompile::class.java)
}
internal val javaSourceSet: Future<SourceSet?> get() = javaSourceSetImpl
private val javaSourceSetImpl: CompletableFuture<SourceSet?> = CompletableFuture<SourceSet?>().also { future ->
/**
* If no SourceSet was set until 'AfterFinaliseDsl', then user really did never call into 'withJava', hence
* we can complete the Future with 'null' notifying everybody, that there won't be any java source set associated with
* this compilation
*/
target.project.launchInStage(AfterFinaliseDsl) {
if (!future.isCompleted) {
future.complete(null)
}
}
}
internal fun maybeCreateJavaSourceSet(): SourceSet {
check(target.withJavaEnabled)
val sourceSet = target.project.javaSourceSets.maybeCreate(compilationName)
javaSourceSetImpl.complete(sourceSet)
return sourceSet
}
override val processResourcesTaskName: String
get() = compilation.processResourcesTaskName ?: error("Missing 'processResourcesTaskName'")
}
| 183 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,373 | kotlin | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/jvm/KotlinJvmCompilation.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch") // Old package for compatibility
package org.jetbrains.kotlin.gradle.plugin.mpp
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle.Stage.AfterFinaliseDsl
import org.jetbrains.kotlin.gradle.plugin.internal.JavaSourceSetsAccessor
import org.jetbrains.kotlin.gradle.plugin.mpp.compilationImpl.KotlinCompilationImpl
import org.jetbrains.kotlin.gradle.plugin.variantImplementationFactory
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask
import org.jetbrains.kotlin.gradle.utils.CompletableFuture
import org.jetbrains.kotlin.gradle.utils.Future
import org.jetbrains.kotlin.gradle.utils.lenient
import javax.inject.Inject
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION")
open class KotlinJvmCompilation @Inject internal constructor(
compilation: KotlinCompilationImpl,
) : DeprecatedAbstractKotlinCompilationToRunnableFiles<KotlinJvmOptions>(compilation),
DeprecatedKotlinCompilationWithResources<KotlinJvmOptions> {
final override val target: KotlinJvmTarget = compilation.target as KotlinJvmTarget
@Suppress("DEPRECATION")
@Deprecated(
"To configure compilation compiler options use 'compileTaskProvider':\ncompilation.compileTaskProvider.configure{\n" +
" compilerOptions {}\n}"
)
override val compilerOptions: DeprecatedHasCompilerOptions<KotlinJvmCompilerOptions> =
compilation.compilerOptions.castCompilerOptionsType()
@Deprecated("Replaced with compileTaskProvider", replaceWith = ReplaceWith("compileTaskProvider"))
@Suppress("UNCHECKED_CAST", "DEPRECATION")
override val compileKotlinTaskProvider: TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
get() = compilation.compileKotlinTaskProvider as TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
@Suppress("DEPRECATION")
@Deprecated("Accessing task instance directly is deprecated", replaceWith = ReplaceWith("compileTaskProvider"))
override val compileKotlinTask: org.jetbrains.kotlin.gradle.tasks.KotlinCompile
get() = compilation.compileKotlinTask as org.jetbrains.kotlin.gradle.tasks.KotlinCompile
@Suppress("UNCHECKED_CAST")
override val compileTaskProvider: TaskProvider<out KotlinCompilationTask<KotlinJvmCompilerOptions>>
get() = compilation.compileTaskProvider as TaskProvider<KotlinCompilationTask<KotlinJvmCompilerOptions>>
/**
* **Note**: requesting this too early (right after target creation and before any target configuration) may falsely return `null`
* value, but later target will be configured to run with Java enabled. If possible, please use [compileJavaTaskProviderSafe].
*/
val compileJavaTaskProvider: TaskProvider<out JavaCompile>?
get() = if (target.withJavaEnabled) {
val project = target.project
val javaSourceSets = project.variantImplementationFactory<JavaSourceSetsAccessor.JavaSourceSetsAccessorVariantFactory>()
.getInstance(project)
.sourceSets
val javaSourceSet = javaSourceSets.getByName(compilationName)
project.tasks.withType(JavaCompile::class.java).named(javaSourceSet.compileJavaTaskName)
} else null
/**
* Alternative to [compileJavaTaskProvider] to safely receive [JavaCompile] task provider when [KotlinJvmTarget.withJavaEnabled]
* will be enabled after call to this method.
*/
internal val compileJavaTaskProviderSafe: Provider<JavaCompile> = target.project.providers
.provider { javaSourceSet.lenient.getOrNull() }
.flatMap { javaSourceSet ->
checkNotNull(javaSourceSet)
project.tasks.named(javaSourceSet.compileJavaTaskName, JavaCompile::class.java)
}
internal val javaSourceSet: Future<SourceSet?> get() = javaSourceSetImpl
private val javaSourceSetImpl: CompletableFuture<SourceSet?> = CompletableFuture<SourceSet?>().also { future ->
/**
* If no SourceSet was set until 'AfterFinaliseDsl', then user really did never call into 'withJava', hence
* we can complete the Future with 'null' notifying everybody, that there won't be any java source set associated with
* this compilation
*/
target.project.launchInStage(AfterFinaliseDsl) {
if (!future.isCompleted) {
future.complete(null)
}
}
}
internal fun maybeCreateJavaSourceSet(): SourceSet {
check(target.withJavaEnabled)
val sourceSet = target.project.javaSourceSets.maybeCreate(compilationName)
javaSourceSetImpl.complete(sourceSet)
return sourceSet
}
override val processResourcesTaskName: String
get() = compilation.processResourcesTaskName ?: error("Missing 'processResourcesTaskName'")
}
| 183 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,373 | kotlin | Apache License 2.0 |
androidApp/src/main/java/press/editor/UrlPopupMenu.kt | saket | 201,701,386 | false | null | package press.editor
import android.content.Context
import android.graphics.Point
import android.text.style.URLSpan
import android.view.View
import androidx.appcompat.view.menu.MenuPopupHelper
import androidx.appcompat.widget.PopupMenu
import me.saket.press.shared.localization.strings
import press.extensions.reflect
class UrlPopupMenu(
context: Context,
anchor: View,
url: String
) : PopupMenu(context, anchor) {
init {
val openString = context.strings().editor.open_url
val editString = context.strings().editor.edit_url
menu.add(openString)
menu.add(editString)
setOnMenuItemClickListener { item ->
if (item.title == openString) {
URLSpan(url).onClick(anchor)
}
false
}
}
fun showAt(location: Point) {
val popupHelper = reflect<PopupMenu>().field("mPopup")?.get(this) as? MenuPopupHelper
val tryShowMethod = reflect<MenuPopupHelper>().method("tryShow", Int::class.java, Int::class.java)
if (popupHelper != null && tryShowMethod != null) {
tryShowMethod.invoke(popupHelper, location.x, location.y)
} else {
show()
}
}
}
| 13 | null | 110 | 1,849 | 5f64350ec51402f3e6aeff145cbc35438780a03c | 1,126 | press | Apache License 2.0 |
sdk/examples/fido2demo/src/main/java/com/ibm/security/verifysdk/fido2/demoapp/model/IvCreds.kt | ibm-security-verify | 430,929,749 | false | {"Kotlin": 366062} | /*
* Copyright contributors to the IBM Security Verify FIDO2 Sample App for Android project
*/
package com.ibm.security.verifysdk.fido2.demoapp.model
import kotlinx.serialization.Serializable
@Serializable
data class IvCreds(
val name: String = "ivcreds-name",
val username: String = "ivcreds-username",
val email: String = "ivcreds-email",
val AZN_CRED_PRINCIPAL_NAME: String
)
| 1 | Kotlin | 4 | 1 | fd09a6d0c6586059e5d1cd00451b32dfbfe6e36a | 401 | verify-sdk-android | MIT License |
server/src/main/com/broll/gainea/server/core/cards/impl/play/C_Spion.kt | Rolleander | 253,573,579 | false | {"Kotlin": 426720, "Java": 265966, "HTML": 1714, "CSS": 1069, "JavaScript": 24} | package com.broll.gainea.server.core.cards.impl.play
import com.broll.gainea.server.core.cards.Card
import com.broll.gainea.server.core.utils.getHostileLocations
class C_Spion : Card(8, "Spion", "Platziert einen Soldat auf ein besetztes Land eines anderen Spielers ohne einen Kampf.") {
override val isPlayable: Boolean
get() = true
override fun play() {
val locations = game.getHostileLocations(owner)
placeUnitHandler.placeSoldier(owner, locations.toList())
}
}
| 0 | Kotlin | 1 | 3 | 35593a78a4b81e1758cc9bca23e78fb14b427334 | 503 | Gainea | MIT License |
src/main/kotlin/com/fiap/order/usecases/SearchCustomerUseCase.kt | FIAP-3SOAT-G15 | 794,350,212 | false | {"Kotlin": 146232, "HCL": 4525, "Dockerfile": 283} | package com.fiap.order.usecases
import com.fiap.order.domain.entities.Customer
interface SearchCustomerUseCase {
fun searchByName(name: String): List<Customer>
}
| 1 | Kotlin | 0 | 1 | 0af711519d99107aff1ec93f60d3f2defa47e7d5 | 168 | orders-api | MIT License |
vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileController.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright 2020 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 im.vector.app.features.roommemberprofile
import com.airbnb.epoxy.TypedEpoxyController
import im.vector.app.R
import im.vector.app.core.epoxy.profiles.buildProfileAction
import im.vector.app.core.epoxy.profiles.buildProfileSection
import im.vector.app.core.resources.StringProvider
import im.vector.app.core.ui.list.genericFooterItem
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper
import org.matrix.android.sdk.api.session.room.powerlevels.Role
import javax.inject.Inject
class RoomMemberProfileController @Inject constructor(
private val stringProvider: StringProvider,
private val session: Session
) : TypedEpoxyController<RoomMemberProfileViewState>() {
var callback: Callback? = null
interface Callback {
fun onIgnoreClicked()
fun onTapVerify()
fun onShowDeviceList()
fun onShowDeviceListNoCrossSigning()
fun onOpenDmClicked()
fun onJumpToReadReceiptClicked()
fun onMentionClicked()
fun onEditPowerLevel(currentRole: Role)
fun onKickClicked(isSpace: Boolean)
fun onBanClicked(isSpace: Boolean, isUserBanned: Boolean)
fun onCancelInviteClicked()
fun onInviteClicked()
}
override fun buildModels(data: RoomMemberProfileViewState?) {
if (data?.userMatrixItem?.invoke() == null) {
return
}
if (data.showAsMember) {
buildRoomMemberActions(data)
} else {
buildUserActions(data)
}
}
private fun buildUserActions(state: RoomMemberProfileViewState) {
val ignoreActionTitle = state.buildIgnoreActionTitle() ?: return
// More
buildProfileSection(stringProvider.getString(R.string.room_profile_section_more))
buildProfileAction(
id = "ignore",
title = ignoreActionTitle,
destructive = true,
editable = false,
divider = false,
action = { callback?.onIgnoreClicked() }
)
if (!state.isMine) {
buildProfileAction(
id = "direct",
editable = false,
title = stringProvider.getString(R.string.room_member_open_or_create_dm),
action = { callback?.onOpenDmClicked() }
)
}
}
private fun buildRoomMemberActions(state: RoomMemberProfileViewState) {
if (!state.isSpace) {
buildSecuritySection(state)
}
buildMoreSection(state)
buildAdminSection(state)
}
private fun buildSecuritySection(state: RoomMemberProfileViewState) {
// Security
buildProfileSection(stringProvider.getString(R.string.room_profile_section_security))
val host = this
if (state.isRoomEncrypted) {
if (state.userMXCrossSigningInfo != null) {
// Cross signing is enabled for this user
if (state.userMXCrossSigningInfo.isTrusted()) {
// User is trusted
val icon = if (state.allDevicesAreTrusted) {
R.drawable.ic_shield_trusted
} else {
R.drawable.ic_shield_warning
}
val titleRes = if (state.allDevicesAreTrusted) {
R.string.verification_profile_verified
} else {
R.string.verification_profile_warning
}
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(titleRes),
editable = true,
icon = icon,
tintIcon = false,
divider = false,
action = { callback?.onShowDeviceList() }
)
} else {
// Not trusted, propose to verify
if (!state.isMine) {
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.verification_profile_verify),
editable = true,
icon = R.drawable.ic_shield_black,
divider = false,
action = { callback?.onTapVerify() }
)
} else {
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.room_profile_section_security_learn_more),
editable = false,
divider = false,
action = { callback?.onShowDeviceListNoCrossSigning() }
)
}
genericFooterItem {
id("verify_footer")
text(host.stringProvider.getString(R.string.room_profile_encrypted_subtitle))
centered(false)
}
}
} else {
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.room_profile_section_security_learn_more),
editable = false,
divider = false,
subtitle = stringProvider.getString(R.string.room_profile_encrypted_subtitle),
action = { callback?.onShowDeviceListNoCrossSigning() }
)
}
} else {
genericFooterItem {
id("verify_footer_not_encrypted")
text(host.stringProvider.getString(R.string.room_profile_not_encrypted_subtitle))
centered(false)
}
}
}
private fun buildMoreSection(state: RoomMemberProfileViewState) {
// More
if (!state.isMine) {
val membership = state.asyncMembership() ?: return
buildProfileSection(stringProvider.getString(R.string.room_profile_section_more))
buildProfileAction(
id = "direct",
editable = false,
title = stringProvider.getString(R.string.room_member_open_or_create_dm),
action = { callback?.onOpenDmClicked() }
)
if (!state.isSpace && state.hasReadReceipt) {
buildProfileAction(
id = "read_receipt",
editable = false,
title = stringProvider.getString(R.string.room_member_jump_to_read_receipt),
action = { callback?.onJumpToReadReceiptClicked() }
)
}
val ignoreActionTitle = state.buildIgnoreActionTitle()
if (!state.isSpace) {
buildProfileAction(
id = "mention",
title = stringProvider.getString(R.string.room_participants_action_mention),
editable = false,
divider = ignoreActionTitle != null,
action = { callback?.onMentionClicked() }
)
}
val canInvite = state.actionPermissions.canInvite
if (canInvite && (membership == Membership.LEAVE || membership == Membership.KNOCK)) {
buildProfileAction(
id = "invite",
title = stringProvider.getString(R.string.room_participants_action_invite),
destructive = false,
editable = false,
divider = ignoreActionTitle != null,
action = { callback?.onInviteClicked() }
)
}
if (ignoreActionTitle != null) {
buildProfileAction(
id = "ignore",
title = ignoreActionTitle,
destructive = true,
editable = false,
divider = false,
action = { callback?.onIgnoreClicked() }
)
}
}
}
private fun buildAdminSection(state: RoomMemberProfileViewState) {
val powerLevelsContent = state.powerLevelsContent ?: return
val powerLevelsStr = state.userPowerLevelString() ?: return
val powerLevelsHelper = PowerLevelsHelper(powerLevelsContent)
val userPowerLevel = powerLevelsHelper.getUserRole(state.userId)
val myPowerLevel = powerLevelsHelper.getUserRole(session.myUserId)
if ((!state.isMine && myPowerLevel <= userPowerLevel)) {
return
}
val membership = state.asyncMembership() ?: return
val canKick = !state.isMine && state.actionPermissions.canKick
val canBan = !state.isMine && state.actionPermissions.canBan
val canEditPowerLevel = state.actionPermissions.canEditPowerLevel
if (canKick || canBan || canEditPowerLevel) {
buildProfileSection(stringProvider.getString(R.string.room_profile_section_admin))
}
if (canEditPowerLevel) {
buildProfileAction(
id = "edit_power_level",
editable = true,
title = stringProvider.getString(R.string.power_level_title),
subtitle = powerLevelsStr,
divider = canKick || canBan,
editableRes = R.drawable.ic_edit,
action = { callback?.onEditPowerLevel(userPowerLevel) }
)
}
if (canKick) {
when (membership) {
Membership.JOIN -> {
buildProfileAction(
id = "kick",
editable = false,
divider = canBan,
destructive = true,
title = stringProvider.getString(R.string.room_participants_action_kick),
action = { callback?.onKickClicked(state.isSpace) }
)
}
Membership.INVITE -> {
buildProfileAction(
id = "cancel_invite",
title = stringProvider.getString(R.string.room_participants_action_cancel_invite),
divider = canBan,
destructive = true,
editable = false,
action = { callback?.onCancelInviteClicked() }
)
}
else -> Unit
}
}
if (canBan) {
val banActionTitle = if (membership == Membership.BAN) {
stringProvider.getString(R.string.room_participants_action_unban)
} else {
stringProvider.getString(R.string.room_participants_action_ban)
}
buildProfileAction(
id = "ban",
editable = false,
destructive = true,
title = banActionTitle,
action = { callback?.onBanClicked(state.isSpace, membership == Membership.BAN) }
)
}
}
private fun RoomMemberProfileViewState.buildIgnoreActionTitle(): String? {
val isIgnored = isIgnored() ?: return null
return if (isIgnored) {
stringProvider.getString(R.string.unignore)
} else {
stringProvider.getString(R.string.ignore)
}
}
}
| 96 | null | 7 | 9 | a2c060c687b0aa69af681138c5788d6933d19860 | 12,621 | tchap-android | Apache License 2.0 |
compose/ui/ui/src/test/kotlin/androidx/compose/ui/graphics/GraphicsLayerScopeTest.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.graphics
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class GraphicsLayerScopeTest {
@Test
fun initialValuesAreCorrect() {
GraphicsLayerScope().assertCorrectDefaultValuesAreCorrect()
}
@Test
fun resetValuesAreCorrect() {
val scope = GraphicsLayerScope() as ReusableGraphicsLayerScope
scope.scaleX = 2f
scope.scaleY = 2f
scope.alpha = 0.5f
scope.translationX = 5f
scope.translationY = 5f
scope.shadowElevation = 5f
scope.rotationX = 5f
scope.rotationY = 5f
scope.rotationZ = 5f
scope.cameraDistance = 5f
scope.transformOrigin = TransformOrigin(0.7f, 0.1f)
scope.shape = object : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
) = Outline.Rectangle(size.toRect())
}
scope.clip = true
scope.size = Size(100f, 200f)
scope.reset()
scope.assertCorrectDefaultValuesAreCorrect()
}
@Test
fun testDpPixelConversions() {
val scope = GraphicsLayerScope() as ReusableGraphicsLayerScope
scope.graphicsDensity = Density(2.0f, 3.0f)
with(scope) {
assertEquals(4.0f, 2f.dp.toPx())
assertEquals(6.0f, 3f.dp.toSp().toPx())
}
}
@Test
fun testGraphicsLayerSize() {
val scope = GraphicsLayerScope() as ReusableGraphicsLayerScope
scope.size = Size(2560f, 1400f)
with(scope) {
assertEquals(2560f, size.width)
assertEquals(1400f, size.height)
}
}
fun GraphicsLayerScope.assertCorrectDefaultValuesAreCorrect() {
assertThat(scaleX).isEqualTo(1f)
assertThat(scaleY).isEqualTo(1f)
assertThat(alpha).isEqualTo(1f)
assertThat(translationX).isEqualTo(0f)
assertThat(translationY).isEqualTo(0f)
assertThat(shadowElevation).isEqualTo(0f)
assertThat(rotationX).isEqualTo(0f)
assertThat(rotationY).isEqualTo(0f)
assertThat(rotationZ).isEqualTo(0f)
assertThat(cameraDistance).isEqualTo(DefaultCameraDistance)
assertThat(transformOrigin).isEqualTo(TransformOrigin.Center)
assertThat(shape).isEqualTo(RectangleShape)
assertThat(clip).isEqualTo(false)
assertThat(size).isEqualTo(Size.Unspecified)
}
}
| 29 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,426 | androidx | Apache License 2.0 |
app/src/main/java/com/umang/reminderapp/ui/components/ToDoItemCards/ToDoItemCardClicked.kt | umangSharmacs | 805,851,021 | false | {"Kotlin": 112570} | package com.umang.reminderapp.ui.components.ToDoItemCards
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.ElevatedAssistChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.umang.reminderapp.data.classes.TodoItem
import com.umang.reminderapp.ui.theme.ReminderAppTheme
@Composable
fun ToDoItemCardClicked(
modifier: Modifier = Modifier,
item: TodoItem,
onClick: () -> Unit,
onEdit: () -> Unit,
onDelete: () -> Unit
) {
OutlinedCard(
modifier = modifier,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
),
shape = MaterialTheme.shapes.large,
onClick = onClick
) {
Column(){
// TOP ROW
Row(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
//Checkbox
Checkbox(
modifier = Modifier.weight(1f),
checked = item.completed,
colors = CheckboxDefaults.colors(
checkedColor = MaterialTheme.colorScheme.primary,
checkmarkColor = MaterialTheme.colorScheme.onPrimary
),
onCheckedChange = { item.completed != item.completed }
)
// TITLE
Text(
modifier = Modifier.weight(4f),
text = item.title,
// color = MaterialTheme.colorScheme.onSecondaryContainer
)
// DUE DATE
Column(modifier = Modifier.weight(2f)) {
Text(
modifier = Modifier.padding(start = 5.dp, end = 5.dp),
text = "Due By",
// color = MaterialTheme.colorScheme.onSecondaryContainer
)
Text(text = item.dueDate)
}
}
// TAGS
Row(){
Spacer(modifier = Modifier.weight(1f))
// Tags row
LazyRow(
contentPadding = PaddingValues(
top = 16.dp,
end = 12.dp,
bottom = 16.dp
),
modifier = Modifier.weight(6f)
) {
items(item.tags.size) { index ->
AssistChip(
colors = AssistChipDefaults.assistChipColors(
containerColor = MaterialTheme.colorScheme.background,
labelColor = MaterialTheme.colorScheme.onBackground
),
modifier = Modifier.padding(2.dp),
onClick = { },
label = { Text(text = item.tags[index]) }
)
}
}
}
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer,
contentColor = MaterialTheme.colorScheme.onTertiaryContainer,
),
shape = MaterialTheme.shapes.large
){
// DESCRIPTION
Row(modifier=Modifier.padding(5.dp)) {
Spacer(modifier = Modifier.weight(1f))
Text(
modifier = Modifier
.padding(end = 15.dp, bottom = 15.dp)
.weight(6f),
text = item.description
)
}
// EDIT AND DELETE
Row(modifier = modifier
.fillMaxWidth()
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
){
Spacer(modifier = Modifier.weight(1f))
Row(modifier = Modifier.weight(6f)) {
// EDIT
ElevatedAssistChip(
modifier = Modifier.padding(5.dp),
onClick = onEdit ,
leadingIcon = {Icon(imageVector = Icons.Default.Edit, contentDescription = "Edit")},
label = { Text(text = "Edit") }
)
// DELETE
ElevatedAssistChip(
modifier = Modifier.padding(5.dp),
onClick = onDelete ,
leadingIcon = {Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")},
label = { Text(text = "Delete") }
)
}
}
}
}
}
}
@Preview
@Composable
fun ToDoItemCardClickedPreview() {
val item = TodoItem()
item.title = "TitleTitleTitleTitleTitleTitleTitleTitle"
item.tags = listOf("tag1", "tag2")
item.description = "Hello World. THis is a test description to see the result of the text overflow"
ReminderAppTheme {
ToDoItemCardClicked(item = item, onClick = { }, onEdit = {}, onDelete = {})
}
} | 0 | Kotlin | 0 | 0 | 76a0ebe9c27a0340172fed34acfd35fe90115d0f | 6,781 | ReminderApp | MIT License |
scale/src/commonMain/kotlin/io/data2viz/scale/Quantize.kt | data2viz | 89,368,762 | false | null | /*
* Copyright (c) 2018-2019. data2viz sàrl.
*
* 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.data2viz.scale
/**
* Quantize scales are similar to linear scales, except they use a discrete rather than continuous range.
*
* The continuous input domain is divided into uniform segments based on the number of values
* in (i.e., the cardinality of) the output range.
* Each range value y can be expressed as a quantized linear function of the domain value x: y = m round(x) + b.
*/
public class QuantizeScale<R> internal constructor() : Scale<Double, R>, StrictlyContinuousDomain<Double>, DiscreteRange<R> {
private val quantizedDomain:MutableList<Double> = mutableListOf(.5)
// copy the value (no binding intended)
override var range: List<R> = listOf()
get() = field.toList()
set(value) {
field = value.toList()
rescale()
}
override var domain: StrictlyContinuous<Double> = intervalOf(0.0, 1.0)
get() = field
set(value) {
field = value
rescale()
}
private fun rescale() {
quantizedDomain.clear()
val size = range.size - 1
for(index in 0 until size) {
val element = ((index + 1) * domain.end - (index - size) * domain.start) / (size + 1)
quantizedDomain.add(element)
}
}
override fun invoke(domainValue: Double): R {
return range[bisectRight(quantizedDomain, domainValue, naturalOrder(), 0, range.size - 1)]
}
public fun invertExtent(rangeValue: R): List<Double> {
val i = range.indexOf(rangeValue)
val size = range.size - 1
return when {
i < 0 -> listOf(Double.NaN, Double.NaN)
i < 1 -> listOf(domain.start, quantizedDomain.first())
i >= size -> listOf(quantizedDomain[size - 1], domain.end)
else -> listOf(quantizedDomain[i - 1], quantizedDomain[i])
}
}
override fun copy(): QuantizeScale<R> {
return QuantizeScale<R>().also{
it.domain = domain
it.range = range
it.rescale()
}
}
}
| 80 | null | 29 | 400 | bc4ed872c526264727f868f5127e48462301dbf8 | 2,673 | data2viz | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/service/DeliverySessionsServiceTest.kt | ministryofjustice | 312,544,431 | false | null | package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.service
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.eq
import org.mockito.kotlin.firstValue
import org.mockito.kotlin.isNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.http.HttpStatus
import org.springframework.web.server.ResponseStatusException
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.events.ActionPlanAppointmentEventPublisher
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AppointmentDeliveryType
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AppointmentSessionType
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AppointmentType.SERVICE_DELIVERY
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.Attended
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AuthUser
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.DeliverySession
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.ActionPlanRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.AppointmentRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.AuthUserRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.DeliverySessionRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ActionPlanFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.AuthUserFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.DeliverySessionFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ReferralFactory
import java.time.OffsetDateTime
import java.util.UUID
import javax.persistence.EntityExistsException
import javax.persistence.EntityNotFoundException
internal class DeliverySessionsServiceTest {
private val actionPlanRepository: ActionPlanRepository = mock()
private val deliverySessionRepository: DeliverySessionRepository = mock()
private val authUserRepository: AuthUserRepository = mock()
private val actionPlanAppointmentEventPublisher: ActionPlanAppointmentEventPublisher = mock()
private val communityAPIBookingService: CommunityAPIBookingService = mock()
private val appointmentRepository: AppointmentRepository = mock()
private val appointmentService: AppointmentService = mock()
private val actionPlanFactory = ActionPlanFactory()
private val deliverySessionFactory = DeliverySessionFactory()
private val authUserFactory = AuthUserFactory()
private val referralFactory = ReferralFactory()
private val deliverySessionsService = DeliverySessionService(
deliverySessionRepository, actionPlanRepository,
authUserRepository, actionPlanAppointmentEventPublisher,
communityAPIBookingService, appointmentService, appointmentRepository,
)
private fun createActor(userName: String = "action_plan_session_test"): AuthUser =
authUserFactory.create(userName = userName)
.also { whenever(authUserRepository.save(it)).thenReturn(it) }
@Test
fun `create unscheduled sessions creates one for each action plan session`() {
val actionPlan = actionPlanFactory.create(numberOfSessions = 3)
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(eq(actionPlan.referral.id), any())).thenReturn(null)
whenever(authUserRepository.save(actionPlan.createdBy)).thenReturn(actionPlan.createdBy)
whenever(deliverySessionRepository.save(any())).thenAnswer { it.arguments[0] }
deliverySessionsService.createUnscheduledSessionsForActionPlan(actionPlan)
verify(deliverySessionRepository, times(3)).save(any())
}
@Test
fun `create unscheduled sessions where there is a previously approved action plan`() {
val newActionPlanId = UUID.randomUUID()
val referral = referralFactory.createSent()
val previouslyApprovedActionPlan = actionPlanFactory.createApproved(numberOfSessions = 2, referral = referral)
val newActionPlan = actionPlanFactory.createSubmitted(id = newActionPlanId, numberOfSessions = 3, referral = referral)
referral.actionPlans = mutableListOf(previouslyApprovedActionPlan, newActionPlan)
whenever(deliverySessionRepository.findAllByActionPlanId(any())).thenReturn(listOf(deliverySessionFactory.createAttended(), deliverySessionFactory.createAttended()))
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(eq(newActionPlan.id), any())).thenReturn(null)
whenever(authUserRepository.save(newActionPlan.createdBy)).thenReturn(newActionPlan.createdBy)
whenever(deliverySessionRepository.save(any())).thenAnswer { it.arguments[0] }
deliverySessionsService.createUnscheduledSessionsForActionPlan(newActionPlan)
verify(deliverySessionRepository, times(1)).save(any())
}
@Test
fun `create unscheduled sessions throws exception if session already exists`() {
val actionPlan = actionPlanFactory.create(numberOfSessions = 1)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlan.id, 1))
.thenReturn(deliverySessionFactory.createUnscheduled(sessionNumber = 1))
assertThrows(EntityExistsException::class.java) {
deliverySessionsService.createUnscheduledSessionsForActionPlan(actionPlan)
}
}
@Test
fun `updates a session appointment for an unscheduled session`() {
val session = deliverySessionFactory.createUnscheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val appointmentTime = OffsetDateTime.now().plusHours(1)
val durationInMinutes = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(appointmentTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(durationInMinutes)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isEqualTo("scheduler")
assertThat(updatedSession.currentAppointment?.attended).isNull()
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isNull()
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedBy).isNull()
}
@Test
fun `create session appointment for a historic appointment`() {
val session = deliverySessionFactory.createUnscheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null,
null,
Attended.YES,
"additional information",
false,
"description"
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(updatedSession)
verify(actionPlanAppointmentEventPublisher).behaviourRecordedEvent(updatedSession)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(updatedSession)
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(appointmentTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(durationInMinutes)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isEqualTo("scheduler")
assertThat(updatedSession.currentAppointment?.attended).isEqualTo(Attended.YES)
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isEqualTo("additional information")
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isEqualTo(false)
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isEqualTo("description")
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNotNull
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedBy).isNotNull
}
@Test
fun `updates session appointment for a historic appointment non attended`() {
val session = deliverySessionFactory.createUnscheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null,
null,
Attended.NO,
"additional information"
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(appointmentTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(durationInMinutes)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isEqualTo("scheduler")
assertThat(updatedSession.currentAppointment?.attended).isEqualTo(Attended.NO)
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isEqualTo("additional information")
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isEqualTo(user)
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedBy).isEqualTo(user)
}
@Test
fun `updates a session appointment for a scheduled session`() {
val originalTime = OffsetDateTime.now()
val originalDuration = 60
val session = deliverySessionFactory.createScheduled(appointmentTime = originalTime, durationInMinutes = originalDuration)
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("re-scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val newTime = OffsetDateTime.now()
val newDuration = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
newTime,
newDuration,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(newTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(newDuration)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isNotEqualTo("re-scheduler")
assertThat(updatedSession.currentAppointment?.attended).isNull()
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isNull()
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNull()
}
@Test
fun `makes a booking when a session is updated`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val referral = session.referral
val createdByUser = createActor("scheduler")
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
whenever(
communityAPIBookingService.book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
null
)
).thenReturn(999L)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber))
.thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
createdByUser,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
assertThat(updatedSession).isEqualTo(session)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
verify(communityAPIBookingService).book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
null
)
verify(appointmentRepository, times(1)).saveAndFlush(
ArgumentMatchers.argThat {
it.deliusAppointmentId == 999L
}
)
}
@Test
fun `does not make a booking when a session is updated because timings aren't present`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val referral = session.referral
val createdByUser = createActor("scheduler")
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
whenever(
communityAPIBookingService.book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
null
)
).thenReturn(null)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
createdByUser,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
verify(appointmentRepository, times(1)).saveAndFlush(
ArgumentMatchers.argThat {
it.deliusAppointmentId == null
}
)
}
@Test
fun `updates a session and throws exception if it not exists`() {
val actionPlanId = UUID.randomUUID()
val sessionNumber = 1
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(null)
val exception = assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
authUserFactory.create(),
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
}
assertThat(exception.message).isEqualTo("Action plan session not found [actionPlanId=$actionPlanId, sessionNumber=$sessionNumber]")
}
@Test
fun `gets a session`() {
val time = OffsetDateTime.now()
val duration = 500
val session = deliverySessionFactory.createScheduled(sessionNumber = 1, appointmentTime = time, durationInMinutes = duration)
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(session.referral.id, 1)).thenReturn(session)
val actualSession = deliverySessionsService.getSession(session.referral.id, 1)
assertThat(actualSession.sessionNumber).isEqualTo(1)
assertThat(actualSession.currentAppointment?.appointmentTime).isEqualTo(time)
assertThat(actualSession.currentAppointment?.durationInMinutes).isEqualTo(duration)
}
@Test
fun `gets a session and throws exception if it not exists`() {
val referralId = UUID.randomUUID()
val sessionNumber = 1
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(referralId, sessionNumber)).thenReturn(null)
val exception = assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.getSession(referralId, sessionNumber)
}
assertThat(exception.message).isEqualTo("Action plan session not found [referralId=$referralId, sessionNumber=$sessionNumber]")
}
@Test
fun `gets all sessions for an action plan`() {
val time = OffsetDateTime.now()
val duration = 500
val session = deliverySessionFactory.createScheduled(sessionNumber = 1, appointmentTime = time, durationInMinutes = duration)
val referralId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByReferralId(referralId)).thenReturn(listOf(session))
val sessions = deliverySessionsService.getSessions(referralId)
assertThat(sessions.first().sessionNumber).isEqualTo(1)
assertThat(sessions.first().currentAppointment?.appointmentTime).isEqualTo(time)
assertThat(sessions.first().currentAppointment?.durationInMinutes).isEqualTo(duration)
}
@Test
fun `update session with attendance`() {
val attended = Attended.YES
val additionalInformation = "extra info"
val existingSession = deliverySessionFactory.createScheduled(sessionNumber = 1)
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1))
.thenReturn(existingSession)
whenever(deliverySessionRepository.save(any())).thenReturn(existingSession)
val actor = createActor("attendance_submitter")
val savedSession = deliverySessionsService.recordAppointmentAttendance(actor, actionPlanId, 1, attended, additionalInformation)
val argumentCaptor: ArgumentCaptor<DeliverySession> = ArgumentCaptor.forClass(DeliverySession::class.java)
// verify(appointmentEventPublisher).appointmentNotAttendedEvent(existingSession)
verify(deliverySessionRepository).save(argumentCaptor.capture())
assertThat(argumentCaptor.firstValue.currentAppointment?.attended).isEqualTo(attended)
assertThat(argumentCaptor.firstValue.currentAppointment?.additionalAttendanceInformation).isEqualTo(additionalInformation)
assertThat(argumentCaptor.firstValue.currentAppointment?.attendanceSubmittedAt).isNotNull
assertThat(argumentCaptor.firstValue.currentAppointment?.attendanceSubmittedBy?.userName).isEqualTo("attendance_submitter")
assertThat(savedSession).isNotNull
}
@Test
fun `update session with attendance - no session found`() {
val actionPlanId = UUID.randomUUID()
val sessionNumber = 1
val attended = Attended.YES
val additionalInformation = "extra info"
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber))
.thenReturn(null)
val actor = createActor()
val exception = assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.recordAppointmentAttendance(actor, actionPlanId, 1, attended, additionalInformation)
}
assertThat(exception.message).isEqualTo("Action plan session not found [actionPlanId=$actionPlanId, sessionNumber=$sessionNumber]")
}
@Test
fun `updating session behaviour sets relevant fields`() {
val actionPlanId = UUID.randomUUID()
val session = deliverySessionFactory.createScheduled()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(any(), any())).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val actor = createActor("behaviour_submitter")
val updatedSession = deliverySessionsService.recordBehaviour(actor, actionPlanId, 1, "not good", false)
verify(deliverySessionRepository, times(1)).save(session)
assertThat(updatedSession).isSameAs(session)
assertThat(session.currentAppointment?.attendanceBehaviour).isEqualTo("not good")
assertThat(session.currentAppointment?.notifyPPOfAttendanceBehaviour).isFalse
assertThat(session.currentAppointment?.attendanceBehaviourSubmittedAt).isNotNull
assertThat(session.currentAppointment?.attendanceBehaviourSubmittedBy?.userName).isEqualTo("behaviour_submitter")
}
@Test
fun `updating session behaviour for missing session throws error`() {
val actor = createActor()
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(any(), any())).thenReturn(null)
assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.recordBehaviour(actor, UUID.randomUUID(), 1, "not good", false)
}
}
@Test
fun `session feedback cant be submitted more than once`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val actor = createActor()
deliverySessionsService.recordAppointmentAttendance(actor, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.recordBehaviour(actor, actionPlanId, 1, "bad", false)
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, actor)
val exception = assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, actor)
}
assertThat(exception.status).isEqualTo(HttpStatus.CONFLICT)
}
@Test
fun `session feedback can't be submitted without attendance`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val actor = createActor()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
deliverySessionsService.recordBehaviour(actor, actionPlanId, 1, "bad", false)
val exception = assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, actor)
}
assertThat(exception.status).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY)
}
@Test
fun `session feedback can be submitted and stores time and actor`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val user = createActor()
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.recordBehaviour(user, actionPlanId, 1, "bad", true)
val submitter = createActor("test-submitter")
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, submitter)
val sessionCaptor = argumentCaptor<DeliverySession>()
verify(deliverySessionRepository, atLeastOnce()).save(sessionCaptor.capture())
sessionCaptor.allValues.forEach {
if (it == sessionCaptor.lastValue) {
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedAt != null)
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedBy?.userName).isEqualTo("test-submitter")
} else {
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedAt == null)
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedBy == null)
}
}
}
@Test
fun `session feedback emits application events`() {
val user = createActor()
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.recordBehaviour(user, actionPlanId, 1, "bad", true)
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, session.referral.createdBy)
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).behaviourRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(session)
}
@Test
fun `attendance can't be updated once session feedback has been submitted`() {
val user = createActor()
val session = deliverySessionFactory.createAttended()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
}
}
@Test
fun `behaviour can't be updated once session feedback has been submitted`() {
val user = createActor()
val session = deliverySessionFactory.createAttended()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.recordBehaviour(user, actionPlanId, 1, "bad", false)
}
}
@Test
fun `session feedback can be submitted when session not attended`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val user = createActor()
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.NO, "")
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, user)
verify(deliverySessionRepository, atLeastOnce()).save(session)
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(session)
}
@Test
fun `session feedback can be submitted when session is attended and there is no behaviour feedback`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val user = createActor()
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, user)
verify(deliverySessionRepository, atLeastOnce()).save(session)
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(session)
}
@Test
fun `makes a booking with delius office location`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val referral = session.referral
val createdByUser = session.referral.createdBy
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
val npsOfficeCode = "CRS0001"
whenever(
communityAPIBookingService.book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
npsOfficeCode
)
).thenReturn(999L)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(
session
)
whenever(authUserRepository.save(createdByUser)).thenReturn(createdByUser)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
createdByUser,
AppointmentDeliveryType.IN_PERSON_MEETING_PROBATION_OFFICE,
AppointmentSessionType.ONE_TO_ONE,
null,
npsOfficeCode
)
assertThat(updatedSession).isEqualTo(session)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.IN_PERSON_MEETING_PROBATION_OFFICE), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), eq(npsOfficeCode))
verify(communityAPIBookingService).book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
npsOfficeCode
)
verify(appointmentRepository, times(1)).saveAndFlush(
ArgumentMatchers.argThat {
it.deliusAppointmentId == 999L
}
)
}
}
| 7 | null | 1 | 2 | e77060a93c6736b5bf9032b3c917207d6b809568 | 32,663 | hmpps-interventions-service | MIT License |
mobile_app1/module957/src/main/java/module957packageKt0/Foo446.kt | uber-common | 294,831,672 | false | null | package module1248packageKt0;
annotation class Foo446Fancy
@Foo446Fancy
class Foo446 {
fun foo0(){
module1248packageKt0.Foo445().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 329 | android-build-eval | Apache License 2.0 |
mobile_app1/module957/src/main/java/module957packageKt0/Foo446.kt | uber-common | 294,831,672 | false | null | package module1248packageKt0;
annotation class Foo446Fancy
@Foo446Fancy
class Foo446 {
fun foo0(){
module1248packageKt0.Foo445().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 329 | android-build-eval | Apache License 2.0 |
app/src/main/java/com/example/jetpackcomposesample/presentation/RecipeApplication.kt | vengateshm | 325,912,870 | false | {"Kotlin": 29422} | package com.example.jetpackcomposesample.presentation
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class RecipeApplication : Application() {
} | 0 | Kotlin | 0 | 1 | 19aa787692ea2be6a37a447597f3b37a15294840 | 188 | android_jetpack_compose_MVVM | Apache License 2.0 |
komapper-core/src/main/kotlin/org/komapper/core/dsl/SchemaDsl.kt | komapper | 349,909,214 | false | null | package org.komapper.core.dsl
import org.komapper.core.dsl.context.SchemaContext
import org.komapper.core.dsl.metamodel.EntityMetamodel
import org.komapper.core.dsl.query.SchemaCreateQuery
import org.komapper.core.dsl.query.SchemaCreateQueryImpl
import org.komapper.core.dsl.query.SchemaDropAllQuery
import org.komapper.core.dsl.query.SchemaDropAllQueryImpl
import org.komapper.core.dsl.query.SchemaDropQuery
import org.komapper.core.dsl.query.SchemaDropQueryImpl
/**
* The entry point for constructing schema related queries.
*/
object SchemaDsl : Dsl {
/**
* Creates a query for creating tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun create(metamodels: List<EntityMetamodel<*, *, *>>): SchemaCreateQuery {
return SchemaCreateQueryImpl(SchemaContext(metamodels))
}
/**
* Creates a query for creating tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun create(vararg metamodels: EntityMetamodel<*, *, *>): SchemaCreateQuery {
return create(metamodels.toList())
}
/**
* Creates a query for dropping tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun drop(metamodels: List<EntityMetamodel<*, *, *>>): SchemaDropQuery {
return SchemaDropQueryImpl(SchemaContext(metamodels))
}
/**
* Creates a query for dropping tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun drop(vararg metamodels: EntityMetamodel<*, *, *>): SchemaDropQuery {
return drop(metamodels.toList())
}
/**
* Creates a query for dropping all tables and their associated constraints.
*/
fun dropAll(): SchemaDropAllQuery {
return SchemaDropAllQueryImpl(SchemaContext())
}
}
| 1 | Kotlin | 0 | 20 | 2a8827d7c410a5366d875578a635b02dc176e989 | 1,900 | komapper | Apache License 2.0 |
qrose-oned/src/commonMain/kotlin/io/github/alexzhirkevich/qrose/oned/Code128Painter.kt | alexzhirkevich | 704,899,229 | false | {"Kotlin": 199162, "HTML": 564} | package io.github.alexzhirkevich.qrose.oned
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.painter.Painter
/**
* Code 128 barcode painter
*
* @param brush code brush
* @param compact Specifies whether to use compact mode for Code-128 code.
* This can yield slightly smaller bar codes. This option and [forceCodeSet] are mutually exclusive.
* @param forceCodeSet Forces which encoding will be used. This option and [compact] are mutually exclusive.
* @param onError called when input content is invalid.
* @param builder build code path using painter size and encoded boolean list.
*
* @see Code128Painter
* */
@Composable
internal fun rememberCode128Painter(
data: String,
brush: Brush = SolidColor(Color.Black),
compact : Boolean = true,
forceCodeSet : Code128Type? = null,
onError : (Throwable) -> Painter = { throw it },
builder : BarcodePathBuilder = ::defaultBarcodeBuilder
) : Painter {
val updatedBuilder by rememberUpdatedState(builder)
return remember(data, brush, forceCodeSet) {
runCatching {
Code128Painter(
data = data,
brush = brush,
compact = compact,
codeSet = forceCodeSet,
builder = { size, code ->
updatedBuilder(size, code)
},
)
}.getOrElse(onError)
}
}
enum class Code128Type(internal val v: Int) {
A(Code128Encoder.CODE_CODE_A),
B(Code128Encoder.CODE_CODE_B),
C(Code128Encoder.CODE_CODE_C)
}
@Stable
fun Code128Painter(
data : String,
brush: Brush = SolidColor(Color.Black),
compact : Boolean = true,
codeSet : Code128Type? = null,
builder : BarcodePathBuilder= ::defaultBarcodeBuilder
) = BarcodePainter(
code = Code128Encoder.encode(data, compact, codeSet),
brush = brush,
builder = builder
)
| 1 | Kotlin | 4 | 219 | 7dca5a15ba9b9eaf507a78b9e0acb3a742022679 | 2,209 | qrose | MIT License |
src/main/kotlin/dev/zacsweers/BlogActivity.kt | ZacSweers | 288,008,412 | false | null | package dev.zacsweers
import com.slack.eithernet.ApiResult
import com.slack.eithernet.ApiResultCallAdapterFactory
import com.slack.eithernet.ApiResultConverterFactory
import com.tickaroo.tikxml.TikXml
import com.tickaroo.tikxml.TypeConverter
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.converter.htmlescape.HtmlEscapeStringConverter
import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.create
import retrofit2.http.GET
import java.time.Instant
import java.time.format.DateTimeFormatter
// https://www.zacsweers.dev/rss/
internal interface BlogApi {
@GET("/rss")
suspend fun main(): ApiResult<Feed, Unit>
companion object {
fun create(client: OkHttpClient, tikXml: TikXml): BlogApi {
return Retrofit.Builder()
.baseUrl("https://www.zacsweers.dev")
.validateEagerly(true)
.client(client)
.addCallAdapterFactory(ApiResultCallAdapterFactory)
.addConverterFactory(ApiResultConverterFactory)
.addConverterFactory(TikXmlConverterFactory.create(tikXml))
.build()
.create()
}
}
}
@Xml
data class Feed(
@Element
val channel: Channel
)
@Xml
data class Channel(
@Element
val itemList: List<Entry>,
@PropertyElement
val title: String? = null,
@PropertyElement
val description: String? = null
)
@Xml(name = "item")
data class Entry(
@PropertyElement(converter = HtmlEscapeStringConverter::class)
val title: String,
@PropertyElement
val link: String,
@PropertyElement(converter = InstantTypeConverter::class)
val pubDate: Instant
)
internal class InstantTypeConverter : TypeConverter<Instant> {
override fun write(value: Instant): String = TODO("Unsupported")
override fun read(value: String): Instant {
return Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(value))
}
}
| 4 | Kotlin | 1 | 15 | fab8139be563d2301749d596dd687bfca945ec48 | 2,001 | ZacSweers | Apache License 2.0 |
Corona-Warn-App/src/main/java/be/sciensano/coronalert/service/diagnosiskey/DiagnosisKeyService.kt | ici-be | 310,042,293 | true | {"Kotlin": 979464, "HTML": 189219} | package be.sciensano.coronalert.service.diagnosiskey
import KeyExportFormat
import be.sciensano.coronalert.storage.k
import be.sciensano.coronalert.storage.r0
import be.sciensano.coronalert.storage.resultChannel
import be.sciensano.coronalert.storage.t0
import be.sciensano.coronalert.storage.t3
import de.rki.coronawarnapp.exception.DiagnosisKeyRetrievalException
import de.rki.coronawarnapp.exception.DiagnosisKeySubmissionException
import de.rki.coronawarnapp.http.WebRequestBuilder
import de.rki.coronawarnapp.storage.LocalData
import timber.log.Timber
/**
* The Diagnosis Key Service is used to interact with the Server to submit and retrieve keys through
* predefined structures.
*
* @throws DiagnosisKeyRetrievalException An Exception thrown when an error occurs during Key Retrieval from the Server
* @throws DiagnosisKeySubmissionException An Exception thrown when an error occurs during Key Reporting to the Server
*/
object DiagnosisKeyService {
private val TAG: String? = DiagnosisKeyService::class.simpleName
/**
* Asynchronously submits keys to the Server with the WebRequestBuilder by retrieving
* keys out of the Google API.
*
*
* @throws de.rki.coronawarnapp.exception.DiagnosisKeySubmissionException An Exception thrown when an error occurs during Key Reporting to the Server
*
* @param keysToReport - KeyList in the Server Format to submit to the Server
*/
suspend fun asyncSubmitKeys(
keysToReport: List<Pair<KeyExportFormat.TemporaryExposureKey, String>>
) {
Timber.d("Diagnosis Keys will be submitted.")
val k = LocalData.k() ?: throw IllegalStateException()
val r0 = LocalData.r0() ?: throw IllegalStateException()
val t0 = LocalData.t0() ?: throw IllegalStateException()
val t3 = LocalData.t3() ?: throw IllegalStateException()
val resultChannel = LocalData.resultChannel()
if (resultChannel == -1) {
throw IllegalStateException()
}
WebRequestBuilder.getInstance().beAsyncSubmitKeysToServer(
k, r0, t0, t3, resultChannel,
keysToReport
)
}
}
| 0 | null | 0 | 0 | 652f37467a375e0857437a0615ecd6e018c9ed78 | 2,160 | cwa-app-android | Apache License 2.0 |
app/src/main/java/com/kotlin/sacalabici/data/models/medals/MedalBase.kt | Saca-la-Bici | 849,110,267 | false | {"Kotlin": 595596} | package com.kotlin.sacalabici.data.models.medals
import com.google.gson.annotations.SerializedName
data class MedalBase(
@SerializedName("_id") val id: String,
@SerializedName("nombre") val name: String,
@SerializedName("imagen") val url: String,
@SerializedName("estado") val state: Boolean,
@SerializedName("idMedalla") val idMedal: Int
) | 1 | Kotlin | 1 | 1 | b8a06baa119ffb0d355d1ae7fe7e607bb8f1c52c | 362 | app-android | MIT License |
app/src/main/java/data/repository/ItemRepository.kt | omertzroya | 809,783,374 | false | {"Kotlin": 31122} | package data.repository
import android.app.Application
import data.local_db.ItemDao
import data.local_db.ItemDataBase
import data.model.Item
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ItemRepository(application: Application) {
private val itemDao: ItemDao? = ItemDataBase.getDatabase(application.applicationContext)?.itemsDao()
suspend fun addItem(item: Item) {
withContext(Dispatchers.IO) {
itemDao?.addItem(item)
}
}
suspend fun updateItem(item: Item) {
withContext(Dispatchers.IO) {
itemDao?.updateItem(item)
}
}
suspend fun deleteItem(item: Item) {
withContext(Dispatchers.IO) {
itemDao?.deleteItem(item)
}
}
suspend fun deleteAll() {
withContext(Dispatchers.IO) {
itemDao?.deleteAll()
}
}
fun getItems() = itemDao?.getItems()
}
| 0 | Kotlin | 0 | 0 | 1648a953c794a0441a31c9b1e21f1748851414e3 | 932 | CouponChest-Kotlin-App | MIT License |
android/engine/src/test/java/org/smartregister/fhircore/engine/ui/userprofile/UserProfileViewModelTest.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.engine.ui.userprofile
import android.os.Looper
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.spyk
import io.mockk.verify
import javax.inject.Inject
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.robolectric.Shadows
import org.smartregister.fhircore.engine.auth.AccountAuthenticator
import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry
import org.smartregister.fhircore.engine.robolectric.RobolectricTest
import org.smartregister.fhircore.engine.sync.SyncBroadcaster
import org.smartregister.fhircore.engine.sync.SyncInitiator
import org.smartregister.fhircore.engine.ui.register.model.Language
import org.smartregister.fhircore.engine.util.SecureSharedPreference
import org.smartregister.fhircore.engine.util.SharedPreferencesHelper
@HiltAndroidTest
class UserProfileViewModelTest : RobolectricTest() {
@get:Rule var hiltRule = HiltAndroidRule(this)
lateinit var userProfileViewModel: UserProfileViewModel
lateinit var accountAuthenticator: AccountAuthenticator
lateinit var secureSharedPreference: SecureSharedPreference
lateinit var sharedPreferencesHelper: SharedPreferencesHelper
lateinit var configurationRegistry: ConfigurationRegistry
@Inject lateinit var realConfigurationRegistry: ConfigurationRegistry
val syncBroadcaster = SyncBroadcaster
@Before
fun setUp() {
hiltRule.inject()
accountAuthenticator = mockk()
secureSharedPreference = mockk()
sharedPreferencesHelper = mockk()
configurationRegistry = mockk()
userProfileViewModel =
UserProfileViewModel(
syncBroadcaster,
accountAuthenticator,
secureSharedPreference,
sharedPreferencesHelper,
configurationRegistry
)
}
@Test
fun testRunSync() {
val mockSyncInitiator = mockk<SyncInitiator> { every { runSync() } returns Unit }
syncBroadcaster.unRegisterSyncInitiator()
syncBroadcaster.registerSyncInitiator(mockSyncInitiator)
userProfileViewModel.runSync()
verify { mockSyncInitiator.runSync() }
}
@Test
fun testRetrieveUsernameShouldReturnDemo() {
every { secureSharedPreference.retrieveSessionUsername() } returns "demo"
Assert.assertEquals("demo", userProfileViewModel.retrieveUsername())
verify { secureSharedPreference.retrieveSessionUsername() }
}
@Test
fun testLogoutUserShouldCallAuthLogoutService() {
every { accountAuthenticator.logout() } returns Unit
userProfileViewModel.logoutUser()
verify(exactly = 1) { accountAuthenticator.logout() }
Shadows.shadowOf(Looper.getMainLooper()).idle()
Assert.assertTrue(userProfileViewModel.onLogout.value!!)
}
@Test
fun allowSwitchingLanguagesShouldReturnTrueWhenMultipleLanguagesAreConfigured() {
val languages = listOf(Language("es", "Spanish"), Language("en", "English"))
userProfileViewModel = spyk(userProfileViewModel)
every { userProfileViewModel.languages } returns languages
Assert.assertTrue(userProfileViewModel.allowSwitchingLanguages())
}
@Test
fun allowSwitchingLanguagesShouldReturnFalseWhenConfigurationIsFalse() {
val languages = listOf(Language("es", "Spanish"))
userProfileViewModel = spyk(userProfileViewModel)
every { userProfileViewModel.languages } returns languages
Assert.assertFalse(userProfileViewModel.allowSwitchingLanguages())
}
@Test
fun loadSelectedLanguage() {
every { sharedPreferencesHelper.read(SharedPreferencesHelper.LANG, "en") } returns "fr"
Assert.assertEquals("French", userProfileViewModel.loadSelectedLanguage())
verify { sharedPreferencesHelper.read(SharedPreferencesHelper.LANG, "en") }
}
@Test
fun setLanguageShouldCallSharedPreferencesHelperWriteWithSelectedLanguageTagAndPostValue() {
val language = Language("es", "Spanish")
var postedValue: Language? = null
every { sharedPreferencesHelper.write(any(), any<String>()) } just runs
userProfileViewModel.language.observeForever { postedValue = it }
userProfileViewModel.setLanguage(language)
Shadows.shadowOf(Looper.getMainLooper()).idle()
verify { sharedPreferencesHelper.write(SharedPreferencesHelper.LANG, "es") }
Assert.assertEquals(language, postedValue!!)
}
@Test
fun fetchLanguagesShouldReturnEnglishAndSwahiliAsModels() {
every { accountAuthenticator.launchLoginScreen() } just runs
realConfigurationRegistry.loadAppConfigurations("appId", accountAuthenticator) {}
userProfileViewModel =
UserProfileViewModel(
syncBroadcaster,
accountAuthenticator,
secureSharedPreference,
sharedPreferencesHelper,
realConfigurationRegistry
)
val languages = userProfileViewModel.fetchLanguages()
Assert.assertEquals("English", languages[0].displayName)
Assert.assertEquals("en", languages[0].tag)
Assert.assertEquals("Swahili", languages[1].displayName)
Assert.assertEquals("sw", languages[1].tag)
}
@Test
fun languagesLazyPropertyShouldRunFetchLanguagesAndReturnConfiguredLanguages() {
realConfigurationRegistry.appId = "appId"
every { accountAuthenticator.launchLoginScreen() } just runs
userProfileViewModel =
spyk(
UserProfileViewModel(
syncBroadcaster,
accountAuthenticator,
secureSharedPreference,
sharedPreferencesHelper,
realConfigurationRegistry
)
)
every { userProfileViewModel.fetchLanguages() } returns mockk()
val languages = userProfileViewModel.languages
Assert.assertEquals("English", languages[0].displayName)
Assert.assertEquals("en", languages[0].tag)
Assert.assertEquals("Swahili", languages[1].displayName)
Assert.assertEquals("sw", languages[1].tag)
}
}
| 138 | Kotlin | 7 | 16 | 87dc9bc1c909cd5586dbb5d05615918c0ebd9488 | 6,560 | fhircore | Apache License 2.0 |
app/src/main/java/com/teaphy/diffutildemo/callback/DiffCallback.kt | teaphy | 127,724,997 | false | null | package com.teaphy.diffutildemo.callback
import android.os.Bundle
import android.support.v7.util.DiffUtil
import com.teaphy.diffutildemo.bean.DiffBean
import com.teaphy.diffutildemo.global.KEY_DESC
/**
* @desc
* @author Tiany
* @date 2018/4/2 0002
*/
class DiffCallback(private val oldList: List<DiffBean>, private val newList: List<DiffBean>) : DiffUtil.Callback() {
/**
* 被DiffUtil调用,用来判断 两个对象是否是相同的Item。
* 例如,如果你的Item有唯一的id字段,这个方法就 判断id是否相等,或者重写equals方法
*/
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].name == newList[newItemPosition].name
}
/**
* 老数据集size
*/
override fun getOldListSize(): Int {
return oldList.size
}
/**
* 新数据集size
*/
override fun getNewListSize(): Int {
return newList.size
}
/**
* 被DiffUtil调用,用来检查 两个item是否含有相同的数据
* DiffUtil用返回的信息(true false)来检测当前item的内容是否发生了变化
*/
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldBean = oldList[oldItemPosition]
val newBean = newList[newItemPosition]
if (oldBean.desc != newBean.desc) {
return false
}
// //默认两个data内容是相同的
return true
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldBean = oldList[oldItemPosition]
val newBean = newList[newItemPosition]
val bundle = Bundle()
if (oldBean.desc != newBean.desc) {
bundle.putString(KEY_DESC, "getChangePayLoad: " + newBean.desc)
} else { // 如果没有数据变化,返回null
return null
}
return bundle
}
} | 0 | Kotlin | 0 | 9 | 8afe5c39d2306ea2a314bfb32e8808ed998b991f | 1,738 | DiffUtilDemo | Apache License 2.0 |
compiler/fir/analysis-tests/testData/resolve/inference/pcla/doubleSquareBracketsInBuilderArgument.kt | JetBrains | 3,432,266 | false | null | // ISSUE: KT-47982
fun test() {
<!CANNOT_INFER_PARAMETER_TYPE, NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>build<!> {
<!UNSUPPORTED!>[<!UNSUPPORTED!>[]<!>]<!>
}
}
class Buildee<TV>
fun <PTV> build(instructions: Buildee<PTV>.() -> Unit): Buildee<PTV> {
return Buildee<PTV>().apply(instructions)
}
| 182 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 322 | kotlin | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/canvas/CanvasPath.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6472581} | // Automatically generated - do not modify!
@file:Suppress(
"NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE",
)
package web.canvas
sealed external interface CanvasPath {
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/arc)
*/
fun arc(
x: Number,
y: Number,
radius: Number,
startAngle: Number,
endAngle: Number,
counterclockwise: Boolean = definedExternally,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/arcTo)
*/
fun arcTo(
x1: Number,
y1: Number,
x2: Number,
y2: Number,
radius: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/bezierCurveTo)
*/
fun bezierCurveTo(
cp1x: Number,
cp1y: Number,
cp2x: Number,
cp2y: Number,
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/closePath)
*/
fun closePath(): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/ellipse)
*/
fun ellipse(
x: Number,
y: Number,
radiusX: Number,
radiusY: Number,
rotation: Number,
startAngle: Number,
endAngle: Number,
counterclockwise: Boolean = definedExternally,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineTo)
*/
fun lineTo(
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/moveTo)
*/
fun moveTo(
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/quadraticCurveTo)
*/
fun quadraticCurveTo(
cpx: Number,
cpy: Number,
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/rect)
*/
fun rect(
x: Number,
y: Number,
w: Number,
h: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/roundRect)
*/
fun roundRect(
x: Number,
y: Number,
w: Number,
h: Number,
radii: Any /* number | DOMPointInit | (number | DOMPointInit)[] */ = definedExternally,
): Unit = definedExternally
}
| 0 | Kotlin | 6 | 27 | e8d3760ae4b6f6dc971ca3b242bffed65af5f3d1 | 2,872 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/example/lemonade/MainActivity.kt | google-developer-training | 385,324,701 | false | null | /*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
/**
* DO NOT ALTER ANY VARIABLE OR VALUE NAMES OR THEIR INITIAL VALUES.
*
* Anything labeled var instead of val is expected to be changed in the functions but DO NOT
* alter their initial values declared here, this could cause the app to not function properly.
*/
private val LEMONADE_STATE = "LEMONADE_STATE"
private val LEMON_SIZE = "LEMON_SIZE"
private val SQUEEZE_COUNT = "SQUEEZE_COUNT"
// SELECT represents the "pick lemon" state
private val SELECT = "select"
// SQUEEZE represents the "squeeze lemon" state
private val SQUEEZE = "squeeze"
// DRINK represents the "drink lemonade" state
private val DRINK = "drink"
// RESTART represents the state where the lemonade has been drunk and the glass is empty
private val RESTART = "restart"
// Default the state to select
private var lemonadeState = "select"
// Default lemonSize to -1
private var lemonSize = -1
// Default the squeezeCount to -1
private var squeezeCount = -1
private var lemonTree = LemonTree()
private var lemonImage: ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// === DO NOT ALTER THE CODE IN THE FOLLOWING IF STATEMENT ===
if (savedInstanceState != null) {
lemonadeState = savedInstanceState.getString(LEMONADE_STATE, "select")
lemonSize = savedInstanceState.getInt(LEMON_SIZE, -1)
squeezeCount = savedInstanceState.getInt(SQUEEZE_COUNT, -1)
}
// === END IF STATEMENT ===
lemonImage = findViewById(R.id.image_lemon_state)
setViewElements()
lemonImage!!.setOnClickListener {
// TODO: call the method that handles the state when the image is clicked
clickLemonImage()
}
lemonImage!!.setOnLongClickListener {
// TODO: replace 'false' with a call to the function that shows the squeeze count
showSnackbar()
false
}
}
/**
* === DO NOT ALTER THIS METHOD ===
*
* This method saves the state of the app if it is put in the background.
*/
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(LEMONADE_STATE, lemonadeState)
outState.putInt(LEMON_SIZE, lemonSize)
outState.putInt(SQUEEZE_COUNT, squeezeCount)
super.onSaveInstanceState(outState)
}
/**
* Clicking will elicit a different response depending on the state.
* This method determines the state and proceeds with the correct action.
*/
private fun clickLemonImage() {
// TODO: use a conditional statement like 'if' or 'when' to track the lemonadeState
// when the image is clicked we may need to change state to the next step in the
// lemonade making progression (or at least make some changes to the current state in the
// case of squeezing the lemon). That should be done in this conditional statement
// TODO: When the image is clicked in the SELECT state, the state should become SQUEEZE
// - The lemonSize variable needs to be set using the 'pick()' method in the LemonTree class
// - The squeezeCount should be 0 since we haven't squeezed any lemons just yet.
// TODO: When the image is clicked in the SQUEEZE state the squeezeCount needs to be
// INCREASED by 1 and lemonSize needs to be DECREASED by 1.
// - If the lemonSize has reached 0, it has been juiced and the state should become DRINK
// - Additionally, lemonSize is no longer relevant and should be set to -1
// TODO: When the image is clicked in the DRINK state the state should become RESTART
// TODO: When the image is clicked in the RESTART state the state should become SELECT
// TODO: lastly, before the function terminates we need to set the view elements so that the
// UI can reflect the correct state
when(lemonadeState){
SELECT -> {
lemonadeState = SQUEEZE
lemonSize = lemonTree.pick()
squeezeCount = 0
}
SQUEEZE -> {
squeezeCount++
lemonSize--
if(lemonSize == 0) lemonadeState = DRINK
}
DRINK -> {
lemonadeState = RESTART
lemonSize = -1
}
else -> lemonadeState = SELECT
}
setViewElements()
}
/**
* Set up the view elements according to the state.
*/
private fun setViewElements() {
val textAction: TextView = findViewById(R.id.text_action)
// TODO: set up a conditional that tracks the lemonadeState
// TODO: for each state, the textAction TextView should be set to the corresponding string from
// the string resources file. The strings are named to match the state
// TODO: Additionally, for each state, the lemonImage should be set to the corresponding
// drawable from the drawable resources. The drawables have the same names as the strings
// but remember that they are drawables, not strings.
when(lemonadeState){
SELECT -> {
textAction.text = getString(R.string.click_text)
lemonImage?.setImageResource( R.drawable.lemon_tree)
}
SQUEEZE -> {
textAction.text = getString(R.string.squeeze_text)
lemonImage?.setImageResource( R.drawable.lemon_squeeze)
}
DRINK -> {
textAction.text = getString(R.string.drink_text)
lemonImage?.setImageResource( R.drawable.lemon_drink)
}
else -> {
textAction.text = getString(R.string.restart_text)
lemonImage?.setImageResource( R.drawable.lemon_restart)
}
}
}
/**
* === DO NOT ALTER THIS METHOD ===
*
* Long clicking the lemon image will show how many times the lemon has been squeezed.
*/
private fun showSnackbar(): Boolean {
if (lemonadeState != SQUEEZE) {
return false
}
val squeezeText = getString(R.string.squeeze_count, squeezeCount)
Snackbar.make(
findViewById(R.id.constraint_Layout),
squeezeText,
Snackbar.LENGTH_SHORT
).show()
return true
}
}
/**
* A Lemon tree class with a method to "pick" a lemon. The "size" of the lemon is randomized
* and determines how many times a lemon needs to be squeezed before you get lemonade.
*/
class LemonTree {
fun pick(): Int {
return (2..4).random()
}
}
| 40 | null | 42 | 94 | f87aca701d69850320bad8e61f6aeb45fda16a78 | 7,693 | android-basics-kotlin-lemonade-app | Apache License 2.0 |
maplibre/app/src/main/java/danbroid/util/demo/SimpleMapActivity.kt | danbrough | 290,871,172 | false | {"C": 241261, "Kotlin": 199375, "C++": 74987, "Java": 9058, "Shell": 9035, "Go": 304} | package danbroid.util.demo
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
/**
* Test activity showcasing a simple MapView without any MapboxMap interaction.
*/
class SimpleMapActivity : AppCompatActivity() {
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_simple)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { mapboxMap: MapboxMap ->
mapboxMap.cameraPosition = CameraPosition.Builder()
.target(LatLng(-41.308618, 174.769413))
.zoom(14.0)
.build()
mapboxMap.setStyle(Style.Builder().fromUri(Style.MAPBOX_STREETS))
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
// NavUtils.navigateHome(this);
finish()
}
} | 0 | C | 0 | 2 | f5b1b0e0b9688c9fc0e7ff3d6d092ab86bf99fea | 2,204 | misc_demos | Apache License 2.0 |
app/src/main/java/dev/tcode/thinmp/view/screen/MainScreen.kt | tcode-dev | 392,735,283 | false | {"Kotlin": 248408} | package dev.tcode.thinmp.view.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import dev.tcode.thinmp.R
import dev.tcode.thinmp.constant.StyleConstant
import dev.tcode.thinmp.view.cell.AlbumCellView
import dev.tcode.thinmp.view.cell.GridCellView
import dev.tcode.thinmp.view.cell.ShortcutCellView
import dev.tcode.thinmp.view.dropdownMenu.ShortcutDropdownMenuItemView
import dev.tcode.thinmp.view.layout.MiniPlayerLayoutView
import dev.tcode.thinmp.view.nav.LocalNavigator
import dev.tcode.thinmp.view.row.DropdownMenuView
import dev.tcode.thinmp.view.row.PlainRowView
import dev.tcode.thinmp.view.title.SectionTitleView
import dev.tcode.thinmp.view.util.CustomGridCellsFixed
import dev.tcode.thinmp.view.util.CustomLifecycleEventObserver
import dev.tcode.thinmp.view.util.DividerView
import dev.tcode.thinmp.view.util.EmptyMiniPlayerView
import dev.tcode.thinmp.view.util.gridSpanCount
import dev.tcode.thinmp.viewModel.MainViewModel
@Composable
fun MainScreen(navController: NavController, viewModel: MainViewModel = viewModel()) {
val uiState by viewModel.uiState.collectAsState()
val context = LocalContext.current
val spanCount: Int = gridSpanCount()
val navigator = LocalNavigator.current
CustomLifecycleEventObserver(viewModel)
MiniPlayerLayoutView {
LazyVerticalGrid(columns = CustomGridCellsFixed(spanCount)) {
item(span = { GridItemSpan(spanCount) }) {
Column(
modifier = Modifier
.fillMaxWidth()
.statusBarsPadding()
.padding(start = StyleConstant.PADDING_LARGE.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = StyleConstant.PADDING_MEDIUM.dp)
.height(StyleConstant.ROW_HEIGHT.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
val expanded = remember { mutableStateOf(false) }
Text(
stringResource(R.string.library),
color = MaterialTheme.colorScheme.primary,
textAlign = TextAlign.Left,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = StyleConstant.FONT_HUGE.sp
)
Box(contentAlignment = Alignment.Center, modifier = Modifier
.size(StyleConstant.BUTTON_SIZE.dp)
.clickable { expanded.value = !expanded.value }) {
Icon(
painter = painterResource(id = R.drawable.round_more_vert_24),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(StyleConstant.ICON_SIZE.dp)
)
DropdownMenu(expanded = expanded.value,
offset = DpOffset((-1).dp, 0.dp),
modifier = Modifier.background(MaterialTheme.colorScheme.onBackground),
onDismissRequest = { expanded.value = false }) {
DropdownMenuItem(text = { Text(stringResource(R.string.edit), color = MaterialTheme.colorScheme.primary) }, onClick = {
navigator.mainEdit()
})
}
}
}
DividerView()
}
}
items(items = uiState.menu, span = { GridItemSpan(spanCount) }) { item ->
if (item.visibility) {
PlainRowView(stringResource(item.id), modifier = Modifier.clickable {
navController.navigate(item.key)
})
}
}
if (uiState.shortcutVisibility && uiState.shortcuts.isNotEmpty()) {
item(span = { GridItemSpan(spanCount) }) {
SectionTitleView(stringResource(R.string.shortcut))
}
itemsIndexed(items = uiState.shortcuts) { index, shortcut ->
DropdownMenuView(dropdownContent = { callback ->
val callbackShortcut = {
callback()
viewModel.load(context)
}
ShortcutDropdownMenuItemView(shortcut.itemId, callbackShortcut)
}) { callback ->
GridCellView(index, spanCount) {
ShortcutCellView(shortcut.primaryText, shortcut.secondaryText, shortcut.imageUri, shortcut.type, Modifier.pointerInput(shortcut.url) {
detectTapGestures(onLongPress = { callback() }, onTap = { navController.navigate(shortcut.url) })
})
}
}
}
}
if (uiState.recentlyAlbumsVisibility && uiState.albums.isNotEmpty()) {
item(span = { GridItemSpan(spanCount) }) {
SectionTitleView(stringResource(R.string.recently_added))
}
itemsIndexed(items = uiState.albums) { index, album ->
DropdownMenuView(dropdownContent = { callback ->
val callbackAlbum = {
callback()
viewModel.load(context)
}
ShortcutDropdownMenuItemView(album.albumId, callbackAlbum)
}) { callback ->
GridCellView(index, spanCount) {
AlbumCellView(album.name, album.artistName, album.getImageUri(), Modifier.pointerInput(album.url) {
detectTapGestures(onLongPress = { callback() }, onTap = { navigator.albumDetail(album.id) })
})
}
}
}
}
item(span = { GridItemSpan(spanCount) }) {
EmptyMiniPlayerView()
}
}
}
} | 0 | Kotlin | 0 | 7 | ecd7a7585788d0d4355dbfa596aa56f27dec0087 | 8,462 | ThinMP_Android_Kotlin | MIT License |
core-ui/src/main/kotlin/com/laomuji666/compose/core/ui/we/icons/ChatsSelect.kt | laomuji666 | 844,336,531 | false | {"Kotlin": 235984} | package com.laomuji666.compose.core.ui.we.icons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import kotlin.Suppress
val WeIcons.ChatsSelect: ImageVector
get() {
if (_ChatsSelect != null) {
return _ChatsSelect!!
}
_ChatsSelect = ImageVector.Builder(
name = "WeIcons.ChatsSelect",
defaultWidth = 29.dp,
defaultHeight = 28.dp,
viewportWidth = 29f,
viewportHeight = 28f
).apply {
path(
fill = SolidColor(Color(0xFF39CD80)),
pathFillType = PathFillType.EvenOdd
) {
moveTo(14.875f, 23.333f)
curveTo(21.318f, 23.333f, 26.542f, 18.893f, 26.542f, 13.417f)
curveTo(26.542f, 7.94f, 21.318f, 3.5f, 14.875f, 3.5f)
curveTo(8.432f, 3.5f, 3.208f, 7.94f, 3.208f, 13.417f)
curveTo(3.208f, 16.376f, 4.733f, 19.032f, 7.151f, 20.849f)
lineTo(6.799f, 23.881f)
curveTo(6.762f, 24.201f, 6.991f, 24.491f, 7.311f, 24.528f)
curveTo(7.42f, 24.541f, 7.531f, 24.522f, 7.631f, 24.475f)
lineTo(11.111f, 22.806f)
curveTo(12.292f, 23.148f, 13.558f, 23.333f, 14.875f, 23.333f)
close()
}
}.build()
return _ChatsSelect!!
}
@Suppress("ObjectPropertyName")
private var _ChatsSelect: ImageVector? = null
| 1 | Kotlin | 0 | 99 | 55ebed2733bdbc2330f3297b74b5514fea786ba3 | 1,671 | Quickly-Use-Jetpack-Compose | Apache License 2.0 |
app/src/main/java/com/kcteam/features/viewAllOrder/presentation/OrderSizeQtyDetailsDelAdapter.kt | DebashisINT | 558,234,039 | false | null | package com.breezefieldsalesgypmart.features.viewAllOrder.presentation
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.breezefieldsalesgypmart.R
import com.breezefieldsalesgypmart.app.utils.Toaster
import com.breezefieldsalesgypmart.features.viewAllOrder.interf.NewOrderSizeQtyDelOnClick
import com.breezefieldsalesgypmart.features.viewAllOrder.model.ProductOrder
import kotlinx.android.synthetic.main.row_new_order_size_qty_list.view.*
class OrderSizeQtyDetailsDelAdapter (var context: Context, var size_qty_list:ArrayList<ProductOrder>, val listner: NewOrderSizeQtyDelOnClick):
RecyclerView.Adapter<OrderSizeQtyDetailsDelAdapter.SizeQtyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SizeQtyViewHolder {
val view= LayoutInflater.from(context).inflate(R.layout.row_new_order_size_qty_list,parent,false)
return SizeQtyViewHolder(view)
}
override fun getItemCount(): Int {
return size_qty_list!!.size
}
override fun onBindViewHolder(holder: SizeQtyViewHolder, position: Int) {
holder.tv_size.text= size_qty_list.get(position).size
holder.tv_qty.text= size_qty_list.get(position).qty
holder.iv_del.visibility = View.INVISIBLE
if(holder.ch_flag.isChecked){
size_qty_list.get(position).isCheckedStatus=true
}else{
size_qty_list.get(position).isCheckedStatus=false
}
holder.ch_flag.setOnClickListener { v: View? ->
if (holder.ch_flag.isChecked()) {
size_qty_list.get(position).isCheckedStatus=true
listner.sizeQtySelListOnClick(size_qty_list)
// listner.sizeQtyListOnClick(size_qty_list.get(position),position)
// holder.iv_del.setOnClickListener{listner.sizeQtyListOnClick(size_qty_list.get(position),position)}
}
else{
size_qty_list.get(position).isCheckedStatus=false
// holder.iv_del.setOnclic
// Toaster.msgShort(context,"No Checkbox Selected For Deleted")
}
}
}
inner class SizeQtyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val tv_size=itemView.tv_new_order_size
val tv_qty=itemView.tv_new_order_qty
val iv_del=itemView.iv_new_order_del
val ch_flag = itemView.new_order_size_qty_checked
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 2,526 | NationalPlastic | Apache License 2.0 |
src/test/kotlin/no/nav/eessi/pensjon/klienter/fagmodul/FagmodulKlientTest.kt | navikt | 178,813,650 | false | {"Kotlin": 790534, "Shell": 1714, "Dockerfile": 155} | package no.nav.eessi.pensjon.klienter.fagmodul
import io.mockk.every
import io.mockk.mockk
import no.nav.eessi.pensjon.eux.model.buc.SakType.ALDER
import no.nav.eessi.pensjon.listeners.fagmodul.FagmodulKlient
import no.nav.eessi.pensjon.oppgaverouting.SakInformasjon
import no.nav.eessi.pensjon.utils.toJson
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.client.RestTemplate
class FagmodulKlientTest {
private val fagmodulOidcRestTemplate: RestTemplate = mockk()
private val fagmodulKlient = FagmodulKlient(fagmodulOidcRestTemplate)
@Test
fun `Gitt at saktypen ikke er en enum så skal vi kaste RuntimeException`() {
val jsonResponse = getJsonBody("PAM_PAM")
every { fagmodulKlientExchange() } returns ResponseEntity(jsonResponse, HttpStatus.OK)
assertThrows<RuntimeException> {
fagmodulKlient.hentPensjonSaklist("321654987")
}
}
@Test
fun `Gitt at apikallet feiler så skal vi logge en error og returnere en tom liste`() {
every { fagmodulKlientExchange() } throws RuntimeException("En feil oppstod under henting av pensjonsakliste")
assertEquals(emptyList<SakInformasjon>(), fagmodulKlient.hentPensjonSaklist("321654987"))
}
@Test
fun `Gitt at vi har sakType Alder, så skal vi returnere en liste over saksinformasjon`() {
val jsonBody = getJsonBody(ALDER.name)
every { fagmodulKlientExchange() } returns ResponseEntity(jsonBody, HttpStatus.OK)
val result = fagmodulKlient.hentPensjonSaklist("321654987")
assertEquals(jsonBody, result.toJson())
}
private fun fagmodulKlientExchange() = fagmodulOidcRestTemplate.exchange(
"/pensjon/sakliste/321654987",
HttpMethod.GET,
null,
String::class.java
)
private fun getJsonBody(sakType: String) = """
[ {
"sakId" : "321",
"sakType" : "$sakType",
"sakStatus" : "LOPENDE",
"saksbehandlendeEnhetId" : "",
"nyopprettet" : false
} ]
""".trimIndent()
} | 3 | Kotlin | 3 | 5 | e77a3059a567bf93922d6904847b70835dd62052 | 2,362 | eessi-pensjon-journalforing | MIT License |
common/all/src/commonMain/kotlin/com/tunjid/me/common/ui/settings/SettingsRoute.kt | tunjid | 439,670,817 | false | null | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tunjid.me.settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
import com.tunjid.me.feature.LocalRouteServiceLocator
import com.tunjid.me.scaffold.globalui.InsetFlags
import com.tunjid.me.scaffold.globalui.NavVisibility
import com.tunjid.me.scaffold.globalui.ScreenUiState
import com.tunjid.me.scaffold.globalui.UiState
import com.tunjid.me.scaffold.nav.AppRoute
import com.tunjid.me.scaffold.nav.LocalNavigator
import com.tunjid.treenav.push
import kotlinx.serialization.Serializable
@Serializable
data class SettingsRoute(
override val id: String,
) : AppRoute {
@Composable
override fun Render() {
SettingsScreen(
mutator = LocalRouteServiceLocator.current.locate(this),
)
}
}
@Composable
private fun SettingsScreen(mutator: SettingsMutator) {
val state by mutator.state.collectAsState()
val scrollState = rememberScrollState()
val navigator = LocalNavigator.current
ScreenUiState(
UiState(
toolbarShows = true,
toolbarTitle = "Settings",
navVisibility = NavVisibility.Visible,
insetFlags = InsetFlags.NO_BOTTOM,
statusBarColor = MaterialTheme.colors.primary.toArgb(),
)
)
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(state = scrollState),
horizontalAlignment = Alignment.Start,
) {
state.routes.forEach { path ->
Column(
modifier = Modifier
.fillMaxWidth()
.clickable {
navigator.navigate { currentNav.push(path.toRoute) }
},
content = {
Text(
modifier = Modifier.padding(16.dp),
text = path,
)
}
)
}
}
}
| 0 | Kotlin | 1 | 17 | 710745fa1cc2201458b69c61351fe5f585b87a28 | 3,117 | me | Apache License 2.0 |
app/src/main/java/app/tivi/inject/ApplicationComponent.kt | chrisbanes | 100,624,553 | false | null | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.inject
import android.app.Application
import android.content.Context
import app.tivi.TiviApplication
import app.tivi.appinitializers.AppInitializers
import app.tivi.common.imageloading.ImageLoadingComponent
import app.tivi.core.analytics.AnalyticsComponent
import app.tivi.core.perf.PerformanceComponent
import app.tivi.data.AndroidSqlDelightDatabaseComponent
import app.tivi.data.episodes.EpisodeBinds
import app.tivi.data.followedshows.FollowedShowsBinds
import app.tivi.data.popularshows.PopularShowsBinds
import app.tivi.data.recommendedshows.RecommendedShowsBinds
import app.tivi.data.search.SearchBinds
import app.tivi.data.showimages.ShowImagesBinds
import app.tivi.data.shows.ShowsBinds
import app.tivi.data.traktauth.RelatedShowsBinds
import app.tivi.data.traktauth.TraktAuthComponent
import app.tivi.data.traktusers.TraktUsersBinds
import app.tivi.data.trendingshows.TrendingShowsBinds
import app.tivi.data.watchedshows.WatchedShowsBinds
import app.tivi.home.ContentViewSetterComponent
import app.tivi.settings.PreferencesComponent
import app.tivi.tasks.TasksComponent
import app.tivi.tasks.TiviWorkerFactory
import app.tivi.tmdb.TmdbComponent
import app.tivi.trakt.TraktComponent
import app.tivi.util.LoggerComponent
import app.tivi.util.PowerControllerComponent
import me.tatarka.inject.annotations.Component
import me.tatarka.inject.annotations.Provides
@Component
@ApplicationScope
abstract class ApplicationComponent(
@get:Provides val application: Application,
) : AndroidSqlDelightDatabaseComponent,
TraktAuthComponent,
TmdbComponent,
TraktComponent,
AppComponent,
NetworkComponent,
TasksComponent,
PowerControllerComponent,
ImageLoadingComponent,
AnalyticsComponent,
PerformanceComponent,
PreferencesComponent,
EpisodeBinds,
FollowedShowsBinds,
PopularShowsBinds,
RecommendedShowsBinds,
RelatedShowsBinds,
SearchBinds,
ShowImagesBinds,
ShowsBinds,
TraktUsersBinds,
TrendingShowsBinds,
WatchedShowsBinds,
LoggerComponent,
ContentViewSetterComponent,
VariantAwareComponent {
abstract val initializers: AppInitializers
abstract val workerFactory: TiviWorkerFactory
companion object {
fun from(context: Context): ApplicationComponent {
return (context.applicationContext as TiviApplication).component
}
}
}
| 20 | null | 792 | 5,749 | 5dc4d831fd801afab556165d547042c517f98875 | 2,985 | tivi | Apache License 2.0 |
plugins/settings-sync/src/com/intellij/settingsSync/CloudConfigServerCommunicator.kt | ingokegel | 72,937,917 | false | null | package com.intellij.settingsSync
import com.intellij.ide.plugins.PluginManagerCore.isRunningFromSources
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.settingsSync.auth.SettingsSyncAuthService
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.delete
import com.intellij.util.io.inputStream
import com.jetbrains.cloudconfig.*
import com.jetbrains.cloudconfig.auth.JbaTokenAuthProvider
import com.jetbrains.cloudconfig.exception.InvalidVersionIdException
import org.jdom.JDOMException
import org.jetbrains.annotations.VisibleForTesting
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.util.*
import java.util.concurrent.atomic.AtomicReference
internal const val CROSS_IDE_SYNC_MARKER_FILE = "cross-ide-sync-enabled"
internal const val SETTINGS_SYNC_SNAPSHOT = "settings.sync.snapshot"
internal const val SETTINGS_SYNC_SNAPSHOT_ZIP = "$SETTINGS_SYNC_SNAPSHOT.zip"
private const val CONNECTION_TIMEOUT_MS = 10000
private const val READ_TIMEOUT_MS = 50000
internal open class CloudConfigServerCommunicator : SettingsSyncRemoteCommunicator {
internal open val client get() = _client.value
private val _client = lazy { createCloudConfigClient(clientVersionContext) }
protected val clientVersionContext = CloudConfigVersionContext()
private val lastRemoteErrorRef = AtomicReference<Throwable>()
@VisibleForTesting
@Throws(IOException::class)
protected fun currentSnapshotFilePath(): String? {
try {
val crossIdeSyncEnabled = isFileExists(CROSS_IDE_SYNC_MARKER_FILE)
if (crossIdeSyncEnabled != SettingsSyncLocalSettings.getInstance().isCrossIdeSyncEnabled) {
LOG.info("Cross-IDE sync status on server is: ${enabledOrDisabled(crossIdeSyncEnabled)}. Updating local settings with it.")
SettingsSyncLocalSettings.getInstance().isCrossIdeSyncEnabled = crossIdeSyncEnabled
}
return if (crossIdeSyncEnabled) {
SETTINGS_SYNC_SNAPSHOT_ZIP
}
else {
"${ApplicationNamesInfo.getInstance().productName.lowercase()}/$SETTINGS_SYNC_SNAPSHOT_ZIP"
}
}
catch (e: Throwable) {
if (e is IOException) {
throw e
}
else {
LOG.warn("Couldn't check if $CROSS_IDE_SYNC_MARKER_FILE exists", e)
return null
}
}
}
@Throws(IOException::class)
private fun receiveSnapshotFile(snapshotFilePath: String): Pair<InputStream?, String?> {
return clientVersionContext.doWithVersion(snapshotFilePath, null) { filePath ->
try {
val stream = client.read(filePath)
val actualVersion: String? = clientVersionContext.get(filePath)
if (actualVersion == null) {
LOG.warn("Version not stored in the context for $filePath")
}
Pair(stream, actualVersion)
}
catch (fileNotFound: FileNotFoundException) {
Pair(null, null)
}
}
}
private fun sendSnapshotFile(inputStream: InputStream, knownServerVersion: String?, force: Boolean): SettingsSyncPushResult {
return sendSnapshotFile(inputStream, knownServerVersion, force, clientVersionContext, client)
}
@VisibleForTesting
internal fun sendSnapshotFile(
inputStream: InputStream,
knownServerVersion: String?,
force: Boolean,
versionContext: CloudConfigVersionContext,
cloudConfigClient: CloudConfigFileClientV2
): SettingsSyncPushResult {
val snapshotFilePath: String
val defaultMessage = "Unknown during checking $CROSS_IDE_SYNC_MARKER_FILE"
try {
snapshotFilePath = currentSnapshotFilePath() ?: return SettingsSyncPushResult.Error(defaultMessage)
}
catch (ioe: IOException) {
return SettingsSyncPushResult.Error(ioe.message ?: defaultMessage)
}
val versionToPush: String?
if (force) {
// get the latest server version: pushing with it will overwrite the file in any case
versionToPush = getLatestVersion(snapshotFilePath)?.versionId
}
else {
if (knownServerVersion != null) {
versionToPush = knownServerVersion
}
else {
val serverVersion = getLatestVersion(snapshotFilePath)?.versionId
if (serverVersion == null) {
// no file on the server => just push it there
versionToPush = null
}
else {
// we didn't store the server version locally yet => reject the push to avoid overwriting the server version;
// the next update after the rejected push will store the version information, and subsequent push will be successful.
return SettingsSyncPushResult.Rejected
}
}
}
val serverVersionId = versionContext.doWithVersion(snapshotFilePath, versionToPush) { filePath ->
cloudConfigClient.write(filePath, inputStream)
val actualVersion: String? = versionContext.get(filePath)
if (actualVersion == null) {
LOG.warn("Version not stored in the context for $filePath")
}
actualVersion
}
// errors are thrown as exceptions, and are handled above
return SettingsSyncPushResult.Success(serverVersionId)
}
override fun checkServerState(): ServerState {
try {
val snapshotFilePath = currentSnapshotFilePath() ?: return ServerState.Error("Unknown error during checkServerState")
val latestVersion = client.getLatestVersion(snapshotFilePath)
LOG.debug("Latest version info: $latestVersion")
clearLastRemoteError()
when (latestVersion?.versionId) {
null -> return ServerState.FileNotExists
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId -> return ServerState.UpToDate
else -> return ServerState.UpdateNeeded
}
}
catch (e: Throwable) {
val message = handleRemoteError(e)
return ServerState.Error(message)
}
}
override fun receiveUpdates(): UpdateResult {
LOG.info("Receiving settings snapshot from the cloud config server...")
try {
val snapshotFilePath = currentSnapshotFilePath() ?: return UpdateResult.Error("Unknown error during receiveUpdates")
val (stream, version) = receiveSnapshotFile(snapshotFilePath)
clearLastRemoteError()
if (stream == null) {
LOG.info("$snapshotFilePath not found on the server")
return UpdateResult.NoFileOnServer
}
val tempFile = FileUtil.createTempFile(SETTINGS_SYNC_SNAPSHOT, UUID.randomUUID().toString() + ".zip")
try {
FileUtil.writeToFile(tempFile, stream.readAllBytes())
val snapshot = SettingsSnapshotZipSerializer.extractFromZip(tempFile.toPath())
return if (snapshot.isDeleted()) UpdateResult.FileDeletedFromServer else UpdateResult.Success(snapshot, version)
}
finally {
FileUtil.delete(tempFile)
}
}
catch (e: Throwable) {
val message = handleRemoteError(e)
return UpdateResult.Error(message)
}
}
override fun push(snapshot: SettingsSnapshot, force: Boolean, expectedServerVersionId: String?): SettingsSyncPushResult {
LOG.info("Pushing setting snapshot to the cloud config server...")
val zip = try {
SettingsSnapshotZipSerializer.serializeToZip(snapshot)
}
catch (e: Throwable) {
LOG.warn(e)
return SettingsSyncPushResult.Error(e.message ?: "Couldn't prepare zip file")
}
try {
val pushResult = sendSnapshotFile(zip.inputStream(), expectedServerVersionId, force)
clearLastRemoteError()
return pushResult
}
catch (ive: InvalidVersionIdException) {
LOG.info("Rejected: version doesn't match the version on server: ${ive.message}")
return SettingsSyncPushResult.Rejected
}
// todo handle authentication failure: propose to login
catch (e: Throwable) {
val message = handleRemoteError(e)
return SettingsSyncPushResult.Error(message)
}
finally {
try {
zip.delete()
}
catch (e: Throwable) {
LOG.warn(e)
}
}
}
private fun clearLastRemoteError(){
if (lastRemoteErrorRef.get() != null) {
LOG.info("Connection to setting sync server is restored")
}
lastRemoteErrorRef.set(null)
}
private fun handleRemoteError(e: Throwable): String {
val defaultMessage = "Error during communication with server"
if (e is IOException) {
if (lastRemoteErrorRef.get()?.message != e.message) {
lastRemoteErrorRef.set(e)
LOG.warn("$defaultMessage: ${e.message}")
}
}
else {
LOG.error(e)
}
return e.message ?: defaultMessage
}
fun downloadSnapshot(filePath: String, version: FileVersionInfo): InputStream? {
val stream = clientVersionContext.doWithVersion(filePath, version.versionId) { path ->
client.read(path)
}
if (stream == null) {
LOG.info("$filePath not found on the server")
}
return stream
}
override fun createFile(filePath: String, content: String) {
client.write(filePath, content.byteInputStream())
}
private fun getLatestVersion(filePath: String): FileVersionInfo? {
return client.getLatestVersion(filePath)
}
@Throws(IOException::class)
override fun deleteFile(filePath: String) {
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = null
client.delete(filePath)
}
@Throws(IOException::class)
override fun isFileExists(filePath: String): Boolean {
return client.getLatestVersion(filePath) != null
}
@Throws(Exception::class)
fun fetchHistory(filePath: String): List<FileVersionInfo> {
return client.getVersions(filePath)
}
companion object {
private const val URL_PROVIDER = "https://www.jetbrains.com/config/IdeaCloudConfig.xml"
internal const val DEFAULT_PRODUCTION_URL = "https://cloudconfig.jetbrains.com/cloudconfig"
private const val DEFAULT_DEBUG_URL = "https://stgn.cloudconfig.jetbrains.com/cloudconfig"
internal const val URL_PROPERTY = "idea.settings.sync.cloud.url"
internal val url get() = _url.value
private val _url = lazy {
val explicitUrl = System.getProperty(URL_PROPERTY)
when {
explicitUrl != null -> {
LOG.info("Using SettingSync server URL (from properties): $explicitUrl")
explicitUrl
}
isRunningFromSources() -> {
LOG.info("Using SettingSync server URL (DEBUG): $DEFAULT_DEBUG_URL")
DEFAULT_DEBUG_URL
}
else -> getProductionUrl()
}
}
private fun getProductionUrl(): String {
val configUrl = HttpRequests.request(URL_PROVIDER)
.productNameAsUserAgent()
.connect(HttpRequests.RequestProcessor { request: HttpRequests.Request ->
try {
val documentElement = JDOMUtil.load(request.inputStream)
documentElement.getAttributeValue("baseUrl")
}
catch (e: JDOMException) {
throw IOException(e)
}
}, DEFAULT_PRODUCTION_URL, LOG)
LOG.info("Using SettingSync server URL: $configUrl")
return configUrl
}
internal fun createCloudConfigClient(versionContext: CloudConfigVersionContext): CloudConfigFileClientV2 {
val conf = createConfiguration()
return CloudConfigFileClientV2(url, conf, DUMMY_ETAG_STORAGE, versionContext)
}
private fun createConfiguration(): Configuration {
val userId = SettingsSyncAuthService.getInstance().getUserData()?.id
if (userId == null) {
throw SettingsSyncAuthException("Authentication required")
}
return Configuration().connectTimeout(CONNECTION_TIMEOUT_MS).readTimeout(READ_TIMEOUT_MS).auth(JbaTokenAuthProvider(userId))
}
private val LOG = logger<CloudConfigServerCommunicator>()
@VisibleForTesting
internal val DUMMY_ETAG_STORAGE: ETagStorage = object : ETagStorage {
override fun get(path: String): String? {
return null
}
override fun store(path: String, value: String) {
// do nothing
}
override fun remove(path: String?) {
// do nothing
}
}
}
}
| 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 12,188 | intellij-community | Apache License 2.0 |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/symbols/KtFirPropertyGetterSymbol.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.analysis.api.fir.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.analysis.api.fir.annotations.KtFirAnnotationListForDeclaration
import org.jetbrains.kotlin.analysis.api.fir.findPsi
import org.jetbrains.kotlin.analysis.api.fir.utils.cached
import org.jetbrains.kotlin.analysis.api.symbols.KtPropertyGetterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.LLFirResolveSession
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.utils.isInline
import org.jetbrains.kotlin.fir.declarations.utils.isOverride
import org.jetbrains.kotlin.fir.declarations.utils.modalityOrFinal
import org.jetbrains.kotlin.fir.declarations.utils.visibility
import org.jetbrains.kotlin.fir.resolve.getHasStableParameterNames
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertyAccessorSymbol
import org.jetbrains.kotlin.name.CallableId
internal class KtFirPropertyGetterSymbol(
override val firSymbol: FirPropertyAccessorSymbol,
override val firResolveSession: LLFirResolveSession,
override val token: KtLifetimeToken,
private val builder: KtSymbolByFirBuilder,
) : KtPropertyGetterSymbol(), KtFirSymbol<FirPropertyAccessorSymbol> {
init {
require(firSymbol.isGetter)
}
override val psi: PsiElement? by cached { firSymbol.findPsi() }
override val isDefault: Boolean get() = withValidityAssertion { firSymbol.fir is FirDefaultPropertyAccessor }
override val isInline: Boolean get() = withValidityAssertion { firSymbol.isInline }
override val isOverride: Boolean get() = withValidityAssertion { firSymbol.isOverride }
override val hasBody: Boolean get() = withValidityAssertion { firSymbol.fir.body != null }
override val modality: Modality get() = withValidityAssertion { firSymbol.modalityOrFinal }
override val visibility: Visibility get() = withValidityAssertion { firSymbol.visibility }
override val returnType: KtType get() = withValidityAssertion { firSymbol.returnType(builder) }
override val receiverType: KtType? get() = withValidityAssertion { firSymbol.receiverType(builder) }
override val annotationsList by cached { KtFirAnnotationListForDeclaration.create(firSymbol, firResolveSession.useSiteFirSession, token) }
/**
* Returns [CallableId] of the delegated Java method if the corresponding property of this setter is a synthetic Java property.
* Otherwise, returns `null`
*/
override val callableIdIfNonLocal: CallableId? by cached {
val fir = firSymbol.fir
if (fir is FirSyntheticPropertyAccessor) {
fir.delegate.symbol.callableId
} else null
}
override val valueParameters: List<KtValueParameterSymbol> get() = withValidityAssertion { emptyList() }
override val hasStableParameterNames: Boolean
get() = withValidityAssertion { firSymbol.fir.getHasStableParameterNames(firSymbol.moduleData.session) }
override fun createPointer(): KtSymbolPointer<KtPropertyGetterSymbol> {
KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it }
TODO("Creating pointers for getters from library is not supported yet")
}
override fun equals(other: Any?): Boolean = symbolEquals(other)
override fun hashCode(): Int = symbolHashCode()
}
| 4 | null | 5686 | 47,397 | a47dcc227952c0474d27cc385021b0c9eed3fb67 | 4,246 | kotlin | Apache License 2.0 |
app/src/main/java/com/kcteam/features/report/presentation/AchievementAdapter.kt | DebashisINT | 558,234,039 | false | null | package com.prakashspicesfsm.features.report.presentation
import android.content.Context
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.prakashspicesfsm.R
import com.prakashspicesfsm.features.report.model.AchievementDataModel
import kotlinx.android.synthetic.main.inflate_visit_report_item.view.*
/**
* Created by Saikat on 22-Jul-20.
*/
class AchievementAdapter(context: Context, val achvData: ArrayList<AchievementDataModel>?, val listener: OnClickListener) :
RecyclerView.Adapter<AchievementAdapter.MyViewHolder>() {
private val layoutInflater: LayoutInflater
private var context: Context
init {
layoutInflater = LayoutInflater.from(context)
this.context = context
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindItems(context, achvData, listener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val v = layoutInflater.inflate(R.layout.inflate_visit_report_item, parent, false)
return MyViewHolder(v)
}
override fun getItemCount(): Int {
return achvData?.size!!
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(context: Context, achvData: ArrayList<AchievementDataModel>?, listener: OnClickListener) {
if (adapterPosition % 2 == 0)
itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.report_screen_bg))
else
itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.white))
itemView.tv_name.text = achvData?.get(adapterPosition)?.member_name
if (!TextUtils.isEmpty(achvData?.get(adapterPosition)?.report_to)) {
itemView.tv_report_to_name.visibility = View.VISIBLE
itemView.tv_report_to_name.text = achvData?.get(adapterPosition)?.report_to
}
else
itemView.tv_report_to_name.visibility = View.GONE
itemView.tv_shop_count.text = achvData?.get(adapterPosition)?.stage_count
itemView.tv_distance.visibility = View.GONE
//itemView.rl_arrow.visibility = View.GONE
itemView.setOnClickListener({
listener.onViewClick(adapterPosition)
})
}
}
interface OnClickListener {
fun onViewClick(adapterPosition: Int)
}
} | 0 | null | 1 | 1 | a9aabcf48662c76db18bcece75cae9ac961da1ed | 2,598 | NationalPlastic | Apache License 2.0 |
src/main/kotlin/org/veupathdb/lib/blast/common/fields/MultiThreadingMode.kt | VEuPathDB | 362,472,079 | false | null | package org.veupathdb.lib.blast.common.fields
import com.fasterxml.jackson.databind.node.ObjectNode
import org.veupathdb.lib.blast.common.FlagMultiThreadingMode
import org.veupathdb.lib.blast.common.FlagNumThreads
import org.veupathdb.lib.blast.serial.BlastField
import org.veupathdb.lib.blast.util.*
private val Def = MultiThreadingModeValue.SplitByDatabase
internal fun ParseMultiThreadingMode(js: ObjectNode) =
js.optInt(FlagMultiThreadingMode) { MultiThreadingMode(parse(it)) }
?: MultiThreadingMode()
/**
* -mt_mode `<Integer, (>=0 and =<1)>`
*
* Multi-thread mode to use in RPS BLAST search:
* * 0 (auto) split by database vols
* * 1 split by queries
*
* Default = `0`
*/
@JvmInline
value class MultiThreadingMode(val value: MultiThreadingModeValue = Def) : BlastField {
override val isDefault get() = value == Def
override val name: String
get() = FlagNumThreads
override fun appendJson(js: ObjectNode) =
js.put(isDefault, FlagMultiThreadingMode, value.ordinal)
override fun appendCliSegment(cli: StringBuilder) =
cli.append(isDefault, FlagMultiThreadingMode, value.ordinal)
override fun appendCliParts(cli: MutableList<String>) =
cli.add(isDefault, FlagMultiThreadingMode, value.ordinal)
override fun clone() = this
}
@Suppress("NOTHING_TO_INLINE")
private inline fun parse(v: Int) =
MultiThreadingModeValue.values()[v.inSet(FlagMultiThreadingMode, 0, 1)]
enum class MultiThreadingModeValue {
SplitByDatabase,
SplitByQuery
} | 20 | Kotlin | 0 | 0 | e0639a45d45fce3e393ab1eff1176c5c75375738 | 1,491 | service-multi-blast | Apache License 2.0 |
Dataset Summary
KStack is the largest collection of permissively licensed Kotlin code.
Comparison with The Stack v2
In the table below one can find the comparsion between the Kotlin part of The Stack v2 and KStack:
Files | Repositories | Lines | Tokens | |
---|---|---|---|---|
Kotlin in The Stack v2 | 2M | 109,457 | 162M | 1.7B |
Kstack | 4M | 168,902 | 292M | 3.1B |
Dataset Creation
Collection procedure
We collected repositories from GitHub with the main language being Kotlin, as well as any repositories with Kotlin files that have received 10 or more stars (as of February 2024). Additionally, we gathered repositories with Kotlin files from The Stack v1.2. Kotlin files were identified using go-enry and include files with extensions such as .kt
, .kts
, and .gradle.kts
. It is estimated that we have collected 97% of available Kotlin repositories as of February 2024.
Initial filtering
We conducted full deduplication, using the hash of file content, as well as near deduplication using the same method as in The Stack v1.2. We aggregated the files from one near-deduplicated cluster into a file from the repository with the most stars.
Detecting permissive licenses
We filtered permissive repositories based on the licenses detected by GitHub, and using go-license-detector if GitHub did not have licensing information available. The list of permissive licenses used in dataset can be found here.
Personal and Sensitive Information
To filter out personal information, we applied the same model that was used for The Stack v2 — star-pii.
Column description
The dataset contains the following columns:
size
— size of the file in bytescontent
— text (content) of the file after removing personal identifiable informationrepo_id
— GitHub ID of the repositorypath
— path to a fileowner
— repo owner on GitHubname
— repo name on GitHubcommit_sha
— hash of the commit, from which the revision of the file is takenstars
— number of stars in the repo at the moment of collectionforks
— number of forks in the repo at the moment of collectionissues
— number of issues in the repo at the moment of collectionis_fork
—true
if the repo is a fork or not as defined by GitHubmain_language
— main language of the repo as defined by GitHublanguages_distribution
— JSON with the distribution of languages by size in bytes in the repolicense
— permissive license of the repository
Opt-out
If you want your data to be removed from dataset, or have any other questions, please reach out to Sergey Titov: [email protected]
- Downloads last month
- 335
Models trained or fine-tuned on JetBrains/KStack
