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
server/server/src/main/kotlin/org/jetbrains/bsp/bazel/server/sync/languages/android/AndroidLanguagePlugin.kt
JetBrains
826,262,028
false
null
package org.jetbrains.bsp.bazel.server.sync.languages.android import ch.epfl.scala.bsp4j.BuildTarget import org.jetbrains.bsp.bazel.info.BspTargetInfo import org.jetbrains.bsp.bazel.server.dependencygraph.DependencyGraph import org.jetbrains.bsp.bazel.server.paths.BazelPathsResolver import org.jetbrains.bsp.bazel.server.sync.languages.LanguagePlugin import org.jetbrains.bsp.bazel.server.sync.languages.SourceRootAndData import org.jetbrains.bsp.bazel.server.sync.languages.java.JavaLanguagePlugin import org.jetbrains.bsp.bazel.server.sync.languages.kotlin.KotlinLanguagePlugin import org.jetbrains.bsp.bazel.server.sync.languages.kotlin.KotlinModule import org.jetbrains.bsp.protocol.AndroidBuildTarget import org.jetbrains.bsp.protocol.AndroidTargetType import java.net.URI import java.nio.file.Path class AndroidLanguagePlugin( private val javaLanguagePlugin: JavaLanguagePlugin, private val kotlinLanguagePlugin: KotlinLanguagePlugin, private val bazelPathsResolver: BazelPathsResolver, ) : LanguagePlugin<AndroidModule>() { override fun applyModuleData(moduleData: AndroidModule, buildTarget: BuildTarget) { val androidBuildTarget = with(moduleData) { AndroidBuildTarget( androidJar = androidJar.toString(), androidTargetType = androidTargetType, manifest = manifest?.toString(), resourceDirectories = resourceDirectories.map { it.toString() }, resourceJavaPackage = resourceJavaPackage, assetsDirectories = assetsDirectories.map { it.toString() }, ) } moduleData.javaModule?.let { javaLanguagePlugin.toJvmBuildTarget(it) }?.let { androidBuildTarget.jvmBuildTarget = it } moduleData.kotlinModule?.let { kotlinLanguagePlugin.toKotlinBuildTarget(it) }?.let { androidBuildTarget.kotlinBuildTarget = it } buildTarget.dataKind = "android" buildTarget.data = androidBuildTarget } override fun resolveModule(targetInfo: BspTargetInfo.TargetInfo): AndroidModule? { if (!targetInfo.hasAndroidTargetInfo()) return null val androidTargetInfo = targetInfo.androidTargetInfo val androidJar = bazelPathsResolver.resolveUri(androidTargetInfo.androidJar) val manifest = if (androidTargetInfo.hasManifest()) { bazelPathsResolver.resolveUri(androidTargetInfo.manifest) } else { null } val resourceDirectories = bazelPathsResolver.resolveUris(androidTargetInfo.resourceDirectoriesList) val resourceJavaPackage = androidTargetInfo.resourceJavaPackage.takeIf { it.isNotEmpty() } val assetsDirectories = bazelPathsResolver.resolveUris(androidTargetInfo.assetsDirectoriesList) val kotlinModule: KotlinModule? = kotlinLanguagePlugin.resolveModule(targetInfo) return AndroidModule( androidJar = androidJar, androidTargetType = getAndroidTargetType(targetInfo), manifest = manifest, resourceDirectories = resourceDirectories, resourceJavaPackage = resourceJavaPackage, assetsDirectories = assetsDirectories, javaModule = kotlinModule?.javaModule ?: javaLanguagePlugin.resolveModule(targetInfo), kotlinModule = kotlinModule, correspondingKotlinTarget = null, ) } private fun getAndroidTargetType(targetInfo: BspTargetInfo.TargetInfo): AndroidTargetType = when (targetInfo.kind) { "android_binary" -> AndroidTargetType.APP "android_library" -> AndroidTargetType.LIBRARY "android_local_test", "android_instrumentation_test" -> AndroidTargetType.TEST else -> AndroidTargetType.LIBRARY } override fun dependencySources(targetInfo: BspTargetInfo.TargetInfo, dependencyGraph: DependencyGraph): Set<URI> = javaLanguagePlugin.dependencySources(targetInfo, dependencyGraph) override fun calculateSourceRootAndAdditionalData(source: Path): SourceRootAndData = javaLanguagePlugin.calculateSourceRootAndAdditionalData(source) override fun resolveAdditionalResources(targetInfo: BspTargetInfo.TargetInfo): Set<URI> { if (!targetInfo.hasAndroidTargetInfo()) return emptySet() val androidTargetInfo = targetInfo.androidTargetInfo if (!androidTargetInfo.hasManifest()) return emptySet() return bazelPathsResolver .resolveUris(listOf(targetInfo.androidTargetInfo.manifest) + targetInfo.androidTargetInfo.resourceDirectoriesList) .toSet() } }
6
null
6
45
1d79484cfdf8fc31d3a4b214655e857214071723
4,366
hirschgarten
Apache License 2.0
Mobilex/src/commonMain/kotlin/au/com/crazybean/mobilex/repository/auth/network/AuthNetworkDataSource.kt
ravishanker
203,143,699
false
null
package au.com.crazybean.mobilex.repository.auth.network import au.com.crazybean.mobilex.data.model.Auth import au.com.crazybean.mobilex.data.responses.AuthResponse import au.com.crazybean.mobilex.repository.auth.AuthDataSource import au.com.crazybean.mobilex.sdk.network.HttpConfig import au.com.crazybean.mobilex.sdk.network.HttpEngine import io.ktor.client.request.get private val httpConfig = HttpConfig("localhost", 80, true) { serializer -> serializer.register(AuthResponse.serializer()) } class AuthNetworkDataSource : HttpEngine(httpConfig), AuthDataSource { override suspend fun login(name: String, password: String): Auth { return httpClient.get<AuthResponse>("").auth } override suspend fun register(name: String, password: String, mobile: String): Auth { return httpClient.get<AuthResponse>("").auth } }
3
Kotlin
1
0
551b457c5ddb6095ef70f6bcb91be6dd80b1a1db
855
kurir-x
Apache License 2.0
app/src/main/java/com/movies/douqi/base/BaseBindingActivity.kt
kuzzh
163,270,378
true
{"Kotlin": 172198, "Java": 3423}
package com.movies.douqi.base import androidx.lifecycle.ViewModel import com.movies.douqi.inject.ViewModelFactory import dagger.android.support.DaggerAppCompatActivity import javax.inject.Inject import kotlin.reflect.KClass /** * @author donnieSky * @created_at 2018/8/27. * @description * @version */ abstract class BaseBindingActivity<V : KClass<out ViewModel>> : DaggerAppCompatActivity() { @Inject lateinit var factory: ViewModelFactory }
0
Kotlin
0
0
0c749449664c0fc729a2ed67a9ce4f4d70ca4514
459
Digging
MIT License
bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/SiteService.kt
eclipse-tractusx
526,621,398
false
null
/******************************************************************************* * Copyright (c) 2021,2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.eclipse.tractusx.bpdm.gate.service import mu.KotlinLogging import org.eclipse.tractusx.bpdm.common.dto.response.PageResponse import org.eclipse.tractusx.bpdm.common.dto.saas.BusinessPartnerSaas import org.eclipse.tractusx.bpdm.common.exception.BpdmNotFoundException import org.eclipse.tractusx.bpdm.gate.api.model.LsaType import org.eclipse.tractusx.bpdm.common.model.OutputInputEnum import org.eclipse.tractusx.bpdm.gate.api.model.SiteGateInputRequest import org.eclipse.tractusx.bpdm.gate.api.model.SiteGateInputResponse import org.eclipse.tractusx.bpdm.gate.api.model.SiteGateOutputRequest import org.eclipse.tractusx.bpdm.gate.api.model.SiteGateOutputResponse import org.eclipse.tractusx.bpdm.gate.config.BpnConfigProperties import org.eclipse.tractusx.bpdm.gate.entity.ChangelogEntry import org.eclipse.tractusx.bpdm.gate.entity.Site import org.eclipse.tractusx.bpdm.gate.exception.SaasNonexistentParentException import org.eclipse.tractusx.bpdm.gate.repository.ChangelogRepository import org.eclipse.tractusx.bpdm.gate.repository.SiteRepository import org.springframework.data.domain.Page import org.springframework.data.domain.PageRequest import org.springframework.stereotype.Service @Service class SiteService( private val saasRequestMappingService: SaasRequestMappingService, private val saasClient: SaasClient, private val bpnConfigProperties: BpnConfigProperties, private val changelogRepository: ChangelogRepository, private val sitePersistenceService: SitePersistenceService, private val siteRepository: SiteRepository ) { private val logger = KotlinLogging.logger { } fun getSites(page: Int, size: Int, externalIds: Collection<String>? = null): PageResponse<SiteGateInputResponse> { val sitesPage = if (externalIds != null) { siteRepository.findByExternalIdInAndDataType(externalIds, OutputInputEnum.Input, PageRequest.of(page, size)) } else { siteRepository.findByDataType(OutputInputEnum.Input, PageRequest.of(page, size)) } return PageResponse( page = page, totalElements = sitesPage.totalElements, totalPages = sitesPage.totalPages, contentSize = sitesPage.content.size, content = toValidSite(sitesPage) ) } private fun toValidSite(sitePage: Page<Site>): List<SiteGateInputResponse> { return sitePage.content.map { site -> site.toSiteGateInputResponse(site) } } fun getSiteByExternalId(externalId: String): SiteGateInputResponse { val siteRecord = siteRepository.findByExternalIdAndDataType(externalId, OutputInputEnum.Input) ?: throw BpdmNotFoundException("Site", externalId) return siteRecord.toSiteGateInputResponse(siteRecord) } /** * Get output sites by first fetching sites from the database */ fun getSitesOutput(externalIds: Collection<String>?, page: Int, size: Int): PageResponse<SiteGateOutputResponse> { val sitePage = if (externalIds != null && externalIds.isNotEmpty()) { siteRepository.findByExternalIdInAndDataType(externalIds, OutputInputEnum.Output, PageRequest.of(page, size)) } else { siteRepository.findByDataType(OutputInputEnum.Output, PageRequest.of(page, size)) } return PageResponse( page = page, totalElements = sitePage.totalElements, totalPages = sitePage.totalPages, contentSize = sitePage.content.size, content = toValidOutputSites(sitePage), ) } private fun toValidOutputSites(sitePage: Page<Site>): List<SiteGateOutputResponse> { return sitePage.content.map { sites -> sites.toSiteGateOutputResponse(sites) } } /** * Upsert sites input to the database **/ fun upsertSites(sites: Collection<SiteGateInputRequest>) { sites.forEach { site -> changelogRepository.save(ChangelogEntry(site.externalId, LsaType.SITE)) } sitePersistenceService.persistSitesBP(sites, OutputInputEnum.Input) } /** * Upsert sites output to the database **/ fun upsertSitesOutput(sites: Collection<SiteGateOutputRequest>) { sitePersistenceService.persistSitesOutputBP(sites, OutputInputEnum.Output) } /** * Fetches parent information and converts the given [sites] to their corresponding SaaS models */ fun toSaasModels(sites: Collection<SiteGateInputRequest>): Collection<BusinessPartnerSaas> { val parentLegalEntitiesByExternalId = getParentLegalEntities(sites) return sites.map { toSaasModel(it, parentLegalEntitiesByExternalId[it.legalEntityExternalId]) } } private fun getParentLegalEntities(sites: Collection<SiteGateInputRequest>): Map<String, BusinessPartnerSaas> { val parentLegalEntityExternalIds = sites.map { it.legalEntityExternalId }.distinct().toList() val parentLegalEntitiesPage = saasClient.getLegalEntities(externalIds = parentLegalEntityExternalIds) if (parentLegalEntitiesPage.limit < parentLegalEntityExternalIds.size) { // should not happen as long as configured upsert limit is lower than SaaS's limit throw IllegalStateException("Could not fetch all parent legal entities in single request.") } return parentLegalEntitiesPage.values.associateBy { it.externalId!! } } private fun toSaasModel(site: SiteGateInputRequest, parentLegalEntity: BusinessPartnerSaas?): BusinessPartnerSaas { if (parentLegalEntity == null) { throw SaasNonexistentParentException(site.legalEntityExternalId) } val siteSaas = saasRequestMappingService.toSaasModel(site) val parentIdentifiersWithoutBpn = parentLegalEntity.identifiers.filter { it.type?.technicalKey != bpnConfigProperties.id } return siteSaas.copy(identifiers = siteSaas.identifiers.plus(parentIdentifiersWithoutBpn)) } }
36
Kotlin
6
2
c279eab5b76bd4db7778ae00af1787f222844129
6,905
bpdm
Apache License 2.0
feature-explorer-impl/src/main/kotlin/com/blacksquircle/ui/feature/explorer/data/repository/ExplorerRepositoryImpl.kt
massivemadness
100,590,072
false
null
/* * Copyright 2023 Squircle CE contributors. * * 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.blacksquircle.ui.feature.explorer.data.repository import android.content.Context import com.blacksquircle.ui.core.extensions.checkStorageAccess import com.blacksquircle.ui.core.provider.coroutine.DispatcherProvider import com.blacksquircle.ui.core.storage.keyvalue.SettingsManager import com.blacksquircle.ui.feature.explorer.R import com.blacksquircle.ui.feature.explorer.data.utils.fileComparator import com.blacksquircle.ui.feature.explorer.domain.factory.FilesystemFactory import com.blacksquircle.ui.feature.explorer.domain.model.FilesystemModel import com.blacksquircle.ui.feature.explorer.domain.repository.ExplorerRepository import com.blacksquircle.ui.feature.explorer.ui.worker.* import com.blacksquircle.ui.filesystem.base.exception.PermissionException import com.blacksquircle.ui.filesystem.base.model.FileModel import com.blacksquircle.ui.filesystem.base.model.FileTree import com.blacksquircle.ui.filesystem.local.LocalFilesystem import com.blacksquircle.ui.filesystem.root.RootFilesystem import kotlinx.coroutines.withContext import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class ExplorerRepositoryImpl( private val dispatcherProvider: DispatcherProvider, private val settingsManager: SettingsManager, private val filesystemFactory: FilesystemFactory, private val context: Context, ) : ExplorerRepository { private var currentFilesystem = settingsManager.filesystem override suspend fun loadFilesystems(): List<FilesystemModel> { return withContext(dispatcherProvider.io()) { listOf( FilesystemModel( uuid = LocalFilesystem.LOCAL_UUID, title = context.getString(R.string.storage_local), ), FilesystemModel( uuid = RootFilesystem.ROOT_UUID, title = context.getString(R.string.storage_root), ), ) } } override suspend fun selectFilesystem(filesystemUuid: String) { withContext(dispatcherProvider.io()) { settingsManager.filesystem = filesystemUuid currentFilesystem = filesystemUuid } } override suspend fun listFiles(parent: FileModel?): FileTree { return withContext(dispatcherProvider.io()) { suspendCoroutine { cont -> context.checkStorageAccess( onSuccess = { cont.resume(Unit) }, onFailure = { cont.resumeWithException(PermissionException()) }, ) } val filesystem = filesystemFactory.create(currentFilesystem) val fileTree = filesystem.provideDirectory(parent ?: filesystem.defaultLocation()) fileTree.copy( children = fileTree.children .filter { if (it.isHidden) settingsManager.showHidden else true } .sortedWith(fileComparator(settingsManager.sortMode.toInt())) .sortedBy { it.directory != settingsManager.foldersOnTop }, ) } } override suspend fun createFile(fileModel: FileModel) { withContext(dispatcherProvider.io()) { context.checkStorageAccess( onSuccess = { CreateFileWorker.scheduleJob(context, listOf(fileModel)) }, onFailure = { throw PermissionException() }, ) } } override suspend fun renameFile(source: FileModel, dest: FileModel) { withContext(dispatcherProvider.io()) { context.checkStorageAccess( onSuccess = { RenameFileWorker.scheduleJob(context, listOf(source, dest)) }, onFailure = { throw PermissionException() }, ) } } override suspend fun deleteFiles(source: List<FileModel>) { context.checkStorageAccess( onSuccess = { DeleteFileWorker.scheduleJob(context, source) }, onFailure = { throw PermissionException() }, ) } override suspend fun copyFiles(source: List<FileModel>, dest: FileModel) { context.checkStorageAccess( onSuccess = { CopyFileWorker.scheduleJob(context, source + dest) }, onFailure = { throw PermissionException() }, ) } override suspend fun cutFiles(source: List<FileModel>, dest: FileModel) { context.checkStorageAccess( onSuccess = { CutFileWorker.scheduleJob(context, source + dest) }, onFailure = { throw PermissionException() }, ) } override suspend fun compressFiles(source: List<FileModel>, dest: FileModel) { context.checkStorageAccess( onSuccess = { CompressFileWorker.scheduleJob(context, source + dest) }, onFailure = { throw PermissionException() }, ) } override suspend fun extractFiles(source: FileModel, dest: FileModel) { context.checkStorageAccess( onSuccess = { ExtractFileWorker.scheduleJob(context, listOf(source, dest)) }, onFailure = { throw PermissionException() }, ) } }
49
null
75
708
2622fcc49a1d71ea1dec87c460d4586d671646c0
5,767
Squircle-CE
Apache License 2.0
graphql-core/src/main/kotlin/io/github/wickedev/graphql/types/ID.kt
wickedev
439,584,762
false
{"Kotlin": 269467, "JavaScript": 6748, "Java": 2439, "CSS": 1699}
@file:Suppress("MemberVisibilityCanBePrivate", "unused") package io.github.wickedev.graphql.types import io.github.wickedev.graphql.extentions.encodeBase64 import kotlin.reflect.KClass data class ID(val type: String, val value: String) { companion object { val Empty = ID("", "") } val encoded: String = if (type.isNotEmpty()) "$type:$value".encodeBase64() else value.encodeBase64() constructor(value: String) : this("", value) fun toGlobalId(type: String): ID = ID(type, value) fun toGlobalId(type: KClass<*>): ID = ID(type.simpleName ?: "", value) override fun toString(): String = if (type.isEmpty()) value else "ID($type:$value:$encoded)" }
0
Kotlin
0
19
d6913beaecf9e7ef065acdb1805794a10b07d55e
690
graphql-jetpack
The Unlicense
src/test/kotlin/io/justdevit/libs/statemachine/dsl/builder/StateMachineConfigurationBuilderTest.kt
temofey1989
433,707,820
false
null
package io.justdevit.libs.statemachine.dsl.builder import io.justdevit.libs.statemachine.action.TransitionAction import io.justdevit.libs.statemachine.guard.TransitionGuard import io.mockk.isMockKMock import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.util.UUID.randomUUID import java.util.function.Consumer internal class StateMachineConfigurationBuilderTest { @Test fun `Should reject on missed initial state`() { val builder = StateMachineConfigurationBuilder<Any, Any>() builder.finalStates = setOf(2) assertThrows<IllegalStateException> { builder.build() } } @Test fun `Should reject on missed final state`() { val builder = StateMachineConfigurationBuilder<Any, Any>() builder.initialState = 1 assertThrows<IllegalStateException> { builder.build() } } @Test fun `Should be able to create state machine configuration`() { val builder = StateMachineConfigurationBuilder<String, String>() builder.id = randomUUID() builder.initialState = "S1" builder.finalStates = setOf("S2") builder.from("S1") { to("S2").with("TEST") } builder.globalActions { +mockk<TransitionAction<String, String>>() } builder.globalGuards { +mockk<TransitionGuard<String, String>>() } val result = builder.build() with(result) { assertThat(id).isEqualTo(builder.id) assertThat(initialState).isEqualTo(builder.initialState) assertThat(finalStates).isEqualTo(builder.finalStates) assertThat(transitions).singleElement().satisfies(Consumer { assertThat(it.sourceState).isEqualTo("S1") assertThat(it.targetState).isEqualTo("S2") assertThat(it.event).isEqualTo("TEST") assertThat(it.config.actions).isEmpty() assertThat(it.config.guards).isEmpty() }) assertThat(globalActions).singleElement().satisfies(Consumer { isMockKMock(it) }) assertThat(globalGuards).singleElement().satisfies(Consumer { isMockKMock(it) }) } } }
1
Kotlin
0
0
325276532f3b0fe9bf9abd3ebbc3636d5d80ecb1
2,353
state-machine
Apache License 2.0
Chapter01/src/main/kotlin/13_Data_Classes.kt
PacktPublishing
373,735,637
false
null
data class User(val username: String, private val password: String) { fun hidePassword() = "*".repeat(password.length) } fun main() { val user = User("Alexey", "abcd1234") println(user.hidePassword()) }
0
Kotlin
9
7
887086024fbc675d35deb2d077ef0f4ed3d158e6
215
Kotlin-Design-Patterns-and-Best-Practices
MIT License
src/main/kotlin/io/titandata/titan/providers/local/RemoteList.kt
pioro
249,677,535
true
{"Kotlin": 220162, "Shell": 3605, "Dockerfile": 762, "Batchfile": 464, "PowerShell": 170}
/* * Copyright (c) 2019 by Delphix. All rights reserved. */ package io.titandata.titan.providers.local import io.titandata.client.apis.RemotesApi import io.titandata.serialization.RemoteUtil class RemoteList ( private val remotesApi: RemotesApi = RemotesApi() ) { private val n = System.lineSeparator() fun list(container: String) { val remotes = remotesApi.listRemotes(container) System.out.printf("%-20s %-20s${n}", "REMOTE", "URI") for (remote in remotes) { System.out.printf("%-20s %-20s${n}", remote.name, RemoteUtil().toUri(remote).first) } } }
4
null
0
0
da9cc4f29beb6cb5553ff2836ede8473082a2025
620
titan
Apache License 2.0
j2k/new/src/org/jetbrains/kotlin/nj2k/expressions.kt
JetBrains
278,369,660
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. */ package org.jetbrains.kotlin.nj2k import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.nj2k.conversions.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.symbols.JKMethodSymbol import org.jetbrains.kotlin.nj2k.symbols.JKSymbol import org.jetbrains.kotlin.nj2k.symbols.JKUnresolvedMethod import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKNoType import org.jetbrains.kotlin.nj2k.types.JKType import org.jetbrains.kotlin.nj2k.types.JKTypeFactory import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun JKOperator.isEquals() = token.safeAs<JKKtSingleValueOperatorToken>()?.psiToken in equalsOperators private val equalsOperators = TokenSet.create( KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ, KtTokens.EQEQ, KtTokens.EXCLEQ ) fun untilToExpression( from: JKExpression, to: JKExpression, conversionContext: NewJ2kConverterContext ): JKExpression = rangeExpression( from, to, "until", conversionContext ) fun downToExpression( from: JKExpression, to: JKExpression, conversionContext: NewJ2kConverterContext ): JKExpression = rangeExpression( from, to, "downTo", conversionContext ) fun JKExpression.parenthesizeIfBinaryExpression() = when (this) { is JKBinaryExpression -> JKParenthesizedExpression(this) else -> this } fun JKExpression.parenthesize() = JKParenthesizedExpression(this) fun rangeExpression( from: JKExpression, to: JKExpression, operatorName: String, conversionContext: NewJ2kConverterContext ): JKExpression = JKBinaryExpression( from, to, JKKtOperatorImpl( JKKtWordOperatorToken(operatorName), conversionContext.symbolProvider.provideMethodSymbol("kotlin.ranges.$operatorName").returnType!! ) ) fun blockStatement(vararg statements: JKStatement) = JKBlockStatement(JKBlockImpl(statements.toList())) fun blockStatement(statements: List<JKStatement>) = JKBlockStatement(JKBlockImpl(statements)) fun useExpression( receiver: JKExpression, variableIdentifier: JKNameIdentifier, body: JKStatement, symbolProvider: JKSymbolProvider ): JKExpression { val useSymbol = symbolProvider.provideMethodSymbol("kotlin.io.use") val lambdaParameter = JKParameter(JKTypeElement(JKNoType), variableIdentifier) val lambda = JKLambdaExpression( body, listOf(lambdaParameter) ) val methodCall = JKCallExpressionImpl( useSymbol, listOf(lambda).toArgumentList() ) return JKQualifiedExpression(receiver, methodCall) } fun kotlinAssert(assertion: JKExpression, message: JKExpression?, typeFactory: JKTypeFactory) = JKCallExpressionImpl( JKUnresolvedMethod(//TODO resolve assert "assert", typeFactory, typeFactory.types.unit ), listOfNotNull(assertion, message).toArgumentList() ) fun jvmAnnotation(name: String, symbolProvider: JKSymbolProvider) = JKAnnotation( symbolProvider.provideClassSymbol("kotlin.jvm.$name") ) fun throwAnnotation(throws: List<JKType>, symbolProvider: JKSymbolProvider) = JKAnnotation( symbolProvider.provideClassSymbol("kotlin.jvm.Throws"), throws.map { JKAnnotationParameterImpl( JKClassLiteralExpression(JKTypeElement(it), JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS) ) } ) fun JKAnnotationList.annotationByFqName(fqName: String): JKAnnotation? = annotations.firstOrNull { it.classSymbol.fqName == fqName } fun stringLiteral(content: String, typeFactory: JKTypeFactory): JKExpression { val lines = content.split('\n') return lines.mapIndexed { i, line -> val newlineSeparator = if (i == lines.size - 1) "" else "\\n" JKLiteralExpression("\"$line$newlineSeparator\"", JKLiteralExpression.LiteralType.STRING) }.reduce { acc: JKExpression, literalExpression: JKLiteralExpression -> JKBinaryExpression(acc, literalExpression, JKKtOperatorImpl(JKOperatorToken.PLUS, typeFactory.types.string)) } } fun JKVariable.findUsages(scope: JKTreeElement, context: NewJ2kConverterContext): List<JKFieldAccessExpression> { val symbol = context.symbolProvider.provideUniverseSymbol(this) val usages = mutableListOf<JKFieldAccessExpression>() val searcher = object : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element is JKExpression) { element.unboxFieldReference()?.also { if (it.identifier == symbol) { usages += it } } } return recurse(element) } } searcher.runConversion(scope, context) return usages } fun JKExpression.unboxFieldReference(): JKFieldAccessExpression? = when { this is JKFieldAccessExpression -> this this is JKQualifiedExpression && receiver is JKThisExpression -> selector as? JKFieldAccessExpression else -> null } fun JKFieldAccessExpression.asAssignmentFromTarget(): JKKtAssignmentStatement? = parent.safeAs<JKKtAssignmentStatement>()?.takeIf { it.field == this } fun JKFieldAccessExpression.isInDecrementOrIncrement(): Boolean = when (parent.safeAs<JKUnaryExpression>()?.operator?.token) { JKOperatorToken.PLUSPLUS, JKOperatorToken.MINUSMINUS -> true else -> false } fun JKVariable.hasWritableUsages(scope: JKTreeElement, context: NewJ2kConverterContext): Boolean = findUsages(scope, context).any { it.asAssignmentFromTarget() != null || it.isInDecrementOrIncrement() } fun equalsExpression(left: JKExpression, right: JKExpression, typeFactory: JKTypeFactory) = JKBinaryExpression( left, right, JKKtOperatorImpl( JKOperatorToken.EQEQ, typeFactory.types.boolean ) ) fun createCompanion(declarations: List<JKDeclaration>): JKClass = JKClass( JKNameIdentifier(""), JKInheritanceInfo(emptyList(), emptyList()), JKClass.ClassKind.COMPANION, JKTypeParameterList(), JKClassBody(declarations), JKAnnotationList(), emptyList(), JKVisibilityModifierElement(Visibility.PUBLIC), JKModalityModifierElement(Modality.FINAL) ) fun JKClass.getCompanion(): JKClass? = declarationList.firstOrNull { it is JKClass && it.classKind == JKClass.ClassKind.COMPANION } as? JKClass fun JKClass.getOrCreateCompanionObject(): JKClass = getCompanion() ?: createCompanion(declarations = emptyList()) .also { classBody.declarations += it } fun runExpression(body: JKStatement, symbolProvider: JKSymbolProvider): JKExpression { val lambda = JKLambdaExpression( body, emptyList() ) return JKCallExpressionImpl( symbolProvider.provideMethodSymbol("kotlin.run"), listOf(lambda).toArgumentList() ) } fun JKTreeElement.asQualifierWithThisAsSelector(): JKQualifiedExpression? = parent?.safeAs<JKQualifiedExpression>() ?.takeIf { it.selector == this } fun JKAnnotationMemberValue.toExpression(symbolProvider: JKSymbolProvider): JKExpression { fun handleAnnotationParameter(element: JKTreeElement): JKTreeElement = when (element) { is JKClassLiteralExpression -> element.also { element.literalType = JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS } is JKTypeElement -> JKTypeElement(element.type.replaceJavaClassWithKotlinClassType(symbolProvider)) else -> applyRecursive(element, ::handleAnnotationParameter) } return handleAnnotationParameter( when (this) { is JKStubExpression -> this is JKAnnotation -> JKNewExpression( classSymbol, JKArgumentList( arguments.map { argument -> val value = argument.value.copyTreeAndDetach().toExpression(symbolProvider) when (argument) { is JKAnnotationNameParameter -> JKNamedArgument(value, JKNameIdentifier(argument.name.value)) else -> JKArgumentImpl(value) } } ), JKTypeArgumentList() ) is JKKtAnnotationArrayInitializerExpression -> JKKtAnnotationArrayInitializerExpression(initializers.map { it.detached(this).toExpression(symbolProvider) }) is JKExpression -> this else -> error("Bad initializer") } ) as JKExpression } fun JKExpression.asLiteralTextWithPrefix(): String? = when { this is JKPrefixExpression && (operator.token == JKOperatorToken.MINUS || operator.token == JKOperatorToken.PLUS) && expression is JKLiteralExpression -> operator.token.text + expression.cast<JKLiteralExpression>().literal this is JKLiteralExpression -> literal else -> null } fun JKClass.primaryConstructor(): JKKtPrimaryConstructor? = classBody.declarations.firstIsInstanceOrNull() fun List<JKExpression>.toArgumentList(): JKArgumentList = JKArgumentList(map { JKArgumentImpl(it) }) fun JKExpression.asStatement(): JKExpressionStatement = JKExpressionStatement(this) fun <T : JKExpression> T.nullIfStubExpression(): T? = if (this is JKStubExpression) null else this fun JKExpression.qualified(qualifier: JKExpression?) = if (qualifier != null && qualifier !is JKStubExpression) { JKQualifiedExpression(qualifier, this) } else this fun JKExpression.callOn( symbol: JKMethodSymbol, arguments: List<JKExpression> = emptyList(), typeArguments: List<JKTypeElement> = emptyList() ) = JKQualifiedExpression( this, JKCallExpressionImpl( symbol, JKArgumentList(arguments.map { JKArgumentImpl(it) }), JKTypeArgumentList(typeArguments) ) ) val JKStatement.statements: List<JKStatement> get() = when (this) { is JKBlockStatement -> block.statements else -> listOf(this) } val JKElement.psi: PsiElement? get() = (this as? PsiOwner)?.psi inline fun <reified Elem : PsiElement> JKElement.psi(): Elem? = (this as? PsiOwner)?.psi as? Elem fun JKTypeElement.present(): Boolean = type != JKNoType fun JKStatement.isEmpty(): Boolean = when (this) { is JKEmptyStatement -> true is JKBlockStatement -> block is JKBodyStub is JKExpressionStatement -> expression is JKStubExpression else -> false } fun JKInheritanceInfo.present(): Boolean = extends.isNotEmpty() || implements.isNotEmpty() fun JKClass.isLocalClass(): Boolean = parent !is JKClassBody && parent !is JKFile val JKClass.declarationList: List<JKDeclaration> get() = classBody.declarations val JKTreeElement.identifier: JKSymbol? get() = when (this) { is JKFieldAccessExpression -> identifier is JKCallExpression -> identifier is JKClassAccessExpression -> identifier is JKPackageAccessExpression -> identifier is JKNewExpression -> classSymbol else -> null } val JKClass.isObjectOrCompanionObject get() = classKind == JKClass.ClassKind.OBJECT || classKind == JKClass.ClassKind.COMPANION
214
null
4829
82
cc81d7505bc3e9ad503d706998ae8026c067e838
12,077
intellij-kotlin
Apache License 2.0
app/src/main/kotlin/dev/aaa1115910/bv/component/controllers2/MenuController.kt
aaa1115910
571,702,700
false
null
package dev.aaa1115910.bv.component.controllers2 import android.content.Context import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.animation.expandHorizontally import androidx.compose.animation.shrinkHorizontally import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ClearAll import androidx.compose.material.icons.outlined.ClosedCaption import androidx.compose.material.icons.outlined.Image import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.tv.material3.Surface import androidx.tv.material3.SurfaceDefaults import dev.aaa1115910.biliapi.entity.video.Subtitle import dev.aaa1115910.biliapi.entity.video.SubtitleAiStatus import dev.aaa1115910.biliapi.entity.video.SubtitleAiType import dev.aaa1115910.biliapi.entity.video.SubtitleType import dev.aaa1115910.bv.R import dev.aaa1115910.bv.component.controllers.LocalVideoPlayerControllerData import dev.aaa1115910.bv.component.controllers.VideoPlayerControllerData import dev.aaa1115910.bv.component.controllers2.playermenu.ClosedCaptionMenuList import dev.aaa1115910.bv.component.controllers2.playermenu.DanmakuMenuList import dev.aaa1115910.bv.component.controllers2.playermenu.MenuNavList import dev.aaa1115910.bv.component.controllers2.playermenu.PictureMenuList import dev.aaa1115910.bv.entity.Audio import dev.aaa1115910.bv.entity.VideoAspectRatio import dev.aaa1115910.bv.entity.VideoCodec import dev.aaa1115910.bv.ui.theme.BVTheme import dev.aaa1115910.bv.util.requestFocus import dev.aaa1115910.bv.util.swapList import kotlinx.coroutines.delay @Composable fun MenuController( modifier: Modifier = Modifier, show: Boolean, onResolutionChange: (Int) -> Unit = {}, onCodecChange: (VideoCodec) -> Unit = {}, onAspectRatioChange: (VideoAspectRatio) -> Unit, onPlaySpeedChange: (Float) -> Unit = {}, onAudioChange: (Audio) -> Unit, onDanmakuSwitchChange: (List<DanmakuType>) -> Unit, onDanmakuSizeChange: (Float) -> Unit, onDanmakuOpacityChange: (Float) -> Unit, onDanmakuAreaChange: (Float) -> Unit, onSubtitleChange: (Subtitle) -> Unit, onSubtitleSizeChange: (TextUnit) -> Unit, onSubtitleBackgroundOpacityChange: (Float) -> Unit, onSubtitleBottomPadding: (Dp) -> Unit ) { val scope = rememberCoroutineScope() val defaultFocusRequester = remember { FocusRequester() } LaunchedEffect(show) { if (show) { delay(100) defaultFocusRequester.requestFocus(scope) } } Box( modifier = modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd ) { AnimatedVisibility( visible = show, enter = expandHorizontally(), exit = shrinkHorizontally() ) { MenuController( defaultFocusRequester = defaultFocusRequester, onResolutionChange = onResolutionChange, onCodecChange = onCodecChange, onAspectRatioChange = onAspectRatioChange, onPlaySpeedChange = onPlaySpeedChange, onAudioChange = onAudioChange, onDanmakuSwitchChange = onDanmakuSwitchChange, onDanmakuSizeChange = onDanmakuSizeChange, onDanmakuOpacityChange = onDanmakuOpacityChange, onDanmakuAreaChange = onDanmakuAreaChange, onSubtitleChange = onSubtitleChange, onSubtitleSizeChange = onSubtitleSizeChange, onSubtitleBackgroundOpacityChange = onSubtitleBackgroundOpacityChange, onSubtitleBottomPadding = onSubtitleBottomPadding ) } } } @Composable fun MenuController( modifier: Modifier = Modifier, defaultFocusRequester: FocusRequester, onResolutionChange: (Int) -> Unit = {}, onCodecChange: (VideoCodec) -> Unit = {}, onAspectRatioChange: (VideoAspectRatio) -> Unit, onPlaySpeedChange: (Float) -> Unit, onAudioChange: (Audio) -> Unit, onDanmakuSwitchChange: (List<DanmakuType>) -> Unit, onDanmakuSizeChange: (Float) -> Unit, onDanmakuOpacityChange: (Float) -> Unit, onDanmakuAreaChange: (Float) -> Unit, onSubtitleChange: (Subtitle) -> Unit, onSubtitleSizeChange: (TextUnit) -> Unit, onSubtitleBackgroundOpacityChange: (Float) -> Unit, onSubtitleBottomPadding: (Dp) -> Unit ) { var selectedNavItem by remember { mutableStateOf(VideoPlayerMenuNavItem.Picture) } var focusState by remember { mutableStateOf(MenuFocusState.MenuNav) } Surface( modifier = modifier .fillMaxHeight(), colors = SurfaceDefaults.colors( containerColor = Color.Black.copy(alpha = 0.5f) ) ) { CompositionLocalProvider( LocalMenuFocusStateData provides MenuFocusStateData( focusState = focusState ) ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.End ) { MenuList( selectedNavMenu = selectedNavItem, onResolutionChange = onResolutionChange, onCodecChange = onCodecChange, onPlaySpeedChange = onPlaySpeedChange, onAspectRatioChange = onAspectRatioChange, onAudioChange = onAudioChange, onDanmakuSwitchChange = onDanmakuSwitchChange, onDanmakuSizeChange = onDanmakuSizeChange, onDanmakuOpacityChange = onDanmakuOpacityChange, onDanmakuAreaChange = onDanmakuAreaChange, onFocusStateChange = { focusState = it }, onSubtitleChange = onSubtitleChange, onSubtitleSizeChange = onSubtitleSizeChange, onSubtitleBackgroundOpacityChange = onSubtitleBackgroundOpacityChange, onSubtitleBottomPadding = onSubtitleBottomPadding ) MenuNavList( modifier = Modifier .focusRequester(defaultFocusRequester) .onPreviewKeyEvent { if (it.type == KeyEventType.KeyUp) { if (listOf(Key.Enter, Key.DirectionCenter).contains(it.key)) { return@onPreviewKeyEvent false } return@onPreviewKeyEvent true } if (it.key == Key.DirectionLeft) focusState = MenuFocusState.Menu false }, selectedMenu = selectedNavItem, onSelectedChanged = { selectedNavItem = it }, isFocusing = focusState == MenuFocusState.MenuNav ) } } } } @Composable private fun MenuList( modifier: Modifier = Modifier, selectedNavMenu: VideoPlayerMenuNavItem, onResolutionChange: (Int) -> Unit, onCodecChange: (VideoCodec) -> Unit, onAspectRatioChange: (VideoAspectRatio) -> Unit, onPlaySpeedChange: (Float) -> Unit, onAudioChange: (Audio) -> Unit, onDanmakuSwitchChange: (List<DanmakuType>) -> Unit, onDanmakuSizeChange: (Float) -> Unit, onDanmakuOpacityChange: (Float) -> Unit, onDanmakuAreaChange: (Float) -> Unit, onSubtitleChange: (Subtitle) -> Unit, onSubtitleSizeChange: (TextUnit) -> Unit, onSubtitleBackgroundOpacityChange: (Float) -> Unit, onSubtitleBottomPadding: (Dp) -> Unit, onFocusStateChange: (MenuFocusState) -> Unit ) { Box( modifier = modifier .animateContentSize(), contentAlignment = Alignment.Center ) { when (selectedNavMenu) { VideoPlayerMenuNavItem.Picture -> { PictureMenuList( onResolutionChange = onResolutionChange, onCodecChange = onCodecChange, onAspectRatioChange = onAspectRatioChange, onPlaySpeedChange = onPlaySpeedChange, onAudioChange = onAudioChange, onFocusStateChange = onFocusStateChange ) } VideoPlayerMenuNavItem.Danmaku -> { DanmakuMenuList( onDanmakuSwitchChange = onDanmakuSwitchChange, onDanmakuSizeChange = onDanmakuSizeChange, onDanmakuOpacityChange = onDanmakuOpacityChange, onDanmakuAreaChange = onDanmakuAreaChange, onFocusStateChange = onFocusStateChange, ) } VideoPlayerMenuNavItem.ClosedCaption -> { ClosedCaptionMenuList( onSubtitleChange = onSubtitleChange, onSubtitleSizeChange = onSubtitleSizeChange, onSubtitleBackgroundOpacityChange = onSubtitleBackgroundOpacityChange, onSubtitleBottomPadding = onSubtitleBottomPadding, onFocusStateChange = onFocusStateChange ) } } } } enum class VideoPlayerMenuNavItem(private val strRes: Int, val icon: ImageVector) { Picture(R.string.video_player_menu_nav_picture, Icons.Outlined.Image), Danmaku(R.string.video_player_menu_nav_danmaku, Icons.Outlined.ClearAll), ClosedCaption(R.string.video_player_menu_nav_subtitle, Icons.Outlined.ClosedCaption); fun getDisplayName(context: Context) = context.getString(strRes) } enum class VideoPlayerPictureMenuItem(private val strRes: Int) { Resolution(R.string.video_player_menu_picture_resolution), Codec(R.string.video_player_menu_picture_codec), AspectRatio(R.string.video_player_menu_picture_aspect_ratio), PlaySpeed(R.string.video_player_menu_picture_play_speed), Audio(R.string.video_player_menu_picture_audio); fun getDisplayName(context: Context) = context.getString(strRes) } enum class VideoPlayerDanmakuMenuItem(private val strRes: Int) { Switch(R.string.video_player_menu_danmaku_switch), Size(R.string.video_player_menu_danmaku_size), Opacity(R.string.video_player_menu_danmaku_opacity), Area(R.string.video_player_menu_danmaku_area); fun getDisplayName(context: Context) = context.getString(strRes) } enum class VideoPlayerClosedCaptionMenuItem(private val strRes: Int) { Switch(R.string.video_player_menu_subtitle_switch), Size(R.string.video_player_menu_subtitle_size), Opacity(R.string.video_player_menu_subtitle_background_opacity), Padding(R.string.video_player_menu_subtitle_bottom_padding); fun getDisplayName(context: Context) = context.getString(strRes) } enum class DanmakuType(private val strRes: Int) { All(R.string.video_player_menu_danmaku_type_all), Top(R.string.video_player_menu_danmaku_type_top), Rolling(R.string.video_player_menu_danmaku_type_cross), Bottom(R.string.video_player_menu_danmaku_type_bottom); fun getDisplayName(context: Context) = context.getString(strRes) } @Preview(device = "id:tv_1080p") @Composable fun MenuControllerPreview() { val defaultFocusRequester = remember { FocusRequester() } var currentResolution by remember { mutableIntStateOf(1) } var currentCodec by remember { mutableStateOf(VideoCodec.HEVC) } var currentVideoAspectRatio by remember { mutableStateOf(VideoAspectRatio.Default) } var currentPlaySpeed by remember { mutableFloatStateOf(1f) } var currentAudio by remember { mutableStateOf(Audio.A192K) } val currentDanmakuSwitch = remember { mutableStateListOf<DanmakuType>() } var currentDanmakuSize by remember { mutableFloatStateOf(1f) } var currentDanmakuOpacity by remember { mutableFloatStateOf(1f) } var currentDanmakuArea by remember { mutableFloatStateOf(1f) } var currentSubtitleId by remember { mutableLongStateOf(-1L) } val currentSubtitleList = remember { mutableStateListOf<Subtitle>() } var currentSubtitleFontSize by remember { mutableStateOf(24.sp) } var currentSubtitleBackgroundOpacity by remember { mutableFloatStateOf(0.4f) } var currentSubtitleBottomPadding by remember { mutableStateOf(8.dp) } LaunchedEffect(Unit) { currentSubtitleList.apply { addAll( listOf( Subtitle( id = -1, langDoc = "关闭", lang = "", url = "", type = SubtitleType.CC, aiType = SubtitleAiType.Normal, aiStatus = SubtitleAiStatus.None ), Subtitle( id = 1111, langDoc = "ai-zh", lang = "中文(自动翻译)", url = "", type = SubtitleType.CC, aiType = SubtitleAiType.Normal, aiStatus = SubtitleAiStatus.None ), Subtitle( id = 222, lang = "zh", langDoc = "中文", url = "", type = SubtitleType.CC, aiType = SubtitleAiType.Normal, aiStatus = SubtitleAiStatus.None ), Subtitle( id = 1333, lang = "ai-en", langDoc = "English", url = "", type = SubtitleType.CC, aiType = SubtitleAiType.Normal, aiStatus = SubtitleAiStatus.None ) ) ) } } BVTheme { Surface( colors = SurfaceDefaults.colors( containerColor = Color.White ) ) { Box(modifier = Modifier.fillMaxSize()) { CompositionLocalProvider( LocalVideoPlayerControllerData provides VideoPlayerControllerData( resolutionMap = mapOf( 1 to "1440", 2 to "1080", 3 to "720", 4 to "480", 5 to "360" ), availableVideoCodec = VideoCodec.entries, availableAudio = Audio.entries, currentResolution = currentResolution, currentVideoCodec = currentCodec, currentVideoAspectRatio = currentVideoAspectRatio, currentVideoSpeed = currentPlaySpeed, currentAudio = currentAudio, currentDanmakuEnabledList = currentDanmakuSwitch, currentDanmakuScale = currentDanmakuSize, currentDanmakuOpacity = currentDanmakuOpacity, currentDanmakuArea = currentDanmakuArea, currentSubtitleId = currentSubtitleId, availableSubtitleTracks = currentSubtitleList, currentSubtitleFontSize = currentSubtitleFontSize, currentSubtitleBackgroundOpacity = currentSubtitleBackgroundOpacity, currentSubtitleBottomPadding = currentSubtitleBottomPadding ) ) { MenuController( modifier = Modifier .align(Alignment.CenterEnd), defaultFocusRequester = defaultFocusRequester, onResolutionChange = { currentResolution = it }, onCodecChange = { currentCodec = it }, onAspectRatioChange = { currentVideoAspectRatio = it }, onPlaySpeedChange = { currentPlaySpeed = it }, onAudioChange = { currentAudio = it }, onDanmakuSwitchChange = { val a = currentDanmakuSwitch.toList() currentDanmakuSwitch.swapList(it) val b = currentDanmakuSwitch.toList() println("a=$a") println("b=$b") }, onDanmakuSizeChange = { currentDanmakuSize = it }, onDanmakuOpacityChange = { currentDanmakuOpacity = it }, onDanmakuAreaChange = { currentDanmakuArea = it }, onSubtitleChange = { currentSubtitleId = it.id }, onSubtitleSizeChange = { currentSubtitleFontSize = it }, onSubtitleBackgroundOpacityChange = { currentSubtitleBackgroundOpacity = it }, onSubtitleBottomPadding = { currentSubtitleBottomPadding = it } ) } } } } } enum class MenuFocusState { MenuNav, Menu, Items } data class MenuFocusStateData( val focusState: MenuFocusState = MenuFocusState.MenuNav ) val LocalMenuFocusStateData = compositionLocalOf { MenuFocusStateData() }
23
null
97
999
e93863f4f266485e16e1768fcea6e6b9ad0b276b
19,090
bv
MIT License
app/src/main/java/wannabit/io/cosmostaion/data/model/req/JsonRpcRequest.kt
cosmostation
418,314,439
false
null
package wannabit.io.cosmostaion.data.model.req data class JsonRpcRequest( val method: String, val jsonrpc: String, val id: Long, val params: List<Any?> ) { constructor(method: String, params: List<Any?>) : this( method, "2.0", 1, params ) } data class EstimateGasParams( val from: String?, val to: String?, val data: String? ) data class EstimateGasParamsWithValue( val from: String?, val to: String?, val data: String?, val value: String? ) data class EthCall( val from: String?, val to: String?, val data: String? )
0
null
43
83
b04f3615c7c7b4407d719e160155a8c03fbae3a9
581
cosmostation-android
MIT License
library/src/main/java/com/github/ushiosan23/android_utilities/android/activity/ActivityCompat.kt
Ushiosan23
381,842,600
false
null
package com.github.ushiosan23.android_utilities.android.activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity /** * Custom activity. * This activity load layout automatically, only you need to define [contentView] property to load target layout. * * @see AppCompatActivity * @see IActivityCompat */ abstract class ActivityCompat : AppCompatActivity(), IActivityCompat { /* --------------------------------------------------------- * * Properties * * --------------------------------------------------------- */ /** * Target layout id. * This property is required to create the activity. */ protected abstract val contentView: Int /* --------------------------------------------------------- * * Methods * * --------------------------------------------------------- */ /** * Attach to activity content and initialize all fragments. * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in [onSaveInstanceState]. ***Note: Otherwise it is null.*** */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Set defined content view resource id setContentView(contentView) // Called only if activity is loaded onActivityLoaded(savedInstanceState) } }
0
Kotlin
1
0
fde8e00cb3123018288c6cbd5a0f5730ef5ba18c
1,388
android_utilities
MIT License
compiler/fir/analysis-tests/testData/resolve/checkers/notUselessCast_1.kt
JetBrains
3,432,266
false
null
// ISSUE: KT-42136 // WITH_STDLIB open class Base class Derived : Base() fun test_0(d: Derived) { fun take(d: Derived) {} take(d <!USELESS_CAST!>as Derived<!>) // should be USELESS_CAST } fun test_1() { val list = listOf<Any>().map { Derived() as Base }.toMutableList() // should be no USELESS_CAST list.add(Base()) } fun test_2() { val list = listOf<Any>().map { Derived() }.toMutableList() list.add(<!ARGUMENT_TYPE_MISMATCH!>Base()<!>) // should be an error }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
490
kotlin
Apache License 2.0
app/src/main/java/com/jamal_aliev/paginator/MainViewModel.kt
jamal-wia
745,495,585
false
null
package com.jamal_aliev.paginator import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.jamal_aliev.paginator.MainViewState.DataState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class MainViewModel : ViewModel() { private val _state = MutableStateFlow(DataState(emptyList())) val state = _state.asStateFlow() private val paginator = Paginator(source = { SampleRepository.loadPage(it.toInt()) }) private var paginatorJob: Job? = null init { paginator.snapshot .onEach { data -> _state.update { DataState(data) } } .flowOn(Dispatchers.Main) .launchIn(viewModelScope) paginatorJob = viewModelScope.launch { delay(timeMillis = 1L) val async1 = async { paginator.loadPageState(1u, forceLoading = true) } val async2 = async { paginator.loadPageState(2u, forceLoading = true) } val async3 = async { paginator.loadPageState(3u, forceLoading = true) } val pageState1 = async1.await() val pageState2 = async2.await() val pageState3 = async3.await() paginator.setPageState(state = pageState1, silently = true) paginator.setPageState(state = pageState2, silently = true) paginator.setPageState(state = pageState3, silently = true) paginator.jumpForward() paginatorJob = null } } fun endReached() { if (paginatorJob != null) return paginatorJob = viewModelScope.launch { delay(timeMillis = 1L) paginator.nextPage() paginatorJob = null } } override fun onCleared() { paginator.release() super.onCleared() } fun refreshPage(pageState: Paginator.PageState.Error<String>) { if (paginatorJob != null) return paginatorJob = viewModelScope.launch { delay(timeMillis = 1L) val newState = paginator.loadPageState( page = pageState.page, forceLoading = true, loading = { page -> paginator.setPageState(paginator.ProgressState(page)) } ) paginator.setPageState(newState) paginatorJob = null } } class Factory : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return MainViewModel() as T } } }
0
null
0
3
b8857d079cd5d76b978cc6672d10b12859b2354a
2,927
Paginator
MIT License
src/main/kotlin/com/bruce/calculator/RpnInvoker.kt
gitbruce
186,278,558
false
null
package com.bruce.calculator import java.text.DecimalFormat import java.util.* class RpnInvoker { val valueStack = Stack<Double>() val undoStack = Stack<Command>() private val calculator = Calculator() private var positionIndex = 0 fun parse(input: String) { positionIndex = 1 val tokens = input.trim().split(" ") for (token in tokens) { if (StringUtils.isNumeric(token)) { valueStack.push(token.toDouble()) undoStack.push(null) } else { when (token.toLowerCase()) { "clear" -> { valueStack.clear() undoStack.clear() } "undo" -> { if (undoStack.size > 0 && valueStack.size > 0) { val lastResult = valueStack.pop() val lastCommand = undoStack.pop() if (lastCommand != null) { lastCommand.unExecute(lastResult) valueStack.push(calculator.getResult()) val reverseOperand = calculator.getReverseOperand() ?: throw CalculatorException("Reverse operand is missing") valueStack.push(reverseOperand) } } else { throw CalculatorException("There is no more to undo!") } } else -> { val map = ArithmeticOperation.arithmeticOperationMap() val operation = map[token] ?: throw CalculatorException("Available operators are +, -, *, /, sqrt, undo, clear.") val numOperands = operation.operandNumber if (numOperands > valueStack.size) { throwOperatorException(operation.symbol, positionIndex) } val firstOperand = valueStack.pop().toDouble() val secondOperand = if (numOperands > 1) valueStack.pop().toDouble() else null val command = CalculatorCommand(calculator, token, firstOperand, secondOperand) command.execute() valueStack.push(calculator.getResult()) undoStack.push(command) } } } positionIndex = positionIndex + 2 //consider empty space as one of position } } fun printStack() { val format = DecimalFormat("0.##########") print("stack: ") valueStack.map { print(format.format(it)+" ") } println() } private fun throwOperatorException(operator: String, positionIndex: Int) { val msg = String.format("operator %s (position: %d): insufficient parameters", operator, positionIndex) throw CalculatorException(msg) } }
0
Kotlin
0
0
9b1c69471602969f6a7dbab2a814e1282bd4ebbf
3,045
rpn
Apache License 2.0
Android/app/src/main/java/com/example/pro_diction/data/dto/SignDto.kt
GDSC-SWU
738,141,316
false
{"Kotlin": 373175, "Java": 92597, "Python": 59149, "Jupyter Notebook": 47255, "Dockerfile": 342}
package com.example.pro_diction.data.dto import androidx.annotation.DrawableRes data class SignDto( @DrawableRes val image: Int, val name: String )
0
Kotlin
0
1
51ced1607b5336ce33becce66f408d53c7e3358e
162
2024-ProDiction-SolutionChallenge
MIT License
compiler/tests-spec/testData/diagnostics/notLinked/dfa/neg/11.kt
JetBrains
3,432,266
false
null
// !DIAGNOSTICS: -UNUSED_EXPRESSION // SKIP_TXT /* * KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (NEGATIVE) * * SECTIONS: dfa * NUMBER: 11 * DESCRIPTION: Raw data flow analysis test * HELPERS: classes, objects, typealiases, functions, enumClasses, interfaces, sealedClasses * UNEXPECTED BEHAVIOUR * ISSUES: KT-28369 */ // TESTCASE NUMBER: 1 fun case_1() { var x: Boolean? = true if (<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> is Boolean && if (true) { x = null; true } else { false }) { <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!><!UNSAFE_CALL!>.<!>not() } } // TESTCASE NUMBER: 2 fun case_2() { var x: Boolean? = true if (<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> != null && try { x = null; true } catch (e: Exception) { false }) { <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!><!UNSAFE_CALL!>.<!>not() } } // TESTCASE NUMBER: 3 fun case_3() { var x: Boolean? = true if (<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> is Boolean) { funWithAnyArg(try { x = null; true } catch (e: Exception) { false }) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!><!UNSAFE_CALL!>.<!>not() } } // TESTCASE NUMBER: 4 fun case_4() { var x: Boolean? = true if (<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> != null) { false || when { else -> {x = null; true} } <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean? & kotlin.Nothing?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean? & kotlin.Nothing?")!>x<!><!UNSAFE_CALL!>.<!>not() } } /* * TESTCASE NUMBER: 5 * ISSUES: KT-35668 */ fun case_5() { var x: Int? = null if (<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int?")!>x<!> == try { x = 10; null } finally {} && <!SENSELESS_COMPARISON!>x != null<!>) { <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>x<!>.inv() } } // TESTCASE NUMBER: 6 fun case_6() { var x: Boolean? = true x as Boolean if (if (true) { x = null; true } else { false }) { <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!><!UNSAFE_CALL!>.<!>not() } } // TESTCASE NUMBER: 7 fun case_7() { var x: Boolean? = true x!! if (if (true) { x = null; true } else { false }) {} <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Boolean?")!>x<!><!UNSAFE_CALL!>.<!>not() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,720
kotlin
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/iam/ManagedPolicyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.iam import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.services.iam.IGroup import software.amazon.awscdk.services.iam.IRole import software.amazon.awscdk.services.iam.IUser import software.amazon.awscdk.services.iam.ManagedPolicy import software.amazon.awscdk.services.iam.PolicyDocument import software.amazon.awscdk.services.iam.PolicyStatement import software.constructs.Construct /** * Managed policy. * * Example: * ``` * Build build; * Role role = Role.Builder.create(this, "Role") * .assumedBy(new CompositePrincipal(new ServicePrincipal("gamelift.amazonaws.com"))) * .build(); * role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("CloudWatchAgentServerPolicy")); * BuildFleet fleet = BuildFleet.Builder.create(this, "Game server fleet") * .fleetName("test-fleet") * .content(build) * .instanceType(InstanceType.of(InstanceClass.C5, InstanceSize.LARGE)) * .runtimeConfiguration(RuntimeConfiguration.builder() * .serverProcesses(List.of(ServerProcess.builder() * .launchPath("/local/game/GameLiftExampleServer.x86_64") * .build())) * .build()) * .role(role) * .build(); * // Actions can also be grantted through dedicated method * fleet.grant(role, "gamelift:ListFleets"); * ``` */ @CdkDslMarker public class ManagedPolicyDsl( scope: Construct, id: String, ) { private val cdkBuilder: ManagedPolicy.Builder = ManagedPolicy.Builder.create(scope, id) private val _groups: MutableList<IGroup> = mutableListOf() private val _roles: MutableList<IRole> = mutableListOf() private val _statements: MutableList<PolicyStatement> = mutableListOf() private val _users: MutableList<IUser> = mutableListOf() /** * A description of the managed policy. * * Typically used to store information about the permissions defined in the policy. For example, * "Grants access to production DynamoDB tables." The policy description is immutable. After a * value is assigned, it cannot be changed. * * Default: - empty * * @param description A description of the managed policy. */ public fun description(description: String) { cdkBuilder.description(description) } /** * Initial PolicyDocument to use for this ManagedPolicy. * * If omited, any `PolicyStatement` provided in the `statements` property will be applied * against the empty default `PolicyDocument`. * * Default: - An empty policy. * * @param document Initial PolicyDocument to use for this ManagedPolicy. */ public fun document(document: PolicyDocumentDsl.() -> Unit = {}) { val builder = PolicyDocumentDsl() builder.apply(document) cdkBuilder.document(builder.build()) } /** * Initial PolicyDocument to use for this ManagedPolicy. * * If omited, any `PolicyStatement` provided in the `statements` property will be applied * against the empty default `PolicyDocument`. * * Default: - An empty policy. * * @param document Initial PolicyDocument to use for this ManagedPolicy. */ public fun document(document: PolicyDocument) { cdkBuilder.document(document) } /** * Groups to attach this policy to. * * You can also use `attachToGroup(group)` to attach this policy to a group. * * Default: - No groups. * * @param groups Groups to attach this policy to. */ public fun groups(vararg groups: IGroup) { _groups.addAll(listOf(*groups)) } /** * Groups to attach this policy to. * * You can also use `attachToGroup(group)` to attach this policy to a group. * * Default: - No groups. * * @param groups Groups to attach this policy to. */ public fun groups(groups: Collection<IGroup>) { _groups.addAll(groups) } /** * The name of the managed policy. * * If you specify multiple policies for an entity, specify unique names. For example, if you * specify a list of policies for an IAM role, each policy must have a unique name. * * Default: - A name is automatically generated. * * @param managedPolicyName The name of the managed policy. */ public fun managedPolicyName(managedPolicyName: String) { cdkBuilder.managedPolicyName(managedPolicyName) } /** * The path for the policy. * * This parameter allows (through its regex pattern) a string of characters consisting of either * a forward slash (/) by itself or a string that must begin and end with forward slashes. In * addition, it can contain any ASCII character from the ! (\u0021) through the DEL character * (\u007F), including most punctuation characters, digits, and upper and lowercased letters. * * For more information about paths, see IAM Identifiers in the IAM User Guide. * * Default: - "/" * * @param path The path for the policy. */ public fun path(path: String) { cdkBuilder.path(path) } /** * Roles to attach this policy to. * * You can also use `attachToRole(role)` to attach this policy to a role. * * Default: - No roles. * * @param roles Roles to attach this policy to. */ public fun roles(vararg roles: IRole) { _roles.addAll(listOf(*roles)) } /** * Roles to attach this policy to. * * You can also use `attachToRole(role)` to attach this policy to a role. * * Default: - No roles. * * @param roles Roles to attach this policy to. */ public fun roles(roles: Collection<IRole>) { _roles.addAll(roles) } /** * Initial set of permissions to add to this policy document. * * You can also use `addPermission(statement)` to add permissions later. * * Default: - No statements. * * @param statements Initial set of permissions to add to this policy document. */ public fun statements(statements: PolicyStatementDsl.() -> Unit) { _statements.add(PolicyStatementDsl().apply(statements).build()) } /** * Initial set of permissions to add to this policy document. * * You can also use `addPermission(statement)` to add permissions later. * * Default: - No statements. * * @param statements Initial set of permissions to add to this policy document. */ public fun statements(statements: Collection<PolicyStatement>) { _statements.addAll(statements) } /** * Users to attach this policy to. * * You can also use `attachToUser(user)` to attach this policy to a user. * * Default: - No users. * * @param users Users to attach this policy to. */ public fun users(vararg users: IUser) { _users.addAll(listOf(*users)) } /** * Users to attach this policy to. * * You can also use `attachToUser(user)` to attach this policy to a user. * * Default: - No users. * * @param users Users to attach this policy to. */ public fun users(users: Collection<IUser>) { _users.addAll(users) } public fun build(): ManagedPolicy { if (_groups.isNotEmpty()) cdkBuilder.groups(_groups) if (_roles.isNotEmpty()) cdkBuilder.roles(_roles) if (_statements.isNotEmpty()) cdkBuilder.statements(_statements) if (_users.isNotEmpty()) cdkBuilder.users(_users) return cdkBuilder.build() } }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
7,938
awscdk-dsl-kotlin
Apache License 2.0
fuzzer/fuzzing_output/crashing_tests/verified/useSiteVariance.kt-446984019.kt
ItsLastDay
102,885,402
false
null
import kotlin.reflect.KVariance import kotlin.test.assertEquals class Fourple<A, B, C, D> fun Int.foo(): Fourple<String, in String, out String, * > = null!! fun listOfStrings(): List<String> = null!! fun box(): String { assertEquals(listOf(KVariance.INVARIANT, KVariance.IN, KVariance.OUT, null), ::foo.returnType.arguments.map({it.variance})) assertEquals(KVariance.INVARIANT, (if ((::listOfStrings) !in (::listOfStrings)) { (::listOfStrings) } else { false }).returnType.arguments.first().variance) return "OK" }
2
null
1
6
56f50fc307709443bb0c53972d0c239e709ce8f2
514
KotlinFuzzer
MIT License
rssparser/src/main/java/com/prof/rssparser/caching/CachedFeedDao.kt
htchien
298,763,244
true
{"Kotlin": 211322, "Java": 14901}
package com.prof.rssparser.caching import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao internal abstract class CachedFeedDao { @Query(CacheConstants.QUERY_GET_CACHED_PROJECT) abstract suspend fun getCachedProject(urlHash: Int): CachedFeed? @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertFeed(cachedFeed: CachedFeed) @Query(CacheConstants.DELETE_ALL_QUERY) abstract suspend fun deleteAllFeed() @Query(CacheConstants.DELETE_CACHED_FEED) abstract suspend fun deleteFeed(urlHash: Int) }
0
null
0
1
571ed1b71b4e70e39394f3115eb98c360254dd98
622
RSS-Parser
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/jiraactions/page/IssueCreateDialog.kt
swidnow2
206,813,097
true
{"Kotlin": 142073, "Java": 1959, "Shell": 145}
package com.atlassian.performance.tools.jiraactions.page import com.atlassian.performance.tools.jiraactions.api.page.JiraErrors import com.atlassian.performance.tools.jiraactions.api.page.form.IssueForm import com.atlassian.performance.tools.jiraactions.api.page.isElementPresent import com.atlassian.performance.tools.jiraactions.api.page.tolerateDirtyFormsOnCurrentPage import com.atlassian.performance.tools.jiraactions.api.page.wait import org.openqa.selenium.By import org.openqa.selenium.WebDriver import org.openqa.selenium.support.ui.ExpectedConditions.* import java.time.Duration import java.util.function.Supplier internal class IssueCreateDialog( private val driver: WebDriver ) { private val form = IssueForm(By.cssSelector("form[name=jiraform]"), driver) private val projectField = SingleSelect(driver, By.id("project-field")) private val issueTypeField = SingleSelect(driver, By.id("issuetype-field")) private val configColumnField = By.id("qf-field-picker-trigger") fun waitForDialog(): IssueCreateDialog { val jiraErrors = JiraErrors(driver) driver.wait( timeout = Duration.ofSeconds(30), condition = or( visibilityOfElementLocated(By.id("create-issue-dialog")), jiraErrors.anyCommonError() ) ) jiraErrors.assertNoErrors() driver.tolerateDirtyFormsOnCurrentPage() return this } fun selectProject(projectName: String) = form.waitForRefresh(Supplier { projectField.select(projectName) return@Supplier this }) fun selectIssueType(issueType: String) = form.waitForRefresh(Supplier { issueTypeField.select(issueType) return@Supplier this }) fun getIssueTypes() = issueTypeField.getSuggestions() .plus(issueTypeField.getCurrentValue()) fun fill(fieldId: String, value: String): IssueCreateDialog { driver.wait(elementToBeClickable(By.id(fieldId))).sendKeys(value) return this } /** * Click 'Configure Fields' to display 'All' to ensure * all mandatory fields are displayed in creation dialog. * */ fun showAllFields(): IssueCreateDialog { driver.wait(elementToBeClickable(configColumnField)).click() val configureFieldsDialogId = "inline-dialog-field_picker_popup" driver.wait(visibilityOfElementLocated(By.id(configureFieldsDialogId))) val locator = By.xpath("//div[@id='$configureFieldsDialogId']//dd[1]//a") if (driver.isElementPresent(locator)) { driver.wait(elementToBeClickable(locator)).click() driver.wait(invisibilityOfElementLocated(By.id(configureFieldsDialogId))) driver.wait(visibilityOfElementLocated(By.id(configureFieldsDialogId))) } dismissConfigureFieldsDialog() return this } private fun dismissConfigureFieldsDialog(){ driver.wait(elementToBeClickable(By.xpath("//div[@id='create-issue-dialog']//h2"))).click() } fun fillRequiredFields(): IssueCreateDialog { form.fillRequiredFields() return this } fun submit() { driver.wait(elementToBeClickable(By.id("create-issue-submit"))).click() driver.wait(Duration.ofSeconds(30), invisibilityOfElementLocated(By.className("aui-blanket"))) } }
0
null
0
0
82319990663d5d6bbd7f3eb1ff775ad369beca33
3,351
jira-actions
Apache License 2.0
src/main/kotlin/com/github/oowekyala/ijcc/ide/structureview/JccFileStructureTreeElement.kt
oowekyala
160,946,520
false
{"Kotlin": 636577, "HTML": 12321, "Lex": 10654, "Shell": 1940, "Just": 101}
package com.github.oowekyala.ijcc.ide.structureview import com.github.oowekyala.ijcc.lang.model.GrammarNature.JJTREE import com.github.oowekyala.ijcc.lang.model.SyntheticToken import com.github.oowekyala.ijcc.lang.psi.* import com.github.oowekyala.ijcc.util.associateByToMostlySingular import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.common.PsiTreeElementBase import com.intellij.navigation.ItemPresentation import com.intellij.util.containers.MostlySingularMultiMap import javax.swing.Icon /** * Root of the structure view tree. * * @author Clément Fournier * @since 1.1 */ class JccFileStructureTreeElement(private val myFile: JccFile) : PsiTreeElementBase<JccFile>(myFile) { override fun getPresentation(): ItemPresentation = myFile.presentationForStructure override fun getPresentableText(): String? = myFile.presentableText override fun getIcon(open: Boolean): Icon? = myFile.presentationIcon override fun getValue(): JccFile = myFile override fun getChildrenBase(): Collection<StructureViewTreeElement> { // only iterates the tokens of the lexical grammar once instead of once per production. with(myFile) { val syntheticTokensByProd: MostlySingularMultiMap<JccNonTerminalProduction, JccRegexExpansionUnit?> = lexicalGrammar .defaultState .tokens .asSequence() .mapNotNull { it as? SyntheticToken } .associateByToMostlySingular({ it.regularExpression?.firstAncestorOrNull<JccNonTerminalProduction>() }) { it.declUnit } val nonTerminalChildren = nonTerminalProductions.map { val jjtNodes = when { it is JccBnfProduction && myFile.grammarNature >= JJTREE -> it.expansion ?.descendantSequence(includeSelf = true) ?.filterIsInstance<JccScopedExpansionUnit>() .orEmpty() else -> emptySequence() } JccStructureTreeElement( it, jjtNodes .plus(syntheticTokensByProd[it].filterNotNull()) .sortedBy(JccPsiElement::getTextOffset) .map(::JccStructureTreeElement) .toList() ) } val regexChildren = regexProductions.map { JccStructureTreeElement(it, it.regexSpecList.map(::JccStructureTreeElement)) } val optionsNode = options?.let { JccStructureTreeElement(it, it.optionBindingList.map(::JccStructureTreeElement)) } ?.let { sequenceOf(it) } .orEmpty() val otherLeaves = listOfNotNull(tokenManagerDecls.firstOrNull()).map(::JccStructureTreeElement) val parserClass = myFile.classes.toList().map { JccJavaClassTreeElementWrapper(it, myFile) } return sequenceOf( optionsNode, otherLeaves.asSequence(), parserClass.asSequence(), regexChildren, nonTerminalChildren ) .flatMap { it } .toList() } } }
11
Kotlin
6
44
c514083a161db56537d2473e42f2a1d4bf57eee1
3,621
intellij-javacc
MIT License
src/main/java/net/ccbluex/liquidbounce/features/module/modules/combat/BowAura.kt
Rmejia39
733,988,804
false
{"Kotlin": 2304965, "Java": 1271227, "GLSL": 13515, "JavaScript": 8926}
/* * FDPClient Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge by LiquidBounce. * https://github.com/SkidderMC/FDPClient/ */ package net.ccbluex.liquidbounce.features.module.modules.combat import net.ccbluex.liquidbounce.event.EventTarget import net.ccbluex.liquidbounce.event.Render3DEvent import net.ccbluex.liquidbounce.event.UpdateEvent import net.ccbluex.liquidbounce.features.module.Module import net.ccbluex.liquidbounce.features.module.ModuleCategory import net.ccbluex.liquidbounce.features.module.ModuleInfo import net.ccbluex.liquidbounce.features.value.BoolValue import net.ccbluex.liquidbounce.features.value.FloatValue import net.ccbluex.liquidbounce.features.value.ListValue import net.ccbluex.liquidbounce.utils.EntityUtils import net.ccbluex.liquidbounce.utils.RotationUtils import net.ccbluex.liquidbounce.utils.render.RenderUtils import net.minecraft.entity.Entity import net.minecraft.entity.EntityLivingBase import net.minecraft.init.Items import net.minecraft.item.ItemBow import net.minecraft.network.play.client.C07PacketPlayerDigging import net.minecraft.util.BlockPos import net.minecraft.util.EnumFacing import java.awt.Color @ModuleInfo(name = "BowAura", category = ModuleCategory.COMBAT) object BowAura : Module() { private val silentValue = BoolValue("Silent", true) private val predictValue = BoolValue("Predict", true) private val throughWallsValue = BoolValue("ThroughWalls", false) private val predictSizeValue = FloatValue("PredictSize", 2F, 0.1F, 5F).displayable { predictValue.get() } private val priorityValue = ListValue("Priority", arrayOf("Health", "Distance", "Direction"), "Direction") private val maxDistance = FloatValue("MaxDistance",100F,5F,200F) private val markValue = BoolValue("Mark", true) private var target: Entity? = null @EventTarget fun onUpdate(event: UpdateEvent){ target = null val invBow = bow ?: return target = getTarget(priorityValue.get()) ?: return mc.thePlayer!!.inventory.currentItem = invBow mc.gameSettings.keyBindUseItem.pressed = true RotationUtils.faceBow(target, silentValue.get(), predictValue.get(), predictSizeValue.get()) if (mc.thePlayer.isUsingItem&&mc.thePlayer.itemInUseDuration > 20){ mc.gameSettings.keyBindUseItem.pressed = false mc.thePlayer.stopUsingItem() mc.netHandler.addToSendQueue(C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN)) } } @EventTarget fun onRender3D(event: Render3DEvent){ if (!markValue.get()||target==null) return RenderUtils.drawPlatform(target, Color(37, 126, 255, 70)) } override fun onDisable() { target = null } private val bow: Int? get() { var arrow = false for (inv in mc.thePlayer.inventory.mainInventory){ if (inv != null&&inv.item==Items.arrow) { arrow = true break } } if (!arrow&&!mc.playerController.isInCreativeMode) return null for (i in 0..8) { val itemStack = mc.thePlayer.inventory.getStackInSlot(i) ?: continue if (itemStack.item is ItemBow) { return i } } return null } private fun getTarget(priorityMode: String): Entity? { val targets = mc.theWorld!!.loadedEntityList.filter { it is EntityLivingBase&& EntityUtils.isSelected(it, true)&& (throughWallsValue.get() || mc.thePlayer!!.canEntityBeSeen(it))&& mc.thePlayer.getDistanceToEntity(it)<=maxDistance.get() } return when { priorityMode.equals("distance", true) -> targets.minByOrNull { mc.thePlayer!!.getDistanceToEntity(it) } priorityMode.equals("direction", true) -> targets.minByOrNull { RotationUtils.getRotationDifference(it) } priorityMode.equals("health", true) -> targets.minByOrNull { (it as EntityLivingBase).health } else -> null } } }
3
Kotlin
0
0
b48c4e83c888568111a6665037db7fd3f7813ed3
4,161
FDPClient
MIT License
src/test/kotlin/LeidenAlgorithmTests.kt
Mishavint
364,892,431
false
null
import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.assertDoesNotThrow import visualizer.view.* import com.github.doyaaaaaken.kotlincsv.dsl.csvReader import visualizer.model.Algorithms class LeidenAlgorithmTests { private val graphView = GraphView() @BeforeEach fun setUp() { graphView.updateGraph(props.SAMPLE_GRAPH) } private val leiden = Algorithms() @Test fun `leiden Algorithm is working`() { assertDoesNotThrow { leiden.communitiesDetection(graphView,0.5) } } @Test fun `leiden Algorithm with 1 resolution will do as many communities as number of vertices`() { leiden.communitiesDetection(graphView,1.0) csvReader().open("tmp/fileAfterLeidenAlg.csv") { var line: List<String>? = readNext() while (line != null) { val column = line[0] val digits = column.split("\t") assertEquals(digits[0], digits[1]) line = readNext() } } } }
0
Kotlin
0
0
5d88c0ca3e4f9836021cfe67cab79895fcc49c8c
1,127
Graph-Visualizer
Apache License 2.0
services/csm.cloud.project.activity/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/project/facade/listener/strategies/state/CleanupStateFromProjectDeletedEventTest.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.project.project.facade.listener.strategies.state import com.bosch.pt.csm.cloud.common.test.event.EventStreamGeneratorStaticExtensions.Companion.getByReference import com.bosch.pt.csm.cloud.projectmanagement.activity.ActivityMatchers.hasId import com.bosch.pt.csm.cloud.projectmanagement.activity.andExpectOk import com.bosch.pt.csm.cloud.projectmanagement.application.SmartSiteSpringBootTest import com.bosch.pt.csm.cloud.projectmanagement.application.common.AbstractActivityIntegrationTest import com.bosch.pt.csm.cloud.projectmanagement.project.event.listener.message.buildAggregateIdentifier import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitProject import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitTask import com.bosch.pt.csm.cloud.projectmanagement.project.messages.ProjectEventEnumAvro.DELETED import com.bosch.pt.csm.cloud.projectmanagement.project.task.repository.findLatest import com.bosch.pt.csm.cloud.projectmanagement.task.message.getIdentifier import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskAggregateAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskStatusEnumAvro.DRAFT import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test @DisplayName("Verify project state and activities") @SmartSiteSpringBootTest class CleanupStateFromProjectDeletedEventTest : AbstractActivityIntegrationTest() { private val task by lazy { context["task"] as TaskAggregateAvro } @BeforeEach fun init() { eventStreamGenerator.submitTask(auditUserReference = "fm-user") { it.assignee = getByReference("fm-participant") it.name = "task" it.status = DRAFT // setting all non-mandatory fields to null it.location = null it.description = null } } @Test fun `are cleaned up after project deleted event`() { // Check activities and project state are not empty requestActivities(task).andExpectOk().andExpect(hasId(findLatestActivity().identifier)) val project = repositories.projectRepository.findById(project.buildAggregateIdentifier()) assertThat(project.isPresent).isTrue assertThat(repositories.taskRepository.findLatest(task.getIdentifier())).isNotNull eventStreamGenerator.submitProject(eventType = DELETED) // Check if state is cleaned up and related activities are deleted assertThat(repositories.activityRepository.findAll()).isEmpty() assertThat(repositories.projectRepository.findAll()).isEmpty() assertThat(repositories.taskRepository.findAll()).isEmpty() } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
2,919
bosch-pt-refinemysite-backend
Apache License 2.0
domain/monster-compendium/core/src/commonMain/kotlin/br/alexandregpereira/hunter/monster/compendium/domain/GetMonsterCompendiumBaseUseCase.kt
alexandregpereira
347,857,709
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.alexandregpereira.hunter.monster.compendium.domain import br.alexandregpereira.hunter.monster.compendium.domain.model.MonsterCompendium import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.single class GetMonsterCompendiumUseCase internal constructor( private val getMonsterPreviewsBySectionUseCase: GetMonsterPreviewsBySectionUseCase, private val getTableContentUseCase: GetTableContentUseCase, private val getAlphabetUseCase: GetAlphabetUseCase ) { operator fun invoke(): Flow<MonsterCompendium> { return getMonsterPreviewsBySectionUseCase().map { items -> val (tableContent, alphabet) = coroutineScope { val tableContentDeferred = async { getTableContentUseCase(items).single() } val alphabetDeferred = async { getAlphabetUseCase(items).single() } tableContentDeferred.await() to alphabetDeferred.await() } MonsterCompendium( items = items, tableContent = tableContent, alphabet = alphabet ) } } }
6
null
5
85
46a636ec6fe5a60101e761847c85776180c6f5b2
1,807
Monster-Compendium
Apache License 2.0
app/src/main/java/com/example/car_builder/Car.kt
EikeMB
700,591,077
false
{"Kotlin": 92113}
package com.example.car_builder class Car(var userEmail: String, var name:String, var parts: List<CarPart>, var vin:Int) { }
3
Kotlin
0
0
a7833fed4b4408ab743bae9658eb067178e18dd9
130
AppDev2_Project
MIT License
src/test/kotlin/de/bringmeister/spring/aws/kinesis/metrics/MetricsOutboundStreamTest.kt
bringmeister
125,221,797
false
null
package de.bringmeister.spring.aws.kinesis.metrics import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import de.bringmeister.spring.aws.kinesis.KinesisOutboundStream import de.bringmeister.spring.aws.kinesis.Record import io.micrometer.core.instrument.Tags import io.micrometer.core.instrument.simple.SimpleMeterRegistry import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.Test class MetricsOutboundStreamTest { private val registry = SimpleMeterRegistry() private val mockDelegate = mock<KinesisOutboundStream> { on { stream } doReturn "test" } private val mockTagsProvider = mock<KinesisTagsProvider> { } private val handler = MetricsOutboundStream(mockDelegate, registry, mockTagsProvider) private val record = Record(Any(), Any()) @Test fun `should time calls to delegate`() { val tags = Tags.of("test", "should time calls to delegate") whenever(mockTagsProvider.outboundTags("test", arrayOf(record), null)).thenReturn(tags) handler.send(record) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.outbound" && tags == Tags.of(it.tags) } } @Test fun `should count successful calls to delegate`() { val tags = Tags.of("test", "should count successful calls to delegate") whenever(mockTagsProvider.outboundTags("test", arrayOf(record), null)).thenReturn(tags) handler.send(record) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.outbound" && tags == Tags.of(it.tags) } } @Test fun `should count failed calls to delegate and bubble exception`() { val tags = Tags.of("test", "should count failed calls to delegate and bubble exception") whenever(mockTagsProvider.outboundTags("test", arrayOf(record), MyException)).thenReturn(tags) whenever(mockDelegate.send(record)).doThrow(MyException) assertThatCode { handler.send(record) } .isSameAs(MyException) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.outbound" && tags == Tags.of(it.tags) } } @Test fun `should invoke delegate listener`() { handler.send(record, record) verify(mockDelegate).send(record, record) } private object MyException : RuntimeException() }
5
null
6
24
1133096e4355403f50bb38ba46e7a98d7ead450f
2,624
aws-kinesis-spring-boot-starter
MIT License
app/src/test/kotlin/com/example/videogames/HttpControllersTests.kt
raoulsson
600,711,983
false
null
package com.example.videogames //import org.springframework.restdocs.RestDocumentationExtension //import org.springframework.restdocs.RestDocumentationContextProvider //import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document //import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration //import org.springframework.test.context.junit.jupiter.SpringExtension //import org.junit.jupiter.api.extension.ExtendWith //import org.junit.jupiter.api.BeforeEach //import org.springframework.test.web.servlet.setup.MockMvcBuilders //import org.springframework.web.context.WebApplicationContext /** * @see: https://www.baeldung.com/kotlin/spring-boot-testing * @see: https://github.com/spring-projects/spring-restdocs/blob/main/docs/src/docs/asciidoc/getting-started.adoc#setting-up-your-junit-5-tests */ /* @WebMvcTest //@ExtendWith(RestDocumentationExtension::class) //@ExtendWith(SpringExtension::class) @ActiveProfiles("unit-testing") class HttpControllersTests(@Autowired val mockMvc: MockMvc) { @MockkBean lateinit var userRepository: UserRepository @MockkBean lateinit var articleRepository: ArticleRepository/ // private var docMockMvc: MockMvc? = null */ /** * Should generate asciidoc snippets when running tests. Currently not working. * https://github.com/eugenp/tutorials/blob/master/spring-5/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java *//* // @BeforeEach // fun setUp(webApplicationContext: WebApplicationContext?, restDocumentation: RestDocumentationContextProvider?) { // docMockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext!!) // .apply(documentationConfiguration(restDocumentation)) // .alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()))) // .build() // } @Test fun `List articles`() { val johnDoe = User("johnDoe", "John", "Doe") val lorem5Article = Article("Lorem", "Lorem", "dolor sit amet", johnDoe) val ipsumArticle = Article("Ipsum", "Ipsum", "dolor sit amet", johnDoe) every { articleRepository.findAllByOrderByAddedAtDesc() } returns listOf(lorem5Article, ipsumArticle) mockMvc.perform(get("/api/article/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("\$.[0].author.login").value(johnDoe.login)) .andExpect(jsonPath("\$.[0].slug").value(lorem5Article.slug)) .andExpect(jsonPath("\$.[1].author.login").value(johnDoe.login)) .andExpect(jsonPath("\$.[1].slug").value(ipsumArticle.slug)) } @Test fun `List users`() { val johnDoe = User("johnDoe", "John", "Doe") val janeDoe = User("janeDoe", "Jane", "Doe") every { userRepository.findAll() } returns listOf(johnDoe, janeDoe) mockMvc.perform(get("/api/user/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("\$.[0].login").value(johnDoe.login)) .andExpect(jsonPath("\$.[1].login").value(janeDoe.login)) } } */
0
Kotlin
0
0
0999cfbdf83a6a13681757ea1f502cd4799fd019
3,130
gradle-kotlin-spring
MIT License
src/main/kotlin/icu/windea/pls/script/codeStyle/ParadoxScriptCodeStyleSettingsProvider.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.script.codeStyle import com.intellij.application.options.* import com.intellij.psi.codeStyle.* import icu.windea.pls.* class ParadoxScriptCodeStyleSettingsProvider : CodeStyleSettingsProvider() { override fun createCustomSettings(settings: CodeStyleSettings) = ParadoxScriptCodeStyleSettings(settings) override fun getConfigurableDisplayName() = paradoxScriptName override fun createConfigurable(settings: CodeStyleSettings, modelSettings: CodeStyleSettings): CodeStyleConfigurable { return object : CodeStyleAbstractConfigurable(settings, modelSettings, configurableDisplayName) { override fun createPanel(settings: CodeStyleSettings): CodeStyleAbstractPanel { return ParadoxScriptCodeStylePanel(currentSettings, settings) } } } }
1
Kotlin
1
7
037b9b4ba467ed49ea221b99efb0a26cd630bb67
778
Paradox-Language-Support
MIT License
app/src/main/java/com/elhady/movies/domain/mappers/TrailerMapper.kt
islamelhady
301,591,032
false
{"Kotlin": 393174}
package com.elhady.movies.domain.mappers import com.elhady.movies.data.remote.response.video.VideoDto import com.elhady.movies.domain.models.Trailer import com.elhady.movies.utilities.getKey import javax.inject.Inject class TrailerMapper @Inject constructor() : Mapper<VideoDto, Trailer> { override fun map(input: VideoDto): Trailer { return Trailer(videoKey = input.results?.getKey() ?: "") } }
1
Kotlin
0
0
37d0a811fa3c107a6018a80dcb443b4d340a96a3
416
movie-night-v2
Apache License 2.0
app/src/main/java/com/javavirys/mvvmsample/presentation/adapter/ProgramAdapter.kt
javavirys
369,163,438
false
null
/* * Copyright (C) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.javavirys.mvvmsample.presentation.adapter import android.view.ViewGroup import com.javavirys.mvvmsample.R import com.javavirys.mvvmsample.core.entity.ProgramType import com.javavirys.mvvmsample.presentation.entity.BaseProgramUi import com.javavirys.mvvmsample.presentation.entity.DayUi import com.javavirys.mvvmsample.presentation.entity.ProgramUi import com.javavirys.mvvmsample.util.extension.inflate class ProgramAdapter : BaseAdapter<BaseProgramUi>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): BaseViewHolder<BaseProgramUi> { return when (viewType) { ProgramType.PROGRAM.ordinal -> ProgramViewHolder(parent.inflate(R.layout.view_program_item)) ProgramType.DAY.ordinal -> DayViewHolder(parent.inflate(R.layout.view_day_item)) else -> throw RuntimeException("Unsupported type!") } } override fun getItemViewType(position: Int): Int { return when (list[position]) { is ProgramUi -> ProgramType.PROGRAM.ordinal is DayUi -> ProgramType.DAY.ordinal else -> throw RuntimeException("Unsupported type!") } } }
0
Kotlin
0
0
4efbbe88fb89dbe737f5d5aabb9d3e068e04a29d
1,783
MvvmSample
Apache License 2.0
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/HasExpectedMarker.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.highlighter.markers import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.MemberDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.util.expectedDescriptors import org.jetbrains.kotlin.idea.util.expectedDeclarationIfAny import org.jetbrains.kotlin.psi.KtDeclaration fun getExpectedDeclarationTooltip(declaration: KtDeclaration): String? { val descriptor = declaration.toDescriptor() as? MemberDescriptor ?: return null val expectDescriptors = descriptor.expectedDescriptors() val modulesString = getModulesStringForExpectActualMarkerTooltip(expectDescriptors) ?: return null return KotlinBundle.message( "highlighter.tool.tip.has.expect.declaration.in", modulesString ) } fun KtDeclaration.allNavigatableExpectedDeclarations(): List<KtDeclaration> = listOfNotNull(expectedDeclarationIfAny()) + findMarkerBoundDeclarations().mapNotNull { it.expectedDeclarationIfAny() } @NlsContexts.PopupTitle fun KtDeclaration.navigateToExpectedTitle() = KotlinBundle.message("highlighter.title.choose.expected.for", name.toString()) @NlsContexts.TabTitle fun KtDeclaration.navigateToExpectedUsagesTitle() = KotlinBundle.message("highlighter.title.expected.for", name.toString()) fun buildNavigateToExpectedDeclarationsPopup(element: PsiElement?): NavigationPopupDescriptor? { return element?.markerDeclaration?.let { val navigatableExpectedDeclarations = it.allNavigatableExpectedDeclarations() if (navigatableExpectedDeclarations.isEmpty()) return null return NavigationPopupDescriptor( navigatableExpectedDeclarations, it.navigateToExpectedTitle(), it.navigateToExpectedUsagesTitle(), ActualExpectedPsiElementCellRenderer() ) } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
2,093
intellij-community
Apache License 2.0
src/main/kotlin/me/hanslovsky/alkorithms/compare/BooleanComparator.kt
hanslovsky
246,364,714
false
null
package me.hanslovsky.alkorithms.compare interface BooleanComparator { fun compare(b1: Boolean, b2: Boolean): Int val reversed get() = this.let { object : BooleanComparator { override fun compare(b1: Boolean, b2: Boolean) = it.compare(b2, b1) } } companion object { // TODO replace with SAM conversion when Kotlin 1.4 is available val naturalOrder: BooleanComparator = object : BooleanComparator { override fun compare(b1: Boolean, b2: Boolean) = b1.compareTo(b2) } val naturalOrderReversed = naturalOrder.reversed } }
0
Kotlin
0
0
70e947c8fdaf58c8f09921fc6b192edde4483297
559
alkorithms
MIT License
composeApp/src/commonMain/kotlin/me/gustavolopezxyz/common/money/CurrencyPair.kt
gusaln
736,062,721
false
{"Kotlin": 304914}
/* * Copyright (c) 2023. <NAME>. All rights reserved. */ package me.gustavolopezxyz.common.money import androidx.compose.runtime.Immutable @Immutable data class CurrencyPair(val baseCurrency: Currency, val counterCurrency: Currency, val value: Double) { override fun toString(): String { return "$baseCurrency/$counterCurrency ${MoneyAmountFormat.format(value)}" } fun convert(amount: Money): Money { if (baseCurrency != amount.currency) { throw IllegalArgumentException("Pair $this can't convert ${amount.currency}") } return amount.copy(currency = counterCurrency, value = amount.value * value) } }
0
Kotlin
0
1
d1e56bb6dce4a0d9c430a8d4f6bcf67b1249ea52
667
wimm
MIT License
app/src/main/java/io/ak1/paper/data/repositories/image/ImageRepository.kt
akshay2211
165,540,070
false
null
/* * Copyright (C) 2022 akshay2211 (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.ak1.paper.data.repositories.image import io.ak1.paper.models.Image /** * Created by akshay on 04/06/22 * https://ak1.io */ interface ImageRepository { suspend fun create(image: Image) suspend fun getImageById(imageId: String): Image? suspend fun deleteImageById(imageId: String) suspend fun deleteImageByNoteId(noteId: String) }
5
Kotlin
25
150
44fd2eebfc52adee516d64171aef03f64fdbe1c1
963
Paper
Apache License 2.0
clashJ/src/main/kotlin/io/github/maicolantali/Client.kt
MaicolAntali
665,565,216
false
{"Kotlin": 210542}
package io.github.maicolantali import io.github.maicolantali.exception.BadGatewayException import io.github.maicolantali.exception.InvalidCredentialException import io.github.maicolantali.exception.MaintenanceException import io.github.maicolantali.exception.NotFoundException import io.github.maicolantali.http.query.PaginationQuery import io.github.maicolantali.http.query.SearchClanQuery import io.github.maicolantali.types.api.model.clans.capitalraidseasons.ClanCapitalRaidSeasons import io.github.maicolantali.types.api.model.clans.clan.Clan import io.github.maicolantali.types.api.model.clans.clan.ClanList import io.github.maicolantali.types.api.model.clans.clanMember.ClanMemberList import io.github.maicolantali.types.api.model.clans.clanwar.ClanWar import io.github.maicolantali.types.api.model.clans.clanwar.ClanWarLog import io.github.maicolantali.types.api.model.clans.clanwarleaguegroup.ClanWarLeagueGroup import io.github.maicolantali.types.api.model.goldpass.GoldPassSeason import io.github.maicolantali.types.api.model.labels.LabelList import io.github.maicolantali.types.api.model.leagues.league.League import io.github.maicolantali.types.api.model.leagues.league.LeagueList import io.github.maicolantali.types.api.model.leagues.leagueseason.LeagueSeasonList import io.github.maicolantali.types.api.model.leagues.simpleleague.SimpleLeague import io.github.maicolantali.types.api.model.leagues.simpleleague.SimpleLeagueList import io.github.maicolantali.types.api.model.locations.location.Location import io.github.maicolantali.types.api.model.locations.location.LocationList import io.github.maicolantali.types.api.model.locations.ranking.clan.ClanBuilderBaseRankingList import io.github.maicolantali.types.api.model.locations.ranking.clan.ClanCapitalRankingList import io.github.maicolantali.types.api.model.locations.ranking.clan.ClanRankingList import io.github.maicolantali.types.api.model.locations.ranking.player.PlayerBuilderBaseRankingList import io.github.maicolantali.types.api.model.locations.ranking.player.PlayerRankingList import io.github.maicolantali.types.api.model.players.player.Player import io.github.maicolantali.types.internal.configuration.ClientConfiguration import io.github.maicolantali.util.API_BASE_URL import io.github.maicolantali.util.encodeTag import io.github.maicolantali.util.getConfiguredRequestHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async /** * Client class is used to interact with the Clash of Clans API. * * This class provides methods to interact with the Clash of Clans API * by making HTTP requests using the provided [requestHandler]. * It encapsulates the logic for making specific API calls and handling the response data. * * @param email The email used for authentication. * @param password The password used for authentication. * @param clientConfiguration The configuration for the client. */ open class Client( internal open val email: String, internal open val password: String, clientConfiguration: ClientConfiguration.() -> Unit = {}, ) { internal val config = ClientConfiguration().apply(clientConfiguration) private val requestHandler by lazy { getConfiguredRequestHandler() } /** * Performs login into the Clash of Clans developer website using the provided credentials. * * The function uses the [requestHandler] to perform the login request and handle the response. * If the login is successful, temporary API keys are retrieved and filtered based on the current IP address. * * @throws InvalidCredentialException if the provided login credentials are incorrect or invalid. */ suspend fun login() { requestHandler.login() } /** * Searches for clans based on the provided [searchClanQuery]. * * @param searchClanQuery The [SearchClanQuery] object containing various search parameters. * @return A [Deferred] [ClanList] object containing a list of clans that match the search criteria. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun searchClan(searchClanQuery: SearchClanQuery): Deferred<ClanList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans?${searchClanQuery.createQuery()}") } } /** * Gets the Clan War League group for the clan specified by [clanTag]. * * @param clanTag The tag of the clan for which to retrieve the Clan War League group. * @return A [Deferred] [ClanWarLeagueGroup] object representing the Clan War League group for the specified clan. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested clan is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanWarLeagueGroup(clanTag: String): Deferred<ClanWarLeagueGroup> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans/${encodeTag(clanTag)}/currentwar/leaguegroup") } } /** * Gets the Clan War League war specified by [warTag]. * * @param warTag The tag of the Clan War League war to retrieve. * @return A [Deferred] [ClanWar] object representing the Clan War League war with the specified tag. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested war is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanWarLeagueWar(warTag: String): Deferred<ClanWar> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clanwarleagues/wars/${encodeTag(warTag)}") } } /** * Retrieves the current war of a clan based on the provided [clanTag]. * * @param clanTag The tag of the clan for which to retrieve the current war status. * @return A [Deferred] [ClanWar] object representing the current war status of the specified clan. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested clan is not found or does not have an ongoing war. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanCurrentWar(clanTag: String): Deferred<ClanWar> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans/${encodeTag(clanTag)}/currentwar") } } /** * Retrieves detailed information about a clan based on the provided [clanTag]. * * @param clanTag The tag of the clan for which to retrieve the detailed information. * @return A [Deferred] [Clan] object representing the detailed information of the specified clan. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested clan is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClan(clanTag: String): Deferred<Clan> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans/${encodeTag(clanTag)}") } } /** * Retrieves the war log of a clan based on the provided [clanTag]. * * @param clanTag The tag of the clan for which to retrieve the war log. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [ClanWarLog] object representing the war log of the specified clan. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested clan is not found or has no war log data available. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanWarLog( clanTag: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<ClanWarLog> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans/${encodeTag(clanTag)}/warlog?${pagination.createQuery()}") } } /** * Retrieves the list of members in a clan based on the provided [clanTag]. * * @param clanTag The tag of the clan for which to retrieve the member list. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [ClanMemberList] object representing the list of members in the specified clan. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested clan is not found or has no members. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanMembers( clanTag: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<ClanMemberList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans/${encodeTag(clanTag)}/members?${pagination.createQuery()}") } } /** * Retrieves the capital raid seasons of a clan based on the provided [clanTag]. * * @param clanTag The tag of the clan for which to retrieve the capital raid seasons. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [ClanCapitalRaidSeasons] object representing the capital raid seasons of the specified clan. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested clan is not found or has no capital raid season data available. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanCapitalRaidSeasons( clanTag: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<ClanCapitalRaidSeasons> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/clans/${encodeTag(clanTag)}/capitalraidseasons?${pagination.createQuery()}") } } /** * Retrieves detailed information about a player based on the provided [playerTag]. * * @param playerTag The tag of the player for which to retrieve the information. * @return A [Deferred] [Player] object representing detailed information about the specified player. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested player is not found or has no available information. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getPlayer(playerTag: String): Deferred<Player> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/players/${encodeTag(playerTag)}") } } /** * Retrieves a list of capital leagues. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [SimpleLeagueList] object representing the list of capital leagues. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getCapitalLeagues(pagination: PaginationQuery = PaginationQuery()): Deferred<SimpleLeagueList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/capitalleagues?${pagination.createQuery()}") } } /** * Retrieves detailed information about a specific capital league based on the provided [leagueId]. * * @param leagueId The ID of the capital league for which to retrieve the information. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [SimpleLeague] object representing detailed information about the specified capital league. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested capital league is not found or has no available information. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getCapitalLeague( leagueId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<SimpleLeague> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/capitalleagues/$leagueId?${pagination.createQuery()}") } } /** * Retrieves a list of leagues. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [LeagueList] object representing the list of leagues. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLeagues(pagination: PaginationQuery = PaginationQuery()): Deferred<LeagueList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/leagues?${pagination.createQuery()}") } } /** * Retrieves detailed information about a specific league based on the provided [leagueId]. * * @param leagueId The ID of the league for which to retrieve the information. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [League] object representing detailed information about the specified league. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested league is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLeague( leagueId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<League> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/leagues/$leagueId?${pagination.createQuery()}") } } /** * Retrieves a list of seasons for a specific league based on the provided [leagueId]. * * @param leagueId The ID of the league for which to retrieve the list of seasons. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [LeagueSeasonList] object representing the list of seasons for the specified league. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested league is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLeagueSeasons( leagueId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<LeagueSeasonList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/leagues/$leagueId/seasons?${pagination.createQuery()}") } } /** * Retrieves the ranking of players for a specific league season based on the provided [leagueId] and [seasonId]. * * @param leagueId The ID of the league for which to retrieve the ranking. * @param seasonId The ID of the season for which to retrieve the ranking. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [PlayerRankingList] object representing the ranking of players for the specified league season. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested league or season or its ranking is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLeagueSeasonRanking( leagueId: String, seasonId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<PlayerRankingList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/leagues/$leagueId/seasons/$seasonId?${pagination.createQuery()}") } } /** * Retrieves the list of Builder Base leagues. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [SimpleLeagueList] object representing the list of Builder Base leagues. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getBuilderBaseLeagues(pagination: PaginationQuery = PaginationQuery()): Deferred<SimpleLeagueList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/builderbaseleagues?${pagination.createQuery()}") } } /** * Retrieves information about a specific Builder Base league based on the provided [leagueId]. * * @param leagueId The ID of the Builder Base league to retrieve. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [SimpleLeague] object representing the specified Builder Base league. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested league is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getBuilderBaseLeague( leagueId: Int, pagination: PaginationQuery = PaginationQuery(), ): Deferred<SimpleLeague> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/builderbaseleagues/$leagueId?${pagination.createQuery()}") } } /** * Retrieves the list of War Leagues. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [SimpleLeagueList] object representing the list of War Leagues. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getWarLeagues(pagination: PaginationQuery = PaginationQuery()): Deferred<SimpleLeagueList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/warleagues?${pagination.createQuery()}") } } /** * Retrieves information about a specific War League based on the provided [leagueId]. * * @param leagueId The ID of the War League to retrieve. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [SimpleLeague] object representing the specified War League. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested league is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getWarLeague( leagueId: Int, pagination: PaginationQuery = PaginationQuery(), ): Deferred<SimpleLeague> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/warleagues/$leagueId?${pagination.createQuery()}") } } /** * Retrieves the list of available locations. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [LocationList] object representing the list of available locations. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocations(pagination: PaginationQuery = PaginationQuery()): Deferred<LocationList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations?${pagination.createQuery()}") } } /** * Retrieves information about a specific location based on the provided [locationId]. * * @param locationId The ID of the location to retrieve. * @return A [Deferred] [Location] object representing the specified location. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested location is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocation(locationId: String): Deferred<Location> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations/$locationId") } } /** * Retrieves the list of clans ranked in a specific location based on the provided [locationId]. * * @param locationId The ID of the location for which to retrieve the clan rankings. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [ClanRankingList] object representing the list of clans ranked in the specified location. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested location is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocationClanRanking( locationId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<ClanRankingList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations/$locationId/rankings/clans?${pagination.createQuery()}") } } /** * Retrieves the list of players ranked in a specific location based on the provided [locationId]. * * @param locationId The ID of the location for which to retrieve the player rankings. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [PlayerRankingList] object representing the list of players ranked in the specified location. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested location is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocationPlayerRanking( locationId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<PlayerRankingList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations/$locationId/rankings/players?${pagination.createQuery()}") } } /** * Retrieves the list of clans * ranked in the Builder Base for a specific location based on the provided [locationId]. * * @param locationId The ID of the location for which to retrieve the Builder Base clan rankings. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [ClanBuilderBaseRankingList] object representing the list of clans ranked in the Builder Base * for the specified location. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested location is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocationClanBuilderBaseRanking( locationId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<ClanBuilderBaseRankingList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations/$locationId/rankings/clans-builder-base?${pagination.createQuery()}") } } /** * Retrieves the list of players * ranked in the Builder Base for a specific location based on the provided [locationId]. * * @param locationId The ID of the location for which to retrieve the Builder Base player rankings. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [PlayerBuilderBaseRankingList] object representing the list of players ranked in the Builder Base * for the specified location. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested location is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocationPlayerBuilderBaseRanking( locationId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<PlayerBuilderBaseRankingList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations/$locationId/rankings/players-builder-base?${pagination.createQuery()}") } } /** * Retrieves the list of clans ranked in the Capital for a specific location based on the provided [locationId]. * * @param locationId The ID of the location for which to retrieve the Capital clan rankings. * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * @return A [Deferred] [ClanCapitalRankingList] object representing the list of clans ranked in the Capital * for the specified location. * * @throws MaintenanceException If the API is in maintenance. * @throws NotFoundException If the requested location is not found. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getLocationCapitalRanking( locationId: String, pagination: PaginationQuery = PaginationQuery(), ): Deferred<ClanCapitalRankingList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/locations/$locationId/rankings/capitals?${pagination.createQuery()}") } } /** * Retrieves the current Gold Pass season information. * * @return A [Deferred] [GoldPassSeason] object representing the current Gold Pass season information. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getCurrentGoldPass(): Deferred<GoldPassSeason> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/goldpass/seasons/current") } } /** * Retrieves a list of player labels. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * * @return A [Deferred] [LabelList] containing the list of player labels. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getPlayerLabels(pagination: PaginationQuery = PaginationQuery()): Deferred<LabelList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/labels/players?$pagination.createQuery()") } } /** * Retrieves a list of clan labels. * * @param pagination An optional [PaginationQuery] object for customizing the pagination of the results. * * @return A [Deferred] [LabelList] containing the list of clan labels. * * @throws MaintenanceException If the API is in maintenance. * @throws BadGatewayException If the API returns an unexpected gateway exception. */ suspend fun getClanLabels(pagination: PaginationQuery = PaginationQuery()): Deferred<LabelList> { return CoroutineScope(Dispatchers.IO).async { requestHandler.request("$API_BASE_URL/labels/clans?${pagination.createQuery()}") } } }
1
Kotlin
0
0
be0bae7345fc88830ff5a2c0ea34dc41171502c6
28,969
clashJ
MIT License
app/src/test/java/com/babylon/wallet/android/presentation/dialogs/address/AddressDetailsDialogViewModelTest.kt
radixdlt
513,047,280
false
null
@file:OptIn(ExperimentalCoroutinesApi::class) package com.babylon.wallet.android.presentation.dialogs.address import androidx.lifecycle.SavedStateHandle import app.cash.turbine.test import com.babylon.wallet.android.domain.usecases.GetResourcesUseCase import com.babylon.wallet.android.domain.usecases.VerifyAddressOnLedgerUseCase import com.babylon.wallet.android.domain.usecases.assets.GetPoolsUseCase import com.babylon.wallet.android.domain.usecases.assets.GetValidatorsUseCase import com.babylon.wallet.android.fakes.FakeProfileRepository import com.babylon.wallet.android.mockdata.sampleWithLedgerAccount import com.babylon.wallet.android.presentation.StateViewModelTest import com.babylon.wallet.android.presentation.ui.composables.actionableaddress.ActionableAddress import com.radixdlt.sargon.AccountAddress import com.radixdlt.sargon.Address import com.radixdlt.sargon.AddressFormat import com.radixdlt.sargon.IdentityAddress import com.radixdlt.sargon.IntentHash import com.radixdlt.sargon.NetworkId import com.radixdlt.sargon.NonEmptyMax64Bytes import com.radixdlt.sargon.NonFungibleGlobalId import com.radixdlt.sargon.NonFungibleLocalId import com.radixdlt.sargon.Profile import com.radixdlt.sargon.extensions.formatted import com.radixdlt.sargon.extensions.init import com.radixdlt.sargon.extensions.string import com.radixdlt.sargon.extensions.toBagOfBytes import com.radixdlt.sargon.samples.sample import com.radixdlt.sargon.samples.sampleMainnet import com.radixdlt.sargon.samples.sampleRandom import io.mockk.coEvery import io.mockk.every import io.mockk.mockk import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import rdx.works.core.domain.resources.Resource import rdx.works.core.domain.resources.Validator import rdx.works.core.domain.resources.sampleMainnet import rdx.works.core.sargon.activeAccountsOnCurrentNetwork import rdx.works.core.sargon.activePersonasOnCurrentNetwork import rdx.works.core.sargon.changeGatewayToNetworkId import rdx.works.core.sargon.isLedgerAccount import rdx.works.profile.domain.GetProfileUseCase import kotlin.random.Random class AddressDetailsDialogViewModelTest : StateViewModelTest<AddressDetailsDialogViewModel>() { private val savedStateHandle = mockk<SavedStateHandle>() private val profileRepository = FakeProfileRepository() private val getProfileUseCase = GetProfileUseCase( profileRepository = profileRepository, dispatcher = coroutineRule.dispatcher ) private val verifyAddressOnLedgerUseCase = mockk<VerifyAddressOnLedgerUseCase>() private val getResourcesUseCase = mockk<GetResourcesUseCase>() private val getPoolsUseCase = mockk<GetPoolsUseCase>() private val getValidatorsUseCase = mockk<GetValidatorsUseCase>() override fun initVM(): AddressDetailsDialogViewModel = AddressDetailsDialogViewModel( savedStateHandle = savedStateHandle, getProfileUseCase = getProfileUseCase, verifyAddressOnLedgerUseCase = verifyAddressOnLedgerUseCase, getResourcesUseCase = getResourcesUseCase, getPoolsUseCase = getPoolsUseCase, getValidatorsUseCase = getValidatorsUseCase ) @Test fun `given account address, verify that basic sections are added`() = runTest { val address = AccountAddress.sampleMainnet() provideInput(Address.Account(address)) val vm = vm.value advanceUntilIdle() val state = vm.state.value assertEquals( listOf( AddressDetailsDialogViewModel.State.Section.AccountAddressQRCode(accountAddress = address), with(address.formatted(AddressFormat.RAW)) { AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = this, boldRanges = persistentListOf( 0 until 4, length - 6 until length ) ) }, AddressDetailsDialogViewModel.State.Section.VisitDashboard( url = "https://dashboard.radixdlt.com/account/${address.formatted(AddressFormat.RAW)}" ) ), state.sections ) } @Test fun `given account address created with Ledger, verify that verify on ledger section is shown`() = runTest { val profile = Profile.sampleWithLedgerAccount().also { profileRepository.saveProfile(it) } val account = profile.activeAccountsOnCurrentNetwork.find { it.isLedgerAccount } ?: error("Expected ledger account but none found") provideInput(Address.Account(account.address)) val vm = vm.value advanceUntilIdle() val state = vm.state.value assertEquals( AddressDetailsDialogViewModel.State.Section.VerifyAddressOnLedger(accountAddress = account.address), state.sections.last() ) } @Test fun `given owned account, resolve title with account's name`() = runTest { val profile = Profile.sample().changeGatewayToNetworkId(NetworkId.MAINNET) profileRepository.saveProfile(profile = profile) val account = profile.activeAccountsOnCurrentNetwork.first() provideInput(Address.Account(account.address)) val vm = vm.value advanceUntilIdle() assertEquals( account.displayName.value, vm.state.value.title ) } @Test fun `given not owned account address, resolve no title`() = runTest { provideInput(Address.Account(AccountAddress.sampleRandom(NetworkId.MAINNET))) val vm = vm.value advanceUntilIdle() assertNull(vm.state.value.title) } @Test fun `given owned identity address, resolve title with persona's name`() = runTest { val profile = Profile.sample().changeGatewayToNetworkId(NetworkId.MAINNET) profileRepository.saveProfile(profile = profile) val persona = profile.activePersonasOnCurrentNetwork.first() provideInput(Address.Identity(persona.address)) val vm = vm.value advanceUntilIdle() assertEquals( persona.displayName.value, vm.state.value.title ) } @Test fun `given not owned identity address, resolve no title`() = runTest { provideInput(Address.Identity(IdentityAddress.sampleRandom(NetworkId.MAINNET))) val vm = vm.value advanceUntilIdle() assertNull(vm.state.value.title) } @Test fun `given fungible resource address, resolve title with name and symbol`() = runTest { val resource = Resource.FungibleResource.sampleMainnet() coEvery { getResourcesUseCase(setOf(resource.address)) } returns Result.success( listOf( resource ) ) provideInput(Address.Resource(resource.address)) val vm = vm.value advanceUntilIdle() assertEquals( "${resource.name} (${resource.symbol})", vm.state.value.title ) } @Test fun `given non fungible resource address, resolve title with name`() = runTest { val resource = Resource.NonFungibleResource.sampleMainnet() coEvery { getResourcesUseCase(setOf(resource.address)) } returns Result.success( listOf( resource ) ) provideInput(Address.Resource(resource.address)) val vm = vm.value advanceUntilIdle() assertEquals( resource.name, vm.state.value.title ) } @Test fun `given validator address, resolve title with validator's name`() = runTest { val validator = Validator.sampleMainnet() coEvery { getValidatorsUseCase(setOf(validator.address)) } returns Result.success( listOf( validator ) ) provideInput(Address.Validator(validator.address)) val vm = vm.value advanceUntilIdle() assertEquals( validator.name, vm.state.value.title ) } @Test fun `given address, when copy clicked, verify that copy event is sent`() = runTest { val address = AccountAddress.sampleRandom(NetworkId.MAINNET) provideInput(Address.Account(address)) val vm = vm.value advanceUntilIdle() vm.onCopyClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.PerformCopy( valueToCopy = address.formatted(AddressFormat.RAW) ), event ) } } @Test fun `given address, when enlarge clicked, verify that enlarge event is sent`() = runTest { val addressString = "account_tdx_2_12xn3lgz7xv4d0d4cx25nvfekyxx0fsawhmtht0dd550vcu5wwl0g70" val address = AccountAddress.init(addressString) provideInput(Address.Account(address)) val vm = vm.value advanceUntilIdle() vm.onEnlargeClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.PerformEnlarge( value = addressString, numberRanges = listOf( 12 until 13, 14 until 16, 18 until 19, 22 until 23, 25 until 26, 27 until 28, 29 until 30, 32 until 34, 42 until 43, 52 until 53, 55 until 58, 61 until 62, 65 until 66, 67 until 69 ) ), event ) } } @Test fun `when hide enlarge clicked, verify that close enlarge event is sent`() = runTest { provideInput(Address.Account(AccountAddress.sampleRandom(NetworkId.MAINNET))) val vm = vm.value advanceUntilIdle() vm.onHideEnlargeClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.CloseEnlarged, event ) } } @Test fun `given account address, when share click, verify the share event is sent with correct title and value`() = runTest { val profile = Profile.sample().changeGatewayToNetworkId(NetworkId.MAINNET) profileRepository.saveProfile(profile = profile) val account = profile.activeAccountsOnCurrentNetwork.first() provideInput(Address.Account(account.address)) val vm = vm.value advanceUntilIdle() vm.onShareClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.PerformShare( shareTitle = account.displayName.value, shareValue = account.address.formatted(AddressFormat.RAW) ), event ) } } @Test fun `given account address, when visit on dashboard click, verify the dashboard event is sent with correct url`() = runTest { val addressString = "account<KEY>" val address = AccountAddress.init(addressString) provideInput(Address.Account(address)) val vm = vm.value advanceUntilIdle() vm.onVisitDashboardClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.PerformVisitDashBoard( url = "https://stokenet-dashboard.radixdlt.com/account/$addressString", ), event ) } } @Test fun `given account address created with ledger and address verifiable, when verify on ledger click, verify the success event is sent`() = runTest { val profile = Profile.sampleWithLedgerAccount().also { profileRepository.saveProfile(it) } val account = profile.activeAccountsOnCurrentNetwork.find { it.isLedgerAccount } ?: error("Expected Ledger account but none found") provideInput(Address.Account(account.address)) coEvery { verifyAddressOnLedgerUseCase(address = account.address) } returns Result.success(Unit) val vm = vm.value advanceUntilIdle() vm.onVerifyOnLedgerDeviceClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.ShowLedgerVerificationResult(isVerified = true), event ) } } @Test fun `given account address created with ledger and address not verifiable, when verify on ledger click, verify the error event is sent`() = runTest { val profile = Profile.sampleWithLedgerAccount().also { profileRepository.saveProfile(it) } val account = profile.activeAccountsOnCurrentNetwork.find { it.isLedgerAccount } ?: error("Expected Ledger account but none found") provideInput(Address.Account(account.address)) coEvery { verifyAddressOnLedgerUseCase(address = account.address) } returns Result.failure(RuntimeException("An error")) val vm = vm.value advanceUntilIdle() vm.onVerifyOnLedgerDeviceClick() vm.oneOffEvent.test { val event = awaitItem() assertEquals( AddressDetailsDialogViewModel.Event.ShowLedgerVerificationResult(isVerified = false), event ) } } @Test fun `test full address section for simple address`() { val rawAddress = "account_tdx_2_12xn3lgz7xv4d0d4cx25nvfekyxx0fsawhmtht0dd550vcu5wwl0g70" val accountAddress = AccountAddress.init(rawAddress) val actionableAddress = ActionableAddress.Address(address = Address.Account(accountAddress), isVisitableInDashboard = true) val section = AddressDetailsDialogViewModel.State.Section.FullAddress.from(actionableAddress) assertEquals( AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = rawAddress, boldRanges = persistentListOf( 0 until 4, rawAddress.length - 6 until rawAddress.length ) ), section ) } @Test fun `test full address section for transaction id`() { val rawAddress = "txid_tdx_2_1kduv3jxmn62r6xqknvsfn3ps5fpqj3ad5474e0z2hhgpwmlxj7fq8hp7gk" val intentHash = IntentHash.init(rawAddress) val actionableAddress = ActionableAddress.TransactionId(hash = intentHash, isVisitableInDashboard = true) val section = AddressDetailsDialogViewModel.State.Section.FullAddress.from(actionableAddress) assertEquals( AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = rawAddress, boldRanges = persistentListOf( 0 until 4, rawAddress.length - 6 until rawAddress.length ) ), section ) } @Test fun `test full address section for integer based global id`() { val number = "1232042334232" val rawAddress = "resource_tdx_2_1n2kfpqnlzntcgddq0sfzq9attnc7y7hqkdz6ykedhn76ghw662el6s:#$number#" val globalId = NonFungibleGlobalId.init(rawAddress) val actionableAddress = ActionableAddress.GlobalId(address = globalId, isVisitableInDashboard = true, isOnlyLocalIdVisible = true) val section = AddressDetailsDialogViewModel.State.Section.FullAddress.from(actionableAddress) val resourceAddressRaw = globalId.resourceAddress.string assertEquals( AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = rawAddress, boldRanges = persistentListOf( 0 until 4, resourceAddressRaw.length - 6 until resourceAddressRaw.length, rawAddress.length - 1 - number.length until rawAddress.length - 1 ) ), section ) } @Test fun `test full address section for ruid based global id`() { val rawAddress = "resource_tdx_2_1nth7zjtujhvmzfpyn9rvu9nexzmye554q6uv7xcchhalsa53r4zqfe:" + "{bce508b789ed38e4-9a8552cb3142fdc5-3491317d130e6483-46df034d5ffbd210}" val globalId = NonFungibleGlobalId.init(rawAddress) val actionableAddress = ActionableAddress.GlobalId(address = globalId, isVisitableInDashboard = true, isOnlyLocalIdVisible = true) val section = AddressDetailsDialogViewModel.State.Section.FullAddress.from(actionableAddress) val resourceAddressRaw = globalId.resourceAddress.string assertEquals( AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = rawAddress, boldRanges = persistentListOf( 0 until 4, resourceAddressRaw.length - 6 until resourceAddressRaw.length, resourceAddressRaw.length + 2 until resourceAddressRaw.length + 2 + 4, rawAddress.length - 1 - 4 until rawAddress.length - 1 ) ), section ) } @Test fun `test full address section for bytes based global id`() { val localId = NonFungibleLocalId.Bytes(value = NonEmptyMax64Bytes(Random.nextBytes(64).toBagOfBytes())) val rawAddress = "resource_tdx_2_1nth7zjtujhvmzfpyn9rvu9nexzmye554q6uv7xcchhalsa53r4zqfe:${localId.string}" val globalId = NonFungibleGlobalId.init(rawAddress) val actionableAddress = ActionableAddress.GlobalId(address = globalId, isVisitableInDashboard = true, isOnlyLocalIdVisible = true) val section = AddressDetailsDialogViewModel.State.Section.FullAddress.from(actionableAddress) val resourceAddressRaw = globalId.resourceAddress.string assertEquals( AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = rawAddress, boldRanges = persistentListOf( 0 until 4, resourceAddressRaw.length - 6 until resourceAddressRaw.length, resourceAddressRaw.length + 2 until rawAddress.length - 1 ) ), section ) } @Test fun `test full address section for string based global id`() { val rawAddress = "resource_tdx_2_1nth7zjtujhvmzfpyn9rvu9nexzmye554q6uv7xcchhalsa53r4zqfe:<a_very_big_string_that_is_not_truncated>" val globalId = NonFungibleGlobalId.init(rawAddress) println(globalId.nonFungibleLocalId.formatted()) val actionableAddress = ActionableAddress.GlobalId(address = globalId, isVisitableInDashboard = true, isOnlyLocalIdVisible = true) val section = AddressDetailsDialogViewModel.State.Section.FullAddress.from(actionableAddress) val resourceAddressRaw = globalId.resourceAddress.string assertEquals( AddressDetailsDialogViewModel.State.Section.FullAddress( rawAddress = rawAddress, boldRanges = persistentListOf( 0 until 4, resourceAddressRaw.length - 6 until resourceAddressRaw.length, resourceAddressRaw.length + 2 until rawAddress.length - 1 ) ), section ) } private fun provideInput(address: Address) { val actionableAddress = ActionableAddress.Address( address = address, isVisitableInDashboard = true ) every { savedStateHandle.get<String>(ARG_ACTIONABLE_ADDRESS) } returns Json.encodeToString<ActionableAddress>(actionableAddress) } }
7
null
6
9
36c670dd32d181e462e9962d476cb8a370fbe4fe
20,736
babylon-wallet-android
Apache License 2.0
src/main/kotlin/com/poseplz/server/infrastructure/naver/NaverGeoCodeService.kt
pobu-team
678,194,623
false
{"Kotlin": 164925, "HTML": 51573, "Dockerfile": 340, "CSS": 122}
package com.poseplz.server.infrastructure.naver import com.poseplz.server.domain.geocode.GeoCodeService import com.poseplz.server.domain.photobooth.Coordinates import org.springframework.stereotype.Component @Component class NaverGeoCodeService( private val naverApiClient: NaverApiClient, ) : GeoCodeService { override fun toCoordinates(address: String): Coordinates { val reverseGeoCode = naverApiClient.reverseGeoCode(address) if (reverseGeoCode.addresses.isEmpty()) { return Coordinates.empty() } return Coordinates( latitude = reverseGeoCode.addresses.first().y, longitude = reverseGeoCode.addresses.first().x, ) } }
0
Kotlin
0
0
aee909c988149f0d67847c42c956a1b6cb8e4378
712
poseplz-server
MIT License
src/test/kotlin/no/nav/k9brukerdialogapi/ytelse/pleiepengerlivetssluttfase/domene/ArbeidIPeriodeTest.kt
navikt
460,765,798
false
{"Kotlin": 835877, "Dockerfile": 103}
package no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene import no.nav.k9.søknad.felles.type.Periode import no.nav.k9brukerdialogapi.TestUtils.Companion.verifiserFeil import no.nav.k9brukerdialogapi.TestUtils.Companion.verifiserIngenFeil import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.JobberIPeriodeSvar.HELT_FRAVÆR import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.JobberIPeriodeSvar.REDUSERT import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.JobberIPeriodeSvar.SOM_VANLIG import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.INGEN_ARBEIDSDAG import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.FULL_ARBEIDSDAG import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.HALV_ARBEIDSDAG import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.enkeltDagerMedFulltFravær import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.enkeltDagerMedJobbSomVanlig import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.enkeltDagerMedRedusertArbeid import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.fredag import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.mandag import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.onsdag import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.tirsdag import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PILSTestUtils.torsdag import no.nav.k9brukerdialogapi.ytelse.pleiepengersyktbarn.soknad.domene.arbeid.NULL_TIMER import org.junit.jupiter.api.Disabled import java.time.Duration import java.time.LocalDate import kotlin.test.Test import kotlin.test.assertEquals class ArbeidIPeriodeTest { @Test fun `Gyldig ArbeidIPeriode gir ingen valideringsfeil`() { ArbeidIPeriode(HELT_FRAVÆR, enkeltDagerMedFulltFravær).valider(normaltimerPerDag = FULL_ARBEIDSDAG) .verifiserIngenFeil() ArbeidIPeriode(SOM_VANLIG, enkeltDagerMedJobbSomVanlig).valider(normaltimerPerDag = FULL_ARBEIDSDAG) .verifiserIngenFeil() ArbeidIPeriode(REDUSERT, enkeltDagerMedRedusertArbeid).valider(normaltimerPerDag = FULL_ARBEIDSDAG) .verifiserIngenFeil() } @Test fun `Forvent feil derom det sendes tom liste med enkeltdager`() { ArbeidIPeriode(HELT_FRAVÆR, emptyList()).valider(normaltimerPerDag = FULL_ARBEIDSDAG) .verifiserFeil(1, listOf("arbeidIPeriode.enkeltdager kan ikke være tom liste.")) } @Test @Disabled fun `Forvent feil dersom HELT_FRAVÆR og enkeltdager inneholder timer med arbeid`() { ArbeidIPeriode( HELT_FRAVÆR, listOf( Enkeltdag(mandag, NULL_TIMER), Enkeltdag(tirsdag, NULL_TIMER), Enkeltdag(onsdag, HALV_ARBEIDSDAG), Enkeltdag(torsdag, NULL_TIMER), Enkeltdag(fredag, NULL_TIMER), ) ) .valider(normaltimerPerDag = FULL_ARBEIDSDAG) .verifiserFeil( 1, listOf("Dersom arbeidIPeriode.jobberIPerioden er HELT_FRAVÆR, så kreves det at arbeidIPeriode.enkeltdager[2].tid er 0 timer.") ) } @Test @Disabled fun `Forvent feil dersom SOM_VANLIG og enkeltdager inneholder timer med ingen arbeid`() { ArbeidIPeriode( SOM_VANLIG, listOf( Enkeltdag(mandag, FULL_ARBEIDSDAG), Enkeltdag(tirsdag, FULL_ARBEIDSDAG), Enkeltdag(onsdag, HALV_ARBEIDSDAG), Enkeltdag(torsdag, FULL_ARBEIDSDAG), Enkeltdag(fredag, INGEN_ARBEIDSDAG), ) ) .valider(normaltimerPerDag = FULL_ARBEIDSDAG) .verifiserFeil( 2, listOf( "Dersom arbeidIPeriode.jobberIPerioden er SOM_VANLIG, så kreves det at arbeidIPeriode.enkeltdager[2].tid er $FULL_ARBEIDSDAG timer per dag.", "Dersom arbeidIPeriode.jobberIPerioden er SOM_VANLIG, så kreves det at arbeidIPeriode.enkeltdager[4].tid er $FULL_ARBEIDSDAG timer per dag.", ) ) } @Test fun `Mapping til K9Arbeidstid når man ikke jobber i perioden skal gi null faktiskTimer`() { val k9Arbeidstid = ArbeidIPeriode(HELT_FRAVÆR, enkeltDagerMedFulltFravær).somK9ArbeidstidInfo(FULL_ARBEIDSDAG) assertEquals(k9Arbeidstid.perioder.size, enkeltDagerMedFulltFravær.size) k9Arbeidstid.perioder.forEach { _, arbeidstidPeriodeInfo -> assertEquals(FULL_ARBEIDSDAG, arbeidstidPeriodeInfo.jobberNormaltTimerPerDag) assertEquals(INGEN_ARBEIDSDAG, arbeidstidPeriodeInfo.faktiskArbeidTimerPerDag) } } @Test fun `Mapping av redusert arbeidstid blir mappet til k9format som forventet`() { val k9Arbeidstid = ArbeidIPeriode( REDUSERT, listOf( Enkeltdag(mandag, HALV_ARBEIDSDAG), Enkeltdag(tirsdag, HALV_ARBEIDSDAG), ) ).somK9ArbeidstidInfo(FULL_ARBEIDSDAG) assertEquals(k9Arbeidstid.perioder.size, 2) listOf(mandag, tirsdag).forEach { assertEquals(FULL_ARBEIDSDAG, k9Arbeidstid.perioder[Periode(it, it)]!!.jobberNormaltTimerPerDag) assertEquals(HALV_ARBEIDSDAG, k9Arbeidstid.perioder[Periode(it, it)]!!.faktiskArbeidTimerPerDag) } } @Test fun `Mapping til K9Arbeidtid når man jobber som vanlig`() { val k9ArbeidstidInfo = ArbeidIPeriode(SOM_VANLIG, enkeltDagerMedJobbSomVanlig).somK9ArbeidstidInfo(FULL_ARBEIDSDAG) assertEquals(k9ArbeidstidInfo.perioder.size, enkeltDagerMedJobbSomVanlig.size) k9ArbeidstidInfo.perioder.forEach { _, u -> assertEquals(FULL_ARBEIDSDAG, u.jobberNormaltTimerPerDag) assertEquals(FULL_ARBEIDSDAG, u.faktiskArbeidTimerPerDag) } } }
1
Kotlin
0
0
5d7c40c3b0303d90f4ae374acb6e6e9a6baedf42
6,138
k9-brukerdialog-api
MIT License
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/CalendarLocale.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2023 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.material3 import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable /** * Represents a Locale for the calendar. This locale will be used when formatting dates, determining * the input format, and more. * * Note: For JVM based platforms, this would be equivalent to [java.util.Locale]. */ @ExperimentalMaterial3Api expect class CalendarLocale /** * Returns the default [CalendarLocale]. * * Note: For JVM based platforms, this would be equivalent to [java.util.Locale.getDefault]. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @ReadOnlyComposable internal expect fun defaultLocale(): CalendarLocale /** * Returns a string representation of an integer for the current Locale. * * @param minDigits sets the minimum number of digits allowed in the integer portion of a number. * If the minDigits value is greater than the [maxDigits] value, then [maxDigits] will also be set * to this value. */ internal expect fun Int.toLocalString( minDigits: Int = 1, // Removed other arguments comparing with upstream because they aren't used ): String
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
1,750
compose
Apache License 2.0
android/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt
PsrkGrmez
759,525,035
false
{"Kotlin": 336480, "Dart": 77560, "Java": 9475, "Swift": 689, "Objective-C": 38}
package com.xray.lite.ui.adapters import android.graphics.Color import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.google.gson.Gson import com.tencent.mmkv.MMKV import com.xray.lite.AppConfig import com.xray.lite.dto.EConfigType import com.xray.lite.dto.SubscriptionItem import com.xray.lite.extension.toast import com.xray.lite.helper.ItemTouchHelperAdapter import com.xray.lite.helper.ItemTouchHelperViewHolder import com.xray.lite.service.V2RayServiceManager import com.xray.lite.ui.MainAngActivity import com.xray.lite.util.AngConfigManager import com.xray.lite.util.MmkvManager import com.xray.lite.util.Utils import rx.Observable import rx.android.schedulers.AndroidSchedulers import sp.inetvpn.R import sp.inetvpn.databinding.ItemRecyclerFooterBinding import sp.inetvpn.databinding.ItemRecyclerMainBinding import java.util.concurrent.TimeUnit class MainRecyclerAdapter(val activity: MainAngActivity) : RecyclerView.Adapter<MainRecyclerAdapter.BaseViewHolder>(), ItemTouchHelperAdapter { companion object { private const val VIEW_TYPE_ITEM = 1 private const val VIEW_TYPE_FOOTER = 2 } private var mActivity: MainAngActivity = activity private val mainStorage by lazy { MMKV.mmkvWithID( MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE ) } private val subStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SUB, MMKV.MULTI_PROCESS_MODE) } // private val settingsStorage by lazy { // MMKV.mmkvWithID( // MmkvManager.ID_SETTING, // MMKV.MULTI_PROCESS_MODE // ) // } private val share_method: Array<out String> by lazy { mActivity.resources.getStringArray(R.array.share_method) } var isRunning = false override fun getItemCount() = mActivity.mainViewModel.serversCache.size + 1 override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { if (holder is MainViewHolder) { val guid = mActivity.mainViewModel.serversCache[position].guid val config = mActivity.mainViewModel.serversCache[position].config // //filter // if (mActivity.mainViewModel.subscriptionId.isNotEmpty() // && mActivity.mainViewModel.subscriptionId != config.subscriptionId // ) { // holder.itemMainBinding.cardView.visibility = View.GONE // } else { // holder.itemMainBinding.cardView.visibility = View.VISIBLE // } val outbound = config.getProxyOutbound() val aff = MmkvManager.decodeServerAffiliationInfo(guid) holder.itemMainBinding.tvName.text = config.remarks holder.itemView.setBackgroundColor(Color.TRANSPARENT) holder.itemMainBinding.tvTestResult.text = aff?.getTestDelayString() ?: "" if ((aff?.testDelayMillis ?: 0L) < 0L) { holder.itemMainBinding.tvTestResult.setTextColor( ContextCompat.getColor( mActivity, R.color.colorPingRed ) ) } else { holder.itemMainBinding.tvTestResult.setTextColor( ContextCompat.getColor( mActivity, R.color.colorPing ) ) } if (guid == mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER)) { holder.itemMainBinding.infoContainer.setBackgroundResource(R.color.colorStatsBlue) // holder.ll_item.setBackgroundColor(context.getResources().getColor(R.color.colorStatsBlue)); } else { holder.itemMainBinding.infoContainer.setBackgroundResource(R.color.colorUnselected) } holder.itemMainBinding.tvSubscription.text = "" val json = subStorage?.decodeString(config.subscriptionId) if (!json.isNullOrBlank()) { val sub = Gson().fromJson(json, SubscriptionItem::class.java) holder.itemMainBinding.tvSubscription.text = sub.remarks } var shareOptions = share_method.asList() when (config.configType) { EConfigType.CUSTOM -> { holder.itemMainBinding.tvType.text = mActivity.getString(R.string.server_customize_config) shareOptions = shareOptions.takeLast(1) } EConfigType.VLESS -> { holder.itemMainBinding.tvType.text = config.configType.name } else -> { holder.itemMainBinding.tvType.text = config.configType.name.lowercase() } } val strState = "${outbound?.getServerAddress()?.dropLast(3)}*** : ${outbound?.getServerPort()}" holder.itemMainBinding.tvStatistics.text = strState // holder.itemMainBinding.layoutShare.setOnClickListener { // AlertDialog.Builder(mActivity).setItems(shareOptions.toTypedArray()) { _, i -> // try { // when (i) { // 0 -> { // if (config.configType == EConfigType.CUSTOM) { // shareFullContent(guid) // } else { // val ivBinding = ItemQrcodeBinding.inflate(LayoutInflater.from(mActivity)) // ivBinding.ivQcode.setImageBitmap(AngConfigManager.share2QRCode(guid)) // AlertDialog.Builder(mActivity).setView(ivBinding.root).show() // } // } // 1 -> { // if (AngConfigManager.share2Clipboard(mActivity, guid) == 0) { // mActivity.toast(R.string.toast_success) // } else { // mActivity.toast(R.string.toast_failure) // } // } // 2 -> shareFullContent(guid) // else -> mActivity.toast("else") // } // } catch (e: Exception) { // e.printStackTrace() // } // }.show() // } // holder.itemMainBinding.layoutEdit.setOnClickListener { // val intent = Intent().putExtra("guid", guid) // .putExtra("isRunning", isRunning) // if (config.configType == EConfigType.CUSTOM) { // mActivity.startActivity(intent.setClass(mActivity, ServerCustomConfigActivity::class.java)) // } else { // mActivity.startActivity(intent.setClass(mActivity, ServerAngActivity::class.java)) // } // } // holder.itemMainBinding.layoutRemove.setOnClickListener { // if (guid != mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER)) { // if (settingsStorage?.decodeBool(AppConfig.PREF_CONFIRM_REMOVE) == true) { // AlertDialog.Builder(mActivity).setMessage(R.string.del_config_comfirm) // .setPositiveButton(android.R.string.ok) { _, _ -> // removeServer(guid, position) // } // .show() // } else { // removeServer(guid, position) // } // } // } holder.itemMainBinding.infoContainer.setOnClickListener { val selected = mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER) if (guid != selected) { mainStorage?.encode(MmkvManager.KEY_SELECTED_SERVER, guid) if (!TextUtils.isEmpty(selected)) { notifyItemChanged(mActivity.mainViewModel.getPosition(selected!!)) } notifyItemChanged(mActivity.mainViewModel.getPosition(guid)) if (isRunning) { // mActivity.showCircle() Utils.stopVService(mActivity) Observable.timer(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { V2RayServiceManager.startV2Ray(mActivity) // mActivity.hideCircle() } } } mActivity.onBackPressed() } } if (holder is FooterViewHolder) { //if (activity?.defaultDPreference?.getPrefBoolean(AppConfig.PREF_INAPP_BUY_IS_PREMIUM, false)) { if (true) { holder.itemFooterBinding.layoutEdit.visibility = View.INVISIBLE } else { holder.itemFooterBinding.layoutEdit.setOnClickListener { Utils.openUri( mActivity, "${Utils.decode(AppConfig.promotionUrl)}?t=${System.currentTimeMillis()}" ) } } } } private fun shareFullContent(guid: String) { if (AngConfigManager.shareFullContent2Clipboard(mActivity, guid) == 0) { mActivity.toast(R.string.toast_success) } else { mActivity.toast(R.string.toast_failure) } } private fun removeServer(guid: String, position: Int) { mActivity.mainViewModel.removeServer(guid) notifyItemRemoved(position) notifyItemRangeChanged(position, mActivity.mainViewModel.serversCache.size) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { return when (viewType) { VIEW_TYPE_ITEM -> MainViewHolder( ItemRecyclerMainBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) else -> FooterViewHolder( ItemRecyclerFooterBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } } override fun getItemViewType(position: Int): Int { return if (position == mActivity.mainViewModel.serversCache.size) { VIEW_TYPE_FOOTER } else { VIEW_TYPE_ITEM } } open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun onItemSelected() { itemView.setBackgroundColor(Color.LTGRAY) } fun onItemClear() { itemView.setBackgroundColor(0) } } class MainViewHolder(val itemMainBinding: ItemRecyclerMainBinding) : BaseViewHolder(itemMainBinding.root), ItemTouchHelperViewHolder class FooterViewHolder(val itemFooterBinding: ItemRecyclerFooterBinding) : BaseViewHolder(itemFooterBinding.root) override fun onItemDismiss(position: Int) { // launch{} val guid = mActivity.mainViewModel.serversCache.getOrNull(position)?.guid ?: return if (guid != mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER)) { // mActivity.alert(R.string.del_config_comfirm) { // positiveButton(android.R.string.ok) { mActivity.mainViewModel.removeServer(guid) notifyItemRemoved(position) // } // show() // } } } override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean { mActivity.mainViewModel.swapServer(fromPosition, toPosition) notifyItemMoved(fromPosition, toPosition) // position is changed, since position is used by click callbacks, need to update range if (toPosition > fromPosition) notifyItemRangeChanged(fromPosition, toPosition - fromPosition + 1) else notifyItemRangeChanged(toPosition, fromPosition - toPosition + 1) return true } override fun onItemMoveCompleted() { // do nothing } }
1
Kotlin
7
85
1a6d3d8e6c6edcfd3be8f23bee339e1c83ab9346
12,732
ChiselBox
MIT License
watch/src/jvmTest/kotlin/matt/file/watch/test/test.kt
mgroth0
513,680,528
false
null
package matt.file.watch.test import matt.file.MFile import matt.file.watch.createFileSizeProp import matt.test.Tests import kotlin.test.Test import kotlin.time.Duration.Companion.seconds class WatchTests : Tests() { @Test fun createAWatchProp() { MFile.createTempFile("abc", "efg").createFileSizeProp(1.seconds) } }
0
Kotlin
0
0
682be5934dc72e5cc524ef5d6489763cc567ff54
338
file
MIT License
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/NotebookOutputInlayControllerUtil.kt
ingokegel
72,937,917
true
null
package org.jetbrains.plugins.notebooks.visualization.outputs import com.intellij.openapi.editor.ex.EditorGutterComponentEx import org.jetbrains.annotations.TestOnly import org.jetbrains.plugins.notebooks.visualization.SwingClientProperty import org.jetbrains.plugins.notebooks.visualization.outputs.impl.CollapsingComponent import org.jetbrains.plugins.notebooks.visualization.outputs.impl.InnerComponent import org.jetbrains.plugins.notebooks.visualization.outputs.impl.SurroundingComponent import java.awt.BorderLayout import java.awt.Component import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.JComponent import javax.swing.JScrollPane import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener import kotlin.math.max internal var EditorGutterComponentEx.hoveredCollapsingComponentRect: CollapsingComponent? by SwingClientProperty("hoveredCollapsingComponentRect") // TODO It severely breaks encapsulation. At least, we should cover it with tests. internal val NotebookOutputInlayController.collapsingComponents: List<CollapsingComponent> get() = inlay .renderer .let { (it as JComponent).getComponent(0)!! } .let { it as SurroundingComponent } .let { (it.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER) } .let { it as InnerComponent } .components .map { it as CollapsingComponent } val NotebookOutputInlayController.outputComponents: List<JComponent> @TestOnly get() = collapsingComponents.map { it.mainComponent } /** * [component] is any component that belongs to an output inlay. * If the component is null or seems to be not inside an output inlay, nothing happens. */ fun resetOutputInlayCustomHeight(component: Component?) { generateSequence(component, Component::getParent) .filterIsInstance<CollapsingComponent>() .firstOrNull() ?.resetCustomHeight() } /** * Scrolls the pane down in case of various size changes, if the pane was scrolled down before the size change. * * If the pane wasn't scrolled to the bottom (i.e. the last pixel of the view wasn't seen), the scroll remains unchanged. */ fun installAutoScrollToBottom(scrollPane: JScrollPane) { var wasScrolledToBottom = true val viewport = scrollPane.viewport val view = viewport.view val scrollToBottomListener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent) { if (wasScrolledToBottom) { scrollPane.verticalScrollBar.value = max(0, view.height - viewport.viewRect.height) } } } viewport.addComponentListener(scrollToBottomListener) view.addComponentListener(scrollToBottomListener) scrollPane.verticalScrollBar.model.addChangeListener(object : ChangeListener { var oldValue = scrollPane.verticalScrollBar.value override fun stateChanged(e: ChangeEvent) { val newValue = scrollPane.verticalScrollBar.value if (oldValue != newValue) { oldValue = newValue wasScrolledToBottom = scrollPane.verticalScrollBar.value + viewport.viewRect.height >= view.height } } }) }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,099
intellij-community
Apache License 2.0
src/main/kotlin/no/nav/klage/clients/dokarkiv/DokArkivClient.kt
navikt
598,507,066
false
{"Kotlin": 252260, "Dockerfile": 134}
package no.nav.klage.clients.dokarkiv import no.nav.klage.util.TokenUtil import no.nav.klage.util.getLogger import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono @Component class DokArkivClient( private val dokArkivWebClient: WebClient, private val tokenUtil: TokenUtil ) { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) } @Value("\${spring.application.name}") lateinit var applicationName: String fun createNewJournalpostBasedOnExistingJournalpost( payload: CreateNewJournalpostBasedOnExistingJournalpostRequest, oldJournalpostId: String, ): CreateNewJournalpostBasedOnExistingJournalpostResponse { try { val journalpostResponse = dokArkivWebClient.put() .uri("/journalpost/${oldJournalpostId}/knyttTilAnnenSak") .header(HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}") .header("Nav-Consumer-Id", applicationName) .header("Nav-User-Id", tokenUtil.getCurrentIdent()) .contentType(MediaType.APPLICATION_JSON) .bodyValue(payload) .retrieve() .bodyToMono(CreateNewJournalpostBasedOnExistingJournalpostResponse::class.java) .block() ?: throw RuntimeException("Journalpost could not be created.") logger.debug("Journalpost successfully created in dokarkiv based on saksid ${payload.fagsakId}, resulting in id ${journalpostResponse.nyJournalpostId}.") return journalpostResponse } catch (e: Exception) { logger.error("Error creating journalpost in dokarkiv based on existing saksid:", e) throw e } } fun updateSakInJournalpost(journalpostId: String, input: UpdateSakInJournalpostRequest) { try { val output = dokArkivWebClient.put() .uri("/journalpost/${journalpostId}") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue(input) .retrieve() .bodyToMono(JournalpostResponse::class.java) .block() ?: throw RuntimeException("Journalpost fagsakid could not be updated.") logger.debug("Svar fra dokarkiv: {}", output) } catch (e: Exception) { logger.error("Error updating journalpost $journalpostId fagsakid:", e) throw e } logger.debug("Document from journalpost $journalpostId updated with saksId ${input.sak.fagsakid}.") } fun updateAvsenderMottakerInJournalpost(journalpostId: String, input: UpdateAvsenderMottakerInJournalpostRequest) { try { val output = dokArkivWebClient.put() .uri("/journalpost/${journalpostId}") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue(input) .retrieve() .bodyToMono(JournalpostResponse::class.java) .block() ?: throw RuntimeException("Journalpost AvsenderMottaker could not be updated.") logger.debug("Svar fra dokarkiv: {}", output) } catch (e: Exception) { logger.error("Error updating journalpost $journalpostId AvsenderMottaker:", e) throw e } } fun updateDocumentTitle( journalpostId: String, input: UpdateDocumentTitleJournalpostInput ) { try { dokArkivWebClient.put() .uri("/journalpost/${journalpostId}") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue(input) .retrieve() .bodyToMono(JournalpostResponse::class.java) .block() ?: throw RuntimeException("Journalpost document title could not be updated.") } catch (e: Exception) { logger.error("Error updating journalpost $journalpostId document title:", e) } logger.debug("Document from journalpost $journalpostId with dokumentInfoId id ${input.dokumenter.first().dokumentInfoId} was successfully updated.") } fun setLogiskeVedlegg( dokumentInfoId: String, payload: SetLogiskeVedleggPayload ) { try { dokArkivWebClient.post() .uri("/dokumentInfo/${dokumentInfoId}/logiskVedlegg") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue(payload) .retrieve() .bodyToMono(JournalpostResponse::class.java) .block() ?: throw RuntimeException("Could not set logiske vedlegg for document.") } catch (e: Exception) { logger.error("Error setting logiske vedlegg for document $dokumentInfoId:", e) } logger.debug("Bulk updated logiske vedlegg for document $dokumentInfoId successfully.") } fun addLogiskVedlegg( dokumentInfoId: String, title: String, ): AddLogiskVedleggResponse { try { val response = dokArkivWebClient.post() .uri("/dokumentInfo/${dokumentInfoId}/logiskVedlegg/") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue( LogiskVedleggPayload( tittel = title ) ) .retrieve() .bodyToMono(AddLogiskVedleggResponse::class.java) .block() ?: throw RuntimeException("Could not add logisk vedlegg to documentInfoId $dokumentInfoId.") logger.debug("Added logisk vedlegg to document $dokumentInfoId successfully.") return response } catch (e: Exception) { logger.error("Error adding logisk vedlegg to document $dokumentInfoId:", e) throw e } } fun updateLogiskVedlegg( dokumentInfoId: String, logiskVedleggId: String, title: String, ) { try { dokArkivWebClient.post() .uri("/dokumentInfo/${dokumentInfoId}/logiskVedlegg/${logiskVedleggId}") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue( LogiskVedleggPayload( tittel = title, ) ) .retrieve() .bodyToMono<Void>() .block() ?: throw RuntimeException("Could not update logisk vedlegg $logiskVedleggId for documentInfoId $dokumentInfoId.") logger.debug("Updated logisk vedlegg $logiskVedleggId for document $dokumentInfoId successfully.") } catch (e: Exception) { logger.error("Error updating logisk vedlegg $dokumentInfoId for document $dokumentInfoId:", e) } } fun deleteLogiskVedlegg( dokumentInfoId: String, logiskVedleggId: String ) { try { dokArkivWebClient.delete() .uri("/dokumentInfo/${dokumentInfoId}/logiskVedlegg/${logiskVedleggId}") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .retrieve() .bodyToMono<Void>() .block() ?: throw RuntimeException("Could not delete logisk vedlegg $logiskVedleggId for documentInfoId $dokumentInfoId.") logger.debug("Deleted logisk vedlegg $logiskVedleggId for document $dokumentInfoId successfully.") } catch (e: Exception) { logger.error("Error deleting logisk vedlegg $dokumentInfoId for document $dokumentInfoId:", e) } } fun finalizeJournalpost(journalpostId: String, journalfoerendeEnhet: String) { try { val output = dokArkivWebClient.patch() .uri("/journalpost/${journalpostId}/ferdigstill") .header( HttpHeaders.AUTHORIZATION, "Bearer ${tokenUtil.getSaksbehandlerAccessTokenWithDokArkivScope()}" ) .contentType(MediaType.APPLICATION_JSON) .bodyValue(FerdigstillJournalpostPayload(journalfoerendeEnhet)) .retrieve() .bodyToMono<String>() .block() ?: throw RuntimeException("Journalpost could not be finalized") logger.debug("Finalized journalpost, response from dokarkiv: $output") } catch (e: Exception) { logger.error("Error finalizing journalpost $journalpostId:", e) throw e } logger.debug("Journalpost with id $journalpostId was successfully finalized.") } data class FerdigstillJournalpostPayload( val journalfoerendeEnhet: String ) data class SetLogiskeVedleggPayload( val titler: List<String> ) data class LogiskVedleggPayload( val tittel: String, ) data class AddLogiskVedleggResponse( val logiskVedleggId: String ) }
2
Kotlin
0
0
fe9d7ebd523bf9130410a222bce48f3e1c87fc92
10,518
kabin-api
MIT License
kotlin/src/main/java/com/mcxiaoke/next/kotlin/Crypto.kt
zhanghuanWang
54,374,600
true
{"INI": 11, "Gradle": 13, "Text": 7, "Shell": 2, "Markdown": 12, "Batchfile": 1, "Ignore List": 6, "XML": 91, "Java": 225, "Java Properties": 1, "Kotlin": 11}
/** */ package com.mcxiaoke.next.kotlin import android.util.Base64 import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.security.SecureRandom import java.util.* import javax.crypto.Cipher import javax.crypto.SecretKeyFactory import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.PBEKeySpec import javax.crypto.spec.SecretKeySpec /** * @author mcxiaoke * * * @version 1.0 2013.03.16 */ private object Helper { val randomString: String get() { val random = SecureRandom() return random.nextLong().toString() } fun getRandomBytes(size: Int): ByteArray { val random = SecureRandom() val bytes = ByteArray(size) random.nextBytes(bytes) return bytes } fun getRawBytes(text: String): ByteArray { try { return text.toByteArray(Const.ENCODING_UTF_8) } catch (e: UnsupportedEncodingException) { return text.toByteArray() } } internal fun getString(data: ByteArray): String { try { return String(data, Const.ENCODING_UTF_8) } catch (e: UnsupportedEncodingException) { return String(data) } } internal fun base64Decode(text: String): ByteArray { return Base64.decode(text, Base64.NO_WRAP) } internal fun base64Encode(data: ByteArray): String { return Base64.encodeToString(data, Base64.NO_WRAP) } } object AES { val ITERATION_COUNT_DEFAULT = 100 val KEY_SIZE_DEFAULT = 256 val IV_SIZE_DEFAULT = 16 val KEY_AES_SPEC = "AES/CBC/PKCS7Padding" @JvmOverloads fun encrypt(text: String, password: String = <PASSWORD>, salt: ByteArray = simpleSalt, iv: ByteArray = simpleIV): String? { val data = Helper.getRawBytes(text) val encryptedData = encrypt(data, password, salt, iv, KEY_SIZE_DEFAULT, ITERATION_COUNT_DEFAULT) return Helper.base64Encode(encryptedData) } @JvmOverloads fun decrypt(text: String, password: String = <PASSWORD>, salt: ByteArray = simpleSalt, iv: ByteArray = simpleIV): String? { val encryptedData = Helper.base64Decode(text) val data = decrypt(encryptedData, password, salt, iv, KEY_SIZE_DEFAULT, ITERATION_COUNT_DEFAULT) return Helper.getString(data) } @JvmOverloads fun encrypt(data: ByteArray, password: String = <PASSWORD>, salt: ByteArray = simpleSalt, iv: ByteArray = simpleIV, keySize: Int = KEY_SIZE_DEFAULT, iterationCount: Int = ITERATION_COUNT_DEFAULT): ByteArray { return process(data, Cipher.ENCRYPT_MODE, password, salt, iv, keySize, iterationCount) } @JvmOverloads fun decrypt(data: ByteArray, password: String = <PASSWORD>, salt: ByteArray = simpleSalt, iv: ByteArray = simpleIV, keySize: Int = KEY_SIZE_DEFAULT, iterationCount: Int = ITERATION_COUNT_DEFAULT): ByteArray { return process(data, Cipher.DECRYPT_MODE, password, salt, iv, keySize, iterationCount) } /** * AES encrypt function * @param original * * * @param key 16, 24, 32 bytes available * * * @param iv initial vector (16 bytes) - if null: ECB mode, otherwise: * * CBC mode * * * @return */ fun encrypt(original: ByteArray, key: ByteArray?, iv: ByteArray?): ByteArray? { if (key == null || key.size != 16 && key.size != 24 && key.size != 32) { return null } if (iv != null && iv.size != 16) { return null } try { var keySpec: SecretKeySpec? = null var cipher: Cipher? = null if (iv != null) { keySpec = SecretKeySpec(key, KEY_AES_SPEC) cipher = Cipher.getInstance(KEY_AES_SPEC) cipher!!.init(Cipher.ENCRYPT_MODE, keySpec, IvParameterSpec(iv)) } else // if(iv == null) { keySpec = SecretKeySpec(key, KEY_AES_SPEC) cipher = Cipher.getInstance(KEY_AES_SPEC) cipher!!.init(Cipher.ENCRYPT_MODE, keySpec) } return cipher.doFinal(original) } catch (e: Exception) { e.printStackTrace() } return null } /** * AES decrypt function * @param encrypted * * * @param key 16, 24, 32 bytes available * * * @param iv initial vector (16 bytes) - if null: ECB mode, otherwise: * * CBC mode * * * @return */ fun decrypt(encrypted: ByteArray, key: ByteArray?, iv: ByteArray?): ByteArray? { if (key == null || key.size != 16 && key.size != 24 && key.size != 32) { return null } if (iv != null && iv.size != 16) { return null } try { var keySpec: SecretKeySpec? = null var cipher: Cipher? = null if (iv != null) { keySpec = SecretKeySpec(key, "AES/CBC/PKCS7Padding")// AES/ECB/PKCS5Padding cipher = Cipher.getInstance("AES/CBC/PKCS7Padding") cipher!!.init(Cipher.DECRYPT_MODE, keySpec, IvParameterSpec(iv)) } else // if(iv == null) { keySpec = SecretKeySpec(key, "AES/ECB/PKCS7Padding") cipher = Cipher.getInstance("AES/ECB/PKCS7Padding") cipher!!.init(Cipher.DECRYPT_MODE, keySpec) } return cipher.doFinal(encrypted) } catch (e: Exception) { e.printStackTrace() } return null } internal fun process(data: ByteArray, mode: Int, password: String, salt: ByteArray, iv: ByteArray, keySize: Int, iterationCount: Int): ByteArray { val keySpec = PBEKeySpec(password.toCharArray(), salt, iterationCount, keySize) try { val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") val keyBytes = keyFactory.generateSecret(keySpec).encoded val key = SecretKeySpec(keyBytes, "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") val ivParams = IvParameterSpec(iv) cipher.init(mode, key, ivParams) return cipher.doFinal(data) } catch (e: Exception) { e.printStackTrace() } return byteArrayOf() } internal val simplePassword: String get() = "<PASSWORD>" internal val simpleSalt: ByteArray get() = "rUiey8D2GNzV69Mp".toByteArray() internal val simpleIV: ByteArray get() { val iv = ByteArray(IV_SIZE_DEFAULT) Arrays.fill(iv, 5.toByte()) return iv } } // http://nelenkov.blogspot.jp/2012/04/using-password-based-encryption-on.html class AESCrypto { lateinit private var password: String lateinit private var salt: ByteArray lateinit private var iv: ByteArray private var keySize: Int = 0 private var iterCount: Int = 0 constructor(password: String) { initialize(password, AES.simpleSalt, AES.simpleIV, KEY_SIZE_DEFAULT, ITERATION_COUNT_DEFAULT) } constructor(password: String, salt: ByteArray) { initialize(password, salt, AES.simpleIV, KEY_SIZE_DEFAULT, ITERATION_COUNT_DEFAULT) } constructor(password: String, keySize: Int, salt: ByteArray, iv: ByteArray) { initialize(password, salt, iv, keySize, ITERATION_COUNT_DEFAULT) } private fun initialize(password: String, salt: ByteArray, iv: ByteArray, keySize: Int, iterCount: Int) { notEmpty(password, "password must not be null or empty") notNull(salt, "salt must bot be null") notNull(iv, "iv must not be null") isTrue(keySize >= KEY_SIZE_MIN && keySize <= KEY_SIZE_MAX, "keySize must between $KEY_SIZE_MIN and $KEY_SIZE_MAX") isTrue(iterCount >= ITERATION_COUNT_MIN && iterCount <= ITERATION_COUNT_MAX, "iterCount must between $ITERATION_COUNT_MIN and $ITERATION_COUNT_MAX") this.password = <PASSWORD> this.salt = <PASSWORD> this.iv = iv this.keySize = keySize this.iterCount = iterCount } fun encrypt(text: String): String { val data = Helper.getRawBytes(text) val encryptedData = encrypt(data) return Helper.base64Encode(encryptedData) } fun encrypt(data: ByteArray): ByteArray { return process(data, Cipher.ENCRYPT_MODE) } fun decrypt(text: String): String { val encryptedData = Helper.base64Decode(text) val data = decrypt(encryptedData) return Helper.getString(data) } fun decrypt(encryptedData: ByteArray): ByteArray { return process(encryptedData, Cipher.DECRYPT_MODE) } private fun process(data: ByteArray, mode: Int): ByteArray { return AES.process(data, mode, password, salt, iv, keySize, iterCount) } companion object { private val ITERATION_COUNT_DEFAULT = 100 private val ITERATION_COUNT_MIN = 10 private val ITERATION_COUNT_MAX = 5000 private val KEY_SIZE_DEFAULT = 256 private val KEY_SIZE_MIN = 64 private val KEY_SIZE_MAX = 1024 private val IV_SIZE = 16 } } object HEX { private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') private val FIRST_CHAR = CharArray(256) private val SECOND_CHAR = CharArray(256) init { for (i in 0..255) { FIRST_CHAR[i] = HEX_DIGITS[i shr 4 and 15] SECOND_CHAR[i] = HEX_DIGITS[i and 15] } } private val DIGITS = ByteArray('f'.toInt() + 1) init { run { var i = 0 while (i <= 'F'.toInt()) { DIGITS[i] = -1 i++ } } for (i in 0..9) { DIGITS['0'.toInt() + i] = i.toByte() } for (i in 0..5) { DIGITS['A'.toInt() + i] = (10 + i).toByte() DIGITS['a'.toInt() + i] = (10 + i).toByte() } } /** * Quickly converts a byte array to a hexadecimal string representation. * @param array byte array, possibly zero-terminated. */ fun encodeHex(array: ByteArray, zeroTerminated: Boolean): String { val cArray = CharArray(array.size * 2) var j = 0 for (i in array.indices) { val index = array[i].toInt() and 255 if (index == 0 && zeroTerminated) { break } cArray[j++] = FIRST_CHAR[index] cArray[j++] = SECOND_CHAR[index] } return String(cArray, 0, j) } /** * Quickly converts a hexadecimal string to a byte array. */ fun decodeHex(hexString: String): ByteArray { val length = hexString.length if (length and 1 != 0) { throw IllegalArgumentException("Odd number of characters.") } var badHex = false val out = ByteArray(length shr 1) var i = 0 var j = 0 while (j < length) { val c1 = hexString[j++].toInt() if (c1 > 'f'.toInt()) { badHex = true break } val d1 = DIGITS[c1] if (d1.toInt() == -1) { badHex = true break } val c2 = hexString[j++].toInt() if (c2 > 'f'.toInt()) { badHex = true break } val d2 = DIGITS[c2] if (d2.toInt() == -1) { badHex = true break } out[i] = (d1.toInt() shl 4 or d2.toInt()).toByte() i++ } if (badHex) { throw IllegalArgumentException( "Invalid hexadecimal digit: " + hexString) } return out } } object HASH { private val MD5 = "MD5" private val SHA_1 = "SHA-1" private val SHA_256 = "SHA-256" private val DIGITS_LOWER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') private val DIGITS_UPPER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') fun md5(data: ByteArray): String { return String(encodeHex(md5Bytes(data))) } fun md5(text: String): String { return String(encodeHex(md5Bytes(Helper.getRawBytes(text)))) } fun md5Bytes(data: ByteArray): ByteArray { return getDigest(MD5).digest(data) } fun sha1(data: ByteArray): String { return String(encodeHex(sha1Bytes(data))) } fun sha1(text: String): String { return String(encodeHex(sha1Bytes(Helper.getRawBytes(text)))) } fun sha1Bytes(data: ByteArray): ByteArray { return getDigest(SHA_1).digest(data) } fun sha256(data: ByteArray): String { return String(encodeHex(sha256Bytes(data))) } fun sha256(text: String): String { return String(encodeHex(sha256Bytes(Helper.getRawBytes(text)))) } fun sha256Bytes(data: ByteArray): ByteArray { return getDigest(SHA_256).digest(data) } private fun getDigest(algorithm: String): MessageDigest { try { return MessageDigest.getInstance(algorithm) } catch (e: NoSuchAlgorithmException) { throw IllegalArgumentException(e) } } private fun encodeHex(data: ByteArray, toLowerCase: Boolean = true): CharArray { return encodeHex(data, if (toLowerCase) DIGITS_LOWER else DIGITS_UPPER) } private fun encodeHex(data: ByteArray, toDigits: CharArray): CharArray { val l = data.size val out = CharArray(l shl 1) var i = 0 var j = 0 while (i < l) { out[j++] = toDigits[(240 and data[i].toInt()).ushr(4)] out[j++] = toDigits[15 and data[i].toInt()] i++ } return out } }
0
Java
0
0
69fe6cb7de5b58e310aa18419f412a26efcc5169
14,829
Android-Next
Apache License 2.0
feature/home/src/main/java/com/kanyideveloper/presentation/home/mymeal/MyMealScreen.kt
JoelKanyi
554,742,212
false
null
/* * Copyright 2022 Joel Kanyi. * * 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.kanyideveloper.presentation.home.mymeal import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells 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.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.kanyideveloper.compose_ui.theme.Shapes import com.kanyideveloper.core.model.Meal import com.kanyideveloper.core.util.LottieAnim import com.kanyideveloper.core.util.showDayCookMessage import com.kanyideveloper.domain.model.MealCategory import com.kanyideveloper.mealtime.core.R import com.kanyideveloper.presentation.home.HomeNavigator import com.kanyideveloper.presentation.home.HomeViewModel import com.kanyideveloper.presentation.home.composables.MealItem import com.ramcosta.composedestinations.annotation.Destination @Destination @Composable fun MyMealScreen( navigator: HomeNavigator, viewModel: HomeViewModel = hiltViewModel() ) { val myMeals = viewModel.myMeals.observeAsState().value?.observeAsState()?.value MyMealScreenContent( myMeals = myMeals, viewModel = viewModel, navigator = navigator, openMealDetails = { meal -> navigator.openMealDetails(meal = meal) }, addToFavorites = { localMealId, imageUrl, name -> viewModel.insertAFavorite( localMealId = localMealId, mealImageUrl = imageUrl, mealName = name ) }, removeFromFavorites = { id -> viewModel.deleteALocalFavorite( localMealId = id ) }, isSelected = { category -> viewModel.selectedCategory.value == category }, onCategoryClick = { category -> viewModel.setSelectedCategory(category) viewModel.getMyMeals(viewModel.selectedCategory.value) } ) } @Composable private fun MyMealScreenContent( myMeals: List<Meal>?, viewModel: HomeViewModel, navigator: HomeNavigator, openMealDetails: (Meal) -> Unit = {}, addToFavorites: (Int, String, String) -> Unit, removeFromFavorites: (Int) -> Unit, isSelected: (String) -> Boolean, onCategoryClick: (String) -> Unit ) { LazyVerticalGrid( modifier = Modifier.fillMaxSize(), columns = GridCells.Fixed(2), contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { item(span = { GridItemSpan(2) }) { Spacer(modifier = Modifier.height(8.dp)) } item(span = { GridItemSpan(2) }) { Text( modifier = Modifier.padding(vertical = 5.dp), text = "Categories", style = MaterialTheme.typography.titleMedium ) } item(span = { GridItemSpan(2) }) { LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp) ) { items(mealCategories) { category -> MyMealsCategoryItem( category = category, isSelected = isSelected, onCategoryClick = onCategoryClick ) } } } item(span = { GridItemSpan(2) }) { Spacer(modifier = Modifier.height(8.dp)) } item(span = { GridItemSpan(2) }) { Card( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) .height(180.dp), shape = Shapes.large, colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Box(Modifier.fillMaxSize()) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(id = R.drawable.randomize_mealss), contentDescription = null, contentScale = ContentScale.Crop ) Column( modifier = Modifier .align(Alignment.BottomEnd) .padding(16.dp) ) { Text( text = showDayCookMessage(), style = MaterialTheme.typography.titleSmall, color = Color.White ) Button( onClick = { navigator.openRandomMeals() } ) { Text( text = "Get a Random Meal", style = MaterialTheme.typography.labelMedium ) } } } } } item(span = { GridItemSpan(2) }) { Spacer(modifier = Modifier.height(8.dp)) } if (!myMeals.isNullOrEmpty()) { item(span = { GridItemSpan(2) }) { Text( modifier = Modifier.padding(vertical = 3.dp), text = "Meals", style = MaterialTheme.typography.titleMedium ) } } items(myMeals ?: emptyList()) { meal -> MealItem( modifier = Modifier.clickable { openMealDetails(meal) }, meal = meal, addToFavorites = addToFavorites, removeFromFavorites = removeFromFavorites, viewModel = viewModel ) } if (myMeals.isNullOrEmpty()) { item(span = { GridItemSpan(2) }) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) .testTag("Empty State Component"), horizontalAlignment = Alignment.CenterHorizontally ) { LottieAnim( resId = R.raw.astronaut, height = 120.dp ) Text( modifier = Modifier .fillMaxWidth(), text = "You don't have local meals, you can add some.", style = MaterialTheme.typography.titleSmall, textAlign = TextAlign.Center ) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun MyMealsCategoryItem( category: MealCategory, isSelected: (String) -> Boolean, onCategoryClick: (String) -> Unit ) { Card( modifier = Modifier .size(65.dp), shape = Shapes.large, colors = CardDefaults.cardColors( containerColor = if (isSelected(category.name)) { MaterialTheme.colorScheme.primary } else { MaterialTheme.colorScheme.surfaceVariant } ), onClick = { onCategoryClick(category.name) } ) { Column( Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Icon( modifier = Modifier .size(32.dp) .padding(4.dp), painter = painterResource(id = category.icon), contentDescription = null, tint = if (isSelected(category.name)) { MaterialTheme.colorScheme.onPrimary } else { MaterialTheme.colorScheme.onSurfaceVariant } ) Text( text = category.name, textAlign = TextAlign.Center, style = MaterialTheme.typography.labelSmall, color = if (isSelected(category.name)) { MaterialTheme.colorScheme.onPrimary } else { MaterialTheme.colorScheme.onSurfaceVariant } ) } } } private val mealCategories = listOf( MealCategory( "All", R.drawable.fork_knife_thin ), MealCategory( "Food", R.drawable.ic_food ), MealCategory( "Breakfast", R.drawable.ic_breakfast ), MealCategory( "Drinks", R.drawable.ic_drinks ), MealCategory( "Fruits", R.drawable.ic_fruit ), MealCategory( "Fast Food", R.drawable.ic_pizza_thin ) )
12
Kotlin
9
69
040b552070450d2e2b34cd1817eece7145fb2086
10,972
MealTime
Apache License 2.0
newm-server/src/main/kotlin/io/newm/server/features/user/database/UserTable.kt
projectNEWM
447,979,150
false
null
package io.newm.server.features.user.database import io.newm.server.auth.oauth.model.OAuthType import io.newm.server.features.user.model.UserVerificationStatus import org.jetbrains.exposed.dao.id.UUIDTable import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.javatime.CurrentDateTime import org.jetbrains.exposed.sql.javatime.datetime import java.time.LocalDateTime object UserTable : UUIDTable(name = "users") { val createdAt: Column<LocalDateTime> = datetime("created_at").defaultExpression(CurrentDateTime) val oauthType: Column<OAuthType?> = enumeration("oauth_type", OAuthType::class).nullable() val oauthId: Column<String?> = text("oauth_id").nullable() val firstName: Column<String?> = text("first_name").nullable() val lastName: Column<String?> = text("last_name").nullable() val nickname: Column<String?> = text("nickname").nullable() val pictureUrl: Column<String?> = text("picture_url").nullable() val bannerUrl: Column<String?> = text("banner_url").nullable() val websiteUrl: Column<String?> = text("website_url").nullable() val twitterUrl: Column<String?> = text("twitter_url").nullable() val instagramUrl: Column<String?> = text("instagram_url").nullable() val spotifyProfile: Column<String?> = text("spotify_profile").nullable() val soundCloudProfile: Column<String?> = text("sound_cloud_profile").nullable() val appleMusicProfile: Column<String?> = text("apple_music_profile").nullable() val location: Column<String?> = text("location").nullable() val role: Column<String?> = text("role").nullable() val genre: Column<String?> = text("genre").nullable() val biography: Column<String?> = text("biography").nullable() val walletAddress: Column<String?> = text("wallet_address").nullable() val email: Column<String> = text("email") val passwordHash: Column<String?> = text("password_hash").nullable() val verificationStatus: Column<UserVerificationStatus> = enumeration("verification_status", UserVerificationStatus::class) .default(UserVerificationStatus.Unverified) val companyName: Column<String?> = text("company_name").nullable() val companyLogoUrl: Column<String?> = text("company_logo_url").nullable() val companyIpRights: Column<Boolean?> = bool("company_ip_rights").nullable() val isni: Column<String?> = text("isni").nullable() val ipi: Column<String?> = text("ipi").nullable() val dspPlanSubscribed: Column<Boolean> = bool("dsp_plan_subscribed").default(false) val admin: Column<Boolean> = bool("admin").default(false) val distributionUserId: Column<String?> = text("distribution_user_id").nullable() val distributionArtistId: Column<Long?> = long("distribution_artist_id").nullable() val distributionParticipantId: Column<Long?> = long("distribution_participant_id").nullable() val distributionSubscriptionId: Column<Long?> = long("distribution_subscription_id").nullable() val distributionLabelId: Column<Long?> = long("distribution_label_id").nullable() val distributionIsni: Column<String?> = text("distribution_isni").nullable() val distributionIpn: Column<String?> = text("distribution_ipn").nullable() val distributionNewmParticipantId: Column<Long?> = long("distribution_newm_participant_id").nullable() }
1
null
4
9
3809a375cc159b540eb35e78fe3d0bdea0c24f6e
3,328
newm-server
Apache License 2.0
app/src/main/java/com/wuruoye/know/ui/home/UserFragment.kt
ruoyewu
183,387,390
false
null
package com.wuruoye.know.ui.home import android.app.Activity.RESULT_OK import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.bumptech.glide.Glide import com.google.android.material.appbar.AppBarLayout import com.wuruoye.know.R import com.wuruoye.know.ui.base.LeakFragment import com.wuruoye.know.ui.home.vm.IUserVM import com.wuruoye.know.ui.home.vm.UserViewModel import com.wuruoye.know.ui.setting.* import com.wuruoye.know.util.InjectorUtil import com.wuruoye.know.util.model.RequestCode.RECORD_FOR_RECORD import com.wuruoye.know.util.model.RequestCode.RECORD_FOR_TYPE import com.wuruoye.know.util.model.RequestCode.USER_FOR_BACKUP import com.wuruoye.know.util.model.RequestCode.USER_FOR_LOGIN import com.wuruoye.know.util.model.RequestCode.USER_FOR_MORE import com.wuruoye.know.util.model.RequestCode.USER_FOR_RECORD_TAG import com.wuruoye.know.util.model.RequestCode.USER_FOR_RECORD_TYPE import com.wuruoye.know.util.model.RequestCode.USER_FOR_REVIEW_STRATEGY import com.wuruoye.know.util.model.RequestCode.USER_FOR_USER_INFO import com.wuruoye.know.util.model.beans.UserInfo import com.wuruoye.know.util.toast import de.hdodenhof.circleimageview.CircleImageView /** * Created at 2019/4/9 21:17 by wuruoye * Description: */ class UserFragment : LeakFragment(), View.OnClickListener { private lateinit var cl: CoordinatorLayout private lateinit var abl: AppBarLayout private lateinit var ivBack: ImageView private lateinit var ivUser: CircleImageView private lateinit var tvName: TextView private lateinit var tvSign: TextView private lateinit var llRecordSize: LinearLayout private lateinit var tvRecordSize: TextView private lateinit var llRecordTypeSize: LinearLayout private lateinit var tvRecordTypeSize: TextView private lateinit var llRecordTagSize: LinearLayout private lateinit var tvRecordTagSize: TextView private lateinit var llUserInfo: LinearLayout private lateinit var llEdiRecordType: LinearLayout private lateinit var llEditReviewStrategy: LinearLayout private lateinit var llEditRecordTag: LinearLayout private lateinit var llBackup: LinearLayout private lateinit var llMoreSetting: LinearLayout private lateinit var vm: IUserVM override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_user, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) vm = ViewModelProviders.of(this, InjectorUtil.userViewModelFactory(context!!)) .get(UserViewModel::class.java) bindView(view) bindListener() initView() subscribeUI() } private fun bindView(view: View) { with(view) { cl = findViewById(R.id.cl_user) abl = findViewById(R.id.abl_user) ivBack = findViewById(R.id.iv_bg_user) ivUser = findViewById(R.id.civ_user) tvName = findViewById(R.id.tv_user_user) tvSign = findViewById(R.id.tv_sign_user) llRecordSize = findViewById(R.id.ll_record_size_user) tvRecordSize = findViewById(R.id.tv_record_size_user) llRecordTypeSize = findViewById(R.id.ll_record_type_size_user) tvRecordTypeSize = findViewById(R.id.tv_record_type_size_user) llRecordTagSize = findViewById(R.id.ll_record_tag_size_user) tvRecordTagSize = findViewById(R.id.tv_record_tag_size_user) llUserInfo = findViewById(R.id.ll_user_info_user) llEdiRecordType = findViewById(R.id.ll_edit_record_type_user) llEditReviewStrategy = findViewById(R.id.ll_edit_review_strategy_user) llEditRecordTag = findViewById(R.id.ll_edit_record_tag_user) llBackup = findViewById(R.id.ll_backup_user) llMoreSetting = findViewById(R.id.ll_more_setting_user) } } private fun bindListener() { cl.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> cl.dispatchDependentViewsChanged(abl) } ivUser.setOnClickListener(this) tvName.setOnClickListener(this) llRecordSize.setOnClickListener(this) llRecordTypeSize.setOnClickListener(this) llRecordTagSize.setOnClickListener(this) llUserInfo.setOnClickListener(this) llEdiRecordType.setOnClickListener(this) llEditReviewStrategy.setOnClickListener(this) llEditRecordTag.setOnClickListener(this) llBackup.setOnClickListener(this) llMoreSetting.setOnClickListener(this) } private fun initView() { } private fun subscribeUI() { vm.recordSize.observe(this, Observer { tvRecordSize.text = it.toString() }) vm.recordTypeSize.observe(this, Observer { tvRecordTypeSize.text = it.toString() }) vm.recordTagSize.observe(this, Observer { tvRecordTagSize.text = it.toString() }) vm.userInfo.observe(this, Observer { if (it != null) { tvName.text = it.name tvSign.text = it.sign Glide.with(ivUser).load(it.avatar).into(ivUser) } else { tvName.text = "未登录" tvSign.text = "用户签名" ivUser.setImageResource(R.drawable.ic_avatar) } }) } override fun onClick(v: View?) { when(v?.id) { R.id.civ_user -> { if (vm.login) { } else { startActivityForResult(Intent(context, UserLoginActivity::class.java), USER_FOR_LOGIN) } } R.id.tv_user_user -> { if (vm.login) { } else { } } R.id.ll_user_info_user -> { if (vm.login) { val intent = Intent(context, UserInfoActivity::class.java) intent.putExtra(UserInfoActivity.USER_INFO, vm.userInfo.value!!) startActivityForResult(intent, USER_FOR_USER_INFO) } else { context?.toast("请先登录") } } R.id.ll_edit_record_type_user -> { startActivityForResult(Intent(context, RecordTypeSetActivity::class.java), USER_FOR_RECORD_TYPE) } R.id.ll_edit_review_strategy_user -> { startActivityForResult(Intent(context, ReviewStrategySetActivity::class.java), USER_FOR_REVIEW_STRATEGY) } R.id.ll_edit_record_tag_user -> { startActivityForResult(Intent(context, RecordTagSetActivity::class.java), USER_FOR_RECORD_TAG) } R.id.ll_backup_user -> { if (vm.login) { startActivityForResult(Intent(context, BackupActivity::class.java), USER_FOR_BACKUP) } else { context?.toast("请先登录") } } R.id.ll_more_setting_user -> { startActivityForResult(Intent(context, SettingActivity::class.java), USER_FOR_MORE) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK) { when(requestCode) { USER_FOR_RECORD_TYPE -> { vm.updateInfo() } USER_FOR_RECORD_TAG -> { vm.updateInfo() } RECORD_FOR_RECORD -> { vm.updateInfo() } RECORD_FOR_TYPE -> { vm.updateInfo() } USER_FOR_LOGIN -> { val userInfo = data!! .getParcelableExtra<UserInfo>(UserLoginActivity.USER_INFO) vm.userInfo.value = userInfo } USER_FOR_USER_INFO -> { val userInfo = data ?.getParcelableExtra<UserInfo>(UserInfoActivity.USER_INFO) vm.userInfo.value = userInfo if (userInfo == null) { vm.logout() } } USER_FOR_BACKUP -> { vm.updateInfo() } USER_FOR_MORE -> { } } } } }
1
null
1
1
2de5a7fdecc8c135463c99c47cde417de0cbe2ec
9,191
know2
Apache License 2.0
app/src/main/java/com/elementary/tasks/core/os/PendingIntentWrapper.kt
naz013
165,067,747
false
null
package com.elementary.tasks.core.os import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build object PendingIntentWrapper { fun getActivity( context: Context, requestCode: Int, intent: Intent, flags: Int, ignoreIn13: Boolean = false ): PendingIntent { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getActivity( context, requestCode, intent, if (ignoreIn13) { flags } else { PendingIntent.FLAG_IMMUTABLE } ) } else { PendingIntent.getActivity(context, requestCode, intent, flags) } } fun getBroadcast( context: Context, requestCode: Int, intent: Intent, flags: Int, ignoreIn13: Boolean = false ): PendingIntent { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getBroadcast( context, requestCode, intent, if (ignoreIn13) { flags } else { PendingIntent.FLAG_IMMUTABLE } ) } else { PendingIntent.getBroadcast(context, requestCode, intent, flags) } } fun getService( context: Context, requestCode: Int, intent: Intent, flags: Int, ignoreIn13: Boolean = false ): PendingIntent { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getService( context, requestCode, intent, if (ignoreIn13) { flags } else { PendingIntent.FLAG_IMMUTABLE } ) } else { PendingIntent.getService(context, requestCode, intent, flags) } } }
0
null
3
6
a6eecfda739be05a4b84e7d47284cd9e2bc782d6
1,727
reminder-kotlin
Apache License 2.0
src/main/kotlin/rsa/UpdateInformation.kt
BAC2-Graf-Rohatynski
208,084,653
false
null
package error import org.json.JSONObject import org.slf4j.Logger import org.slf4j.LoggerFactory import enumstorage.update.UpdateInformation.Application import enumstorage.update.UpdateInformation.Changes import enumstorage.update.UpdateInformation.Version import enumstorage.update.UpdateInformation.Update import java.util.* object UpdateInformation { private val logger: Logger = LoggerFactory.getLogger(UpdateInformation::class.java) fun getAsJson(applicationName: String): JSONObject { return try { val properties = Properties() val presetsStream = UpdateInformation::class.java.classLoader.getResourceAsStream("update.properties") properties.load(presetsStream) val isUpdate = properties.getProperty("$applicationName.${Update.name.toLowerCase()}")?.toBoolean() ?: throw Exception("Field '${Update.name.toLowerCase()}' is null or not existing for $applicationName!") val version = properties.getProperty("$applicationName.${Version.name.toLowerCase()}") ?: throw Exception("Field '${Version.name.toLowerCase()}' is null or not existing for $applicationName!") val changes = properties.getProperty("$applicationName.${Changes.name.toLowerCase()}") ?: throw Exception("Field '${Changes.name.toLowerCase()}' is null or not existing for $applicationName!") val application = properties.getProperty("$applicationName.${Application.name.toLowerCase()}") ?: throw Exception("Field '${Application.name.toLowerCase()}' is null or not existing for $applicationName!") if (isUpdate) { logger.info("Updates available") properties.setProperty("$applicationName.${Update.name.toLowerCase()}", false.toString()) JSONObject() .put(Application.name, application) .put(Version.name, version) .put(Changes.name, changes) } else { logger.info("No updates available") JSONObject() } } catch (ex: Exception) { logger.error("Error occurred while requesting update information!\n${ex.message}") JSONObject() } } fun getAsJson(applicationName: String, version: String, changes: String): JSONObject = JSONObject() .put(enumstorage.update.UpdateInformation.Application.name, applicationName) .put(enumstorage.update.UpdateInformation.Version.name, version) .put(enumstorage.update.UpdateInformation.Changes.name, changes) }
0
null
1
1
375706d0676eb289988e904dbba95a84792aed10
2,579
RsaEncryptionModule
MIT License
app/src/main/java/com/example/background/workers/CleanupWorker.kt
cerberusv2px
155,056,338
false
{"Java": 25187, "Kotlin": 2815}
package com.example.background.workers import android.content.Context import android.text.TextUtils import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import com.example.background.Constants import java.io.File class CleanupWorker constructor( context: Context, workerParameters: WorkerParameters ) : Worker(context, workerParameters) { private val TAG by lazy { CleanupWorker::class.java.simpleName } override fun doWork(): Result { return try { val outputDirectory = File(applicationContext.filesDir, Constants.OUTPUT_PATH) if (outputDirectory.exists()) { val entries = outputDirectory.listFiles() if (entries != null && entries.isNotEmpty()) { for (e: File in entries) { val name = e.name if (!TextUtils.isEmpty(name) && name.endsWith(".png")) { val deleted = e.delete() Log.e(TAG, "Deleted $name - $deleted") } } } } Result.SUCCESS } catch (ex: Exception) { Log.e(TAG, " Error cleaning up", ex) Result.FAILURE } } }
1
null
1
1
189ddfb0647183aeca427543e62ee4a7f89fa29a
1,294
android-workmanager-sample
Apache License 2.0
app/main/oppgavestyring/Dto.kt
navikt
466,112,140
false
null
package oppgavestyring import no.nav.aap.dto.kafka.* import java.time.LocalDate import java.time.LocalDateTime import java.util.* data class DtoInnstillingParagraf_11_6( val harBehovForBehandling: Boolean, val harBehovForTiltak: Boolean, val harMulighetForÅKommeIArbeid: Boolean, val individuellBegrunnelse: String?, ) { internal fun toKafkaDto(vurdertAv: String) = Innstilling_11_6KafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), harBehovForBehandling = harBehovForBehandling, harBehovForTiltak = harBehovForTiltak, harMulighetForÅKommeIArbeid = harMulighetForÅKommeIArbeid, individuellBegrunnelse = individuellBegrunnelse, ) } data class DtoLøsningInngangsvilkår( val løsning_11_2: DtoLøsningParagraf_11_2?, val løsning_11_3: DtoLøsningParagraf_11_3, val løsning_11_4: DtoLøsningParagraf_11_4_ledd2_ledd3?, ) data class DtoLøsningParagraf_11_2( val erMedlem: String ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_2_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), erMedlem = erMedlem ) } data class DtoLøsningParagraf_11_3( val erOppfylt: Boolean ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_3_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), erOppfylt = erOppfylt ) } data class DtoLøsningParagraf_11_4_ledd2_ledd3( val erOppfylt: Boolean ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_4_ledd2_ledd3_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), erOppfylt = erOppfylt ) } data class DtoLøsningParagraf_11_5( val kravOmNedsattArbeidsevneErOppfylt: Boolean, val kravOmNedsattArbeidsevneErOppfyltBegrunnelse: String, val nedsettelseSkyldesSykdomEllerSkade: Boolean, val nedsettelseSkyldesSykdomEllerSkadeBegrunnelse: String, val kilder: List<String>, val legeerklæringDato: LocalDate?, val sykmeldingDato: LocalDate?, ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_5_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), kravOmNedsattArbeidsevneErOppfylt = kravOmNedsattArbeidsevneErOppfylt, kravOmNedsattArbeidsevneErOppfyltBegrunnelse = kravOmNedsattArbeidsevneErOppfyltBegrunnelse, nedsettelseSkyldesSykdomEllerSkade = nedsettelseSkyldesSykdomEllerSkade, nedsettelseSkyldesSykdomEllerSkadeBegrunnelse = nedsettelseSkyldesSykdomEllerSkadeBegrunnelse, kilder = kilder, legeerklæringDato = legeerklæringDato, sykmeldingDato = sykmeldingDato, ) } data class DtoLøsningParagraf_11_6( val harBehovForBehandling: Boolean, val harBehovForTiltak: Boolean, val harMulighetForÅKommeIArbeid: Boolean, val individuellBegrunnelse: String?, ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_6_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), harBehovForBehandling = harBehovForBehandling, harBehovForTiltak = harBehovForTiltak, harMulighetForÅKommeIArbeid = harMulighetForÅKommeIArbeid, individuellBegrunnelse = individuellBegrunnelse, ) } data class DtoLøsningParagraf_11_19( val beregningsdato: LocalDate, val grunnForDato: String, ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_19_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), beregningsdato = beregningsdato ) } data class DtoLøsningParagraf_11_29( val erOppfylt: Boolean ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_11_29_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), erOppfylt = erOppfylt ) } data class DtoLøsningParagraf_22_13( val bestemmesAv: String, val unntak: String?, val unntaksbegrunnelse: String?, val manueltSattVirkningsdato: LocalDate?, val begrunnelseForAnnet: String?, ) { internal fun toKafkaDto(vurdertAv: String) = Løsning_22_13_manuellKafkaDto( vurdertAv = vurdertAv, tidspunktForVurdering = LocalDateTime.now(), bestemmesAv = bestemmesAv, unntak = unntak, unntaksbegrunnelse = unntaksbegrunnelse, manueltSattVirkningsdato = manueltSattVirkningsdato, begrunnelseForAnnet = begrunnelseForAnnet, ) } data class DtoKvalitetssikringParagraf_11_2( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_2KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) } data class DtoKvalitetssikringParagraf_11_3( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_3KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) } data class DtoKvalitetssikringParagraf_11_4_ledd2Og3( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_4_ledd2_ledd3KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) } data class DtoKvalitetssikringParagraf_11_5( val løsningId: UUID, val kravOmNedsattArbeidsevneErGodkjent: Boolean, val kravOmNedsattArbeidsevneErGodkjentBegrunnelse: String?, val nedsettelseSkyldesSykdomEllerSkadeErGodkjent: Boolean, val nedsettelseSkyldesSykdomEllerSkadeErGodkjentBegrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_5KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), kravOmNedsattArbeidsevneErGodkjent = kravOmNedsattArbeidsevneErGodkjent, kravOmNedsattArbeidsevneErGodkjentBegrunnelse = kravOmNedsattArbeidsevneErGodkjentBegrunnelse, nedsettelseSkyldesSykdomEllerSkadeErGodkjent = nedsettelseSkyldesSykdomEllerSkadeErGodkjent, nedsettelseSkyldesSykdomEllerSkadeErGodkjentBegrunnelse = nedsettelseSkyldesSykdomEllerSkadeErGodkjentBegrunnelse, ) } data class DtoKvalitetssikringParagraf_11_6( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_6KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) } data class DtoKvalitetssikringParagraf_11_19( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_19KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) } data class DtoKvalitetssikringParagraf_11_29( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_11_29KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) } data class DtoKvalitetssikringParagraf_22_13( val løsningId: UUID, val erGodkjent: Boolean, val begrunnelse: String?, ) { internal fun toKafkaDto(kvalitetssikretAv: String) = Kvalitetssikring_22_13KafkaDto( løsningId = løsningId, kvalitetssikretAv = kvalitetssikretAv, tidspunktForKvalitetssikring = LocalDateTime.now(), erGodkjent = erGodkjent, begrunnelse = begrunnelse, ) }
11
Kotlin
0
1
3dc039db4f60ca3ab560843fb9396ce81472d134
8,677
aap-oppgavestyring
MIT License
plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/facet/KotlinFacetTypeImpl.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.facet import com.intellij.facet.Facet import com.intellij.facet.ui.FacetEditor import com.intellij.facet.ui.MultipleFacetSettingsEditor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.workspaceModel.KotlinFacetBridgeFactory class KotlinFacetTypeImpl : KotlinFacetType<KotlinFacetConfiguration>() { override fun createDefaultConfiguration() = KotlinFacetBridgeFactory.createFacetConfiguration() override fun createFacet( module: Module, name: String, configuration: KotlinFacetConfiguration, underlyingFacet: Facet<*>? ) = KotlinFacetBridgeFactory.createKotlinFacet(module, name, configuration) override fun createMultipleConfigurationsEditor(project: Project, editors: Array<out FacetEditor>): MultipleFacetSettingsEditor { return KotlinFacetEditorProviderService.getInstance(project).getMultipleConfigurationEditor(project, editors) } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
1,166
intellij-community
Apache License 2.0
mobilesdk/src/main/java/com/swedbankpay/mobilesdk/PreOrderPurchaseIndicator.kt
SwedbankPay
209,749,704
false
null
package com.swedbankpay.mobilesdk import com.google.gson.annotations.SerializedName /** * Purchase indicator values for [RiskIndicator]. */ @Suppress("unused") enum class PreOrderPurchaseIndicator { /** * Merchandise available now */ @SerializedName("01") MERCHANDISE_AVAILABLE, /** * Merchandise will be available in the future */ @SerializedName("02") FUTURE_AVAILABILITY }
1
Kotlin
2
5
98df28d4dda025aebef4f7ab415811ca687f3d73
416
swedbank-pay-sdk-android
Apache License 2.0
app/src/main/java/com/muratozturk/mova/domain/use_case/details/movie/images/GetMovieImagesUseCase.kt
muratozturk5
587,507,400
false
null
package com.muratozturk.mova.domain.use_case.details.movie.images import com.muratozturk.mova.domain.repository.MovaRepository import javax.inject.Inject class GetMovieImagesUseCase @Inject constructor(private val repository: MovaRepository) { operator fun invoke(movieId: Int) = repository.getMovieImages(movieId) }
0
Kotlin
13
96
280ced4d70d4e2f9e7c4549b5c919cc7cd821146
322
Mova
MIT License
app/src/main/java/com/moegirlviewer/api/editingRecord/bean/ComparePageResult.kt
koharubiyori
449,942,456
false
null
package com.moegirlviewer.api.editingRecord.bean import com.google.gson.annotations.SerializedName data class ComparePageResult( val compare: Compare ) { data class Compare( @SerializedName("*") val _asterisk: String, val diffsize: Int, val fromcomment: String, val fromuser: String, val fromuserid: Int, val prev: Int, val tocomment: String, val touser: String, val touserid: Int ) }
1
Kotlin
2
16
e09753e76c11932d6f7344302d48f7a214cccf3a
432
Moegirl-plus-native
MIT License
utils/idgenerators/src/test/kotlin/io/bluetape4k/idgenerators/hashids/HashIdsSupportTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.idgenerators.hashids import io.bluetape4k.collections.asParallelStream import io.bluetape4k.idgenerators.flake.Flake import io.bluetape4k.idgenerators.snowflake.GlobalSnowflake import io.bluetape4k.idgenerators.uuid.TimebasedUuidGenerator import io.bluetape4k.junit5.concurrency.MultithreadingTester import io.bluetape4k.junit5.concurrency.VirtualthreadTester import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import io.bluetape4k.logging.trace import io.bluetape4k.support.toLong import io.bluetape4k.utils.Runtimex import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldNotBeEqualTo import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.util.* import java.util.concurrent.ConcurrentHashMap class HashIdsSupportTest { companion object: KLogging() { const val ITEM_SIZE = 1000 } private val hashids = Hashids("bluetape4k.io") @Nested inner class UuidTest { private val uuidGenerator = TimebasedUuidGenerator() @Test fun `encode random UUID`() { repeat(ITEM_SIZE) { verifyUuidEncode(UUID.randomUUID()) } } @Test fun `encode time based uuid`() { repeat(ITEM_SIZE) { verifyUuidEncode(uuidGenerator.nextUUID()) } } @Test fun `encode time based uuid as parallel`() { val uuids = List(ITEM_SIZE) { uuidGenerator.nextUUID() } uuids.parallelStream() .forEach { verifyUuidEncode(it) } } private fun verifyUuidEncode(uuid: UUID) { val encoded = hashids.encodeUUID(uuid) log.debug { "hashids=$encoded" } val decoded = hashids.decodeUUID(encoded) decoded shouldBeEqualTo uuid } @Test fun `정렬된 UUID에 대한 hashid는 정렬되지 않습니다`() { val uuids = List(ITEM_SIZE) { uuidGenerator.nextUUID() } val encodeds = uuids .map { hashids.encodeUUID(it) } .onEach { log.trace { it } } encodeds.sorted() shouldNotBeEqualTo encodeds } } @Nested inner class SnowflakeTest { private val snowflake = GlobalSnowflake() @Test fun `encode snowflake id`() { repeat(ITEM_SIZE) { val id = snowflake.nextId() verifySnowflakeId(id) } } @Test fun `encode snowflake id as parallel`() { snowflake .nextIds(ITEM_SIZE) .asParallelStream() .forEach { verifySnowflakeId(it) } } @Test fun `encode flake id in multi threading`() { val map = ConcurrentHashMap<Long, Int>() MultithreadingTester() .numThreads(2 * Runtimex.availableProcessors) .roundsPerThread(ITEM_SIZE) .add { val id = snowflake.nextId() verifySnowflakeId(id) map.putIfAbsent(id, 1).shouldBeNull() } .run() } @Test fun `encode flake id in virtual threading`() { val map = ConcurrentHashMap<Long, Int>() VirtualthreadTester() .numThreads(2 * Runtimex.availableProcessors) .roundsPerThread(ITEM_SIZE) .add { val id = snowflake.nextId() verifySnowflakeId(id) map.putIfAbsent(id, 1).shouldBeNull() } .run() } private fun verifySnowflakeId(id: Long) { val encoded = hashids.encode(id) log.debug { "hashids=$encoded" } val decoded = hashids.decode(encoded) decoded.size shouldBeEqualTo 1 decoded[0] shouldBeEqualTo id } } @Nested inner class FlakeTest { private val flake = Flake() @Test fun `encode flake id`() { repeat(ITEM_SIZE) { val id = flake.nextId().toLong() verifyFlakeId(id) } } @Test fun `encode flake id as parallel`() { flake .nextIds(ITEM_SIZE) .asParallelStream() .forEach { verifyFlakeId(it.toLong()) } } private fun verifyFlakeId(id: Long) { val encoded = hashids.encode(id) log.debug { "id=$id, hashids=$encoded" } val decoded = hashids.decode(encoded) decoded.size shouldBeEqualTo 1 decoded[0] shouldBeEqualTo id } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
4,891
bluetape4k
MIT License
api/src/main/kotlin/rchabot/tournament/api/infrastructure/secondary/mapper/PlayerMapper.kt
RomainChabot
667,018,086
false
null
package rchabot.tournament.api.infrastructure.secondary.mapper import rchabot.tournament.api.domain.entity.Player import rchabot.tournament.api.domain.entity.Pseudo import rchabot.tournament.api.domain.entity.Ranking import rchabot.tournament.api.domain.entity.Score import rchabot.tournament.api.infrastructure.secondary.model.PlayerEntity object PlayerMapper { fun toEntity(player: Player) = PlayerEntity( pseudo = player.pseudo.value, score = player.score.value, ranking = player.ranking.value ) fun toDomain(playerEntity: PlayerEntity) = Player( pseudo = Pseudo(playerEntity.pseudo), score = Score(playerEntity.score), ranking = Ranking(playerEntity.ranking) ) }
0
Kotlin
0
0
d4a1868b260cb73243dd2639def22b95c17b74b8
734
tournament-v2
MIT License
foryouandme/src/main/java/com/foryouandme/core/arch/navigation/action/AuthActions.kt
4YouandMeData
610,425,317
false
null
package com.foryouandme.core.arch.navigation.action import com.foryouandme.core.activity.FYAMActivity fun authActivityAction(): ActivityAction = { (it as FYAMActivity).auth() }
0
Kotlin
0
0
bc82972689db5052344365ac07c8f6711f5ad7fa
194
4YouandMeAndroid
MIT License
app/shared/fwup/impl/src/commonTest/kotlin/build/wallet/fwup/FwupManifestParserTests.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.fwup import build.wallet.fwup.FwupManifestParser.FwupSlot.A import build.wallet.fwup.FwupManifestParser.FwupSlot.B import build.wallet.fwup.FwupManifestParser.ParseFwupManifestSuccess import build.wallet.fwup.ParseFwupManifestError.ParsingError import build.wallet.fwup.ParseFwupManifestError.UnknownManifestVersion import build.wallet.testing.shouldBeErrOfType import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.ints.shouldBeGreaterThan import io.kotest.matchers.ints.shouldBeLessThan import io.kotest.matchers.shouldBe class FwupManifestParserTests : FunSpec({ val fwup = FwupManifestParserImpl() val goodJson = """{"manifest_version": "0.0.1", |"fwup_bundle": {"product": "w1a", |"version": "1.2.5", "assets": |{"bootloader": {"image": |{"name": "w1a-proto-0-loader-dev.signed.bin"}, |"signature": |{"name": "w1a-proto-0-loader-dev.detached_signature"}}, |"application_a": |{"image": {"name": "w1a-proto-0-app-a-dev.signed.bin"}, |"signature": {"name": "w1a-proto-0-app-a-dev.detached_signature"}}, |"application_b": {"image": {"name": "w1a-proto-0-app-b-dev.signed.bin"}, |"signature": {"name": "w1a-proto-0-app-b-dev.detached_signature"}}}, |"parameters": {"wca_chunk_size": 452, "signature_offset": 647104, |"app_properties_offset": 1024}}} """.trimMargin() val wrongManifestVersionJson = """{"manifest_version": "0.0.2", |"fwup_bundle": {"product": "w1a", |"version": "1.2.5", "assets": |{"bootloader": {"image": |{"name": "w1a-proto-0-loader-dev.signed.bin"}, |"signature": |{"name": "w1a-proto-0-loader-dev.detached_signature"}}, |"application_a": |{"image": {"name": "w1a-proto-0-app-a-dev.signed.bin"}, |"signature": {"name": "w1a-proto-0-app-a-dev.detached_signature"}}, |"application_b": {"image": {"name": "w1a-proto-0-app-b-dev.signed.bin"}, |"signature": {"name": "w1a-proto-0-app-b-dev.detached_signature"}}}, |"parameters": {"wca_chunk_size": 452, "signature_offset": 647104, |"app_properties_offset": 1024}}} """.trimMargin() val missingSignatureFilesJson = """{"manifest_version": "0.0.2", |"fwup_bundle": {"product": "w1a", |"version": "1.2.5", "assets": |{"bootloader": {"image": |{"name": "w1a-proto-0-loader-dev.signed.bin"}, |"application_a": |{"image": {"name": "w1a-proto-0-app-a-dev.signed.bin"}, |"application_b": {"image": {"name": "w1a-proto-0-app-b-dev.signed.bin"}, |"parameters": {"wca_chunk_size": 452, "signature_offset": 647104, |"app_properties_offset": 1024}}} """.trimMargin() val goodDeltaJson = """{"manifest_version": "0.0.1", |"fwup_bundle": {"product": "w1a", |"from_version": "1.0.16", |"to_version": "1.0.30", "assets": |{"a2b_patch": {"image": |{"name": "w1a-dvt-a-to-b.signed.patch"}, |"signature": |{"name": "w1a-dvt-app-b-dev.detached_signature"}}, |"b2a_patch": |{"image": {"name": "w1a-dvt-b-to-a.signed.patch"}, |"signature": {"name": "w1a-dvt-app-a-dev.detached_signature"}}}, |"parameters": {"wca_chunk_size": 452, "signature_offset": 647104, |"app_properties_offset": 1024}}} """.trimMargin() test("Update from A slot to B slot") { val result = fwup.parseFwupManifest(goodJson, "0.0.0", A, FwupMode.Normal) result.shouldBe( Ok( ParseFwupManifestSuccess( firmwareVersion = "1.2.5", binaryFilename = "w1a-proto-0-app-b-dev.signed.bin", signatureFilename = "w1a-proto-0-app-b-dev.detached_signature", chunkSize = 452U, signatureOffset = 647104U, appPropertiesOffset = 1024U ) ) ) } // [W-1438] Re-enable. // test("No new update available") { // val result = fwup.parseFwupManifest(goodJson, "1.2.5", A) // result.shouldBe(Err(NO_UPDATE_NEEDED)) // } test("Unknown manifest version") { val result = fwup.parseFwupManifest(wrongManifestVersionJson, "1.2.5", A, FwupMode.Normal) result.shouldBe(Err(UnknownManifestVersion)) } test("Missing signature files") { val result = fwup.parseFwupManifest(missingSignatureFilesJson, "1.2.5", A, FwupMode.Normal) result.shouldBeErrOfType<ParsingError>() } test("Delta A to B") { val result = fwup.parseFwupManifest(goodDeltaJson, "1.0.1", A, FwupMode.Delta) result.shouldBe( Ok( ParseFwupManifestSuccess( firmwareVersion = "1.0.30", binaryFilename = "w1a-dvt-a-to-b.signed.patch", signatureFilename = "w1a-dvt-app-b-dev.detached_signature", chunkSize = 452U, signatureOffset = 647104U, appPropertiesOffset = 1024U ) ) ) } test("Delta B to A") { val result = fwup.parseFwupManifest(goodDeltaJson, "1.0.1", B, FwupMode.Delta) result.shouldBe( Ok( ParseFwupManifestSuccess( firmwareVersion = "1.0.30", binaryFilename = "w1a-dvt-b-to-a.signed.patch", signatureFilename = "w1a-dvt-app-a-dev.detached_signature", chunkSize = 452U, signatureOffset = 647104U, appPropertiesOffset = 1024U ) ) ) } test("Parsing normal manifest when trying to delta fwup") { val result = fwup.parseFwupManifest(goodJson, "1.0.1", A, FwupMode.Delta) result.shouldBeErrOfType<ParsingError>() } test("Semver to int conversion") { semverToInt("1.2.5") shouldBe 102005 semverToInt("1.0.65") shouldBe 100065 semverToInt("1.0.0") shouldBe 100000 semverToInt("9.09.999") shouldBe 909999 semverToInt("1.1.2") shouldBeLessThan semverToInt("1.1.3") semverToInt("1.0.999") shouldBeLessThan semverToInt("1.1.0") semverToInt("1.9.9") shouldBeLessThan semverToInt("1.10.0") semverToInt("0.0.1") shouldBe "0000001".toInt() semverToInt("0.0.0") shouldBe "0000000".toInt() semverToInt("0.99.0") shouldBe "0099000".toInt() semverToInt("99.0.0") shouldBe "9900000".toInt() semverToInt("0.1.0") shouldBe "0001000".toInt() semverToInt("1.10.1") shouldBeLessThan semverToInt("1.11.0") semverToInt("1.2.10") shouldBeLessThan semverToInt("1.2.11") semverToInt("10.0.0") shouldBeGreaterThan semverToInt("9.99.999") } })
3
C
16
113
694c152387c1fdb2b6be01ba35e0a9c092a81879
6,711
bitkey
MIT License
subprojects/assemble/proguard-guard/src/main/kotlin/com/avito/android/proguard_guard/shadowr8/R8TaskPrinter.kt
avito-tech
230,265,582
false
null
package com.avito.android.proguard_guard.shadowr8 import com.android.build.gradle.internal.tasks.R8Task import com.avito.logger.GradleLoggerPlugin internal fun R8Task.print() { val logger = GradleLoggerPlugin.getLoggerFactory(this).create("R8TaskPrinter") with(logger) { info("enableDesugaring: ${enableDesugaring.orNull}") info("multiDexKeepFile: ${multiDexKeepFile.orNull}") info("multiDexKeepProguard: ${multiDexKeepProguard.orNull}") info("mainDexRulesFiles: ${mainDexRulesFiles.joinToString()}") info("bootClasspath: ${bootClasspath.joinToString()}") info("errorFormatMode: ${errorFormatMode.orNull}") info("minSdkVersion: ${minSdkVersion.orNull}") info("debuggable: ${debuggable.orNull}") info("disableTreeShaking: ${disableTreeShaking.orNull}") info("duplicateClassesCheck: ${duplicateClassesCheck.joinToString()}") info("disableMinification: ${disableMinification.orNull}") info("proguardConfigurations: ${proguardConfigurations.joinToString()}") info("useFullR8: ${useFullR8.orNull}") // info("dexingType: $dexingType") info("featureClassJars: ${featureClassJars.joinToString()}") info("featureJavaResourceJars: ${featureJavaResourceJars.joinToString()}") info("baseJar: ${baseJar.orNull}") info("coreLibDesugarConfig: ${coreLibDesugarConfig.orNull}") info("outputClasses: ${outputClasses.orNull}") info("outputDex: ${outputDex.orNull}") // info("projectOutputKeepRules: ${projectOutputKeepRules.orNull}") info("baseDexDir: ${baseDexDir.orNull}") info("featureDexDir: ${featureDexDir.orNull}") info("featureJavaResourceOutputDir: ${featureJavaResourceOutputDir.orNull}") info("outputResources: ${outputResources.orNull}") info("Start ProguardConfigurableTask") info("variantName: $variantName") info("includeFeaturesInScopes: ${includeFeaturesInScopes.orNull}") info("testedMappingFile: ${testedMappingFile.joinToString()}") info("classes: ${classes.joinToString()}") // info("resources: ${resources.joinToString()}") info("referencedClasses: ${referencedClasses.joinToString()}") info("referencedResources: ${referencedResources.joinToString()}") info("extractedDefaultProguardFile: ${extractedDefaultProguardFile.orNull}") info("configurationFiles: ${configurationFiles.joinToString()}") info("mappingFile: ${mappingFile.orNull}") } }
8
null
50
414
4dc43d73134301c36793e49289305768e68e645b
2,546
avito-android
MIT License
mobile/src/main/java/com/cm/media/entity/vod/parse/ResolvedVod.kt
zhangwenxue
157,227,854
false
{"Java": 1368464, "Kotlin": 17634}
package com.cm.media.entity.vod.parse data class ResolvedVod(var streams: List<ResolvedStream>?, var lang: String?)
0
Java
1
2
bf6facc4047e52af024d75e06cea4fd432d1dc4d
116
CMMedia
Apache License 2.0
src/test/kotlin/NecklaceMatchingTests.kt
Botbusters4635
247,878,247
false
null
import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertEquals @DisplayName("Necklace Matching Tests") class NecklaceMatchingTests { @Test fun `Test areSameNecklace with 10 inputs`() { assertTrue(areSameNecklace("helloworld", "loworldhel")) assertTrue(areSameNecklace("abcabcabc", "bcabcabca")) assertTrue(areSameNecklace("botbusters", "bustersbot")) assertTrue(areSameNecklace("xyzabc", "bcxyza")) assertTrue(areSameNecklace("", "")) assertFalse(areSameNecklace("a", "b")) assertFalse(areSameNecklace("amarinthine", "blueberry")) assertFalse(areSameNecklace("aaaaaa", "aaaa")) assertFalse(areSameNecklace("xyxy", "yxyy")) assertFalse(areSameNecklace("first", "irst")) } @Test fun `Test repeats with 10 inputs`() { assertEquals(1, repeats("abcded")) assertEquals(1, repeats("botbusters")) assertEquals(6, repeats("aaaaaa")) assertEquals(3, repeats("xyzxyzxyz")) assertEquals(1, repeats("abcxyzabc")) assertEquals(1, repeats("abcabcxyz")) assertEquals(1, repeats("helloworld")) assertEquals(1, repeats("roguelike")) assertEquals(1, repeats("")) assertEquals(1, repeats("a")) assertEquals(1, repeats("abc")) } }
0
Kotlin
0
0
cb35ad3ba2779cc12f8a642029c6631c328a0623
1,472
Botbusters-Tutorial-World
MIT License
app/src/main/java/com/o2/glucomate/ui/home/HomeViewModel.kt
yasiralijaved
680,929,799
false
null
package com.o2.glucomate.ui.home import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.o2.glucomate.db.AppDatabase import com.o2.glucomate.db.tables.GlucoseEntry import com.o2.glucomate.repository.GlucoseEntryRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class HomeViewModel (application: Application) : AndroidViewModel(application = application) { private val repository: GlucoseEntryRepository // Backing property to avoid state updates from other classes private val _glucoseEntries = MutableStateFlow<List<GlucoseEntry>>(emptyList()) // The UI collects from this StateFlow to get its state updates val glucoseEntries: StateFlow<List<GlucoseEntry>> = _glucoseEntries init { val dao = AppDatabase.getDatabase(application).glucoseEntryDao() repository = GlucoseEntryRepository(dao) viewModelScope.launch { repository.getAll().collect { entries -> _glucoseEntries.value = entries } } } fun addGlucoseEntry(entry: GlucoseEntry) { viewModelScope.launch (Dispatchers.IO) { repository.insert(glucoseEntry = entry) } } fun deleteGlucoseEntry(entry: GlucoseEntry) { viewModelScope.launch (Dispatchers.IO) { repository.delete(glucoseEntry = entry) } } }
0
Kotlin
0
0
fe6f34b6b4b010fe931209140e1c7b48ee9e679f
1,523
GlucoMate
Apache License 2.0
src/main/kotlin/io/slama/core/commands.kt
SlamaFR
374,733,122
false
{"Kotlin": 101736}
package io.slama.core import io.slama.utils.command import io.slama.utils.integer import io.slama.utils.invoke import io.slama.utils.option import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.interactions.commands.Command import net.dv8tion.jda.api.interactions.commands.OptionType fun JDA.registerGlobalCommands() { this { command("eval", "Évaluer une expression mathématique.") { option(OptionType.STRING, name = "expression", "Expression à évaluer.") } command("call", "Lancer un appel dans le salon courant.") { option(OptionType.INTEGER, name = "timeout", "Temps imparti pour répondre à l'appel en minutes.") option(OptionType.ROLE, name = "role", "Groupe d'étudiants visé.") } command("poll", "Lancer un sondage dans le salon courant.") { option(OptionType.STRING, name = "question", "Question sur laquelle porte le sondage.", required = true) option( OptionType.BOOLEAN, name = "log", "Sauvegarde un fichier log du résultat du sondage. (Défaut = false)" ) option( OptionType.INTEGER, name = "timeout", "Temps imparti pour répondre au sondage en minutes. (Défaut = 2 minutes)" ) option(OptionType.STRING, name = "a", "Première réponse possible.") option(OptionType.STRING, name = "b", "Seconde réponse possible.") option(OptionType.STRING, name = "c", "Troisième réponse possible.") option(OptionType.STRING, name = "d", "Quatrième réponse possible.") } command("changen", "Lier un salon à un générateur de salons temporaires.") { option(OptionType.CHANNEL, name = "channel", "Salon qui servira de point de départ.", required = true) } command("table", "Générer un tableau en caractères ASCII.") { option(OptionType.STRING, name = "content", "Contenu du tableau. Laisser vide pour obtenir un example.") } command("pfc", "Lancer une partie de Pierre, Feuille, Ciseaux.") { option(OptionType.USER, name = "opponent", "Joueur contre lequel jouer.", required = true) integer(name = "rounds", "Nombre de manches à jouer. Les nombres pairs seront arrondis à l'impair supérieur. (Défaut = 1)", minValue = 1, maxValue = 5) } command("stats", "Afficher vos statistiques ou celles d'un autre utilisateur au Pierre Feuille Ciseaux.") { option(OptionType.USER, name = "player", "Utilisateur duquel afficher les statistiques.") } } } fun Guild.registerGuildCommands() { this { command("autorole", "Créer un attributeur automatique de rôle.") { option(OptionType.STRING, name = "name", "Nom de l'attributeur.") { BotConfiguration.guilds[this@registerGuildCommands.idLong]?.let { it.autoRoles.keys.map { name -> Command.Choice(name, name) } } ?: listOf() } } } }
3
Kotlin
1
3
d63cae8003eb2173015930920d54bb49a6c3fc80
3,169
UGE-Bot
MIT License
codegen/smithy-aws-swift-codegen/src/test/kotlin/software/amazon/smithy/aws/swift/codegen/customizations/FlexibleChecksumMiddlewareTests.kt
awslabs
278,475,105
false
null
package software.amazon.smithy.aws.swift.codegen.customizations import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.aws.swift.codegen.TestContext import software.amazon.smithy.aws.swift.codegen.TestUtils import software.amazon.smithy.aws.swift.codegen.restjson.AWSRestJson1ProtocolGenerator import software.amazon.smithy.aws.swift.codegen.shouldSyntacticSanityCheck import software.amazon.smithy.aws.traits.protocols.RestJson1Trait class FlexibleChecksumMiddlewareTests { @Test fun `Test that FlexibleChecksumsRequestMiddleware and FlexibleChecksumsResponseMiddleware are properly generated`() { val context = setupTests("flexible-checksums.smithy", "aws.flex.checks#ChecksumTests") val contents = TestUtils.getFileContents(context.manifest, "/Example/ChecksumTestsClient.swift") contents.shouldSyntacticSanityCheck() val expectedContents = """ extension ChecksumTestsClient { /// Performs the `SomeOperation` operation on the `ChecksumTests` service. /// /// /// - Parameter SomeOperationInput : [no documentation found] /// /// - Returns: `SomeOperationOutput` : [no documentation found] public func someOperation(input: SomeOperationInput) async throws -> SomeOperationOutput { let context = ClientRuntime.HttpContextBuilder() .withEncoder(value: encoder) .withDecoder(value: decoder) .withMethod(value: .post) .withServiceName(value: serviceName) .withOperation(value: "someOperation") .withIdempotencyTokenGenerator(value: config.idempotencyTokenGenerator) .withLogger(value: config.logger) .withPartitionID(value: config.partitionID) .withAuthSchemes(value: config.authSchemes ?? []) .withAuthSchemeResolver(value: config.authSchemeResolver) .withUnsignedPayloadTrait(value: false) .withIdentityResolver(value: config.awsCredentialIdentityResolver, schemeID: "aws.auth#sigv4") .withIdentityResolver(value: config.awsCredentialIdentityResolver, schemeID: "aws.auth#sigv4a") .withRegion(value: config.region) .build() var operation = ClientRuntime.OperationStack<SomeOperationInput, SomeOperationOutput>(id: "someOperation") operation.initializeStep.intercept(position: .after, middleware: ClientRuntime.URLPathMiddleware<SomeOperationInput, SomeOperationOutput>(SomeOperationInput.urlPathProvider(_:))) operation.initializeStep.intercept(position: .after, middleware: ClientRuntime.URLHostMiddleware<SomeOperationInput, SomeOperationOutput>()) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.ContentMD5Middleware<SomeOperationOutput>()) let endpointParams = EndpointParams() operation.buildStep.intercept(position: .before, middleware: EndpointResolverMiddleware<SomeOperationOutput>(endpointResolver: config.endpointResolver, endpointParams: endpointParams)) operation.buildStep.intercept(position: .before, middleware: AWSClientRuntime.UserAgentMiddleware(metadata: AWSClientRuntime.AWSUserAgentMetadata.fromConfig(serviceID: serviceName, version: "1.0.0", config: config))) operation.buildStep.intercept(position: .before, middleware: ClientRuntime.AuthSchemeMiddleware<SomeOperationOutput>()) operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.HeaderMiddleware<SomeOperationInput, SomeOperationOutput>(SomeOperationInput.headerProvider(_:))) operation.serializeStep.intercept(position: .after, middleware: ContentTypeMiddleware<SomeOperationInput, SomeOperationOutput>(contentType: "application/octet-stream")) operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.BlobBodyMiddleware<SomeOperationInput, SomeOperationOutput>(keyPath: \.content)) operation.serializeStep.intercept(position: .after, middleware: ClientRuntime.FlexibleChecksumsRequestMiddleware<SomeOperationInput, SomeOperationOutput>(checksumAlgorithm: input.checksumAlgorithm?.rawValue)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.ContentLengthMiddleware()) operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware<ClientRuntime.DefaultRetryStrategy, AWSClientRuntime.AWSRetryErrorInfoProvider, SomeOperationOutput>(options: config.retryStrategyOptions)) operation.finalizeStep.intercept(position: .before, middleware: ClientRuntime.SignerMiddleware<SomeOperationOutput>()) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.DeserializeMiddleware<SomeOperationOutput>(responseClosure(decoder: decoder), responseErrorClosure(SomeOperationOutputError.self, decoder: decoder))) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.LoggerMiddleware<SomeOperationOutput>(clientLogMode: config.clientLogMode)) operation.deserializeStep.intercept(position: .after, middleware: ClientRuntime.FlexibleChecksumsResponseMiddleware<SomeOperationOutput>(validationMode: true)) let result = try await operation.handleMiddleware(context: context, input: input, next: client.getHandler()) return result } } """.trimIndent() contents.shouldContainOnlyOnce(expectedContents) } private fun setupTests(smithyFile: String, serviceShapeId: String): TestContext { val context = TestUtils.executeDirectedCodegen(smithyFile, serviceShapeId, RestJson1Trait.ID) val generator = AWSRestJson1ProtocolGenerator() generator.generateProtocolUnitTests(context.ctx) context.ctx.delegator.flushWriters() return context } }
204
null
69
349
a918bcfe1d739c4e9df1546ca27dc3b4874eb033
5,992
aws-sdk-swift
Apache License 2.0
src/main/kotlin/main.kt
dron4ik89
421,977,175
false
{"Kotlin": 9852}
fun main(args: Array<String>) { val longest = "900080003010030080300706002703000208001205900609000704200807001070020060500040007" println("Custom data:") println(longest) val start = System.currentTimeMillis() try { val board = Board(longest) val solver = Solver() val solved = solver.solve(board) println("Solved data:") println(solved) } catch (e: ExceptionInvalidBoard) { println("invalid input") } catch (e: Exception) { println("invalid grid") } println("Time: ${(System.currentTimeMillis() - start)} millis") }
0
Kotlin
1
1
252269cfd42df2ae311c491a7c3a2ecedc4e68fc
620
Kotlin-Sudoku-Solver
Apache License 2.0
src/main/kotlin/net/aruneko/chaindigger/ChainDigger.kt
aruneko
404,251,353
false
null
package net.aruneko.chaindigger import net.aruneko.chaindigger.listeners.ChainDiggerListener import org.bukkit.plugin.java.JavaPlugin class ChainDigger : JavaPlugin() { override fun onEnable() { val config = this.config val defaultRange = 5 config.addDefault("range", defaultRange) config.options().copyDefaults(true) saveConfig() val range = config.getInt("range", defaultRange) server.pluginManager.registerEvents(ChainDiggerListener(this, server, range), this) } override fun onDisable() {} }
0
Kotlin
0
0
6138f8a25622b7e333c153d14f3be75dbc621438
570
ChainDigger
MIT License
src/main/kotlin/dev/ocpd/jsensible/rules/java/Java11Rules.kt
ocpddev
587,719,778
false
null
package dev.ocpd.jsensible.rules.java import com.tngtech.archunit.lang.ArchRule import com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses import java.net.URI import java.nio.file.Path import java.nio.file.Paths import java.util.* /** * Contains rules that are applicable to Java 11 and later. */ object Java11Rules { fun all() = listOf( noOptionalGet(), noPathsGet() ) /** * The [Optional.get] method is deprecated by JDK: * * > The preferred alternative to this method is [Optional.orElseThrow]. * * Solution: Replace [Optional.get] with [Optional.orElseThrow]. */ fun noOptionalGet(): ArchRule = noClasses().should().callMethod(Optional::class.java, "get") .because("JDK recommends [Optional.orElseThrow] as the preferred alternative") /** * The [Paths.get] method is deprecated by JDK: * * > It is recommended to obtain a [Path] via the [Path.of] methods instead * of via the [Paths.get] methods defined in this class as this class may * be deprecated in a future release. * * Solution: Replace [Paths.get] with [Path.of]. */ fun noPathsGet(): ArchRule = noClasses() .should().callMethod(Paths::class.java, "get", String::class.java, Array<String>::class.java) .orShould().callMethod(Paths::class.java, "get", URI::class.java) .because("JDK recommends to obtain a [Path] via the [Path.of] methods instead") }
7
Kotlin
1
1
1f65208df3dad383821b243ad4a0fa3bc466e957
1,504
jsensible
Apache License 2.0
app/src/main/java/com/faskn/app/weatherapp/repo/SearchCitiesRepository.kt
furkanaskin
215,724,494
false
null
package com.rahul.app.weatherapp.repo import NetworkBoundResource import androidx.lifecycle.LiveData import com.rahul.app.weatherapp.core.Constants.NetworkService.RATE_LIMITER_TYPE import com.rahul.app.weatherapp.db.entity.CitiesForSearchEntity import com.rahul.app.weatherapp.domain.datasource.searchCities.SearchCitiesLocalDataSource import com.rahul.app.weatherapp.domain.datasource.searchCities.SearchCitiesRemoteDataSource import com.rahul.app.weatherapp.domain.model.SearchResponse import com.rahul.app.weatherapp.utils.domain.RateLimiter import com.rahul.app.weatherapp.utils.domain.Resource import io.reactivex.Single import java.util.concurrent.TimeUnit import javax.inject.Inject /** * Created by Furkan on 2019-10-31 */ class SearchCitiesRepository @Inject constructor( private val searchCitiesLocalDataSource: SearchCitiesLocalDataSource, private val searchCitiesRemoteDataSource: SearchCitiesRemoteDataSource ) { private val rateLimiter = RateLimiter<String>(1, TimeUnit.SECONDS) fun loadCitiesByCityName(cityName: String?): LiveData<Resource<List<CitiesForSearchEntity>>> { return object : NetworkBoundResource<List<CitiesForSearchEntity>, SearchResponse>() { override fun saveCallResult(item: SearchResponse) = searchCitiesLocalDataSource.insertCities(item) override fun shouldFetch(data: List<CitiesForSearchEntity>?): Boolean { return data == null || data.isEmpty() } override fun loadFromDb(): LiveData<List<CitiesForSearchEntity>> = searchCitiesLocalDataSource.getCityByName(cityName) override fun createCall(): Single<SearchResponse> = searchCitiesRemoteDataSource.getCityWithQuery( cityName ?: "" ) override fun onFetchFailed() = rateLimiter.reset(RATE_LIMITER_TYPE) }.asLiveData } }
2
null
117
560
18e891729d5e792073cd4934e5b5416d12bddca7
1,888
Weatherapp
MIT License
app/src/main/java/com/remonh87/comfortfood/MainActivity.kt
remonh87
256,946,600
false
null
package com.remonh87.comfortfood import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import io.flutter.embedding.android.FlutterActivity import io.flutter.plugin.common.MethodChannel class MainActivity : AppCompatActivity() { private val order = Order() private val viewModel: OrderViewModel by viewModels { OrderViewModelFactory(order) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val app = applicationContext as ComfortFoodApplication MethodChannel( app.flutterEngine.dartExecutor.binaryMessenger, "comfortfoodChannel" ).setMethodCallHandler(OrderMethodCallHandler(viewModel::addToOrder)) val fragment = LaunchScreenFragment() supportFragmentManager.beginTransaction().add(R.id.main_fragment_container, fragment) .commit() } }
2
Kotlin
0
0
2a2fa6175600129d6dc5693acbd1476e8c4471eb
1,045
comfortfood
MIT License
modules/rest-service/src/main/kotlin/org/veupathdb/service/vdi/service/datasets/list-datasets.kt
VEuPathDB
575,990,672
false
null
package org.veupathdb.service.vdi.service.datasets import org.veupathdb.service.vdi.db.AccountDB import org.veupathdb.service.vdi.generated.model.* import org.veupathdb.service.vdi.model.UserDetails import org.veupathdb.vdi.lib.common.field.DatasetID import org.veupathdb.vdi.lib.common.field.ProjectID import org.veupathdb.vdi.lib.common.field.UserID import org.veupathdb.vdi.lib.db.app.AppDB import org.veupathdb.vdi.lib.db.app.model.InstallStatuses import org.veupathdb.vdi.lib.db.cache.CacheDB import org.veupathdb.vdi.lib.db.cache.model.DatasetListQuery import org.veupathdb.vdi.lib.db.cache.model.DatasetRecord import org.veupathdb.vdi.lib.handler.mapping.PluginHandler import org.veupathdb.vdi.lib.handler.mapping.PluginHandlers fun fetchUserDatasetList(query: DatasetListQuery): List<DatasetListEntry> { return fetchDatasetList(CacheDB.selectDatasetList(query)) } fun fetchCommunityUserDatasetList(): List<DatasetListEntry> { return fetchDatasetList(CacheDB.selectNonPrivateDatasets()) } private fun fetchDatasetList(datasetList: List<DatasetRecord>): List<DatasetListEntry> { // build a set for collecting user IDs to use when querying for user details val userIDs = HashSet<UserID>(datasetList.size) // build a map for collecting project ID -> dataset ID collection mappings // to use when querying for dataset status info. val projectToDatasetID = HashMap<String, MutableSet<DatasetID>>(12) // for each dataset the original search returned datasetList.forEach { ds -> // add the owner id to the set of user ids userIDs.add(ds.ownerID) // for each project the dataset is associated with ds.projects.forEach { project -> // add an entry into the projectToDatasetID map for the combination of // project id and dataset id projectToDatasetID.computeIfAbsent(project) { HashSet(1) } .add(ds.datasetID) } } // Get the statuses for each installation by project ID and dataset ID // // The returned map will be indexed on dataset ID and will contain values that // are themselves maps of project ID to installation status details for that // dataset/project id combination val datasetInstallStatusMap = AppDB.getDatasetStatuses(projectToDatasetID) projectToDatasetID.clear() // Get the user details for all the distinct user IDs seen in the dataset // listing returned by the original query. val userDetails = AccountDB.lookupUserDetails(userIDs) userIDs.clear() // Build a list for the results we will be returning. val results = ArrayList<DatasetListEntry>(datasetList.size) // For each dataset we found with the original query. datasetList.forEach { // Convert the found dataset into the expected output type // (DatasetListEntry) and add it to the result list. results.add(it.toListEntry( userDetails[it.ownerID] ?: throw IllegalStateException("missing user details for user id ${it.ownerID}"), PluginHandlers[it.typeName, it.typeVersion]?.displayName ?: throw IllegalStateException("missing plugin ${it.typeName}:${it.typeVersion}"), datasetInstallStatusMap[it.datasetID] ?: emptyMap() )) } return results } private fun DatasetRecord.toListEntry( owner: UserDetails, pluginDisplayName: String, statuses: Map<ProjectID, InstallStatuses> ) = DatasetListEntryImpl().also { out -> out.datasetID = datasetID.toString() out.owner = DatasetOwner(owner) out.datasetType = DatasetTypeInfo(this, pluginDisplayName) out.name = name out.summary = summary out.description = description out.projectIDs = projects.toList() out.visibility = DatasetVisibility(visibility) out.status = DatasetStatusInfo(importStatus, statuses) out.origin = origin out.sourceUrl = sourceURL }
9
Kotlin
0
0
f16c152c5523fc906efd14e2efb5e956863efd3a
3,775
vdi-service
Apache License 2.0
compiler/testData/cli/jvm/noReflect.kt
JakeWharton
99,388,807
true
null
import kotlin.reflect.* fun foo() { String::class.primaryConstructor listOf(42) }
179
Kotlin
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
91
kotlin
Apache License 2.0
lamblin-local-runner/src/main/kotlin/com/lamblin/local/runner/LamblinDelegator.kt
BorislavShekerov
148,893,257
false
null
/* * Lamblin * Copyright 2018 Borislav Shekerov * Licensed under Apache 2.0: https://github.com/BorislavShekerov/lamblin/blob/master/LICENSE */ package com.lamblin.local.runner import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent import com.fasterxml.jackson.databind.ObjectMapper import com.lamblin.core.Lamblin import com.lamblin.core.model.StatusCode import io.javalin.Context import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream internal val OBJECT_MAPPER = ObjectMapper() private val LOGGER = LoggerFactory.getLogger(LamblinDelegator::class.java) class LamblinDelegator( internal val lamblin: Lamblin, private val objectMapper: ObjectMapper = OBJECT_MAPPER) { internal fun delegateToController(context: Context) { val requestEvent = createRequestEvent(context) val responseOutputStream = ByteArrayOutputStream() try { lamblin.handlerRequest( ByteArrayInputStream(objectMapper.writeValueAsBytes(requestEvent)), responseOutputStream) val response = objectMapper.readValue( String(responseOutputStream.toByteArray()), APIGatewayProxyResponseEvent::class.java) context.status(response.statusCode) response?.headers?.forEach { context.header(it.key, it.value) } response.body?.let { context.result(it) } } catch (e: RuntimeException) { LOGGER.error("Error occurred while handling request", e) context.status(StatusCode.API_ERROR.code) } } private fun createRequestEvent(context: Context) = APIGatewayProxyRequestEvent().apply { httpMethod = context.method() path = context.path() queryStringParameters = context.queryParamMap().mapValues { it.value[0] } body = context.body() headers = context.headerMap() } }
1
Kotlin
1
5
3746fabcba23fdea63e232650e1d2e4f2f9462e5
2,035
lamblin
Apache License 2.0
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/OmSolid.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.lineawesomeicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.LineAwesomeIcons public val LineAwesomeIcons.OmSolid: ImageVector get() { if (_omSolid != null) { return _omSolid!! } _omSolid = Builder(name = "OmSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(29.0f, 19.1211f) curveTo(29.0f, 21.207f, 28.1563f, 26.5742f, 23.5898f, 26.5742f) curveTo(19.2383f, 26.5742f, 17.6523f, 22.7305f, 17.9531f, 21.3398f) curveTo(18.2031f, 21.7656f, 18.9961f, 23.957f, 23.2773f, 23.957f) curveTo(27.668f, 23.957f, 27.7148f, 19.0781f, 27.7148f, 19.0781f) curveTo(27.7148f, 19.0781f, 27.6406f, 15.6172f, 24.9648f, 15.6172f) curveTo(21.6992f, 15.6172f, 21.5898f, 20.8086f, 18.3086f, 20.8086f) curveTo(16.6641f, 20.8086f, 16.1133f, 19.9375f, 15.7813f, 19.6992f) curveTo(16.4883f, 21.8945f, 15.6523f, 27.0f, 10.2773f, 27.0f) curveTo(2.6055f, 27.0f, 3.0039f, 18.7227f, 3.0039f, 18.7227f) curveTo(3.0039f, 18.7227f, 4.2891f, 23.8242f, 10.1445f, 23.8242f) curveTo(13.7148f, 23.8242f, 14.1836f, 21.7852f, 14.1836f, 20.8516f) curveTo(14.1836f, 19.9219f, 13.4727f, 18.2813f, 10.2773f, 18.2813f) lineTo(9.5781f, 14.9648f) curveTo(9.5781f, 14.9648f, 10.5234f, 15.2734f, 11.6914f, 15.2734f) curveTo(13.2305f, 15.2734f, 13.582f, 14.2461f, 13.582f, 13.4023f) curveTo(13.582f, 12.5625f, 12.7578f, 11.7109f, 11.25f, 11.7109f) curveTo(8.9141f, 11.7109f, 7.0391f, 14.1094f, 7.0391f, 14.1094f) lineTo(5.2227f, 10.7383f) curveTo(5.2227f, 10.7383f, 6.9102f, 8.5625f, 10.3281f, 8.5625f) curveTo(13.7422f, 8.5625f, 15.293f, 11.3594f, 15.293f, 13.0f) curveTo(15.293f, 14.6406f, 14.5273f, 16.0f, 13.0742f, 16.7695f) curveTo(15.0352f, 17.6914f, 14.4414f, 18.3672f, 15.6914f, 18.3672f) curveTo(17.7617f, 18.3672f, 18.043f, 16.6758f, 19.0156f, 15.1406f) curveTo(19.9141f, 13.7305f, 21.1914f, 12.4688f, 23.4531f, 12.4688f) curveTo(27.9805f, 12.4688f, 29.0f, 17.0391f, 29.0f, 19.1211f) close() moveTo(20.1719f, 11.9805f) curveTo(22.4727f, 11.9805f, 24.2539f, 10.6484f, 24.2539f, 10.6484f) lineTo(22.3438f, 7.2773f) curveTo(22.3438f, 7.2773f, 21.0156f, 9.1406f, 18.4414f, 9.1406f) curveTo(15.8672f, 9.1406f, 13.7383f, 6.7891f, 13.7383f, 6.7891f) curveTo(13.7383f, 6.7891f, 14.7148f, 11.9805f, 20.1719f, 11.9805f) close() moveTo(20.5273f, 6.6133f) lineTo(18.6172f, 4.5703f) lineTo(16.4883f, 6.4336f) lineTo(18.3984f, 8.6094f) close() } } .build() return _omSolid!! } private var _omSolid: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
3,862
compose-icons
MIT License
src/commonMain/kotlin/character/classes/warrior/talents/ImprovedMortalStrike.kt
marisa-ashkandi
332,658,265
false
null
package character.classes.warrior.talents import character.Talent class ImprovedMortalStrike(currentRank: Int) : Talent(currentRank) { companion object { const val name = "Improved Mortal Strike" } override val name: String = Companion.name override val maxRank: Int = 5 }
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
300
tbcsim
MIT License
src/commonMain/kotlin/character/classes/warrior/talents/ImprovedMortalStrike.kt
marisa-ashkandi
332,658,265
false
null
package character.classes.warrior.talents import character.Talent class ImprovedMortalStrike(currentRank: Int) : Talent(currentRank) { companion object { const val name = "Improved Mortal Strike" } override val name: String = Companion.name override val maxRank: Int = 5 }
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
300
tbcsim
MIT License
demo/src/main/java/com/sokarcreative/stepperview/MainActivity.kt
sokarcreative
124,039,121
false
{"Gradle": 4, "Java Properties": 4, "Shell": 1, "XML": 22, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 2, "Java": 2, "Kotlin": 4}
package com.sokarcreative.stepperview import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.text.Editable import android.text.InputFilter import android.text.Spanned import android.text.TextWatcher import android.widget.RadioGroup import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private val handler = Handler() private val runnableStepCountUpdate = Runnable { setupStepperView() } private fun setupStepperView(){ val stepCount = try{ editTextStepCount.text.toString().toIntOrNull() } catch (e: Exception){ null } if(stepCount != null){ stepperView.count = stepCount val titles = arrayListOf<CharSequence>() for (i in 0 until stepCount){ titles.add("Step ${i+1}") } stepperView.titles = titles.toTypedArray() stepperView.step(0) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupStepperView() stepperView.step(2) buttonPrevStep.setOnClickListener { if(stepperView.currentPosition-1 >= 0 && stepperView.currentPosition-1 < stepperView.count) stepperView.step(stepperView.currentPosition-1) } buttonNextStep.setOnClickListener { if(stepperView.currentPosition+1 < stepperView.count && stepperView.currentPosition+1 >= 0) stepperView.step(stepperView.currentPosition+1) } editTextStepCount.filters = arrayOf(InputFilterMinMax(0, 10)) editTextStepCount.addTextChangedListener(object : TextWatcher{ override fun afterTextChanged(s: Editable?) { handler.removeCallbacks(runnableStepCountUpdate) handler.postDelayed(runnableStepCountUpdate, 200) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) radioGroupTitles.setOnCheckedChangeListener(({ radioGroup: RadioGroup, _: Int -> stepperView.showTitles = when(radioGroup.checkedRadioButtonId){ R.id.radioButtonHideTitles -> StepperView.HIDE_TITLES R.id.radioButtonShowCurrentTitles -> StepperView.SHOW_CURRENT_TITLE R.id.radioButtonShowAllTitles -> StepperView.SHOW_ALL_TITLES else -> StepperView.HIDE_TITLES } stepperView.step(stepperView.currentPosition) })) radioButtonShowCurrentTitles.isChecked = true } inner class InputFilterMinMax(val min: Int = 0, val max: Int = 0) : InputFilter { override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { try { val input = Integer.parseInt(dest.toString() + source.toString()) if (isInRange(min, max, input)) return null } catch (nfe: NumberFormatException) { } return "" } private fun isInRange(a: Int, b: Int, c: Int): Boolean { return if (b > a) c >= a && c <= b else c >= b && c <= a } } }
0
Kotlin
0
1
32019cf7b8f31a648c56dc56f445b7aa8a95f4e9
3,384
StepperView
Apache License 2.0
src/en/suryascans/src/eu/kanade/tachiyomi/extension/en/suryascans/SuryaScans.kt
komikku-app
720,497,299
false
{"Kotlin": 6409055, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.en.suryascans import eu.kanade.tachiyomi.multisrc.mangathemesia.MangaThemesia class SuryaScans : MangaThemesia("Surya Scans", "https://suryatoon.com", "en")
8
Kotlin
2
19
88bafd3e5fb05cd4690fc46e4a7d624a2595e7f3
197
komikku-extensions
Apache License 2.0
appcenter/src/main/java/com/example/appcenter/utilities/DaoDataHelper.kt
vickypathak123
381,272,556
false
null
package com.example.appcenter.utilities import android.content.Context import com.example.appcenter.retrofit.model.ModelAppCenter import com.example.jdrodi.utilities.SPUtil import com.google.gson.Gson import com.google.gson.reflect.TypeToken /** * DaoDataHelper.kt - Store model data helper. * @author: <NAME> * @date: 24-Jan-2021 12:12 PM */ private const val KEY_APP_CENTER = "key_app_center" // [START Save & Get App center data] fun Context.saveAppCenter(appCenterData: String) { SPUtil(this).save(KEY_APP_CENTER, appCenterData) } fun Context.saveAppCenterModel(modelAppCenter: ModelAppCenter) { val modelString = Gson().toJson(modelAppCenter) SPUtil(this).save(KEY_APP_CENTER, modelString) } fun Context.getAppCenter(): ModelAppCenter? { val jsonString = SPUtil(this).getString(KEY_APP_CENTER, "") return if (jsonString.isNullOrEmpty() || jsonString.isNullOrBlank()) { null } else { val itemType = object : TypeToken<ModelAppCenter>() {}.type Gson().fromJson<ModelAppCenter>(jsonString, itemType) } } // [END Save & Get App center data]
1
null
1
2
73f9feea0fa77c9df2e6275eec837ae15e07f2be
1,108
VasundharaCommonCode
MIT License
kotlinpoet-ktx/tests/src/com/hendraanggrian/kotlinpoet/collections/TypeNameMapTest.kt
hendraanggrian
209,613,746
false
null
package com.hendraanggrian.kotlinpoet.collections import com.google.common.truth.Truth.assertThat import com.squareup.kotlinpoet.CHAR import com.squareup.kotlinpoet.asTypeName import kotlin.test.Test class TypeNameMapTest { private val map = TypeNameMap(mutableMapOf()) @Test fun test() { map[CHAR] = null map[Double::class.java] = null map[Boolean::class] = null map.put<String>() assertThat(map.keys).containsExactly( CHAR, Double::class.java.asTypeName(), Boolean::class.asTypeName(), String::class.asTypeName() ) } }
1
Kotlin
0
3
9c7ec6bf017caf34bd20ff4853eb851c791e87af
636
kotlinpoet-ktx
Apache License 2.0
TheMovieDBDagger_v3_Animation/app/src/main/java/com/androidavanzado/popcorn/api/response/Person.kt
miguelcamposedu
261,391,292
false
null
package com.androidavanzado.popcorn.api.response data class Person( val adult: Boolean, val gender: Int, val id: Int, val known_for: List<KnownFor>, val known_for_department: String, val name: String, val popularity: Double, val profile_path: String )
0
Kotlin
0
0
919c6738203d900c9c96b16f32ba66e915ec266b
284
kotlinintroduccion
MIT License
app/src/main/java/com/a10miaomiao/bilimiao/commponents/comment/VideoCommentView.kt
10miaomiao
142,169,120
false
null
package com.a10miaomiao.bilimiao.commponents.comment import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.os.Parcelable import android.text.Spannable import android.view.Gravity import android.view.View import android.widget.ImageView import androidx.core.view.marginBottom import bilibili.main.community.reply.v1.ReplyOuterClass import cn.a10miaomiao.miao.binding.android.view._show import cn.a10miaomiao.miao.binding.android.view._tag import cn.a10miaomiao.miao.binding.android.widget._text import cn.a10miaomiao.miao.binding.miaoEffect import com.a10miaomiao.bilimiao.R import com.a10miaomiao.bilimiao.comm.MiaoUI import com.a10miaomiao.bilimiao.comm._network import com.a10miaomiao.bilimiao.comm.entity.video.VideoCommentReplyInfo import com.a10miaomiao.bilimiao.comm.utils.BiliUrlMatcher import com.a10miaomiao.bilimiao.comm.utils.DebugMiao import com.a10miaomiao.bilimiao.comm.utils.NumberUtil import com.a10miaomiao.bilimiao.comm.views import com.a10miaomiao.bilimiao.config.config import com.a10miaomiao.bilimiao.widget._setContent import com.a10miaomiao.bilimiao.widget.expandableTextView import com.a10miaomiao.bilimiao.widget.expandabletext.ExpandableTextView import com.a10miaomiao.bilimiao.widget.expandabletext.UrlImageSpan import com.a10miaomiao.bilimiao.widget.expandabletext.app.LinkType import com.a10miaomiao.bilimiao.widget.gridimage.GlideNineGridImageLoader import com.a10miaomiao.bilimiao.widget.gridimage.OnImageItemClickListener import com.a10miaomiao.bilimiao.widget.nineGridImageView import com.a10miaomiao.bilimiao.widget.rcImageView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import kotlinx.android.parcel.Parcelize import splitties.dimensions.dip import splitties.views.dsl.core.* import splitties.views.padding @Parcelize data class VideoCommentViewContent( // val device: String, val message: String, val emote: List<Emote>?, val picturesList: List<String>, ) : Parcelable { @Parcelize data class Emote( val id: Long, val text: String, val url: String ) : Parcelable @Parcelize data class Picture( val src: String, val width: Int, val height: Int, val size: Int, ) : Parcelable } private fun MiaoUI.commentContentView( content: VideoCommentViewContent, textIsSelectable: Boolean, onLinkClick: ExpandableTextView.OnLinkClickListener? = null ): View { return expandableTextView { setLineSpacing(dip(4).toFloat(), 1.0f) setTextColor(config.foregroundColor) textSize = 16f isNeedContract = true isNeedExpend = false // setTextIsSelectable(textIsSelectable) setNeedMention(false) isNeedSelf = true setNeedConvertUrl(false) miaoEffect(content.emote) { tag = content.emote } miaoEffect(null) { setNextContentListener { ssb -> val content = ssb.toString() (tag as? List<VideoCommentViewContent.Emote>)?.forEach { emote -> val textLen = emote.text.length var index = content.indexOf(emote.text) while (index != -1) { val span = UrlImageSpan( context, emote.url, this ) ssb.setSpan(span, index, index + textLen, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) index = content.indexOf(emote.text, index + textLen) } } } } _setContent(BiliUrlMatcher.customString(content.message)) linkClickListener = onLinkClick } } fun MiaoUI.videoCommentView( index: Int = -1, mid: Long, uname: String, avatar: String, time: String, location: String, floor: Int, content: VideoCommentViewContent, like: Long, count: Long, textIsSelectable: Boolean = false, isLike: Boolean = false, onUpperClick: View.OnClickListener? = null, onLinkClick: ExpandableTextView.OnLinkClickListener? = null, onLikeClick: View.OnClickListener? = null, onImageItemClick: OnImageItemClickListener? = null, ): View { return horizontalLayout { padding = dip(10) setBackgroundResource(config.selectableItemBackground) views { // 头像 +rcImageView { isCircle = true _tag = mid.toString() onUpperClick?.let { setOnClickListener(onUpperClick) } _network(avatar) // .placeholder(R.drawable.ico_user_default) }..lParams { width = dip(40) height = dip(40) rightMargin = dip(10) topMargin = dip(4) } +verticalLayout { views { +textView { setTextColor(config.foregroundColor) textSize = 16f _tag = mid onUpperClick?.let { setOnClickListener(onUpperClick) } _text = uname } +horizontalLayout { views { +textView { setTextColor(config.foregroundAlpha45Color) textSize = 14f _text = time }..lParams { rightMargin = dip(10) } +textView { setTextColor(config.foregroundAlpha45Color) textSize = 14f _show = floor != 0 _text = "#${floor}" }..lParams { rightMargin = dip(10) } +textView { setTextColor(config.foregroundAlpha45Color) textSize = 14f _show = location.isNotBlank() _text = location } } }..lParams { topMargin = dip(4) } +commentContentView( content = content, textIsSelectable = textIsSelectable, onLinkClick = onLinkClick, )..lParams { width = matchParent height = wrapContent verticalMargin = dip(8) } +nineGridImageView { spacing = dip(10) onlyOneSize = dip(200) miaoEffect(null){ imageLoader = GlideNineGridImageLoader() } miaoEffect(content.picturesList) { // externalPosition = holder.bindingAdapterPosition setUrlList(content.picturesList) } onImageItemClick?.let { onImageItemClickListener = it } }..lParams { width = matchParent height = wrapContent bottomMargin = dip(8) } +horizontalLayout { gravity = Gravity.CENTER_VERTICAL views { val iconSize = dip(14) +imageView { setImageResource(R.drawable.ic_comment_unlike) _tag = index miaoEffect(isLike) { imageTintList = ColorStateList.valueOf( if (it) { config.themeColor } else { config.foregroundAlpha45Color } ) } onLikeClick?.let { setOnClickListener(it) } }..lParams(iconSize, iconSize) { rightMargin = dip(4) } +textView { textSize = 14f _text = NumberUtil.converString(like) _tag = index miaoEffect(isLike) { setTextColor( if (it) { config.themeColor } else { config.foregroundAlpha45Color } ) } onLikeClick?.let { setOnClickListener(it) } }..lParams(dip(80), wrapContent) +imageView { setImageResource(R.drawable.ic_comment_reply) imageTintList = ColorStateList.valueOf(config.foregroundAlpha45Color) }..lParams(iconSize, iconSize) { rightMargin = dip(4) } +textView { setTextColor(config.foregroundAlpha45Color) textSize = 14f _text = NumberUtil.converString(count) } } }..lParams { topMargin = dip(3) } } }..lParams(matchParent, wrapContent) } } }
44
null
38
977
1d59b82ba30b4c2e83c781479d09c48c3a82cd47
10,447
bilimiao2
Apache License 2.0
kotlinpoet-dsl/src/main/kotlin/com/hendraanggrian/kotlinpoet/collections/TypeVariableNameCollection.kt
hendraanggrian
209,613,746
false
null
package com.hendraanggrian.kotlinpoet.collections import com.hendraanggrian.kotlinpoet.SpecLoader import com.hendraanggrian.kotlinpoet.createSpecLoader import com.hendraanggrian.kotlinpoet.genericsBy import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeVariableName import java.lang.reflect.Type import kotlin.reflect.KClass /** * A [TypeVariableNameCollection] is responsible for managing a set of type variable name instances. * Since Kotlinpoet keep [TypeVariableName] in lists and sets, this class extends [Collection]. */ class TypeVariableNameCollection internal constructor(actualCollection: MutableCollection<TypeVariableName>) : MutableCollection<TypeVariableName> by actualCollection { /** Add a type variable name without bounds. */ fun add(name: String, variance: KModifier? = null): TypeVariableName = name.genericsBy(variance).also(::add) /** Returns a type variable name with [TypeName] bounds. */ fun add(name: String, vararg bounds: TypeName, variance: KModifier? = null): TypeVariableName = name.genericsBy(*bounds, variance = variance).also(::add) /** Returns a type variable name with [Type] bounds. */ fun add(name: String, vararg bounds: Type, variance: KModifier? = null): TypeVariableName = name.genericsBy(*bounds, variance = variance).also(::add) /** Returns a type variable name with [KClass] bounds. */ fun add(name: String, vararg bounds: KClass<*>, variance: KModifier? = null): TypeVariableName = name.genericsBy(*bounds, variance = variance).also(::add) /** Returns a type variable name with collection of [TypeName] bounds. */ fun add(name: String, bounds: List<TypeName>, variance: KModifier? = null): TypeVariableName = name.genericsBy(bounds, variance).also(::add) /** Returns a type variable name with collection of [Type] bounds. */ @JvmName("addWithTypes") fun add(name: String, bounds: Iterable<Type>, variance: KModifier? = null): TypeVariableName = name.genericsBy(bounds, variance).also(::add) /** Returns a type variable name with collection of [KClass] bounds. */ @JvmName("addWithClasses") fun add(name: String, bounds: Iterable<KClass<*>>, variance: KModifier? = null): TypeVariableName = name.genericsBy(bounds, variance).also(::add) /** Convenient method to add type variable name with operator function. */ inline operator fun plusAssign(name: String) { add(name) } /** Property delegate for adding type variable name without bounds. */ val adding: SpecLoader<TypeVariableName> get() = createSpecLoader(::add) /** Property delegate for adding type variable name with [TypeName] bounds. */ fun adding(vararg bounds: TypeName): SpecLoader<TypeVariableName> = createSpecLoader { add(it, *bounds) } /** Property delegate for adding type variable name with [Type] bounds. */ fun adding(vararg bounds: Type): SpecLoader<TypeVariableName> = createSpecLoader { add(it, *bounds) } /** Property delegate for adding type variable name with [KClass] bounds. */ fun adding(vararg bounds: KClass<*>): SpecLoader<TypeVariableName> = createSpecLoader { add(it, *bounds) } /** Property delegate for adding type variable name with collection of [TypeName] bounds. */ fun adding(bounds: List<TypeName>): SpecLoader<TypeVariableName> = createSpecLoader { add(it, bounds) } /** Property delegate for adding type variable name with collection of [Type] bounds. */ @JvmName("addingType") fun adding(bounds: Iterable<Type>): SpecLoader<TypeVariableName> = createSpecLoader { add(it, bounds) } /** Property delegate for adding type variable name with collection of [KClass] bounds. */ @JvmName("addingClass") fun adding(bounds: Iterable<KClass<*>>): SpecLoader<TypeVariableName> = createSpecLoader { add(it, bounds) } }
1
Kotlin
0
3
98f4ea811ea25b6a85334a15ae90bddd5f015592
3,928
kotlinpoet-ktx
Apache License 2.0
web/core/src/jsMain/kotlin/androidx/compose/web/css/StyleBuilder.kt
wm3
376,524,043
true
{"Kotlin": 609747, "Dockerfile": 5716, "Shell": 5673, "HTML": 2801, "PowerShell": 1708, "Groovy": 1415, "CSS": 1022, "JavaScript": 203}
package org.jetbrains.compose.web.css import kotlin.properties.ReadOnlyProperty interface StyleBuilder { fun property(propertyName: String, value: StylePropertyValue) fun variable(variableName: String, value: StylePropertyValue) fun property(propertyName: String, value: String) = property(propertyName, value.unsafeCast<StylePropertyValue>()) fun property(propertyName: String, value: Number) = property(propertyName, value.unsafeCast<StylePropertyValue>()) fun variable(variableName: String, value: Number) = variable(variableName, value.unsafeCast<StylePropertyValue>()) fun variable(variableName: String, value: String) = variable(variableName, value.unsafeCast<StylePropertyValue>()) operator fun <TValue> CSSStyleVariable<TValue>.invoke(value: TValue) { if (value is CustomStyleValue) { variable(name, value.styleValue()) } else { variable(name, value.toString()) } } } fun variableValue(variableName: String, fallback: StylePropertyValue? = null) = "var(--$variableName${fallback?.let { ", $it" } ?: ""})" interface CSSVariableValue<TValue> : StylePropertyValue { companion object { operator fun <TValue> invoke(value: String) = value.unsafeCast<CSSVariableValue<TValue>>() operator fun <TValue> invoke(value: Number) = value.unsafeCast<CSSVariableValue<TValue>>() operator fun <TValue : CSSStyleValue> invoke(value: TValue) = value.unsafeCast<CSSVariableValue<TValue>>() operator fun <TValue> invoke(value: StylePropertyValue) = value.unsafeCast<CSSVariableValue<TValue>>() } } // after adding `variable` word `add` became ambiguous @Deprecated( "use property instead, will remove it soon", ReplaceWith("property(propertyName, value)") ) fun StyleBuilder.add( propertyName: String, value: StylePropertyValue ) = property(propertyName, value) interface CSSVariables interface CSSVariable { val name: String } interface CustomStyleValue { fun styleValue(): StylePropertyValue } data class CSSStyleVariable<TValue>(override val name: String) : CSSVariable fun <TValue> CSSStyleVariable<TValue>.value(fallback: TValue? = null) = CSSVariableValue<TValue>( variableValue( name, fallback?.let { (fallback as? CustomStyleValue)?.styleValue() ?: fallback.toString().unsafeCast<StylePropertyValue>() } ) ) fun <TValue> CSSVariables.variable() = ReadOnlyProperty<Any?, CSSStyleVariable<TValue>> { _, property -> CSSStyleVariable(property.name) } interface StyleHolder { val properties: StylePropertyList val variables: StylePropertyList } open class StyleBuilderImpl : StyleBuilder, StyleHolder { override val properties: MutableStylePropertyList = mutableListOf() override val variables: MutableStylePropertyList = mutableListOf() override fun property(propertyName: String, value: StylePropertyValue) { properties.add(when (value) { is CSSSizeValue<*> -> StylePropertyDeclaration(propertyName, value.asString()) else -> StylePropertyDeclaration(propertyName, value) }) } override fun variable(variableName: String, value: StylePropertyValue) { variables.add(when (value) { is CSSSizeValue<*> -> StylePropertyDeclaration(variableName, value.asString()) else -> StylePropertyDeclaration(variableName, value) }) } // StylePropertyValue is js native object without equals override fun equals(other: Any?): Boolean { return if (other is StyleHolder) { properties.nativeEquals(other.properties) && variables.nativeEquals(other.variables) } else false } } data class StylePropertyDeclaration( val name: String, val value: StylePropertyValue ) { constructor(name: String, value: String) : this(name, value.unsafeCast<StylePropertyValue>()) constructor(name: String, value: Number) : this(name, value.unsafeCast<StylePropertyValue>()) } typealias StylePropertyList = List<StylePropertyDeclaration> typealias MutableStylePropertyList = MutableList<StylePropertyDeclaration> fun StylePropertyList.nativeEquals(properties: StylePropertyList): Boolean { if (this.size != properties.size) return false var index = 0 return all { prop -> val otherProp = properties[index++] prop.name == otherProp.name && prop.value.toString() == otherProp.value.toString() } }
0
null
0
0
603901b814d39cc1c04b6d955510ad51482aebd0
4,603
compose-jb
Apache License 2.0
shared/src/commonMain/kotlin/com/kgurgul/cpuinfo/data/local/IUserPreferencesRepository.kt
kamgurgul
105,620,694
false
null
package com.kgurgul.cpuinfo.data.local import com.kgurgul.cpuinfo.data.local.model.UserPreferences import kotlinx.coroutines.flow.Flow interface IUserPreferencesRepository { val userPreferencesFlow: Flow<UserPreferences> suspend fun setApplicationsSortingOrder(isAscending: Boolean) suspend fun setProcessesSortingOrder(isAscending: Boolean) suspend fun setApplicationsWithSystemApps(withSystemApps: Boolean) suspend fun setTemperatureUnit(temperatureUnit: Int) suspend fun setTheme(theme: String) }
31
null
98
658
ea3ec63943992cc457faeeaf52d0a451fad49f5a
532
cpu-info
Apache License 2.0
src/main/kotlin/org/rust/lang/core/resolve/ref/RustUseGlobReferenceImpl.kt
johan-sun
75,816,553
true
{"Kotlin": 956110, "Rust": 96870, "Java": 69391, "Lex": 19613, "HTML": 8553, "Shell": 377, "RenderScript": 229}
package org.rust.lang.core.resolve.ref import com.intellij.psi.PsiElement import org.rust.lang.core.completion.RustCompletionEngine import org.rust.lang.core.psi.RustCompositeElement import org.rust.lang.core.psi.RustNamedElement import org.rust.lang.core.psi.RustUseGlobElement import org.rust.lang.core.resolve.RustResolveEngine class RustUseGlobReferenceImpl( useGlob: RustUseGlobElement ) : RustReferenceBase<RustUseGlobElement>(useGlob), RustReference { override val RustUseGlobElement.referenceAnchor: PsiElement get() = referenceNameElement override fun getVariants(): Array<out Any> = RustCompletionEngine.completeUseGlob(element) override fun resolveInner(): List<RustCompositeElement> = RustResolveEngine.resolveUseGlob(element) }
0
Kotlin
0
0
438d1998dc0b100436a93eaef155cd4d68adccdf
776
intellij-rust
MIT License
src/main/kotlin/Main.kt
Akardian
510,512,493
false
null
import prison.Prison fun main(args: Array<String>) { println("Program arguments: ${args.joinToString()} \n") val prison = Prison() prison.printStats() var won = 0 var lost = 0 var played = 0 val runNumber = 100000 val repeat = 10 println("\nNumber of Runs: ${runNumber * repeat} \n") for (int in 0 until repeat) { for (index in 1 .. runNumber) { prison.shuffle() if (prison.loopStrategy()) { won++ }else { lost++ } played++ } val percentage = won.toDouble() / (lost + won) println("Played: $played, Wins: $won, Lost: $lost, Percentage Won: $percentage") } }
0
Kotlin
0
0
0f49fab06979e40e8094bca761418775813b50c2
729
Prisoners-Riddle
MIT License
app/src/main/java/com/moshimoshi/app/domain/usecases/user/UserUseCasesImpl.kt
fsalom
745,398,229
false
{"Kotlin": 57054}
package com.moshimoshi.app.domain.usecases.user import com.moshimoshi.app.domain.repositories.UserRepository class UserUseCasesImpl(private val repository: UserRepository): UserUseCases { override suspend fun getMe() { repository.getMe() } }
0
Kotlin
0
1
78053b14d117bdd00d25b83cbb2216a27efb03b3
259
moshimoshi
MIT License
src/main/kotlin/com/github/ifgeny87/playnio/controllers/GameController.kt
ifgeny87
96,071,716
false
{"JavaScript": 36251, "Kotlin": 10253, "HTML": 1339, "CSS": 205}
package com.github.ifgeny87.playnio.controllers import com.beust.klaxon.* import com.github.ifgeny87.common.distance import com.github.ifgeny87.playnio.actors.Robot import com.github.ifgeny87.playnio.sockets.ClientGameSocket import java.util.concurrent.CopyOnWriteArraySet class GameController : Runnable { // список клиентов val webSockets = CopyOnWriteArraySet<ClientGameSocket>() // время старта сервера val serverStartTime = System.nanoTime() / 1_000_000.0 // время сервера var serverLastTime = serverStartTime // время прошло со старта var serverTimeLength = 0.0 // падающие мячи val robots = ArrayList<Robot>() init { for (i in 0..0) robots.add(Robot()) } /** * Новый клиент подключился */ fun onClientConnect(client: ClientGameSocket) { webSockets.add(client) // акцептую клиента, сообщу ему его id и всю нужную информацию client.sendMessage(json { obj( "server" to statusToJsonObject(), "you" to client.player.toJsonObject() ) }) // отправляю всем клиентам обновленное состояние мира sendWorldToAllClients(worldToJsonArray()) } /** * Клиент отключился */ fun onClientDisconnect(client: ClientGameSocket) { webSockets.remove(client) } /** * Клиент прислал сообщение */ fun onClientMessage(client: ClientGameSocket, jsonObject: JsonObject) { // проверяю, что пришло val playerInfo = jsonObject.obj("player") playerInfo?.let { if (playerInfo.string("action") == "click") { // от клиента пришла информация о щелчке мыши // определяем координаты мыши на поле val px = playerInfo.int("x")!! * 1.0 val py = playerInfo.int("y")!! * 1.0 // поиск мяча под прицелом val ballUnderAttack = robots.firstOrNull { distance(it.x, it.y, px, py) < 20 } // если нашелся хоть один мяч, то надо обработать выстрел ballUnderAttack?.let { // игрок заработал еще одно очко client.player.score++ // обновляем мяч ballUnderAttack.reset() // повышаю скорость падения мяча ballUnderAttack.moveSpeed *= 1.5 // отправляем обновленный мир sendWorldToAllClients(JsonArray<Any>( ballUnderAttack.toJsonObject(), client.player.toJsonObject() )) } } } } /** * Генерирует статус сервера для передачи клиенту */ fun statusToJsonObject(): JsonObject { return json { obj("time" to serverTimeLength) } } /** * Генерирует json состояние всех объектов мира */ fun worldToJsonArray(): JsonArray<Any> { val world = JsonArray<Any>() webSockets.forEach { world.add(it.player.toJsonObject()) } robots.forEach { world.add(it.toJsonObject()) } return world } /** * Рассылка сообщения всем игрокам */ fun sendWorldToAllClients(jsonObj: JsonObject) { val message = json { obj( "server" to statusToJsonObject(), "world" to array(jsonObj) ) } webSockets.forEach { it.sendMessage(message) } } /** * Рассылка сообщения всем игрокам */ fun sendWorldToAllClients(jsonArr: JsonArray<Any>) { val message = json { obj( "server" to statusToJsonObject(), "world" to jsonArr) } webSockets.forEach { it.sendMessage(message) } } /** * Сам процесс игры */ override fun run() { val me = Thread.currentThread() while (!me.isInterrupted) { // расчет времени val now = System.nanoTime() / 1_000_000.0 val delta = (now - serverLastTime) serverLastTime = now serverTimeLength = now - serverStartTime // для каждого клиента пересчитываю координаты webSockets.forEach { it.player.update(delta) } val updateBalls = ArrayList<Robot>() // также пересчитываю мячи robots.forEach { it.update(delta) if (it.y > 420) { it.reset() updateBalls.add(it) } } if (updateBalls.size > 0) sendWorldToAllClients( JsonArray<Any>(updateBalls.map { it.toJsonObject() })) // надо поспать чтобы не вешать сервер Thread.sleep(10) } } }
0
JavaScript
0
0
4019405b1251a3621d2ec4ded060bb60cbbb7783
3,922
playnio
Apache License 2.0
graphql-dgs-codegen-core/src/integTest/kotlin/com/netflix/graphql/dgs/codegen/cases/projectionWithEnum/expected/types/Query.kt
Netflix
317,379,776
false
null
package com.netflix.graphql.dgs.codegen.cases.projectionWithEnum.expected.types import com.fasterxml.jackson.`annotation`.JsonIgnoreProperties import com.fasterxml.jackson.`annotation`.JsonProperty import com.fasterxml.jackson.`annotation`.JsonTypeInfo import com.fasterxml.jackson.databind.`annotation`.JsonDeserialize import com.fasterxml.jackson.databind.`annotation`.JsonPOJOBuilder import java.lang.IllegalStateException import kotlin.collections.List import kotlin.jvm.JvmName @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) @JsonDeserialize(builder = Query.Builder::class) public class Query( e: () -> E? = eDefault, es: () -> List<E?>? = esDefault, ) { private val __e: () -> E? = e private val __es: () -> List<E?>? = es @get:JvmName("getE") public val e: E? get() = __e.invoke() @get:JvmName("getEs") public val es: List<E?>? get() = __es.invoke() public companion object { private val eDefault: () -> E? = { throw IllegalStateException("Field `e` was not requested") } private val esDefault: () -> List<E?>? = { throw IllegalStateException("Field `es` was not requested") } } @JsonPOJOBuilder @JsonIgnoreProperties("__typename") public class Builder { private var e: () -> E? = eDefault private var es: () -> List<E?>? = esDefault @JsonProperty("e") public fun withE(e: E?): Builder = this.apply { this.e = { e } } @JsonProperty("es") public fun withEs(es: List<E?>?): Builder = this.apply { this.es = { es } } public fun build(): Query = Query( e = e, es = es, ) } }
95
null
96
181
57b2e1e6db8da146cfa590a0c331ac15ef156085
1,613
dgs-codegen
Apache License 2.0
api/token/src/test/kotlin/uk/co/baconi/oauth/api/token/AuthorisationCodeGrantTest.kt
beercan1989
345,334,044
false
{"Kotlin": 518336, "JavaScript": 63785, "TypeScript": 5223, "Dockerfile": 4449, "HTML": 1187}
package uk.co.baconi.oauth.api.token import io.kotest.assertions.assertSoftly import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test import uk.co.baconi.oauth.api.common.authentication.AuthenticatedUsername import uk.co.baconi.oauth.api.common.authorisation.AuthorisationCode import uk.co.baconi.oauth.api.common.authorisation.AuthorisationCodeRepository import uk.co.baconi.oauth.api.common.client.ClientId import uk.co.baconi.oauth.api.common.client.ConfidentialClient import uk.co.baconi.oauth.api.common.scope.Scope import uk.co.baconi.oauth.api.common.token.AccessTokenService import uk.co.baconi.oauth.api.common.token.RefreshTokenService import java.time.Instant import java.util.* class AuthorisationCodeGrantTest { private val accessToken = UUID.randomUUID() private val accessTokenService = mockk<AccessTokenService> { every { issue(any(), any(), any()) } returns mockk { val now = Instant.now() every { value } returns accessToken every { scopes } returns setOf(Scope("basic")) every { issuedAt } returns now every { expiresAt } returns now } } private val refreshToken = UUID.randomUUID() private val refreshTokenService = mockk<RefreshTokenService> { every { issue(any(), any(), any()) } returns mockk { every { value } returns refreshToken } } private val authorisationCodeRepository = mockk<AuthorisationCodeRepository> { every { markUsed(any()) } returns Unit } private val underTest = AuthorisationCodeGrant(accessTokenService, refreshTokenService, authorisationCodeRepository) @Test fun `should return success when customer authentication succeeds`() { val principal = mockk<ConfidentialClient> { every { id } returns ClientId("badger") } val authorisationCode = mockk<AuthorisationCode> { every { username } returns AuthenticatedUsername("aardvark") every { clientId } returns principal.id every { scopes } returns setOf(Scope("basic")) every { state } returns "a5385765-0a4b-41be-bb97-5415a5c2be67" } assertSoftly(underTest.exchange(AuthorisationCodeRequest(principal, authorisationCode))) { shouldBeInstanceOf<TokenResponse.Success>() this.accessToken shouldBe accessToken this.refreshToken shouldBe refreshToken this.expiresIn shouldBe 0 this.scope shouldContainExactly setOf(Scope("basic")) this.state shouldBe "a5385765-0a4b-41be-bb97-5415a5c2be67" } verify { authorisationCodeRepository.markUsed(authorisationCode) } } }
1
Kotlin
0
0
2fc541ddcabe344543d023f2e633b3c111546c33
2,896
oauth-api
Apache License 2.0
server/src/test/java/de/zalando/zally/rule/zalando/PluralizeResourceNamesRuleTest.kt
hpdang
148,153,657
false
null
package de.zalando.zally.rule.zalando import de.zalando.zally.getContextFromFixture import de.zalando.zally.rule.ContentParseResult import de.zalando.zally.rule.ContentParseResultAssert.Companion.assertThat import de.zalando.zally.rule.DefaultContextFactory import de.zalando.zally.rule.ZallyAssertions.assertThat import de.zalando.zally.rule.api.Context import de.zalando.zally.testConfig import org.junit.Test class PluralizeResourceNamesRuleTest { private val rule = PluralizeResourceNamesRule(testConfig) @Test fun positiveCase() { val context = getContextFromFixture("pluralizeResourcesValid.json") val violations = rule.validate(context) assertThat(violations).isEmpty() } @Test fun negativeCase() { val context = getContextFromFixture("pluralizeResourcesInvalid.json") val violations = rule.validate(context) assertThat(violations) .descriptionsEqualTo( "Resource 'pet' appears to be singular", "Resource 'tail' appears to be singular" ) .pointersEqualTo( "/paths/~1pet~1cats", "/paths/~1pets~1cats~1{cat-id}~1tail~1{tail-id}~1strands" ) } @Test fun positiveCaseSpp() { val context = getContextFromFixture("api_spp.json") val violations = rule.validate(context) assertThat(violations).isEmpty() } @Test fun positiveCasePathsWithTheApiPrefix() { val context = getContextFromFixture("spp_with_paths_having_api_prefix.json") val violations = rule.validate(context) assertThat(violations).isEmpty() } @Test fun positiveCaseNoMustViolations() { val context = getContextFromFixture("no_must_violations.yaml") val violations = rule.validate(context) assertThat(violations).isEmpty() } @Test fun negativeCaseTinbox() { val context = getContextFromFixture("api_tinbox.yaml") val violations = rule.validate(context) assertThat(violations) .pointersEqualTo( "/paths/~1meta~1article_domains", "/paths/~1meta~1colors", "/paths/~1meta~1commodity_groups", "/paths/~1meta~1size_grids", "/paths/~1meta~1tags", "/paths/~1queue~1configs~1{config-id}", "/paths/~1queue~1models", "/paths/~1queue~1models~1{model-id}", "/paths/~1queue~1summaries" ) } @Test fun `validate with plurals returns no violations`() { val context = openApiContextWithPath("/plurals/things") val violations = rule.validate(context) assertThat(violations) .isEmpty() } @Test fun `validate with singulars returns violations`() { val context = openApiContextWithPath("/singular/thing") val violations = rule.validate(context) assertThat(violations) .descriptionsEqualTo( "Resource 'singular' appears to be singular", "Resource 'thing' appears to be singular" ) .pointersEqualTo( "/paths/~1singular~1thing", "/paths/~1singular~1thing" ) } @Test fun `validate with parameters returns other violations`() { val context = openApiContextWithPath("/prefix/{parameter}/suffix") val violations = rule.validate(context) assertThat(violations) .descriptionsEqualTo( "Resource 'prefix' appears to be singular", "Resource 'suffix' appears to be singular" ) .pointersEqualTo( "/paths/~1prefix~1{parameter}~1suffix", "/paths/~1prefix~1{parameter}~1suffix" ) } @Test fun `validate with configured whitelisted singulars returns no violations`() { val context = openApiContextWithPath("/api/things") val violations = rule.validate(context) assertThat(violations) .isEmpty() } @Test fun `validate with whitelisted prefix returns no violations`() { val context = openApiContextWithPath("/prefix/singular") rule.whitelist += "^/?prefix/.*".toRegex() val violations = rule.validate(context) assertThat(violations) .isEmpty() } @Test fun `validate with whitelisted suffix returns no violations`() { val context = openApiContextWithPath("/singular/suffix") rule.whitelist += ".*/suffix/?${'$'}".toRegex() val violations = rule.validate(context) assertThat(violations) .isEmpty() } @Test fun `validate with whitelisted component returns other violations`() { val context = openApiContextWithPath("/prefix/whitelisted/suffix") rule.whitelist += "/whitelisted/".toRegex() val violations = rule.validate(context) assertThat(violations) .descriptionsEqualTo( "Resource 'prefix' appears to be singular", "Resource 'suffix' appears to be singular" ) .pointersEqualTo( "/paths/~1prefix~1whitelisted~1suffix", "/paths/~1prefix~1whitelisted~1suffix" ) } @Suppress("UnsafeCallOnNullableType") private fun openApiContextWithPath(path: String): Context { val content = """ openapi: 3.0.0 paths: $path: {} """.trimIndent() val result = DefaultContextFactory().createOpenApiContext(content) assertThat(result).resultsInSuccess() return (result as ContentParseResult.ParsedSuccessfully).result } }
0
null
1
415
91bc7341a5b8d9a65bc67e8ca680b6c423d6c684
5,817
zally
MIT License
app/src/test/java/com/example/marsphotos/fake/FakeNetworkMarsPhotosRepository.kt
bobbyecho
564,105,681
false
null
package com.example.marsphotos.fake import com.example.marsphotos.data.MarsPhotoRepository import com.example.marsphotos.model.MarsPhoto class FakeNetworkMarsPhotosRepository: MarsPhotoRepository { override suspend fun getMarsPhotos(): List<MarsPhoto> { return FakeDataSource.photosList } }
0
Kotlin
0
1
464efc34532730d92412aa76e2e1c144eec4e7b7
296
ktx-mars-photo-compose-repository-viewmodel
Apache License 2.0
jupiter/src/main/kotlin/com/fleshgrinder/junit/jupiter/jackson/JacksonInjector.kt
Fleshgrinder
521,609,301
false
{"Kotlin": 178761}
package com.fleshgrinder.junit.jupiter.jackson /** * Provides the ability to inject any of the various Jackson mappers via * constructor injection in JUnit. */ public class JacksonInjector
0
Kotlin
0
0
a5b95e1b68060bed29f6d72619134664eb216ffe
193
junit
The Unlicense
app/src/main/java/com/example/buangin_v1/custom_view/PasswordValidation.kt
Buwang-in
647,663,283
false
null
package com.example.buangin_v1.custom_view import android.content.Context import android.graphics.Canvas import android.text.Editable import android.text.InputType import android.text.Selection import android.text.TextWatcher import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.appcompat.widget.AppCompatEditText import androidx.core.content.ContextCompat import com.example.buangin_v1.R class PasswordValidation: AppCompatEditText, View.OnTouchListener { private var isPasswordVisible = true constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) textAlignment = View.TEXT_ALIGNMENT_VIEW_START } private fun init() { setOnTouchListener(this) addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { error = if (s.length < 8){ "Password must be more or at least 8 characters" }else{ null } } override fun afterTextChanged(s: Editable) { error = if (s.length < 8){ "Password must be more or at least 8 characters" }else{ null } } }) } override fun onTouch(v: View?, event: MotionEvent): Boolean { // if (event.action == MotionEvent.ACTION_UP) { // val drawableRight = compoundDrawablesRelative[2] // if (drawableRight != null && event.rawX >= (right - drawableRight.bounds.width())) { // togglePasswordVisibility() // return true // } // } return false } // private fun togglePasswordVisibility() { // isPasswordVisible = !isPasswordVisible // val drawable = if (isPasswordVisible) { // ContextCompat.getDrawable(context, R.drawable.hide_eye) // } else { // ContextCompat.getDrawable(context, R.drawable.remove_eye) // } // setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null) // // inputType = if (isPasswordVisible) { // InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD // } else { // InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD // } // text?.let { setSelection(it.length) } // } }
0
Kotlin
1
0
75e2990a9d3cc3d9f9c5ec109e73aba5f74195ea
2,910
buwang.in-mobile
MIT License
GenesisAndroid/src/main/java/com/emerchantpay/gateway/genesisandroid/api/exceptions/UnexpectedException.kt
GenesisGateway
132,108,784
false
null
package com.emerchantpay.gateway.genesisandroid.api.exceptions class UnexpectedException : GenesisException { constructor(message: String) : super(message) {} constructor(message: String?, cause: Throwable?) : super(message, cause) {} companion object { private const val serialVersionUID = 1L } }
0
Kotlin
2
1
d08e83d53c959a1dc48c46560b297f84075b2946
328
android_sdk
MIT License
app/src/main/java/ru/nlct/nationalkeyboard/data/database/KeyboardLanguageEntity.kt
NLCodeTeam
490,878,159
false
{"Kotlin": 57762}
package ru.nlct.nationalkeyboard.data.database import androidx.room.ColumnInfo import androidx.room.Entity @Entity( tableName = KeyboardLanguageEntity.Schema.TABLE_NAME, primaryKeys = [KeyboardLanguageEntity.Schema.LANGUAGE_ID] ) data class KeyboardLanguageEntity( @ColumnInfo(name = Schema.LANGUAGE_ID) val id: Int, @ColumnInfo(name = Schema.LANGUAGE_TITLE) val title: String, @ColumnInfo(name = Schema.LANGUAGE_ENABLE) val enabled: Boolean ) { object Schema { const val TABLE_NAME = "languages" const val LANGUAGE_ID = "id" const val LANGUAGE_TITLE = "title" const val LANGUAGE_ENABLE = "enable" } }
0
Kotlin
0
1
4a3918a44f5b86b896d5af76eb79c6eb1653f3b9
663
NationalKeyboard
Apache License 2.0