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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
data/src/main/java/app/tivi/data/repositories/lastrequests/GroupLastRequestStore.kt | chrisbanes | 100,624,553 | false | null | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.data.repositories.lastrequests
import app.tivi.data.daos.LastRequestDao
import app.tivi.data.entities.LastRequest
import app.tivi.data.entities.Request
import app.tivi.data.inPast
import org.threeten.bp.Instant
import org.threeten.bp.temporal.TemporalAmount
open class GroupLastRequestStore(
private val request: Request,
private val dao: LastRequestDao
) {
suspend fun getRequestInstant(): Instant? {
return dao.lastRequest(request, DEFAULT_ID)?.timestamp
}
suspend fun isRequestExpired(threshold: TemporalAmount): Boolean {
return isRequestBefore(threshold.inPast())
}
suspend fun isRequestBefore(instant: Instant): Boolean {
return getRequestInstant()?.isBefore(instant) ?: true
}
suspend fun updateLastRequest(timestamp: Instant = Instant.now()) {
dao.insert(LastRequest(request = request, entityId = DEFAULT_ID, timestamp = timestamp))
}
suspend fun invalidateLastRequest() = updateLastRequest(Instant.EPOCH)
companion object {
private const val DEFAULT_ID = 0L
}
}
| 39 | Kotlin | 780 | 5,603 | bffa49f7c4a61b168317ea59f135699878960bdc | 1,682 | tivi | Apache License 2.0 |
android-test-framework/testSrc/com/android/tools/idea/res/ResourcesTestsUtil.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("ResourcesTestsUtil")
package com.android.tools.idea.res
import com.android.SdkConstants
import com.android.ide.common.rendering.api.ResourceNamespace
import com.android.ide.common.resources.ResourceItem
import com.android.resources.ResourceType
import com.android.resources.getTestAarRepositoryFromExplodedAar
import com.android.tools.idea.testing.Facets
import com.android.tools.idea.util.toIoFile
import com.android.tools.idea.util.toPathString
import com.android.tools.idea.util.toVirtualFile
import com.android.tools.res.LocalResourceRepository
import com.google.common.truth.Truth.assertThat
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.IndexingTestUtil.Companion.waitUntilIndexesAreReady
import com.intellij.testFramework.PsiTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import com.intellij.workspaceModel.ide.legacyBridge.impl.java.JAVA_MODULE_ENTITY_TYPE_ID_NAME
import org.jetbrains.android.AndroidTestBase
import org.jetbrains.android.facet.AndroidFacet
import java.io.File
import java.util.function.Predicate
import java.util.jar.JarEntry
import java.util.jar.JarOutputStream
fun createTestAppResourceRepository(facet: AndroidFacet): LocalResourceRepository {
val moduleResources = createTestModuleRepository(facet, emptyList())
val projectResources = ProjectResourceRepository.createForTest(facet, listOf(moduleResources))
val appResources = AppResourceRepository.createForTest(facet, listOf<LocalResourceRepository>(projectResources), emptyList())
val aar = getTestAarRepositoryFromExplodedAar()
appResources.updateRoots(listOf(projectResources), listOf(aar))
return appResources
}
@JvmOverloads
fun createTestModuleRepository(
facet: AndroidFacet,
resourceDirectories: Collection<VirtualFile>,
namespace: ResourceNamespace = ResourceNamespace.RES_AUTO,
dynamicRepo: DynamicValueResourceRepository? = null
): LocalResourceRepository {
return ModuleResourceRepository.createForTest(facet, resourceDirectories, namespace, dynamicRepo)
}
/**
* Creates and adds an Android Module to the given project.
* The module file would be located under [Project.getBasePath] + "/[moduleName]/[moduleName].iml"
*
* Runs the given [function][createResources] to add resources to the module.
*
* @param moduleName name given to the new module.
* @param project current working project.
* @param packageName the module's package name (this will be recorded in its Android manifest)
* @param createResources code that will be invoked on the module resources folder, to add desired resources. VFS will be refreshed after
* the function is done.
* @return The instance of the created module added to the project.
*/
fun addAndroidModule(moduleName: String, project: Project, packageName: String, createResources: (moduleResDir: File) -> Unit): Module {
val root = project.basePath
val moduleDir = File(FileUtilRt.toSystemDependentName(root!!), moduleName)
val moduleFilePath = File(moduleDir, moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION)
createAndroidManifest(moduleDir, packageName)
val module = runWriteAction { ModuleManager.getInstance(project).newModule(moduleFilePath.path, JAVA_MODULE_ENTITY_TYPE_ID_NAME) }
Facets.createAndAddAndroidFacet(module)
val moduleResDir = moduleDir.resolve(SdkConstants.FD_RES)
moduleResDir.mkdir()
createResources(moduleResDir)
VfsUtil.markDirtyAndRefresh(false, true, true, moduleDir.toVirtualFile(refresh = true))
return module
}
/**
* Creates a minimal AndroidManifest.xml with the given [packageName] in the given [dir].
*/
private fun createAndroidManifest(dir: File, packageName: String) {
dir.mkdirs()
dir.resolve(SdkConstants.FN_ANDROID_MANIFEST_XML).writeText(
// language=xml
"""
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="$packageName">
</manifest>
""".trimIndent()
)
}
/**
* Adds a library dependency to the given module and runs the given function to add resources to it.
*
* [StudioResourceRepositoryManager] will find the newly added library and create a separate repository for it when
* [StudioResourceRepositoryManager.getCachedAppResources] is called.
*
* @param module module to add the dependency to.
* @param libraryName name of the newly created [LibraryOrderEntry].
* @param packageName package name to be put in the library manifest.
* @param createResources code that will be invoked on the library resources folder, to add desired resources. VFS will be refreshed after
* the function is done.
*/
fun addAarDependency(
fixture: CodeInsightTestFixture,
module: Module,
libraryName: String,
packageName: String,
createResources: (File) -> Unit
) {
val aarDir = fixture.tempDirFixture.findOrCreateDir("${libraryName}_exploded").toIoFile()
// Create a manifest file in the right place, so that files inside aarDir are considered resource files.
// See AndroidResourcesIdeUtil#isResourceDirectory which is called from ResourcesDomFileDescription#isResourcesFile.
createAndroidManifest(aarDir, packageName)
val resDir = aarDir.resolve(SdkConstants.FD_RES)
resDir.mkdir()
resDir.resolve(SdkConstants.FD_RES_VALUES).mkdir()
val classesJar = aarDir.resolve(SdkConstants.FN_CLASSES_JAR)
JarOutputStream(classesJar.outputStream()).use {
it.putNextEntry(JarEntry("META-INF/empty"))
}
// See ResourceFolderManager.isAarDependency for what this library must look like to be considered an AAR.
val library = PsiTestUtil.addProjectLibrary(
module,
"$libraryName.aar",
listOf(
resDir.toVirtualFile(refresh = true),
classesJar.toVirtualFile(refresh = true)
),
emptyList()
)
ModuleRootModificationUtil.addDependency(module, library)
createResources(resDir)
VfsUtil.markDirtyAndRefresh(false, true, true, aarDir.toVirtualFile(refresh = true))
waitUntilIndexesAreReady(module.project)
}
/**
* Adds an AARv2 library dependency to the given module. The library uses the checked-in example res.apk file which uses
* `com.example.mylibrary` package name and contains a single resource, `@string/my_aar_string`.
*/
fun addBinaryAarDependency(module: Module) {
// See org.jetbrains.android.facet.ResourceFolderManager#isAarDependency
PsiTestUtil.addLibrary(
module,
"mylibrary.aar",
"${AndroidTestBase.getTestDataPath()}/dom/layout/myaar-v2",
"classes.jar",
"res.apk"
)
}
fun getSingleItem(repository: LocalResourceRepository, type: ResourceType, key: String): ResourceItem {
val list = repository.getResources(ResourceNamespace.RES_AUTO, type, key)
assertThat(list).hasSize(1)
return list[0]
}
fun getSingleItem(repository: LocalResourceRepository, type: ResourceType, key: String, filter: Predicate<ResourceItem>): ResourceItem {
val list = repository.getResources(ResourceNamespace.RES_AUTO, type, key)
var found: ResourceItem? = null
for (item in list) {
if (filter.test(item)) {
assertThat(found).isNull()
found = item
}
}
return found!!
}
class DefinedInOrUnder internal constructor(fileOrDirectory: VirtualFile) : Predicate<ResourceItem> {
private val myFileOrDirectory = fileOrDirectory.toPathString()
override fun test(item: ResourceItem): Boolean {
return item.source!!.startsWith(myFileOrDirectory)
}
}
| 5 | null | 230 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 8,442 | android | Apache License 2.0 |
app/src/main/java/com/tobibur/swipequotes/model/ApiRepo.kt | Tobibur | 141,177,971 | false | {"Kotlin": 9591} | package com.tobibur.swipequotes.model
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.tobibur.swipequotes.model.service.ApiClient
import com.tobibur.swipequotes.model.service.ApiInterface
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ApiRepo{
var endpoints : ApiClient = ApiClient()
fun getPosts() : LiveData<ApiResponse> {
val apiResponse = MutableLiveData<ApiResponse>()
val apiService = endpoints.getClient()!!.create(ApiInterface::class.java)
val call : Call<QuoteModel> = apiService.getQuotes("getQuote","json","en")
call.enqueue(object : Callback<QuoteModel>{
override fun onFailure(call: Call<QuoteModel>?, t: Throwable?) {
apiResponse.postValue(ApiResponse(t!!))
}
override fun onResponse(call: Call<QuoteModel>?, response: Response<QuoteModel>?) {
if (response!!.isSuccessful) {
apiResponse.postValue(ApiResponse(response.body()!!))
}else{
apiResponse.postValue(ApiResponse(response.code()))
}
}
})
return apiResponse
}
} | 0 | Kotlin | 3 | 9 | c27409e5661bc2c78a52854da48057d9dd1ba491 | 1,232 | Retrofit-Kotlin-Example | MIT License |
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/dopeflix/DopeFlixGenerator.kt | aniyomiorg | 360,630,872 | false | null | package eu.kanade.tachiyomi.multisrc.dopeflix
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceGenerator
class DopeFlixGenerator : ThemeSourceGenerator {
override val themePkg = "dopeflix"
override val themeClass = "DopeFlix"
override val baseVersionCode = 19
override val sources = listOf(
SingleLang("DopeBox", "https://dopebox.to", "en", isNsfw = false, overrideVersionCode = 5),
SingleLang("SFlix", "https://sflix.to", "en", isNsfw = false, overrideVersionCode = 4),
)
companion object {
@JvmStatic
fun main(args: Array<String>) = DopeFlixGenerator().createAll()
}
}
| 375 | null | 165 | 426 | 0064c5658da47bec8f0fc444a9994fe8c61bd6c0 | 660 | aniyomi-extensions | Apache License 2.0 |
shippedsuite/src/test/java/com/invisiblecommerce/shippedsuite/ui/WidgetViewTest.kt | InvisibleCommerce | 513,384,323 | false | null | package com.invisiblecommerce.shippedsuite.ui
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.invisiblecommerce.shippedsuite.ShippedSuite
import com.invisiblecommerce.shippedsuite.model.ShippedCurrency
import com.invisiblecommerce.shippedsuite.model.ShippedFeeWithCurrency
import com.invisiblecommerce.shippedsuite.model.ShippedOffers
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.math.BigDecimal
import java.util.*
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [29])
class WidgetViewTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val widgetView: WidgetView by lazy {
WidgetView(context, null)
}
@Test
fun widgetTest() {
val publicKey =
"pk_development_117c2ee46c122fb0ce070fbc984e6a4742040f05a1c73f8a900254a1933a0112"
ShippedSuite.configurePublicKey(context, publicKey)
var configuration = ShippedSuiteConfiguration(
type = ShippedSuiteType.SHIELD,
isInformational = false,
isMandatory = true,
isRespectServer = true,
appearance = ShippedSuiteAppearance.LIGHT
)
widgetView.configuration = configuration
configuration.type = ShippedSuiteType.GREEN
configuration.isMandatory = false
widgetView.configuration = configuration
Assert.assertEquals(widgetView.configuration.type, ShippedSuiteType.GREEN)
configuration.type = ShippedSuiteType.GREEN_AND_SHIELD
configuration.isInformational = true
widgetView.configuration = configuration
Assert.assertEquals(widgetView.configuration.type, ShippedSuiteType.GREEN_AND_SHIELD)
val defaultOrderValue = BigDecimal.valueOf(129.99)
widgetView.updateOrderValue(defaultOrderValue)
widgetView.configuration.type = ShippedSuiteType.GREEN_AND_SHIELD
Assert.assertEquals(widgetView.configuration.type, ShippedSuiteType.GREEN_AND_SHIELD)
widgetView.configuration.type = ShippedSuiteType.GREEN
Assert.assertEquals(widgetView.configuration.type, ShippedSuiteType.GREEN)
widgetView.configuration.type = ShippedSuiteType.SHIELD
Assert.assertEquals(widgetView.configuration.type, ShippedSuiteType.SHIELD)
widgetView.configuration.isMandatory = true
Assert.assertEquals(widgetView.configuration.isMandatory, true)
widgetView.configuration.isRespectServer = true
Assert.assertEquals(widgetView.configuration.isRespectServer, true)
}
@Test
fun configurationTest() {
val configuration = ShippedSuiteConfiguration()
Assert.assertEquals(configuration.type, ShippedSuiteType.SHIELD)
Assert.assertEquals(configuration.isMandatory, false)
Assert.assertEquals(configuration.isInformational, false)
Assert.assertEquals(configuration.isRespectServer, false)
Assert.assertEquals(configuration.appearance, ShippedSuiteAppearance.AUTO)
configuration.type = ShippedSuiteType.GREEN
Assert.assertEquals(configuration.type, ShippedSuiteType.GREEN)
configuration.isMandatory = true
Assert.assertEquals(configuration.isMandatory, true)
configuration.isInformational = true
Assert.assertEquals(configuration.isInformational, true)
configuration.isRespectServer = true
Assert.assertEquals(configuration.isRespectServer, true)
configuration.appearance = ShippedSuiteAppearance.DARK
Assert.assertEquals(configuration.appearance, ShippedSuiteAppearance.DARK)
}
@Test
fun typeTest() {
val currency = ShippedCurrency(
",",
"€",
true,
".",
BigDecimal(100),
"EUR",
"Euro"
)
val shieldFeeWithCurrency = ShippedFeeWithCurrency(
currency,
BigDecimal(227),
"€2,27"
)
val greenFeeWithCurrency = ShippedFeeWithCurrency(
currency,
BigDecimal(39),
"€0,39"
)
val offers = ShippedOffers(
storefrontId = "",
orderValue = BigDecimal(129.99),
shieldFee = BigDecimal(2.99),
shieldFeeWithCurrency = shieldFeeWithCurrency,
greenFee = BigDecimal(0.56),
greenFeeWithCurrency = greenFeeWithCurrency,
isMandatory = false,
offeredAt = Date()
)
val shield = ShippedSuiteType.SHIELD
Assert.assertNotNull(shield.widgetFee(offers, context))
Assert.assertNotNull(shield.learnMoreSubtitle(context))
Assert.assertNull(shield.learnMoreBanner(context))
val green = ShippedSuiteType.GREEN
Assert.assertNotNull(green.widgetFee(offers, context))
Assert.assertNotNull(green.learnMoreSubtitle(context))
Assert.assertNotNull(green.learnMoreBanner(context))
val greenAndShield = ShippedSuiteType.GREEN_AND_SHIELD
Assert.assertNotNull(greenAndShield.widgetFee(offers, context))
Assert.assertNotNull(greenAndShield.learnMoreSubtitle(context))
Assert.assertNotNull(greenAndShield.learnMoreBanner(context))
}
@Test
fun appearanceTest() {
val autoAppearance = ShippedSuiteAppearance.AUTO
Assert.assertFalse(autoAppearance.isDarkMode(context))
Assert.assertNotNull(autoAppearance.widgetTitleColor(context))
Assert.assertNotNull(autoAppearance.widgetLearnMoreColor(context))
Assert.assertNotNull(autoAppearance.widgetFeeColor(context))
Assert.assertNotNull(autoAppearance.widgetDescColor(context))
val lightAppearance = ShippedSuiteAppearance.LIGHT
Assert.assertFalse(lightAppearance.isDarkMode(context))
Assert.assertNotNull(lightAppearance.widgetTitleColor(context))
Assert.assertNotNull(lightAppearance.widgetLearnMoreColor(context))
Assert.assertNotNull(autoAppearance.widgetFeeColor(context))
Assert.assertNotNull(autoAppearance.widgetDescColor(context))
val darkAppearance = ShippedSuiteAppearance.DARK
Assert.assertTrue(darkAppearance.isDarkMode(context))
Assert.assertNotNull(darkAppearance.widgetTitleColor(context))
Assert.assertNotNull(darkAppearance.widgetLearnMoreColor(context))
Assert.assertNotNull(autoAppearance.widgetFeeColor(context))
Assert.assertNotNull(autoAppearance.widgetDescColor(context))
}
}
| 0 | Kotlin | 0 | 0 | 9f97638d84cb25f4a3a3a7821ee71f7a674561ed | 6,645 | shipped-suite-android-client-sdk | MIT License |
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/Crop.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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.TablerIcons
public val TablerIcons.Crop: ImageVector
get() {
if (_crop != null) {
return _crop!!
}
_crop = Builder(name = "Crop", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(8.0f, 5.0f)
verticalLineToRelative(10.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f)
horizontalLineToRelative(10.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 8.0f)
horizontalLineToRelative(10.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(10.0f)
}
}
.build()
return _crop!!
}
private var _crop: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 1,991 | compose-icons | MIT License |
src/main/kotlin/spp/cli/util/ExitManager.kt | sourceplusplus | 423,649,113 | false | null | /*
* Source++, the continuous feedback platform for developers.
* Copyright (C) 2022-2023 CodeBrig, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spp.cli.util
import com.apollographql.apollo3.api.Error
import com.github.ajalt.clikt.output.TermUi
import spp.cli.PlatformCLI.currentContext
import spp.cli.PlatformCLI.echoError
object ExitManager {
var standalone = true
fun exitProcess(status: Int, e: Exception): Nothing {
echoError(e)
if (standalone) kotlin.system.exitProcess(status)
throw e
}
fun exitProcess(status: Int, e: List<Error>? = null) {
if (e != null) {
echo(e[0].message, err = true)
}
if (standalone) kotlin.system.exitProcess(status)
}
fun exitProcess(e: List<Error>): Nothing {
echo(e[0].message, err = true)
if (standalone) exitProcess(-1)
throw IllegalStateException(e[0].message)
}
private fun echo(
message: Any?,
trailingNewline: Boolean = true,
err: Boolean = false,
lineSeparator: String = currentContext.console.lineSeparator,
) {
TermUi.echo(message, trailingNewline, err, currentContext.console, lineSeparator)
}
}
| 2 | Kotlin | 1 | 1 | dd8739c3748b31bd338f200f9d9f59d16b387719 | 1,744 | interface-cli | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/entities/EvmNetwork.kt | horizontalsystems | 142,825,178 | false | null | package io.horizontalsystems.bankwallet.entities
import io.horizontalsystems.bankwallet.core.managers.urls
import io.horizontalsystems.ethereumkit.models.Chain
import io.horizontalsystems.ethereumkit.models.RpcSource
data class EvmNetwork(
val name: String,
val chain: Chain,
val rpcSource: RpcSource
) {
val id: String
get() {
val syncSourceUrl = rpcSource.urls.joinToString(separator = ",") { it.toString() }
return "${chain.id}|$syncSourceUrl"
}
}
| 153 | null | 190 | 348 | fea4c5d96759a865408f92e661a13e10faa66226 | 510 | unstoppable-wallet-android | MIT License |
src/main/kotlin/dev/erdragh/erdbot/handlers/FAQHandler.kt | Erdragh | 723,352,761 | false | {"Kotlin": 16612} | package dev.erdragh.erdbot.handlers
import dev.erdragh.erdbot.LOGGER
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchKey
import kotlin.io.path.extension
import kotlin.io.path.isDirectory
import kotlin.io.path.nameWithoutExtension
object FAQHandler {
private val faqDirectory = File("faq")
private val availableFAQIDs = ArrayList<String>()
private var watcherThread: Thread? = null
init {
LOGGER.info("FAQHandler loading")
if (!faqDirectory.exists() || !faqDirectory.isDirectory) {
LOGGER.error("FAQ directory not specified as directory: ${faqDirectory.absolutePath}")
} else {
val findMarkdownRegex = Regex(".+\\.md$")
val faqFiles = faqDirectory.listFiles { it -> !it.isDirectory }?.filter { it.name.matches(findMarkdownRegex) }?.map { it.nameWithoutExtension }
faqFiles?.forEach(availableFAQIDs::add)
watcherThread = (Thread {
val watcher = FileSystems.getDefault().newWatchService()
val faqDirectoryPath = faqDirectory.toPath()
faqDirectoryPath.register(
watcher,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE
)
try {
var key: WatchKey = watcher.take()
while (!Thread.currentThread().isInterrupted) {
for (event in key.pollEvents()) {
val ctx = event.context()
val path = event.context() as Path
LOGGER.debug("Handling File Event: {} for {}", event.kind(), ctx)
if (!path.isDirectory() && path.extension == "md") {
when (event.kind()) {
StandardWatchEventKinds.ENTRY_CREATE -> {
availableFAQIDs.add(path.nameWithoutExtension)
}
StandardWatchEventKinds.ENTRY_DELETE -> {
availableFAQIDs.remove(path.nameWithoutExtension)
}
}
}
}
key.reset()
key = watcher.take()
}
} catch (_: InterruptedException) {
// Do Nothing. If this thread is interrupted it means it should just stop
}
})
watcherThread?.start()
}
}
fun getFAQForId(id: String): String {
if (!faqDirectory.exists() || !faqDirectory.isDirectory) {
LOGGER.error("FAQ directory not specified as directory: ${faqDirectory.absolutePath}")
return "Bot Error (Contact Bot Operator)"
}
val faqFiles = faqDirectory.listFiles { it -> it.name == "$id.md" }
val faqFile = if (faqFiles?.isNotEmpty() == true) faqFiles[0] else null
return faqFile?.readText(Charsets.UTF_8) ?: "No FAQ registered for id: `$id`"
}
fun suggestFAQIds(slug: String): List<String> {
return availableFAQIDs.filter { it.startsWith(slug, true) }
}
fun shutdownWatcher() {
watcherThread?.interrupt()
}
}
| 0 | Kotlin | 0 | 0 | ff644f743bc7b76ecf6870ea8b836145accbf9c9 | 3,478 | AstralBot | MIT License |
base/domain/src/main/java/org/kafka/base/CoroutineDispatchers.kt | vipulyaara | 612,950,214 | false | {"Kotlin": 635130, "JavaScript": 440999, "HTML": 11959, "CSS": 7888, "Shell": 2974} | package org.kafka.base
import kotlinx.coroutines.CoroutineDispatcher
data class CoroutineDispatchers(
val io: CoroutineDispatcher,
val computation: CoroutineDispatcher,
val main: CoroutineDispatcher
)
| 5 | Kotlin | 19 | 86 | fa64a43602eecac8b93ae9e8b713f6d29ba90727 | 215 | Kafka | Apache License 2.0 |
src/main/kotlin/org/anglur/joglext/jogl2d/impl/gl2/GL2ShapeDrawer.kt | jonatino | 69,714,321 | false | {"Kotlin": 588625, "Java": 17760} | /*
* Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.anglur.joglext.jogl2d.impl.gl2
import com.jogamp.opengl.GL
import com.jogamp.opengl.GL2
import org.anglur.joglext.jogl2d.GLGraphics2D
import org.anglur.joglext.jogl2d.impl.AbstractShapeHelper
import org.anglur.joglext.jogl2d.impl.SimpleOrTesselatingVisitor
import java.awt.BasicStroke
import java.awt.RenderingHints
import java.awt.RenderingHints.Key
import java.awt.Shape
class GL2ShapeDrawer : AbstractShapeHelper() {
private lateinit var gl: GL2
private var simpleFillVisitor: FillSimpleConvexPolygonVisitor
private var complexFillVisitor: SimpleOrTesselatingVisitor
private var simpleStrokeVisitor: LineDrawingVisitor
private var fastLineVisitor: FastLineVisitor
init {
simpleFillVisitor = FillSimpleConvexPolygonVisitor()
complexFillVisitor = SimpleOrTesselatingVisitor(simpleFillVisitor, GL2TesselatorVisitor())
simpleStrokeVisitor = LineDrawingVisitor()
fastLineVisitor = FastLineVisitor()
}
override fun setG2D(g2d: GLGraphics2D) {
super.setG2D(g2d)
val gl = g2d.glContext.gl
simpleFillVisitor.setGLContext(gl)
complexFillVisitor.setGLContext(gl)
simpleStrokeVisitor.setGLContext(gl)
fastLineVisitor.setGLContext(gl)
this.gl = gl.gL2
}
override fun setHint(key: Key, value: Any?) {
super.setHint(key, value)
if (key === RenderingHints.KEY_ANTIALIASING) {
if (value === RenderingHints.VALUE_ANTIALIAS_ON) {
gl.glEnable(GL.GL_MULTISAMPLE)
} else {
gl.glDisable(GL.GL_MULTISAMPLE)
}
}
}
override fun draw(shape: Shape) {
val stroke = stroke
if (stroke is BasicStroke) {
if (fastLineVisitor.isValid(stroke)) {
fastLineVisitor.setStroke(stroke)
traceShape(shape, fastLineVisitor)
return
} else if (stroke.dashArray == null) {
simpleStrokeVisitor.setStroke(stroke)
traceShape(shape, simpleStrokeVisitor)
return
}
}
// can fall through for various reasons
fill(stroke.createStrokedShape(shape))
}
override fun fill(shape: Shape, forceSimple: Boolean)
= traceShape(shape, if (forceSimple) simpleFillVisitor else complexFillVisitor)
}
| 0 | Kotlin | 4 | 28 | b43cbe514a496e2a45b45475c0100622ea190dc0 | 2,739 | JOGL2D | Apache License 2.0 |
src/main/kotlin/hm/binkley/labs/BookController.kt | binkley | 430,991,786 | false | {"Shell": 13155, "Batchfile": 9926, "Kotlin": 8675} | package hm.binkley.labs
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Pageable.unpaged
import org.springframework.data.rest.webmvc.ResourceNotFoundException
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest/books")
@RestController
class BookController(
private val books: BookRepository,
) {
@GetMapping
fun all(pageable: Pageable = unpaged()): Iterable<Book> =
books.findAll(pageable).content
@GetMapping("{isbn}")
fun byISBN(@PathVariable isbn: String): Book = books.findById(isbn)
.orElseThrow { ResourceNotFoundException() }
}
| 8 | Shell | 0 | 1 | 90eca549c775299084bb9069870c6fb60c48bf39 | 826 | kotlin-spring-boot-hateoas-database | The Unlicense |
browser-kotlin/src/main/kotlin/org/w3c/dom/events/RTCPeerConnectionIceEvent.types.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
package org.w3c.dom.events
import org.w3c.dom.events.Event as RTCPeerConnectionIceEvent
inline val RTCPeerConnectionIceEvent.Companion.ICE_CANDIDATE: EventType<RTCPeerConnectionIceEvent>
get() = EventType("icecandidate")
| 0 | Kotlin | 5 | 13 | 0f67fb7955dc2c00a7fd18d369ea546d93fa7a92 | 272 | react-types-kotlin | Apache License 2.0 |
project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/templates/ReactJsClientTemplate.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard.templates
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.Writer
import org.jetbrains.kotlin.tools.projectWizard.core.asPath
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.TemplateSetting
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.ArtifactBasedLibraryDependencyIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.DependencyIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.DependencyType
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.ModuleIR
import org.jetbrains.kotlin.tools.projectWizard.library.MavenArtifact
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repositories
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
class ReactJsClientTemplate : JsClientTemplate() {
override val title: String = KotlinNewProjectWizardBundle.message("module.template.js.react.title")
override val description: String = KotlinNewProjectWizardBundle.message("module.template.js.react.description")
@NonNls
override val id: String = "reactJsClient"
val useStyledComponents by booleanSetting(
KotlinNewProjectWizardBundle.message("module.template.react.use.styled.components"),
GenerationPhase.PROJECT_GENERATION
) {
defaultValue = value(false)
}
val useReactRouterDom by booleanSetting(
KotlinNewProjectWizardBundle.message("module.template.react.use.react.router.dom"),
GenerationPhase.PROJECT_GENERATION
) {
defaultValue = value(false)
}
val useReactRedux by booleanSetting(
KotlinNewProjectWizardBundle.message("module.template.react.use.react.redux"),
GenerationPhase.PROJECT_GENERATION
) {
defaultValue = value(false)
}
override val settings: List<TemplateSetting<*, *>> =
listOf(
useStyledComponents,
useReactRouterDom,
useReactRedux
)
override fun Writer.getRequiredLibraries(module: ModuleIR): List<DependencyIR> = withSettingsOf(module.originalModule) {
buildList {
val kotlinVersion = KotlinPlugin.version.propertyValue
+Dependencies.KOTLIN_REACT(kotlinVersion.version)
+Dependencies.KOTLIN_REACT_DOM(kotlinVersion.version)
if (useStyledComponents.reference.settingValue) {
+Dependencies.KOTLIN_STYLED(kotlinVersion.version)
}
if (useReactRouterDom.reference.settingValue) {
+Dependencies.KOTLIN_REACT_ROUTER_DOM(kotlinVersion.version)
}
if (useReactRedux.reference.settingValue) {
+Dependencies.KOTLIN_REDUX(kotlinVersion.version)
+Dependencies.KOTLIN_REACT_REDUX(kotlinVersion.version)
}
}
}
override fun Reader.getFileTemplates(module: ModuleIR): List<FileTemplateDescriptorWithPath> =
withSettingsOf(module.originalModule) {
buildList {
val hasKtorServNeighbourTarget = hasKtorServNeighbourTarget(module)
if (!hasKtorServNeighbourTarget) {
+(FileTemplateDescriptor("jsClient/index.html.vm") asResourceOf SourcesetType.main)
}
+(FileTemplateDescriptor("$id/reactClient.kt.vm", "client.kt".asPath()) asSrcOf SourcesetType.main)
+(FileTemplateDescriptor("$id/reactComponent.kt.vm", "welcome.kt".asPath()) asSrcOf SourcesetType.main)
if (useStyledComponents.reference.settingValue) {
+(FileTemplateDescriptor("$id/WelcomeStyles.kt.vm") asSrcOf SourcesetType.main)
}
}
}
override fun Reader.getAdditionalSettings(module: Module): Map<String, Any> = withSettingsOf(module) {
mapOf("useStyledComponents" to (useStyledComponents.reference.settingValue))
}
private object Dependencies {
val KOTLIN_REACT = wrapperDependency(
"kotlin-react",
Versions.JS_WRAPPERS.KOTLIN_REACT
)
val KOTLIN_REACT_DOM = wrapperDependency(
"kotlin-react-dom",
Versions.JS_WRAPPERS.KOTLIN_REACT_DOM
)
val KOTLIN_STYLED = wrapperDependency(
"kotlin-styled",
Versions.JS_WRAPPERS.KOTLIN_STYLED
)
val KOTLIN_REACT_ROUTER_DOM = wrapperDependency(
"kotlin-react-router-dom",
Versions.JS_WRAPPERS.KOTLIN_REACT_ROUTER_DOM
)
val KOTLIN_REDUX = wrapperDependency(
"kotlin-redux",
Versions.JS_WRAPPERS.KOTLIN_REDUX
)
val KOTLIN_REACT_REDUX = wrapperDependency(
"kotlin-react-redux",
Versions.JS_WRAPPERS.KOTLIN_REACT_REDUX
)
private fun wrapperDependency(artifact: String, version: (Version) -> Version) = { kotlinVersion: Version ->
ArtifactBasedLibraryDependencyIR(
MavenArtifact(Repositories.KOTLIN_JS_WRAPPERS_BINTRAY, "org.jetbrains", artifact),
version(kotlinVersion),
DependencyType.MAIN
)
}
}
}
| 214 | null | 4829 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 6,007 | intellij-kotlin | Apache License 2.0 |
gto-support-androidx-room/src/main/kotlin/org/ccci/gto/android/common/androidx/room/RoomDatabase+Flow.kt | CruGlobal | 30,609,844 | false | {"Kotlin": 796944, "Java": 258324, "Prolog": 179} | package org.ccci.gto.android.common.androidx.room
import androidx.room.CoroutinesRoom.Companion.createFlow
import androidx.room.RoomDatabase
fun RoomDatabase.changeFlow(vararg tableName: String) = createFlow(
this,
inTransaction = false,
tableNames = arrayOf(*tableName),
callable = {}
)
| 14 | Kotlin | 2 | 9 | e0e52f257d4826f87688f3edd7ad45e732ee54a5 | 306 | android-gto-support | MIT License |
src/test/kotlin/no/nav/bidrag/stonad/service/StonadServiceMockTest.kt | navikt | 360,850,317 | false | null | package no.nav.bidrag.stonad.service
import no.nav.bidrag.behandling.felles.dto.stonad.OpprettStonadRequestDto
import no.nav.bidrag.behandling.felles.enums.Innkreving
import no.nav.bidrag.behandling.felles.enums.StonadType
import no.nav.bidrag.stonad.TestUtil.Companion.byggStonadRequest
import no.nav.bidrag.stonad.bo.PeriodeBo
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertAll
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.function.Executable
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.eq
import org.mockito.Captor
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.doNothing
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.any
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
@DisplayName("stonadServiceMockTest")
@ExtendWith(MockitoExtension::class)
class StonadServiceMockTest {
@InjectMocks
private lateinit var stonadService: StonadService
@Mock
private lateinit var persistenceServiceMock: PersistenceService
@Captor
private lateinit var opprettStonadRequestDto: ArgumentCaptor<OpprettStonadRequestDto>
@Captor
private lateinit var periodeBoCaptor: ArgumentCaptor<PeriodeBo>
@Test
fun `skal opprette ny komplett stonad`() {
Mockito.`when`(persistenceServiceMock.opprettStonad(MockitoHelper.capture(opprettStonadRequestDto)))
.thenReturn(1)
doNothing().`when`(persistenceServiceMock).opprettPeriode(MockitoHelper.capture(periodeBoCaptor), eq(1), any())
val nyStonadOpprettetStonadId = stonadService.opprettStonad(byggStonadRequest())
val stonadDto = opprettStonadRequestDto.value
val periodeDtoListe = periodeBoCaptor.allValues
Mockito.verify(persistenceServiceMock, Mockito.times(1))
.opprettStonad(MockitoHelper.any(OpprettStonadRequestDto::class.java))
/* Mockito.verify(persistenceServiceMock, Mockito.times(2))
.opprettNyPeriode(MockitoHelper.any(PeriodeBo::class.java), nyStonadOpprettetStonadId)*/
assertAll(
Executable { assertThat(nyStonadOpprettetStonadId).isNotNull() },
// Sjekk stonadDto
Executable { assertThat(stonadDto).isNotNull() },
Executable { assertThat(stonadDto.type).isEqualTo(StonadType.BIDRAG) },
Executable { assertThat(stonadDto.sakId).isEqualTo("SAK-001") },
Executable { assertThat(stonadDto.skyldnerId).isEqualTo("01018011111") },
Executable { assertThat(stonadDto.kravhaverId).isEqualTo("01010511111") },
Executable { assertThat(stonadDto.mottakerId).isEqualTo("01018211111") },
Executable { assertThat(stonadDto.opprettetAv).isEqualTo("X123456") },
Executable { assertThat(stonadDto.indeksreguleringAar).isEqualTo("2024") },
Executable { assertThat(stonadDto.innkreving).isEqualTo(Innkreving.JA) },
// Sjekk PeriodeDto
Executable { assertThat(periodeDtoListe).isNotNull() },
Executable { assertThat(periodeDtoListe.size).isEqualTo(2) },
Executable { assertThat(periodeDtoListe[0].periodeFom).isEqualTo(LocalDate.parse("2019-01-01")) },
Executable { assertThat(periodeDtoListe[0].periodeTil).isEqualTo(LocalDate.parse("2019-07-01")) },
Executable { assertThat(periodeDtoListe[0].vedtakId).isEqualTo(321) },
Executable { assertThat(periodeDtoListe[0].belop).isEqualTo(BigDecimal.valueOf(3490)) },
Executable { assertThat(periodeDtoListe[0].valutakode).isEqualTo("NOK") },
Executable { assertThat(periodeDtoListe[0].resultatkode).isEqualTo("KOSTNADSBEREGNET_BIDRAG") },
Executable { assertThat(periodeDtoListe[1].periodeFom).isEqualTo(LocalDate.parse("2019-07-01")) },
Executable { assertThat(periodeDtoListe[1].periodeTil).isEqualTo(LocalDate.parse("2020-01-01")) },
Executable { assertThat(periodeDtoListe[1].vedtakId).isEqualTo(323) },
Executable { assertThat(periodeDtoListe[1].belop).isEqualTo(BigDecimal.valueOf(3520)) },
Executable { assertThat(periodeDtoListe[1].valutakode).isEqualTo("NOK") },
Executable { assertThat(periodeDtoListe[1].resultatkode).isEqualTo("KOSTNADSBEREGNET_BIDRAG") }
)
}
object MockitoHelper {
// use this in place of captor.capture() if you are trying to capture an argument that is not nullable
fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()
fun <T> any(type: Class<T>): T = Mockito.any(type)
}
}
| 6 | Kotlin | 0 | 0 | f6e31fbcc14b71789837a54b022bbbbad7fb53cf | 4,578 | bidrag-stonad | MIT License |
app/src/main/java/dev/synople/glasstuner/NoteFinder.kt | tujson | 203,704,693 | false | null | package dev.synople.glasstuner
/**
* From https://github.com/chRyNaN/Android-Guitar-Tuner/blob/master/app/src/main/java/com/chrynan/android_guitar_tuner/tuner/note/ArrayNoteFinder.java
* Converted from Java to Kotlin
*/
class ArrayNoteFinder {
private val noteFrequencies = doubleArrayOf(
5587.65,
5274.04,
4978.03,
4698.64,
4434.92,
4186.01,
3951.07,
3729.31,
3520.00,
3322.44,
3135.96,
2959.96,
2793.83,
2637.02,
2489.02,
2349.32,
2217.46,
2093.00,
1975.53,
1864.66,
1760.00,
1661.22,
1567.98,
1479.98,
1396.91,
1318.51,
1244.51,
1174.66,
1108.73,
1046.50,
987.767,
932.328,
880.000,
830.609,
783.991,
739.989,
698.456,
659.255,
622.254,
587.330,
554.365,
523.251,
493.883,
466.164,
440.000,
415.305,
391.995,
369.994,
349.228,
329.628,
311.127,
293.665,
277.183,
261.626,
246.942,
233.082,
220.000,
207.652,
195.998,
184.997,
174.614,
164.814,
155.563,
146.832,
138.591,
130.813,
123.471,
116.541,
110.000,
103.826,
97.9989,
92.4986,
87.3071,
82.4069,
77.7817,
73.4162,
69.2957,
65.4064,
61.7354,
58.2705,
55.0000,
51.9131,
48.9994,
46.2493,
43.6535,
41.2034,
38.8909,
36.7081,
34.6478,
32.7032,
30.8677,
29.1352,
27.5000,
25.9565,
24.4997,
23.1247,
21.8268,
20.6017,
19.4454,
18.3540,
17.3239,
16.3516
)
private val noteNames = arrayOf("F", "E", "D♯", "D", "C♯", "C", "B", "A♯", "A", "G♯", "G", "F♯")
var noteName: String? = null
private set
private var percentageDifference: Float = 0.toFloat()
fun setFrequency(frequency: Double) {
val length = noteFrequencies.size
var frequencyIndex = 0
var nextClosestIndex = 0
// Iterate through the note array to find the closest indices
var i = 0
var j = 1
while (i < length && j < length) {
if (i == 0 && frequency > noteFrequencies[i]) {
frequencyIndex = 0
nextClosestIndex = 0
break
} else if (noteFrequencies[i] >= frequency && frequency > noteFrequencies[j]) {
frequencyIndex =
if (noteFrequencies[i] - frequency < frequency - noteFrequencies[j]) i else j
nextClosestIndex = if (frequencyIndex == i) j else i
break
} else if (j == length - 1) {
frequencyIndex = length - 1
nextClosestIndex = length - 1
}
i++
j++
}
// Get the name of the note
noteName = noteNames[frequencyIndex % noteNames.size]
// Get the difference
val difference = frequency - noteFrequencies[frequencyIndex]
val nextClosestFrequency = noteFrequencies[nextClosestIndex]
percentageDifference = if (difference < 0) {
((frequency - nextClosestFrequency) / (noteFrequencies[frequencyIndex] - nextClosestFrequency) * 100).toFloat()
} else {
(-((frequency - noteFrequencies[frequencyIndex]) / (nextClosestFrequency - noteFrequencies[frequencyIndex]) * 100)).toFloat()
}
if (percentageDifference < -100) {
percentageDifference = -100f
} else if (percentageDifference > 100) {
percentageDifference = 100f
}
}
}// Default public constructor | 1 | null | 1 | 1 | 4e94d046650be9b93caa1a6d52f3507272b5e87d | 4,038 | GlassTuner | Apache License 2.0 |
graph/graph-application/src/test/kotlin/eu/tib/orkg/prototype/contenttypes/services/actions/paper/PaperPublicationInfoCreatorUnitTest.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 2449567, "Cypher": 215872, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240} | package eu.tib.orkg.prototype.contenttypes.services.actions
import eu.tib.orkg.prototype.contenttypes.domain.model.PublicationInfo
import eu.tib.orkg.prototype.dummyCreatePaperCommand
import eu.tib.orkg.prototype.createLiteral
import eu.tib.orkg.prototype.createResource
import eu.tib.orkg.prototype.pageOf
import eu.tib.orkg.prototype.shared.PageRequests
import eu.tib.orkg.prototype.statements.api.Classes
import eu.tib.orkg.prototype.statements.api.CreateResourceUseCase
import eu.tib.orkg.prototype.statements.api.LiteralUseCases
import eu.tib.orkg.prototype.statements.api.Literals
import eu.tib.orkg.prototype.statements.api.Predicates
import eu.tib.orkg.prototype.statements.api.ResourceUseCases
import eu.tib.orkg.prototype.statements.api.StatementUseCases
import eu.tib.orkg.prototype.statements.domain.model.ExactSearchString
import eu.tib.orkg.prototype.statements.domain.model.ThingId
import eu.tib.orkg.prototype.statements.spi.ResourceRepository
import io.kotest.assertions.asClue
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldBeEqualIgnoringCase
import io.kotest.matchers.types.shouldBeInstanceOf
import io.mockk.clearAllMocks
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import java.net.URI
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.data.domain.Page
@Nested
class PaperPublicationInfoCreatorUnitTest {
private val resourceRepository: ResourceRepository = mockk()
private val resourceService: ResourceUseCases = mockk()
private val statementService: StatementUseCases = mockk()
private val literalService: LiteralUseCases = mockk()
private val paperPublicationInfoCreator = PaperPublicationInfoCreator(
resourceService = resourceService,
resourceRepository = resourceRepository,
statementService = statementService,
literalService = literalService
)
@BeforeEach
fun resetState() {
clearAllMocks()
}
@AfterEach
fun verifyMocks() {
confirmVerified(resourceRepository, resourceService, statementService, literalService)
}
@Test
fun `Given a paper create command, when linking empty publication info, it returns success`() {
val paperId = ThingId("R123")
val command = dummyCreatePaperCommand().copy(
publicationInfo = null
)
val state = PaperState(
paperId = paperId
)
val result = paperPublicationInfoCreator(command, state)
result.asClue {
it.tempIds.size shouldBe 0
it.validatedIds.size shouldBe 0
it.bakedStatements.size shouldBe 0
it.authors.size shouldBe 0
it.paperId shouldBe state.paperId
}
}
@Test
fun `Given a paper create command, when linking publication month, it returns success`() {
val paperId = ThingId("R123")
val month = 5
val command = dummyCreatePaperCommand().copy(
publicationInfo = PublicationInfo(
publishedMonth = month,
publishedYear = null,
publishedIn = null,
url = null
)
)
val state = PaperState(
paperId = paperId
)
val monthLiteral = createLiteral(value = month.toString())
every {
literalService.create(
userId = command.contributorId,
label = month.toString(),
datatype = Literals.XSD.INT.prefixedUri
)
} returns monthLiteral
every {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.monthPublished,
`object` = monthLiteral.id
)
} just runs
val result = paperPublicationInfoCreator(command, state)
result.asClue {
it.tempIds.size shouldBe 0
it.validatedIds.size shouldBe 0
it.bakedStatements.size shouldBe 0
it.authors.size shouldBe 0
it.paperId shouldBe state.paperId
}
verify(exactly = 1) {
literalService.create(
userId = command.contributorId,
label = month.toString(),
datatype = Literals.XSD.INT.prefixedUri
)
}
verify(exactly = 1) {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.monthPublished,
`object` = monthLiteral.id
)
}
}
@Test
fun `Given a paper create command, when linking publication year, it returns success`() {
val paperId = ThingId("R123")
val year = 5L
val command = dummyCreatePaperCommand().copy(
publicationInfo = PublicationInfo(
publishedMonth = null,
publishedYear = year,
publishedIn = null,
url = null
)
)
val state = PaperState(
paperId = paperId
)
val yearLiteral = createLiteral(value = year.toString())
every {
literalService.create(
userId = command.contributorId,
label = year.toString(),
datatype = Literals.XSD.INT.prefixedUri
)
} returns yearLiteral
every {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.yearPublished,
`object` = yearLiteral.id
)
} just runs
val result = paperPublicationInfoCreator(command, state)
result.asClue {
it.tempIds.size shouldBe 0
it.validatedIds.size shouldBe 0
it.bakedStatements.size shouldBe 0
it.authors.size shouldBe 0
it.paperId shouldBe state.paperId
}
verify(exactly = 1) {
literalService.create(
userId = command.contributorId,
label = year.toString(),
datatype = Literals.XSD.INT.prefixedUri
)
}
verify(exactly = 1) {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.yearPublished,
`object` = yearLiteral.id
)
}
}
@Test
fun `Given a paper create command, when linking existing publication venue, it returns success`() {
val paperId = ThingId("R123")
val venue = "Conference"
val command = dummyCreatePaperCommand().copy(
publicationInfo = PublicationInfo(
publishedMonth = null,
publishedYear = null,
publishedIn = venue,
url = null
)
)
val state = PaperState(
paperId = paperId
)
val venueResource = createResource(label = venue)
every {
resourceRepository.findAllByClassAndLabel(
`class` = Classes.venue,
labelSearchString = any(),
pageable = PageRequests.SINGLE
)
} returns pageOf(venueResource)
every {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.hasVenue,
`object` = venueResource.id
)
} just runs
val result = paperPublicationInfoCreator(command, state)
result.asClue {
it.tempIds.size shouldBe 0
it.validatedIds.size shouldBe 0
it.bakedStatements.size shouldBe 0
it.authors.size shouldBe 0
it.paperId shouldBe state.paperId
}
verify(exactly = 1) {
resourceRepository.findAllByClassAndLabel(
Classes.venue,
withArg {
it.shouldBeInstanceOf<ExactSearchString>()
it.input shouldBeEqualIgnoringCase venue
},
PageRequests.SINGLE
)
}
verify(exactly = 1) {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.hasVenue,
`object` = venueResource.id
)
}
}
@Test
fun `Given a paper create command, when linking non-existing publication venue, it returns success`() {
val paperId = ThingId("R123")
val venue = "Conference"
val command = dummyCreatePaperCommand().copy(
publicationInfo = PublicationInfo(
publishedMonth = null,
publishedYear = null,
publishedIn = venue,
url = null
)
)
val state = PaperState(
paperId = paperId
)
val resourceCreateCommand = CreateResourceUseCase.CreateCommand(
label = venue,
classes = setOf(Classes.venue),
contributorId = command.contributorId
)
val venueId = ThingId("R456")
every {
resourceRepository.findAllByClassAndLabel(
Classes.venue,
any(),
PageRequests.SINGLE
)
} returns Page.empty()
every { resourceService.create(resourceCreateCommand) } returns venueId
every {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.hasVenue,
`object` = venueId
)
} just runs
val result = paperPublicationInfoCreator(command, state)
result.asClue {
it.tempIds.size shouldBe 0
it.validatedIds.size shouldBe 0
it.bakedStatements.size shouldBe 0
it.authors.size shouldBe 0
it.paperId shouldBe state.paperId
}
verify(exactly = 1) {
resourceRepository.findAllByClassAndLabel(
Classes.venue,
withArg {
it.shouldBeInstanceOf<ExactSearchString>()
it.input shouldBeEqualIgnoringCase venue
},
PageRequests.SINGLE
)
}
verify(exactly = 1) { resourceService.create(resourceCreateCommand) }
verify(exactly = 1) {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.hasVenue,
`object` = venueId
)
}
}
@Test
fun `Given a paper create command, when linking publication url, it returns success`() {
val paperId = ThingId("R123")
val url = URI.create("https://orkg.org")
val command = dummyCreatePaperCommand().copy(
publicationInfo = PublicationInfo(
publishedMonth = null,
publishedYear = null,
publishedIn = null,
url = url
)
)
val state = PaperState(
paperId = paperId
)
val urlLiteral = createLiteral(value = url.toString())
every {
literalService.create(
userId = command.contributorId,
label = url.toString(),
datatype = Literals.XSD.URI.prefixedUri
)
} returns urlLiteral
every {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.hasURL,
`object` = urlLiteral.id
)
} just runs
val result = paperPublicationInfoCreator(command, state)
result.asClue {
it.tempIds.size shouldBe 0
it.validatedIds.size shouldBe 0
it.bakedStatements.size shouldBe 0
it.authors.size shouldBe 0
it.paperId shouldBe state.paperId
}
verify(exactly = 1) {
literalService.create(
userId = command.contributorId,
label = url.toString(),
datatype = Literals.XSD.URI.prefixedUri
)
}
verify(exactly = 1) {
statementService.add(
userId = command.contributorId,
subject = state.paperId!!,
predicate = Predicates.hasURL,
`object` = urlLiteral.id
)
}
}
}
| 0 | Kotlin | 2 | 5 | ce3f24748dd2d9c06e6125e033bc7ae83122925f | 13,057 | orkg-backend | MIT License |
idea/tests/testData/inspectionsLocal/simpleRedundantLet/functionCall5.kt | JetBrains | 278,369,660 | false | null | // PROBLEM: none
// WITH_RUNTIME
fun foo(s: String, i: Int) = s.length + i
fun test() {
val s = ""
s.length.let<caret> { foo("", it) }
} | 1 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 146 | intellij-kotlin | Apache License 2.0 |
twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/tweets/statuses/StatusesApi.kt | SorrowBlue | 278,215,181 | false | null | package com.sorrowblue.twitlin.tweets.statuses
import com.sorrowblue.twitlin.client.Response
import com.sorrowblue.twitlin.objects.MediaId
import com.sorrowblue.twitlin.objects.PagingIds
import com.sorrowblue.twitlin.objects.PlaceId
import com.sorrowblue.twitlin.objects.Tweet
import com.sorrowblue.twitlin.objects.TweetId
import com.sorrowblue.twitlin.objects.User
import com.sorrowblue.twitlin.objects.UserId
import kotlinx.coroutines.flow.Flow
/**
* TODO
*/
public interface StatusesApi {
/**
* Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs.
*
* The track, follow, and locations fields should be considered to be combined with an OR operator. `track=foo&follow=1234` returns Tweets matching "foo" OR created by user 1234.
*
* The default access level allows up to 400 track keywords, 5,000 follow userids and 25 0.1-360 degree location boxes. If you need access to more rules and filtering tools, please apply for [enterprise access](https://developer.twitter.com/en/enterprise).
*
* @param follow A comma separated list of user IDs, indicating the users to return statuses for in the stream. See follow for more information.
* @param track Keywords to track. Phrases of keywords are specified by a comma-separated list. See track for more information.
* @param locations Specifies a set of bounding boxes to track. See locations for more information.
* @param delimited Specifies whether messages should be length-delimited. See delimited for more information.
* @param stallWarnings Specifies whether stall warnings should be delivered. See stall_warnings for more information.
* @return
*/
public suspend fun filter(
follow: List<UserId>? = null,
track: List<String>? = null,
locations: List<Double>? = null,
delimited: Int? = null,
stallWarnings: Boolean = false
): Flow<Response<Tweet>>
/**
* Returns a collection of the most recent [Tweet] and Retweets posted by the authenticating
* user and the users they follow. The home timeline is central to how most users interact with
* the Twitter service.
*
* Up to 800 Tweets are obtainable on the home timeline. It is more volatile for users that
* follow many users or follow users who Tweet frequently.
*
* See [Working with Timelines](https://developer.twitter.com/en/docs/tweets/timelines/guides/working-with-timelines)
* for instructions on traversing timelines efficiently.
*
* @param count Specifies the number of records to retrieve. Must be less than or equal to 200.
* Defaults to 20. The value of count is best thought of as a limit to the number of tweets to
* return because suspended or deleted content is removed after the count has been applied.
* @param sinceId Returns results with an ID greater than (that is, more recent than) the
* specified ID. There are limits to the number of Tweets which can be accessed through the API.
* If the limit of Tweets has occured since the since_id, the since_id will be forced to the
* oldest ID available.
* @param maxId Returns results with an ID less than (that is, older than) or equal to the
* specified ID.
* @param trimUser When set to either `true` each Tweet returned in a timeline will include
* a [User] including only the status authors numerical ID. Omit this parameter to receive
* the complete [User].
* @param excludeReplies This parameter will prevent replies from appearing in the returned
* timeline. Using [excludeReplies] with the [count] parameter will mean you will receive up-to
* count Tweets — this is because the [count] parameter retrieves that many Tweets before
* filtering out retweets and replies.
* @param includeEntities The entities node will not be included when set to false.
* @return TODO
*/
public suspend fun homeTimeline(
count: Int = 20,
sinceId: TweetId? = null,
maxId: TweetId? = null,
trimUser: Boolean = false,
excludeReplies: Boolean = false,
includeEntities: Boolean = true
): Response<List<Tweet>>
/**
* **Important notice:** On June 19, 2019, we began enforcing a limit of 100,000 requests per
* day to the [StatusesApi.mentionsTimeline] endpoint. This is in addition to existing
* user-level rate limits (75 requests / 15-minutes). This limit is enforced on a
* per-application basis, meaning that a single developer app can make up to 100,000 calls
* during any single 24-hour period.
*
* Returns the 20 most recent mentions (Tweets containing a users's @screen_name) for the
* authenticating user.
*
* The timeline returned is the equivalent of the one seen when you view
* [your mentions](http://twitter.com/mentions) on twitter.com.
*
* This method can only return up to 800 tweets.
*
* See [Working with Timelines](https://developer.twitter.com/en/docs/tweets/timelines/guides/working-with-timelines)
* for instructions on traversing timelines.
*
* @param count Specifies the number of Tweets to try and retrieve, up to a maximum of 200.
* The value of count is best thought of as a limit to the number of tweets to return because
* suspended or deleted content is removed after the count has been applied. We include retweets
* in the count, even if `include_rts` is not supplied. It is recommended you always send
* `include_rts=1` when using this API method.
* @param sinceId Returns results with an ID greater than (that is, more recent than) the
* specified ID. There are limits to the number of Tweets which can be accessed through the API.
* If the limit of Tweets has occured since the [sinceId], the [sinceId] will be forced to the
* oldest ID available.
* @param maxId Returns results with an ID less than (that is, older than) or equal to the
* specified ID.
* @param trimUser When set to either `true` each tweet returned in a timeline will include
* a [User] including only the status authors numerical ID. Omit this parameter to receive
* the complete [User].
* @param includeEntities The entities node will not be included when set to `false`.
* @return TODO
*/
public suspend fun mentionsTimeline(
count: Int? = null,
sinceId: TweetId? = null,
maxId: TweetId? = null,
trimUser: Boolean = false,
includeEntities: Boolean = true
): Response<List<Tweet>>
/**
* **Important notice:** On June 19, 2019, we began enforcing a limit of 100,000 requests per
* day to the [StatusesApi.userTimeline] endpoint, in addition to existing user-level and
* app-level rate limits. This limit is applied on a per-application basis, meaning that a
* single developer app can make up to 100,000 calls during any single 24-hour period.
*
* Returns a collection of the most recent [Tweet] posted by the [User] indicated by the
* [screenName] or [userId] parameters.
*
* User timelines belonging to protected users may only be requested when the authenticated
* user either "owns" the timeline or is an approved follower of the owner.
*
* The timeline returned is the equivalent of the one seen as a user's profile on Twitter.
*
* This method can only return up to 3,200 of a user's most recent Tweets. Native retweets of
* other statuses by the user is included in this total, regardless of whether [includeRts] is
* set to `false` when requesting this resource.
*
* See [Working with Timelines](https://developer.twitter.com/en/docs/tweets/timelines/guides/working-with-timelines)
* for instructions on traversing timelines.
*
* See [Embedded Timelines](https://developer.twitter.com/web/embedded-timelines),
* [Embedded Tweets](https://developer.twitter.com/web/embedded-tweets), and
* [StatusesApi.oembed] for tools to render Tweets according to
* [Display Requirements](https://about.twitter.com/company/display-requirements).
*
* @param userId The ID of the user for whom to return results.
* @param screenName The screen name of the user for whom to return results.
* @param sinceId Returns results with an ID greater than (that is, more recent than) the
* specified ID. There are limits to the number of Tweets that can be accessed through the API.
* If the limit of Tweets has occured since the [sinceId], the [sinceId] will be forced to
* the oldest ID available.
* @param maxId Returns results with an ID less than (that is, older than) or equal to the
* specified ID.
* @param count Specifies the number of Tweets to try and retrieve, up to a maximum of 200 per
* distinct request. The value of count is best thought of as a limit to the number of Tweets
* to return because suspended or deleted content is removed after the count has been applied.
* We include retweets in the count, even if [includeRts] is not supplied. It is recommended you
* always send `includeRts=1` when using this API method.
* @param trimUser When set to either `true` each Tweet returned in a timeline will include a
* [User] including only the status authors numerical ID. Omit this parameter to receive the
* complete [User].
* @param excludeReplies This parameter will prevent replies from appearing in the returned
* timeline. Using [excludeReplies] with the count parameter will mean you will receive up-to
* count tweets — this is because the [count] parameter retrieves that many Tweets before
* filtering out retweets and replies.
* @param includeRts When set to `false`, the timeline will strip any native retweets
* (though they will still count toward both the maximal length of the timeline and the slice
* selected by the [count] parameter). Note: If you're using the [trimUser] parameter in
* conjunction with [includeRts], the retweets will still contain a full [User].
* @return TODO
*/
public suspend fun userTimeline(
userId: UserId? = null,
screenName: String? = null,
sinceId: TweetId? = null,
maxId: TweetId? = null,
count: Int? = null,
trimUser: Boolean = false,
excludeReplies: Boolean = false,
includeRts: Boolean = true,
): Response<List<Tweet>>
/**
* Returns fully-hydrated [Tweet] for up to 100 Tweets per request, as specified by
* comma-separated values passed to the [id] parameter.
*
* This method is especially useful to get the details (hydrate) a collection of Tweet IDs.
*
* [StatusesApi.show] is used to retrieve a single Tweet object.
*
* There are a few things to note when using this method.
*
* * You must be following a protected user to be able to see their most recent Tweets. If you
* don't follow a protected user their status will be removed.
* * The order of Tweet IDs may not match the order of Tweets in the returned array.
* * If a requested Tweet is unknown or deleted, then that Tweet will not be returned in the
* results list, unless the [map] parameter is set to `true`, in which case it will be returned
* with a value of `null`.
* * If none of your lookup criteria matches valid Tweet IDs an empty array will be returned for
* `map=false`.
* * You are strongly encouraged to use a POST for larger requests.
*
* @param id A comma separated list of Tweet IDs, up to 100 are allowed in a single request.
* @param includeEntities The entities node that may appear within embedded statuses will not be
* included when set to `false`.
* @param trimUser When set to either `true` each Tweet returned in a timeline will include a
* [User] including only the status authors numerical ID. Omit this parameter to receive the
* complete user object.
* @param map When using the map parameter, Tweets that do not exist or cannot be viewed by the
* current user will still have their key represented but with an explicitly null value paired
* with it.
* @param includeExtAltText If alt text has been added to any attached media entities, this
* parameter will return an ext_alt_text value in the top-level key for the media entity.
* If no value has been set, this will be returned as `null`.
* @param includeCardUri When set to either `true` each Tweet returned will include a card_uri
* attribute when there is an ads card attached to the Tweet and when that card was attached
* using the card_uri value.
* @return TODO
*/
public suspend fun lookup(
id: List<TweetId>,
includeEntities: Boolean = false,
trimUser: Boolean = false,
map: Boolean? = null,
includeExtAltText: Boolean? = null,
includeCardUri: Boolean = false
): Response<List<Tweet>>
/**
* Returns a single Tweet, specified by either a Tweet web URL or the Tweet ID, in an
* [oEmbed](http://oembed.com/)-compatible format. The returned HTML snippet will be
* automatically recognized as an
* [Embedded Tweet](https://developer.twitter.com/web/embedded-tweets) when
* [Twitter's widget JavaScript is included on the page](https://developer.twitter.com/web/javascript/loading).
*
* The oEmbed endpoint allows customization of the final appearance of an Embedded Tweet by
* setting the corresponding properties in HTML markup to be interpreted by Twitter's JavaScript
* bundled with the HTML response by default. The format of the returned markup may change over
* time as Twitter adds new features or adjusts its Tweet representation.
*
* The Tweet fallback markup is meant to be cached on your servers for up to the suggested cache
* lifetime specified in the [TweetOembed.cacheAge].
*
* @param url The URL of the Tweet to be embedded
* @param maxWidth The maximum width of a rendered Tweet in whole pixels. A supplied value under
* or over the allowed range will be returned as the minimum or maximum supported width
* respectively; the reset width value will be reflected in the returned [TweetOembed.width]
* property. Note that Twitter does not support the oEmbed `maxheight` parameter. Tweets are
* fundamentally text, and are therefore of unpredictable height that cannot be scaled like an
* image or video. Relatedly, the oEmbed response will not provide a value for
* [TweetOembed.height]. Implementations that need consistent heights for Tweets should refer to
* the [hideThread] and [hideMedia] parameters below.
* @param hideMedia When set to `true` links in a Tweet are not expanded to photo, video, or
* link previews.
* @param hideThread When set to `true` a collapsed version of the previous Tweet in a
* conversation thread will not be displayed when the requested Tweet is in reply to another
* Tweet.
* @param omitScript When set to `true` the `<script>` responsible for loading `widgets.js` will
* not be returned. Your webpages should include their own reference to `widgets.js` for use
* across all Twitter widgets including
* [Embedded Tweets](https://developer.twitter.com/web/embedded-tweets).
* @param align Specifies whether the embedded Tweet should be floated left, right, or center
* in the page relative to the parent element.
* @param related A comma-separated list of Twitter usernames related to your content. This
* value will be forwarded to [Tweet action intents](https://developer.twitter.com/web/intents)
* if a viewer chooses to reply, like, or retweet the embedded Tweet.
* @param lang Request returned HTML and a rendered Tweet in the specified
* [Twitter language supported by embedded Tweets](https://developer.twitter.com/web/overview/languages).
* @param theme When set to [Theme.DARK], the Tweet is displayed with light text over a dark
* background.
* @param linkColor Adjust the color of Tweet text links with a
* [hexadecimal color value](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet).
* @param widgetType Set to [WidgetType.VIDEO] to return a Twitter Video embed for the given
* Tweet.
* @param dnt When set to `true`, the Tweet and its embedded page on your site are not used for
* purposes that include
* [personalized suggestions](https://support.twitter.com/articles/20169421) and
* [personalized ads](https://support.twitter.com/articles/20170405).
* @return TDOD
*/
public suspend fun oembed(
url: String,
maxWidth: Int = 325,
hideMedia: Boolean = false,
hideThread: Boolean = false,
omitScript: Boolean = false,
align: Align = Align.NONE,
related: String? = null,
lang: String = "en",
theme: Theme = Theme.LIGHT,
linkColor: String? = null,
widgetType: WidgetType? = null,
dnt: Boolean = false
): Response<TweetOembed>
/**
* Returns a collection of up to 100 user IDs belonging to users who have retweeted the Tweet
* specified by the [id] parameter.
*
* This method offers similar data to [StatusesApi.retweets].
*
* @param id The numerical ID of the desired status.
* @param count Specifies the number of records to retrieve. Must be less than or equal to 100.
* @param cursor Causes the list of IDs to be broken into pages of no more than 100 IDs at a
* time. The number of IDs returned is not guaranteed to be 100 as suspended users are filtered
* out after connections are queried. If no cursor is provided, a value of -1 will be assumed,
* which is the first "page." The response from the API will include a
* [PagingIds.previousCursor] and [PagingIds.nextCursor] to allow paging back and forth.
* See [our cursor docs](https://developer.twitter.com/en/docs/basics/cursoring)
* for more information. While this method supports the cursor parameter, the entire result set
* can be returned in a single cursored collection. Using the [count] parameter with this method
* will not provide segmented cursors for use with this parameter.
* @return TODO
*/
@Deprecated("The endpoints replaces com.sorrowblue.twitlin.v2.tweets.TweetsApi#retweetedBy.")
public suspend fun retweetersIds(
id: TweetId,
count: Int? = null,
cursor: String = "-1"
): Response<PagingIds<TweetId>>
/**
* Returns a collection of the 100 most recent retweets of the Tweet specified by the [id]
* parameter.
*
* @param id The numerical ID of the desired status.
* @param count Specifies the number of records to retrieve. Must be less than or equal to 100.
* @param trimUser When set to either `true` each tweet returned in a timeline will include a
* [User] including only the status authors numerical ID. Omit this parameter to receive the
* complete [User].
* @return TODO
*/
public suspend fun retweets(
id: TweetId,
count: Int? = null,
trimUser: Boolean = false
): Response<List<Tweet>>
/**
* Returns the most recent Tweets authored by the authenticating user that have been retweeted
* by others. This timeline is a subset of the user's [StatusesApi.userTimeline].
*
* @param count Specifies the number of records to retrieve. Must be less than or equal to 100.
* If omitted, 20 will be assumed.
* @param sinceId Returns results with an ID greater than (that is, more recent than) the
* specified ID. There are limits to the number of Tweets which can be accessed through the API.
* If the limit of Tweets has occured since the [sinceId], the [sinceId] will be forced to the
* oldest ID available.
* @param maxId Returns results with an ID less than (that is, older than) or equal to the
* specified ID.
* @param trimUser When set to either `true` each tweet returned in a timeline will include a
* [User] including only the status authors numerical ID. Omit this parameter to receive the
* complete [User].
* @param includeEntities The tweet entities node will not be included when set to `false`.
* @param includeUserEntities The user entities node will not be included when set to `false`.
* @return TODO
*/
public suspend fun retweetsOfMe(
count: Int = 20,
sinceId: TweetId? = null,
maxId: TweetId? = null,
trimUser: Boolean = false,
includeEntities: Boolean = true,
includeUserEntities: Boolean = true
): Response<List<Tweet>>
/**
* Returns a single [Tweet], specified by the id parameter. The Tweet's author will also be
* embedded within the Tweet.
*
* See [StatusesApi.lookup] for getting Tweets in bulk (up to 100 per call). See also
* [Embedded Timelines](https://developer.twitter.com/web/embedded-timelines),
* [Embedded Tweets](https://developer.twitter.com/web/embedded-tweets), and
* [StatusesApi.oembed] for tools to render Tweets according to Display Requirements.
*
* @param id The numerical ID of the desired Tweet.
* @param trimUser When set to either `true` each Tweet returned in a timeline will include
* a user object including only the status authors numerical ID. Omit this parameter to receive
* the complete user object.
* @param includeMyRetweet When set to either `true` any Tweets returned that have been
* retweeted by the authenticating user will include an additional current_user_retweet node,
* containing the ID of the source status for the retweet.
* @param includeEntities The entities node will not be included when set to false.
* @param includeExtAltText If alt text has been added to any attached media entities, this
* parameter will return an ext_alt_text value in the top-level key for the media entity.
* If no value has been set, this will be returned as `null`.
* @param includeCardUri When set to either `true` , the retrieved Tweet will include a
* card_uri attribute when there is an ads card attached to the Tweet and when that card
* was attached using the card_uri value.
* @return TODO
*/
public suspend fun show(
id: TweetId,
trimUser: Boolean = false,
includeMyRetweet: Boolean = false,
includeEntities: Boolean = true,
includeExtAltText: Boolean? = null,
includeCardUri: Boolean = false
): Response<Tweet>
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be
* the author of the specified status. Returns the destroyed status if successful.
*
* @param id The numerical ID of the desired status.
* @param trimUser When set to either `true` each tweet returned in a timeline will include
* a user object including only the status authors numerical ID. Omit this parameter to
* receive the complete [User].
* @return TODO
*/
public suspend fun destroy(id: TweetId, trimUser: Boolean = false): Response<Tweet>
/**
* Retweets a tweet. Returns the original Tweet with Retweet details embedded.
*
* **Usage Notes:**
* * This method is subject to update limits. A HTTP 403 will be returned if this limit as been
* hit.
* * Twitter will ignore attempts to perform duplicate retweets.
* * The [Tweet.retweetCount] will be current as of when the payload is generated and may not
* reflect the exact count. It is intended as an approximation.
*
* @param id The numerical ID of the desired status.
* @param trimUser When set to either `true` each tweet returned in a timeline will include
* a [User] including only the status authors numerical ID.
* Omit this parameter to receive the complete [User].
* @return TODO
*/
@Deprecated("The endpoints replaces com.sorrowblue.twitlin.v2.users.UsersApi#retweet.")
public suspend fun retweet(id: TweetId, trimUser: Boolean = false): Response<Tweet>
/**
* Untweets a retweeted status. Returns the original Tweet with Retweet details embedded.
*
* **Usage Notes:**
* * This method is subject to update limits.
* A HTTP 429 will be returned if this limit has been hit.
* * The untweeted retweet status ID must be authored by the user backing the authentication
* token.
* * An application must have write privileges to POST. A HTTP 401 will be returned for
* read-only applications.
* * When passing a source status ID instead of the retweet status ID a HTTP 200 response will
* be returned with the same Tweet object but no action.
*
* @param id The numerical ID of the desired status.
* @param trimUser When set to either `true` each Tweet returned in a timeline will include a
* [User] including only the status authors numerical ID. Omit this parameter to receive the
* complete [User].
* @return TODO
*/
@Deprecated("The endpoints replaces com.sorrowblue.twitlin.v2.users.UsersApi#deleteRetweet.")
public suspend fun unretweet(id: TweetId, trimUser: Boolean = false): Response<Tweet>
/**
* TODO
*
* @param status
* @param inReplyToStatusId
* @param autoPopulateReplyMetadata
* @param excludeReplyUserIds
* @param attachmentUrl
* @param mediaIds
* @param possiblySensitive
* @param lat
* @param long
* @param placeId
* @param displayCoordinates
* @param trimUser
* @param enableDmcommands
* @param failDmcommands
* @param cardUri
* @return
*/
public suspend fun update(
status: String,
inReplyToStatusId: TweetId? = null,
autoPopulateReplyMetadata: Boolean = false,
excludeReplyUserIds: List<UserId>? = null,
attachmentUrl: String? = null,
mediaIds: List<MediaId>? = null,
possiblySensitive: Boolean = false,
lat: Float? = null,
long: Float? = null,
placeId: PlaceId? = null,
displayCoordinates: Boolean? = null,
trimUser: Boolean = false,
enableDmcommands: Boolean = false,
failDmcommands: Boolean = true,
cardUri: String? = null
): Response<Tweet>
public fun sample(delimited: Boolean = false, stallWarnings: Boolean = false) : Flow<Response<List<Tweet>>>
}
| 1 | Kotlin | 0 | 1 | 1052f06626feb9807285b71c75125973fbecd0e4 | 27,023 | Twitlin | MIT License |
Oxygen/core/src/main/kotlin/net/evilblock/pidgin/message/listener/MessageListenerData.kt | AndyReckt | 364,514,997 | false | {"Java": 12055418, "Kotlin": 766337, "Shell": 5518} | /*
* Copyright (c) 2020.
* Created by YoloSanta
* Created On 10/22/20, 1:23 AM
*/
package cc.fyre.stark.core.pidgin.message.listener
import java.lang.reflect.Method
/**
* A wrapper class that holds all the information needed to
* identify and execute a message function.
*
*/
data class MessageListenerData(val instance: Any, val method: Method, val id: String)
| 1 | null | 1 | 1 | 200501c7eb4aaf5709b4adceb053fee6707173fa | 373 | Old-Code | Apache License 2.0 |
auth/src/test/java/com/demo/minnies/auth/domain/LoginUserUseCaseImplTest.kt | jsonkile | 572,488,327 | false | {"Kotlin": 482538, "Java": 28720, "Shell": 1599} | package com.demo.minnies.auth.domain
import com.demo.minnies.auth.data.repos.CacheRepo
import com.demo.minnies.auth.data.repos.UserRepo
import com.demo.minnies.database.models.PartialUser
import com.demo.minnies.shared.utils.BAD_LOGIN_MESSAGE
import com.demo.minnies.shared.utils.encryption.Encryptor
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import io.mockk.junit4.MockKRule
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
internal class LoginUserUseCaseImplTest {
@get:Rule
val rule = MockKRule(this)
@MockK(relaxed = true)
lateinit var encryptor: Encryptor
@MockK
lateinit var cacheRepo: CacheRepo
@MockK(relaxed = true)
lateinit var userRepo: UserRepo
@Test
fun testLogin_BadEmail_ThrowsError() = runTest {
coEvery { userRepo.getUser("email") } returns flow { emit(null) }
val loginUserUseCase =
LoginUserUseCaseImpl(userRepo = userRepo, cacheRepo = cacheRepo, encryptor = encryptor)
Assert.assertThrows(
BAD_LOGIN_MESSAGE, IllegalStateException::class.java
) { runBlocking { loginUserUseCase.invoke("email", "") } }
}
@Test
fun testLogin_BadPassword_ThrowsError() = runTest {
coEvery { userRepo.getUser("email") } returns flow {
emit(PartialUser(fullName = "", emailAddress = "email", phoneNumber = ""))
}
coEvery { encryptor.decrypt("password") } returns "hook"
coEvery { userRepo.peekPassword("email") } returns "password"
val loginUserUseCase =
LoginUserUseCaseImpl(userRepo = userRepo, cacheRepo = cacheRepo, encryptor = encryptor)
Assert.assertThrows(
BAD_LOGIN_MESSAGE, IllegalStateException::class.java
) { runBlocking { loginUserUseCase.invoke("email", "bad_password") } }
}
@Test
fun testLogin_Successful() = runTest {
var running = true
val mockUser = PartialUser(fullName = "", emailAddress = "email", phoneNumber = "")
coEvery { userRepo.getUser("email") } returns flow {
emit(mockUser)
}
coEvery { encryptor.decrypt("password") } returns "hook"
coEvery { userRepo.peekPassword("email") } returns "password"
coEvery { cacheRepo.storeLoggedInUser(mockUser) } answers { running = running.not() }
val loginUserUseCase =
LoginUserUseCaseImpl(userRepo = userRepo, cacheRepo = cacheRepo, encryptor = encryptor)
loginUserUseCase.invoke("email", "password")
Assert.assertFalse(running)
}
} | 0 | Kotlin | 0 | 0 | ce016c05333f8a7301447f412e8d38ed46e1b2db | 2,696 | Minnies | MIT License |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/cxx/configure/NdkLocatorKtTest.kt | jomof | 502,039,754 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:>>www.apache.org>licenses>LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.cxx.configure
import com.android.build.gradle.internal.SdkHandler
import com.android.build.gradle.internal.cxx.RandomInstanceGenerator
import com.android.build.gradle.internal.cxx.caching.CachingEnvironment
import com.android.build.gradle.internal.cxx.configure.SdkSourceProperties.Companion.SdkSourceProperty.SDK_PKG_REVISION
import com.android.build.gradle.internal.cxx.logging.LoggingMessage.LoggingLevel
import com.android.build.gradle.internal.cxx.logging.LoggingMessage
import com.android.build.gradle.internal.cxx.logging.PassThroughDeduplicatingLoggingEnvironment
import com.android.build.gradle.internal.cxx.logging.ThreadLoggingEnvironment
import com.android.build.gradle.internal.cxx.logging.text
import com.android.builder.sdk.InstallFailedException
import com.android.builder.sdk.LicenceNotAcceptedException
import com.android.repository.Revision
import com.android.repository.api.RemotePackage
import com.google.common.truth.Truth.assertThat
import org.gradle.api.InvalidUserDataException
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.doThrow
import org.mockito.Mockito.mock as mock
class NdkLocatorKtTest {
class TestLoggingEnvironment : ThreadLoggingEnvironment() {
private val messages = mutableListOf<LoggingMessage>()
override fun log(message: LoggingMessage) {
messages.add(message)
}
fun errors() = messages.filter { it.level == LoggingLevel.ERROR }
fun warnings() = messages.filter { it.level == LoggingLevel.WARN }
}
@get:Rule
val temporaryFolder = TemporaryFolder()
val log = TestLoggingEnvironment()
private fun String.toSlash(): String {
return replace("/", File.separator)
}
private fun String?.toSlashFile() = if (this == null) null else File(toSlash())
private fun findNdkPath(
ndkVersionFromDsl: String?,
ndkPathFromDsl: String?,
ndkDirProperty: String?,
sdkFolder: File?,
ndkVersionedFolderNames: List<String>,
getNdkSourceProperties: (File) -> SdkSourceProperties?,
sdkHandler: SdkHandler?
) =
CachingEnvironment(temporaryFolder.newFolder()).use {
findNdkPathImpl(
ndkVersionFromDsl,
ndkPathFromDsl,
ndkDirProperty,
sdkFolder,
ndkVersionedFolderNames,
getNdkSourceProperties,
sdkHandler
)
}
@Test
fun getVersionedFolderNames() {
val versionRoot = temporaryFolder.newFolder("versionedRoot")
val v1 = versionRoot.resolve("17.1.2")
val v2 = versionRoot.resolve("18.1.2")
val f1 = versionRoot.resolve("my-file")
v1.mkdirs()
v2.mkdirs()
f1.writeText("touch")
assertThat(getNdkVersionedFolders(versionRoot)).containsExactly(
"17.1.2", "18.1.2"
)
}
@Test
fun getVersionedFolderNamesNonExistent() {
val versionRoot = "./getVersionedFolderNamesNonExistent".toSlashFile()!!
assertThat(getNdkVersionedFolders(versionRoot).toList()).isEmpty()
}
@Test
fun getNdkVersionInfoNoFolder() {
val versionRoot = "./non-existent-folder".toSlashFile()!!
assertThat(getNdkVersionInfo(versionRoot)).isNull()
}
@Test
fun `non-existing ndkPath without NDK version in DSL (bug 129789776)`() {
val path =
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> null
"/my/ndk/environment-folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun `non-existing ndkPath without NDK version in DSL and with side-by-side versions available (bug 129789776)`() {
val path =
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.00000", "18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
"/my/sdk/folder/ndk/18.1.00000".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.00000"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun `same version in legacy folder and side-by-side folder (bug 129488603)`() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.00000", "18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
"/my/sdk/folder/ndk-bundle".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkNotConfigured() {
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(log.errors()).hasSize(0) // Only expect a warning
}
@Test
fun ndkPathPropertyLocationDoesntExist() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationExists() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/ndk/folder".toSlashFile())
}
@Test
fun `ndkPath properties has -rc2 in version and ndkVersion exists`() {
val ndk = findNdkPath(
ndkVersionFromDsl = "21.0.6011959-rc2",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "21.0.6011959-rc2"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
assertThat(ndk?.ndk?.path).isEqualTo("/my/ndk/folder".toSlash())
}
@Test
fun `ndk dir properties has -rc2 in version`() {
val path = findNdkPath(
ndkVersionFromDsl = "21.0.6011959-rc2",
ndkPathFromDsl = null,
ndkDirProperty = "/my/ndk/folder".toSlash(),
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "21.0.6011959-rc2"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/ndk/folder".toSlashFile())
}
@Test
fun nonExistingNdkPathWithNdkVersionInDsl() {
findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> null
"/my/ndk/environment-folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
}
@Test
fun sdkFolderNdkBundleExists() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk-bundle".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION
)
)
else -> null
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/sdk/folder/ndk-bundle".toSlashFile())
}
@Test
fun `no version specified by user and only old ndk available (bug 148189425) download fails`() {
try {
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(SDK_PKG_REVISION.key to "18.1.23456")
)
else -> null
}
},
sdkHandler = null
)
} catch (e: InvalidUserDataException) {
assertThat(log.errors()).hasSize(0)
assertThat(log.warnings()).hasSize(0)
assertThat(e.message).contains("NDK not configured.")
return
}
assertThat(false).named("Expected an InvalidUserDataException")
}
@Test
fun `download fails with LicenceNotAcceptedException thrown`() {
val existingNdk = "18.1.23456"
val sdkFolder = "/my/sdk/folder"
val sourceProperties = mapOf(
"/my/sdk/folder/ndk/$existingNdk".toSlash() to
SdkSourceProperties(mapOf(SDK_PKG_REVISION.key to existingNdk))
)
val sdkHandler = mock(SdkHandler::class.java)
val pkg = mock(RemotePackage::class.java)
doThrow(RuntimeException(
LicenceNotAcceptedException(sdkFolder.toSlashFile()!!.toPath(), listOf(pkg))))
.`when`(sdkHandler)
.installNdk(Revision.parseRevision(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION))
try {
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = File(sdkFolder),
ndkVersionedFolderNames = listOf(existingNdk),
getNdkSourceProperties = { path -> sourceProperties[path.path] },
sdkHandler = sdkHandler
)!!
} catch(e: Exception) {
// Expect that SdkHandler#installNdk() converted LicenceNotAcceptedException to
// RuntimeException
assertThat(e.cause is LicenceNotAcceptedException)
.named("${e.cause} is not of the expected type")
.isTrue()
return
}
fail("Expected exception")
}
@Test
fun `download fails with InstallFailedException thrown`() {
val existingNdk = "18.1.23456"
val sdkFolder = "/my/sdk/folder"
val sourceProperties = mapOf(
"/my/sdk/folder/ndk/$existingNdk".toSlash() to
SdkSourceProperties(mapOf(SDK_PKG_REVISION.key to existingNdk))
)
val sdkHandler = mock(SdkHandler::class.java)
val pkg = mock(RemotePackage::class.java)
doThrow(RuntimeException(
InstallFailedException(sdkFolder.toSlashFile()!!.toPath(), listOf(pkg))))
.`when`(sdkHandler)
.installNdk(Revision.parseRevision(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION))
try {
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = File(sdkFolder),
ndkVersionedFolderNames = listOf(existingNdk),
getNdkSourceProperties = { path -> sourceProperties[path.path] },
sdkHandler = sdkHandler
)!!
} catch(e: Exception) {
// Expect that SdkHandler#installNdk() converted InstallFailedException to
// RuntimeException
assertThat(e.cause is InstallFailedException)
.named("${e.cause} is not of the expected type")
.isTrue()
return
}
fail("Expected exception")
}
@Test
fun `download fails with null returned`() {
val existingNdk = "18.1.23456"
val sdkFolder = "/my/sdk/folder"
val sourceProperties = mapOf(
"/my/sdk/folder/ndk/$existingNdk".toSlash() to
SdkSourceProperties(mapOf(SDK_PKG_REVISION.key to existingNdk))
)
val sdkHandler = mock(SdkHandler::class.java)
doReturn(null)
.`when`(sdkHandler)
.installNdk(Revision.parseRevision(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION))
try {
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = File(sdkFolder),
ndkVersionedFolderNames = listOf(existingNdk),
getNdkSourceProperties = { path -> sourceProperties[path.path] },
sdkHandler = sdkHandler
)!!
} catch(e: InvalidUserDataException) {
// Expect an NDK not configured exception
assertThat(e.message).contains("NDK not configured.")
return
}
fail("Expected exception")
}
@Test
fun `no version specified by user and only old ndk available download succeeds`() {
val existingNdk = "18.1.23456"
val sourceProperties = mutableMapOf(
"/my/sdk/folder/ndk/$existingNdk".toSlash() to
SdkSourceProperties(mapOf(SDK_PKG_REVISION.key to existingNdk))
)
val sdkHandler = mock(SdkHandler::class.java)
doReturn(
"/my/sdk/folder/ndk/$ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION".toSlashFile())
.`when`(sdkHandler)
.installNdk(Revision.parseRevision(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION))
val ndk =
findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = File("/my/sdk/folder"),
ndkVersionedFolderNames = listOf(existingNdk),
getNdkSourceProperties = { path -> sourceProperties[path.path] },
sdkHandler = sdkHandler
)!!
assertThat(ndk.ndk)
.isEqualTo("/my/sdk/folder/ndk/$ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION".toSlashFile())
assertThat(log.errors()).hasSize(0)
assertThat(log.warnings()).hasSize(0)
}
@Test
fun `version specified by user and only old ndk available (bug 148189425)`() {
val path = findNdkPath(
ndkVersionFromDsl = "18.9.99999",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(SDK_PKG_REVISION.key to "18.1.23456")
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isEqualTo(null)
assertThat(log.errors()).hasSize(0)
assertThat(log.warnings()).hasSize(0)
}
@Test
fun ndkNotConfiguredWithDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(0) // Only expect a warning
}
@Test
fun `ndk rc configured with space-rc1 version in DSL`() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456 rc1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456 rc1"
)
)
else -> null
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/sdk/folder/ndk/18.1.23456".toSlashFile())
}
@Test
fun `ndk rc configured with dash-rc1 version in DSL`() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456-rc1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456 rc1"
)
)
else -> null
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/sdk/folder/ndk/18.1.23456".toSlashFile())
}
@Test
fun ndkPathPropertyLocationDoesntExistWithDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationExistsWithDslVersion() {
val ndk = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
assertThat(ndk?.ndk?.path).isEqualTo("/my/ndk/folder".toSlash())
}
@Test
fun ndkDirPropertyLocationExistsWithDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = "/my/ndk/folder".toSlash(),
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)!!.ndk
if (log.errors().isNotEmpty()) throw Exception(log.errors()[0].text())
assertThat(path).isEqualTo("/my/ndk/folder".toSlashFile())
}
@Test
fun sdkFolderNdkBundleExistsWithDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk-bundle".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/sdk/folder/ndk-bundle".toSlashFile())
}
@Test
fun ndkNotConfiguredWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(0) // Only expect a warning
}
@Test
fun ndkPathPropertyLocationDoesntExistWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationExistsWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/ndk/folder".toSlashFile())
}
@Test
fun sdkFolderNdkBundleExistsWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = null,
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf(ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/$ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION".toSlash()
-> SdkSourceProperties(mapOf(SDK_PKG_REVISION.key to ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION))
else -> null
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/sdk/folder/ndk/$ANDROID_GRADLE_PLUGIN_FIXED_DEFAULT_NDK_VERSION".toSlashFile())
}
@Test
fun ndkNotConfiguredWithDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(0) // Only expect a warning
}
@Test
fun ndkPathPropertyLocationDoesntExistWithDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationExistsWithDslVersionWithVersionedNdk() {
val ndk = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
assertThat(ndk?.ndk?.path).isEqualTo("/my/ndk/folder".toSlash())
}
@Test
fun ndkDirPropertyLocationExistsWithDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = "/my/ndk/folder".toSlash(),
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/ndk/folder".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/ndk/folder".toSlashFile())
}
@Test
fun sdkFolderNdkBundleExistsWithDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)!!.ndk
assertThat(path).isEqualTo("/my/sdk/folder/ndk/18.1.23456".toSlashFile())
}
@Test
fun multipleMatchingVersions1() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456", "18.1.99999"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
"/my/sdk/folder/ndk/18.1.99999".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.99999"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun multipleMatchingVersions2() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.00000", "18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
"/my/sdk/folder/ndk/18.1.00000".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.00000"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkNotConfiguredWithWrongDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "17.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(0) // Only expect a warning
}
@Test
fun ndkPathPropertyLocationDoesntExistWithWrongDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "17.1.23456",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun sdkFolderNdkBundleExistsWithWrongDslVersion() {
val path =
findNdkPath(
ndkVersionFromDsl = "17.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk-bundle".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkNotConfiguredWithWrongDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "17.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(0) // Only expect a warning
}
@Test
fun ndkPathPropertyLocationDoesntExistWithWrongDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "17.1.23456",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun sdkFolderNdkBundleExistsWithWrongDslVersionWithVersionedNdk() {
val path =
findNdkPath(
ndkVersionFromDsl = "17.1.23456",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun unparseableNdkVersionFromDsl() {
val path =
findNdkPath(
ndkVersionFromDsl = "17.1.unparseable",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(1)
// The test SingleVariantSyncIntegrationTest#testProjectSyncIssuesAreCorrectlyReported
// checks for this exact message. If you need to change this here then you'll also
// have to change it there
assertThat(log.errors().single().message)
.isEqualTo("Requested NDK version '17.1.unparseable' could not be parsed")
}
@Test
fun ndkNotConfiguredWithTwoPartDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationDoesntExistWithTwoPartDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun sdkFolderNdkBundleExistsWithTwoPartDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk-bundle".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkNotConfiguredWithTwoPartDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationDoesntExistWithTwoPartDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun sdkFolderNdkBundleExistsWithTwoPartDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18.1",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isEqualTo(null)
assertThat(path).isNull()
}
@Test
fun ndkNotConfiguredWithOnePartDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationDoesntExistWithOnePartDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun sdkFolderNdkBundleExistsWithOnePartDslVersion() {
val path = findNdkPath(
ndkVersionFromDsl = "18",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf(),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk-bundle".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> throw RuntimeException(path.path)
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkNotConfiguredWithOnePartDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun ndkPathPropertyLocationDoesntExistWithOnePartDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18",
ndkPathFromDsl = "/my/ndk/folder".toSlash(),
ndkDirProperty = null,
sdkFolder = null,
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { null },
sdkHandler = null
)
assertThat(path).isNull()
assertThat(path).isNull()
}
@Test
fun sdkFolderNdkBundleExistsWithOnePartDslVersionWithVersionedNdk() {
val path = findNdkPath(
ndkVersionFromDsl = "18",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
}
@Test
fun `from fuzz, blank ndkVersionFromDsl`() {
val path = findNdkPath(
ndkVersionFromDsl = "",
ndkPathFromDsl = null,
ndkDirProperty = null,
sdkFolder = "/my/sdk/folder".toSlashFile(),
ndkVersionedFolderNames = listOf("18.1.23456"),
getNdkSourceProperties = { path ->
when (path.path) {
"/my/sdk/folder/ndk/18.1.23456".toSlash() -> SdkSourceProperties(
mapOf(
SDK_PKG_REVISION.key to "18.1.23456"
)
)
else -> null
}
},
sdkHandler = null
)
assertThat(path).isNull()
assertThat(log.errors()).hasSize(0) // No NDK found is supposed to be warning
}
@Test
fun `fuzz test`() {
RandomInstanceGenerator().apply {
PassThroughDeduplicatingLoggingEnvironment().use {
for (i in 0..10000) {
val veryOldVersion = "10.1.2"
val properVersion = "18.1.23456"
val properSdkPath = "/my/sdk/folder"
val properNdkPath = "$properSdkPath/ndk/$properVersion"
val properLegacyNdkPath = "$properSdkPath/ndk-bundle"
fun interestingString() = oneOf(
{ nullableString() },
{ "16" },
{ veryOldVersion },
{ "17.1" },
{ "17.1.2" },
{ properVersion },
{ properNdkPath },
{ "/my/sdk/folder/ndk/17.1.2" },
{ "/my/sdk/folder" },
{ SDK_PKG_REVISION.key })
fun pathToNdk() = oneOf({ properNdkPath },
{ properLegacyNdkPath },
{ null },
{ interestingString() })
fun pathToSdk() = oneOf({ properSdkPath }, { null }, { interestingString() })
fun ndkVersion() = oneOf({ properVersion },
{ veryOldVersion },
{ null },
{ interestingString() })
fun ndkVersionList() = makeListOf { ndkVersion() }.filterNotNull()
fun sourcePropertyVersionKey() = oneOf({ SDK_PKG_REVISION.key },
{ SDK_PKG_REVISION.key },
{ null },
{ interestingString() })
findNdkPath(
ndkVersionFromDsl = ndkVersion(),
ndkPathFromDsl = pathToNdk(),
ndkDirProperty = null,
sdkFolder = pathToSdk().toSlashFile(),
ndkVersionedFolderNames = ndkVersionList(),
getNdkSourceProperties = { path ->
when (path.path) {
pathToNdk() -> SdkSourceProperties(
mapOf(
(sourcePropertyVersionKey() ?: "") to (ndkVersion() ?: "")
)
)
else -> null
}
},
sdkHandler = null
)
}
}
}
}
}
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 48,532 | CppBuildCacheWorkInProgress | Apache License 2.0 |
src/main/kotlin/me/enderkill98/testserverstuff/TestserverStuff.kt | EnderKill98 | 589,659,407 | false | null | package me.enderkill98.testserverstuff
import me.enderkill98.testserverstuff.commands.SettingsCommand
import me.enderkill98.testserverstuff.listeners.HumanMovementListener
import me.enderkill98.testserverstuff.listeners.JoinListener
import me.enderkill98.testserverstuff.listeners.MovementListener
import me.enderkill98.testserverstuff.listeners.TeleportListener
import org.bukkit.Bukkit
import org.bukkit.plugin.java.JavaPlugin
class TestserverStuff: JavaPlugin() {
companion object {
@JvmStatic lateinit var INSTANCE: TestserverStuff
const val PREFIX = "§6TestserverStuff §8§l| §f"
}
override fun onEnable() {
INSTANCE = this
getCommand("settings")?.setExecutor(SettingsCommand())
Bukkit.getPluginManager().registerEvents(JoinListener(), this)
Bukkit.getPluginManager().registerEvents(HumanMovementListener(), this)
Bukkit.getPluginManager().registerEvents(MovementListener(), this)
Bukkit.getPluginManager().registerEvents(TeleportListener(), this)
}
} | 0 | Kotlin | 0 | 0 | 7386734e2a5d19d43576a3b90a03c6ad1d77b7fd | 1,042 | TestserverStuff | MIT License |
ktor-client/ktor-client-core/common/src/io/ktor/client/features/HttpPlainText.kt | LloydFinch | 166,520,021 | false | null | package io.ktor.client.features
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.response.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import kotlinx.io.charsets.*
import kotlinx.io.core.*
/**
* [HttpClient] feature that encodes [String] request bodies to [TextContent]
* using a specific charset defined at [HttpPlainText.defaultCharset].
* And also processes the response body as [String].
*
* NOTE: the [HttpPlainText.defaultCharset] is the default one for your JVM so can change between servers!
* So please, specify one if you want consistent results in all your deployments.
*/
class HttpPlainText(var defaultCharset: Charset) {
internal suspend fun read(response: HttpResponse): String = response.use {
it.readText(charset = defaultCharset)
}
class Config {
var defaultCharset: Charset = Charsets.UTF_8
internal fun build(): HttpPlainText = HttpPlainText(defaultCharset)
}
companion object Feature : HttpClientFeature<Config, HttpPlainText> {
override val key = AttributeKey<HttpPlainText>("HttpPlainText")
override fun prepare(block: Config.() -> Unit): HttpPlainText = Config().apply(block).build()
override fun install(feature: HttpPlainText, scope: HttpClient) {
scope.requestPipeline.intercept(HttpRequestPipeline.Render) { content ->
if (content !is String) return@intercept
val contentType = ContentType.Text.Plain.withCharset(feature.defaultCharset)
proceedWith(TextContent(content, contentType))
}
scope.responsePipeline.intercept(HttpResponsePipeline.Parse) { (info, response) ->
if (info.type != String::class || response !is HttpResponse) return@intercept
proceedWith(HttpResponseContainer(info, feature.read(response)))
}
}
}
}
| 0 | null | 0 | 2 | 9b9fc6c3b853c929a806c65cf6bf7c104b4c07fc | 1,939 | ktor | Apache License 2.0 |
rulebook-ktlint/src/main/kotlin/com/hendraanggrian/rulebook/ktlint/RulebookRuleSet.kt | hendraanggrian | 556,969,715 | false | {"Kotlin": 142902, "Java": 3716, "Groovy": 171} | package com.hendraanggrian.rulebook.ktlint
import com.pinterest.ktlint.cli.ruleset.core.api.RuleSetProviderV3
import com.pinterest.ktlint.rule.engine.core.api.RuleProvider
public class RulebookRuleSet : RuleSetProviderV3(RulebookRule.ID) {
override fun getRuleProviders(): Set<RuleProvider> =
setOf(
RuleProvider { BlockCommentSpacingRule() },
RuleProvider { BlockTagPunctuationRule() },
RuleProvider { BlockTagsInitialSpacingRule() },
RuleProvider { ConstructorPositionRule() },
RuleProvider { EmptyBlockWrappingRule() },
RuleProvider { ExceptionThrowingRule() },
RuleProvider { FileInitialWrappingRule() },
RuleProvider { FileSizeLimitationRule() },
RuleProvider { FunctionExpressionRule() },
RuleProvider { GenericsNamingRule() },
RuleProvider { IfStatementNestingRule() },
RuleProvider { KotlinApiConsistencyRule() },
RuleProvider { ObjectsComparisonRule() },
RuleProvider { PropertyIdiomaticNamingRule() },
RuleProvider { QualifierRedundancyRule() },
RuleProvider { SourceAcronymCapitalizationRule() },
RuleProvider { SourceWordMeaningRule() },
RuleProvider { StaticClassPositionRule() },
RuleProvider { StringInterpolationRule() },
RuleProvider { SwitchStatementWrappingRule() },
RuleProvider { TodoCommentFormattingRule() },
)
}
| 0 | Kotlin | 0 | 1 | e268190f7ce7b4721105e566ee1b6b8e91fdc4c3 | 1,510 | rulebook | Apache License 2.0 |
platform/lib/sdk/src/main/kotlin/io/hamal/lib/sdk/ApiSdk.kt | hamal-io | 622,870,037 | false | {"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118} | package io.hamal.lib.sdk
import io.hamal.lib.http.HttpTemplate
import io.hamal.lib.sdk.api.*
interface ApiSdk {
val account: ApiAccountService
val auth: AuthService
val adhoc: ApiAdhocService
val await: ApiAwaitService
val exec: ApiExecService
val execLog: ApiExecLogService
val func: ApiFuncService
val group: ApiGroupService
val namespace: ApiNamespaceService
val topic: ApiTopicService
val trigger: ApiTriggerService
}
data class ApiSdkImpl(
val template: HttpTemplate
) : ApiSdk {
override val account: ApiAccountService by lazy {
ApiAccountServiceImpl(template)
}
override val adhoc: ApiAdhocService by lazy {
ApiAdhocServiceImpl(template)
}
override val auth: AuthService by lazy {
ApiAuthServiceImpl(template)
}
override val await: ApiAwaitService by lazy {
ApiAwaitServiceImpl(template)
}
override val exec: ApiExecService by lazy {
ApiExecServiceImpl(template)
}
override val execLog: ApiExecLogService by lazy {
ApiExecLogServiceImpl(template)
}
override val func: ApiFuncService by lazy {
ApiFuncServiceImpl(template)
}
override val group: ApiGroupService by lazy {
ApiGroupServiceImpl(template)
}
override val namespace: ApiNamespaceService by lazy {
ApiNamespaceServiceImpl(template)
}
override val topic: ApiTopicService by lazy {
ApiTopicServiceImpl(template)
}
override val trigger: ApiTriggerService by lazy {
ApiTriggerServiceImpl(template)
}
} | 6 | Kotlin | 0 | 0 | 6c7f5cc645ba67fb85df20d9a5d2e18372a012f4 | 1,600 | hamal | Creative Commons Zero v1.0 Universal |
platform/lib/sdk/src/main/kotlin/io/hamal/lib/sdk/ApiSdk.kt | hamal-io | 622,870,037 | false | {"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118} | package io.hamal.lib.sdk
import io.hamal.lib.http.HttpTemplate
import io.hamal.lib.sdk.api.*
interface ApiSdk {
val account: ApiAccountService
val auth: AuthService
val adhoc: ApiAdhocService
val await: ApiAwaitService
val exec: ApiExecService
val execLog: ApiExecLogService
val func: ApiFuncService
val group: ApiGroupService
val namespace: ApiNamespaceService
val topic: ApiTopicService
val trigger: ApiTriggerService
}
data class ApiSdkImpl(
val template: HttpTemplate
) : ApiSdk {
override val account: ApiAccountService by lazy {
ApiAccountServiceImpl(template)
}
override val adhoc: ApiAdhocService by lazy {
ApiAdhocServiceImpl(template)
}
override val auth: AuthService by lazy {
ApiAuthServiceImpl(template)
}
override val await: ApiAwaitService by lazy {
ApiAwaitServiceImpl(template)
}
override val exec: ApiExecService by lazy {
ApiExecServiceImpl(template)
}
override val execLog: ApiExecLogService by lazy {
ApiExecLogServiceImpl(template)
}
override val func: ApiFuncService by lazy {
ApiFuncServiceImpl(template)
}
override val group: ApiGroupService by lazy {
ApiGroupServiceImpl(template)
}
override val namespace: ApiNamespaceService by lazy {
ApiNamespaceServiceImpl(template)
}
override val topic: ApiTopicService by lazy {
ApiTopicServiceImpl(template)
}
override val trigger: ApiTriggerService by lazy {
ApiTriggerServiceImpl(template)
}
} | 6 | Kotlin | 0 | 0 | 6c7f5cc645ba67fb85df20d9a5d2e18372a012f4 | 1,600 | hamal | Creative Commons Zero v1.0 Universal |
core/graph/impl/src/main/kotlin/bindings/InjectConstructorProvisionBindingImpl.kt | yandex | 570,094,802 | false | null | /*
* Copyright 2022 Yandex LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yandex.yatagan.core.graph.impl.bindings
import com.yandex.yatagan.core.graph.BindingGraph
import com.yandex.yatagan.core.graph.bindings.Binding
import com.yandex.yatagan.core.graph.bindings.ProvisionBinding
import com.yandex.yatagan.core.graph.impl.NonStaticConditionDependencies
import com.yandex.yatagan.core.graph.impl.VariantMatch
import com.yandex.yatagan.core.model.InjectConstructorModel
import com.yandex.yatagan.core.model.NodeDependency
import com.yandex.yatagan.core.model.isNever
import com.yandex.yatagan.validation.MayBeInvalid
import com.yandex.yatagan.validation.Validator
import com.yandex.yatagan.validation.format.append
import com.yandex.yatagan.validation.format.bindingModelRepresentation
internal class InjectConstructorProvisionBindingImpl(
private val impl: InjectConstructorModel,
override val owner: BindingGraph,
) : ProvisionBinding, ConditionalBindingMixin, ComparableByTargetBindingMixin {
override val target get() = impl.asNode()
override val originModule: Nothing? get() = null
override val scopes get() = impl.scopes
override val provision get() = impl.constructor
override val inputs: List<NodeDependency> get() = impl.inputs
override val requiresModuleInstance: Boolean = false
override val variantMatch: VariantMatch by lazy { VariantMatch(impl, owner.variant) }
override val checkDependenciesConditionScope: Boolean
get() = true
override val dependencies by lazy(LazyThreadSafetyMode.PUBLICATION) {
if (conditionScope.isNever) emptySequence() else impl.inputs.asSequence()
}
override val nonStaticConditionDependencies by lazy {
NonStaticConditionDependencies(this@InjectConstructorProvisionBindingImpl)
}
override fun validate(validator: Validator) {
super.validate(validator)
validator.inline(impl)
}
override fun <R> accept(visitor: Binding.Visitor<R>): R {
return visitor.visitProvision(this)
}
override fun toString(childContext: MayBeInvalid?) = bindingModelRepresentation(
modelClassName = "inject-constructor",
representation = { append(impl.constructor.constructee) },
childContext = childContext,
)
} | 12 | Kotlin | 7 | 188 | 7939201efc0db11a74759c54146491fd336782ee | 2,812 | yatagan | Apache License 2.0 |
anrs/anrs-impl/src/main/java/com/duckduckgo/app/anr/RealAnrRepository.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.app.anr
import com.duckduckgo.anrs.api.Anr
import com.duckduckgo.anrs.api.AnrRepository
import com.duckduckgo.app.anrs.store.AnrEntity
import com.duckduckgo.app.anrs.store.AnrsDatabase
import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
@ContributesBinding(AppScope::class)
class RealAnrRepository @Inject constructor(private val anrDatabase: AnrsDatabase) : AnrRepository {
override fun getAllAnrs(): List<Anr> {
return anrDatabase.arnDao().getAnrs().asAnrs()
}
override fun peekMostRecentAnr(): Anr? {
return anrDatabase.arnDao().latestAnr()?.asAnr()
}
override fun removeMostRecentAnr(): Anr? {
return anrDatabase.arnDao().latestAnr()?.let { entity ->
anrDatabase.arnDao().deleteAnr(entity.hash)
entity
}?.asAnr()
}
}
private fun AnrEntity.asAnr(): Anr {
return Anr(
message = message,
name = name,
file = file,
lineNumber = lineNumber,
stackTrace = stackTrace,
timestamp = timestamp,
webView = webView,
customTab = customTab,
)
}
private fun List<AnrEntity>.asAnrs(): List<Anr> {
val anrs = mutableListOf<Anr>()
forEach { anrEntity ->
anrs.add(anrEntity.asAnr())
}
return anrs
}
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 1,364 | DuckDuckGo | Apache License 2.0 |
part-02/src/test/kotlin/eu/luminis/workshop/smallsteps/api/LegoRentingRoutesTest.kt | nkrijnen | 557,352,579 | false | {"Kotlin": 49450} | package eu.luminis.workshop.smallsteps.api
import eu.luminis.workshop.smallsteps.api.helper.TestLegoStockRepository
import eu.luminis.workshop.smallsteps.api.helper.setupLegoTestApp
import eu.luminis.workshop.smallsteps.logic.domainService.helper.LegoStockHelper.millenniumFalcon
import eu.luminis.workshop.smallsteps.logic.domainService.helper.TestUsers
import eu.luminis.workshop.smallsteps.logic.domainService.state.StockState
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.Test
import kotlin.test.assertEquals
internal class LegoRentingRoutesTest {
@Test
fun `should handle typical reserve and ship flow`() = testApplication {
// given
val stockRepository = TestLegoStockRepository(
StockState(
availableStock = mapOf(
millenniumFalcon to 3
)
)
)
val client = setupLegoTestApp(stockRepository)
// when
client.callReserve()
// then
stockRepository.assertStockState(
StockState(
availableStock = mapOf(millenniumFalcon to 2),
reserved = setOf(millenniumFalcon to TestUsers.harry),
)
)
// and when
client.callShip()
// then
stockRepository.assertStockState(
StockState(
availableStock = mapOf(millenniumFalcon to 2),
reserved = emptySet(),
atBuilder = listOf(millenniumFalcon to TestUsers.harry),
)
)
}
}
private suspend fun HttpClient.callReserve() {
post("/renting/legoset/$millenniumFalcon/reserve") {
header("X-API-GATEWAY-AUTH", "${TestUsers.harry}")
header("X-SELECTED-LEGO-STORE", "${TestUsers.bussum}")
}.apply {
assertEquals(HttpStatusCode.NoContent, status)
assertEquals("Lego set has been reserved", bodyAsText())
}
}
private suspend fun HttpClient.callShip() {
post("/renting/legoset/$millenniumFalcon/ship/${TestUsers.harry}") {
header("X-API-GATEWAY-AUTH", "${TestUsers.bussum}")
header("X-SELECTED-LEGO-STORE", "${TestUsers.bussum}")
}.apply {
assertEquals(HttpStatusCode.NoContent, status)
assertEquals("Shipment registered", bodyAsText())
}
}
| 0 | Kotlin | 1 | 0 | 2d168640126c39d2a13d5dc85d05cd6ab534b6d1 | 2,402 | workshop-ddd-nl-2022-11 | MIT License |
domain/src/main/java/com/mashup/healthyup/domain/usecase/GetUserUseCase.kt | YuChocopie | 422,711,993 | true | {"Kotlin": 28999} | /*
* Created by Leo on 2021. 09. 26 ..
*/
package com.mashup.healthyup.domain.usecase
import com.mashup.healthyup.domain.Result
import com.mashup.healthyup.domain.entity.User
import com.mashup.healthyup.domain.repository.UserRepository
import kotlinx.coroutines.CoroutineDispatcher
class GetUserUseCase(
private val userRepository: UserRepository,
private val dispatcher: CoroutineDispatcher
) : ParameterizedUseCase<Long, User>(dispatcher) {
override suspend fun execute(userId: Long): Result<User> {
return userRepository.getUser(userId)
}
}
| 0 | null | 0 | 0 | 5d45f4ad84ac6ac2abec90c6e05c04817dde348d | 577 | HellTaBus_Android | MIT License |
dd-sdk-android/src/test/kotlin/com/datadog/android/core/internal/utils/ViewUtilsTest.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.rum.internal.utils
import android.content.ComponentName
import androidx.navigation.ActivityNavigator
import androidx.navigation.fragment.DialogFragmentNavigator
import androidx.navigation.fragment.FragmentNavigator
import com.datadog.android.rum.utils.forge.Configurator
import fr.xgouchet.elmyr.annotation.StringForgery
import fr.xgouchet.elmyr.junit5.ForgeConfiguration
import fr.xgouchet.elmyr.junit5.ForgeExtension
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.extension.Extensions
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.junit.jupiter.MockitoSettings
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.mockito.quality.Strictness
@Extensions(
ExtendWith(MockitoExtension::class),
ExtendWith(ForgeExtension::class)
)
@MockitoSettings(strictness = Strictness.LENIENT)
@ForgeConfiguration(Configurator::class)
internal class ViewUtilsTest {
@Test
fun `M return class name W resolveViewUrl() {FragmentNavigator}`(
@StringForgery name: String
) {
// Given
val destination = mock<FragmentNavigator.Destination>().apply {
whenever(className) doReturn name
}
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo(name)
}
@Test
fun `M return class name W resolveViewUrl() {DialogFragmentNavigator}`(
@StringForgery name: String
) {
// Given
val destination = mock<DialogFragmentNavigator.Destination>().apply {
whenever(className) doReturn name
}
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo(name)
}
@Test
fun `M return class name W resolveViewUrl() {ActivityNavigator}`(
@StringForgery packageName: String,
@StringForgery name: String
) {
// Given
val destination = mock<ActivityNavigator.Destination>().apply {
whenever(component) doReturn ComponentName(packageName, name)
}
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo("$packageName.$name")
}
@Test
fun `M return class name W resolveViewUrl() {ActivityNavigator redundant package}`(
@StringForgery packageName: String,
@StringForgery name: String
) {
// Given
val fullClassName = "$packageName.$name"
val destination = mock<ActivityNavigator.Destination>().apply {
whenever(component) doReturn ComponentName(packageName, fullClassName)
}
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo(fullClassName)
}
@Test
fun `M return class name W resolveViewUrl() {ActivityNavigator conflicting package}`(
@StringForgery packageName: String,
@StringForgery(regex = "\\w+\\.\\w+") name: String
) {
// Given
val destination = mock<ActivityNavigator.Destination>().apply {
whenever(component) doReturn ComponentName(packageName, name)
}
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo(name)
}
@Test
fun `M return unknown name W resolveViewUrl() {ActivityNavigator no component}`() {
// Given
val destination = mock<ActivityNavigator.Destination>().apply {
whenever(component) doReturn null
}
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo(UNKNOWN_DESTINATION_URL)
}
@Test
fun `M return the key value W resolveViewUrl() { destination of type String }`(
@StringForgery destination: String
) {
// When
val output = destination.resolveViewUrl()
// Then
assertThat(output).isEqualTo(destination)
}
}
| 52 | null | 60 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 4,408 | dd-sdk-android | Apache License 2.0 |
docs-examples/example-kotlin/src/test/kotlin/io/micronaut/rabbitmq/docs/consumer/custom/annotation/ProductListener.kt | micronaut-projects | 167,575,069 | false | null | package io.micronaut.rabbitmq.docs.consumer.custom.annotation
import io.micronaut.context.annotation.Requires
// tag::imports[]
import io.micronaut.rabbitmq.annotation.Queue
import io.micronaut.rabbitmq.annotation.RabbitListener
import java.util.Collections
// end::imports[]
@Requires(property = "spec.name", value = "DeliveryTagSpec")
// tag::clazz[]
@RabbitListener
class ProductListener {
val messages: MutableSet<Long> = Collections.synchronizedSet(HashSet())
@Queue("product")
fun receive(data: ByteArray, @DeliveryTag tag: Long) { // <1>
messages.add(tag)
}
}
// end::clazz[]
| 20 | null | 20 | 19 | ab5234345d3b9986a2dd49c7035a3f71655d6612 | 611 | micronaut-rabbitmq | Apache License 2.0 |
src/test/kotlin/ai/tochka/protocol/CommandWithContentAndTagTest.kt | TochkaAI | 256,272,206 | false | null | /*
* MIT License
*
* Copyright (c) 2020 <NAME> (ashlanderr) <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package ai.tochka.protocol
import org.junit.Assert.assertEquals
import org.junit.Test
class CommandWithContentAndTagTest : ProtocolTests() {
data class CommandContent(
val foo: String,
val bar: Int
)
data class AnswerContent(
val foo: String,
val tag: Long
)
interface TestClient {
@Command("command-with-content-and-tag")
fun commandWithContentAndTag(@Tag tag: Long, command: CommandContent): AnswerContent
}
class TestServer {
@CommandHandler("command-with-content-and-tag")
fun commandWithContentAndTag(@Tag tag: Long, command: CommandContent): AnswerContent {
assertEquals(123, command.bar)
return AnswerContent(
foo = command.foo,
tag = tag
)
}
}
@Test
fun testCommandWithContentAndTag() {
val client = clientChan.service(TestClient::class.java)
val server = TestServer()
serverChan.handler(server, TestServer::class.java)
val answer = client.commandWithContentAndTag(
-1000,
CommandContent(
foo = "test string",
bar = 123
)
)
assertEquals("test string", answer.foo)
assertEquals(-1000, answer.tag)
}
} | 0 | Kotlin | 0 | 0 | 78461cbbf2e47caa991ab3fe68419c4ea78c1d5a | 2,476 | pproto-java | MIT License |
kotlinx-coroutines-test/test/TestModuleHelpers.kt | hltj | 151,721,407 | true | null | /*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import org.junit.*
import java.time.*
const val SLOW = 10_000L
/**
* Assert a block completes within a second or fail the suite
*/
suspend fun CoroutineScope.assertRunsFast(block: suspend CoroutineScope.() -> Unit) {
val start = Instant.now().toEpochMilli()
// don''t need to be fancy with timeouts here since anything longer than a few ms is an error
this.block()
val duration = Instant.now().minusMillis(start).toEpochMilli()
Assert.assertTrue("All tests must complete within 2000ms (use longer timeouts to cause failure)", duration < 2_000)
}
| 1 | Kotlin | 99 | 244 | 082c45f58986c4d2d72ac1291a55f6c14ce91a98 | 742 | kotlinx.coroutines-cn | Apache License 2.0 |
idea/idea-frontend-fir/testData/symbolPointer/topLevelFunctions.kt | nskvortsov | 4,137,859 | false | null | fun x(): Int = 10
fun y() {}
// SYMBOLS:
KtFirFunctionSymbol:
annotations: []
callableIdIfNonLocal: x
isExtension: false
isExternal: false
isInline: false
isOperator: false
isOverride: false
isSuspend: false
modality: FINAL
name: x
origin: SOURCE
receiverType: null
symbolKind: TOP_LEVEL
type: kotlin/Int
typeParameters: []
valueParameters: []
visibility: PUBLIC
KtFirFunctionSymbol:
annotations: []
callableIdIfNonLocal: y
isExtension: false
isExternal: false
isInline: false
isOperator: false
isOverride: false
isSuspend: false
modality: FINAL
name: y
origin: SOURCE
receiverType: null
symbolKind: TOP_LEVEL
type: kotlin/Unit
typeParameters: []
valueParameters: []
visibility: PUBLIC
| 1 | null | 1 | 3 | 39d15501abb06f18026bbcabfd78ae4fbcbbe2cb | 756 | kotlin | Apache License 2.0 |
platform/src/main/kotlin/researchstack/backend/adapter/incoming/rest/common/StudyDataInfoSerializer.kt | S-ResearchStack | 520,365,362 | false | {"Kotlin": 1297740, "Dockerfile": 202, "Shell": 59} | package researchstack.backend.adapter.incoming.rest.common
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import researchstack.backend.domain.studydata.StudyDataFile
import researchstack.backend.domain.studydata.StudyDataFolder
import java.lang.reflect.Type
object StudyDataInfoSerializer : JsonSerializer<StudyDataFolder> {
override fun serialize(src: StudyDataFolder, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
val jsonObject = JsonObject()
jsonObject.addProperty("id", src.id)
jsonObject.addProperty("name", src.name)
jsonObject.addProperty("studyId", src.studyId)
jsonObject.addProperty("parentId", src.parentId)
jsonObject.addProperty("type", src.type.name)
if (src is StudyDataFile) {
jsonObject.addProperty("fileType", src.fileType.name)
jsonObject.addProperty("filePath", src.filePath)
jsonObject.addProperty("fileSize", src.fileSize)
jsonObject.addProperty("filePreview", src.filePreview)
jsonObject.addProperty("createdAt", src.createdAt.toString())
}
return jsonObject
}
}
| 1 | Kotlin | 9 | 29 | edd76f219cdb10c8151b8ac14175b1e818a6036a | 1,258 | backend-system | Apache License 2.0 |
caffeine-coroutines/src/test/kotlin/dev/hsbrysk/caffeine/internal/CoroutineCacheImplTest.kt | be-hase | 802,042,489 | false | null | package dev.hsbrysk.caffeine.internal
import assertk.assertFailure
import assertk.assertThat
import assertk.assertions.containsAtLeast
import assertk.assertions.containsExactly
import assertk.assertions.isEqualTo
import assertk.assertions.isInstanceOf
import assertk.assertions.isNull
import assertk.assertions.isNullOrEmpty
import com.github.benmanes.caffeine.cache.AsyncCache
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.Caffeine
import dev.hsbrysk.caffeine.buildCoroutine
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.slf4j.MDCContext
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.slf4j.MDC
import java.util.Collections
import java.util.function.Function
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.cancellation.CancellationException
class CoroutineCacheImplTest {
private val target = Caffeine.newBuilder().buildCoroutine<String, String>()
private val invokedKeys = Collections.synchronizedList(mutableListOf<String>())
private val mappingFunction: suspend (String) -> String = {
delay(2000)
invokedKeys.add(it)
"value-$it"
}
private val exceptionFunction: suspend (String) -> String = {
delay(2000)
throw IllegalArgumentException()
}
// Simply testing if the cache is working
@Nested
inner class Simple {
@Test
fun getIfPresent() = runBlocking {
assertThat(target.getIfPresent("1")).isNull()
target.get("1", mappingFunction)
assertThat(target.getIfPresent("1")).isEqualTo("value-1")
assertThat(invokedKeys).containsExactly("1")
}
@Test
fun get() = runBlocking {
assertThat(target.get("1", mappingFunction)).isEqualTo("value-1")
assertThat(target.get("1", mappingFunction)).isEqualTo("value-1")
assertThat(invokedKeys).containsExactly("1")
}
@Test
fun getAll() = runBlocking {
val mappingFunction: suspend (Iterable<String>) -> Map<String, String> = { keys ->
delay(1000)
invokedKeys.addAll(keys)
keys.associateWith { "value-$it" }
}
assertThat(target.getAll(listOf("1", "2"), mappingFunction)).containsAtLeast(
"1" to "value-1",
"2" to "value-2",
)
assertThat(target.getAll(listOf("1", "3"), mappingFunction)).containsAtLeast(
"1" to "value-1",
"3" to "value-3",
)
assertThat(target.getIfPresent("1")).isEqualTo("value-1")
assertThat(target.getIfPresent("2")).isEqualTo("value-2")
assertThat(target.getIfPresent("3")).isEqualTo("value-3")
assertThat(invokedKeys).containsExactly("1", "2", "3")
}
@Test
fun put() = runBlocking {
assertThat(target.getIfPresent("1")).isNull()
target.put("1", "value-1")
assertThat(target.getIfPresent("1")).isEqualTo("value-1")
}
@Test
fun putAll() = runBlocking {
assertThat(target.getIfPresent("1")).isNull()
assertThat(target.getIfPresent("2")).isNull()
target.putAll(mapOf("1" to "value-1", "2" to "value-2"))
assertThat(target.getIfPresent("1")).isEqualTo("value-1")
assertThat(target.getIfPresent("2")).isEqualTo("value-2")
}
@Test
fun exception() {
// If an error occurs, it will not be cached.
assertFailure { runBlocking { target.get("1", exceptionFunction) } }
runBlocking {
assertThat(target.getIfPresent("1")).isNull()
}
}
@Test
fun `null behavior`() = runBlocking {
// Caffeine cannot cache null values.
// Since this is Kotlin, I've made it so that it won't compile.
// target.put("key", null)
// The return value of the mapping function is nullable.
// I think this specification allows for the possibility that, after processing, the decision is made not to cache the result.
// Therefore, I will implement the coroutines version in the same way.
assertThat(
target.get("1") {
invokedKeys.add(it)
null
},
).isNull()
assertThat(
target.get("1") {
invokedKeys.add(it)
null
},
).isNull()
// Since null values are not cached, it is being called twice.
assertThat(invokedKeys).containsExactly("1", "1")
}
@Test
fun synchronous() {
assertThat(target.synchronous()).isInstanceOf(Cache::class.java)
assertThat(target.synchronous().get("1") { "value-$it" }).isEqualTo("value-1")
runBlocking {
assertThat(target.getIfPresent("1")).isEqualTo("value-1")
}
}
@Test
fun asynchronous() {
assertThat(target.asynchronous()).isInstanceOf(AsyncCache::class.java)
assertThat(target.asynchronous().get("1", Function { "value-$it" }).get()).isEqualTo("value-1")
runBlocking {
assertThat(target.getIfPresent("1")).isEqualTo("value-1")
}
}
}
@DelicateCoroutinesApi
@Nested
inner class Complex {
@Test
fun `once executed`() {
// Even if executed almost simultaneously, it should only run once.
val result1 = GlobalScope.async {
target.get("1", mappingFunction)
}
val result2 = GlobalScope.async {
target.get("1", mappingFunction)
}
runBlocking {
assertThat(listOf(result1, result2).awaitAll()).containsExactly("value-1", "value-1")
assertThat(invokedKeys).containsExactly("1")
}
}
@Test
fun `check coroutines context`() {
// I will confirm that the coroutine context is being carried over.
val scope = CoroutineScope(CoroutineName("test") + MDCContext(mapOf("hoge" to "hoge")))
val result1 = scope.async {
target.get("1") {
assertThat(coroutineContext[CoroutineName]).isEqualTo(CoroutineName("test"))
assertThat(MDC.getCopyOfContextMap()).containsAtLeast("hoge" to "hoge")
"value-$it"
}
}
val result2 = GlobalScope.async {
target.get("2") {
assertThat(coroutineContext[CoroutineName]).isNull()
assertThat(MDC.getCopyOfContextMap()).isNullOrEmpty()
"value-$it"
}
}
runBlocking {
assertThat(listOf(result1, result2).awaitAll()).containsExactly("value-1", "value-2")
}
}
@Test
fun `cooperative cancel`() {
// Cancellation within the same scope propagates.
val scope = CoroutineScope(EmptyCoroutineContext)
val result = scope.async {
target.get("1", mappingFunction)
}
scope.launch {
throw IllegalArgumentException()
}
runBlocking {
assertFailure { result.await() }
.isInstanceOf(CancellationException::class)
}
}
@Test
fun `with supervisorJob cancel`() {
// Cancellation within the same scope propagates.
val scope = CoroutineScope(EmptyCoroutineContext + SupervisorJob())
val result = scope.async {
target.get("1", mappingFunction)
}
scope.launch {
throw IllegalArgumentException()
}
runBlocking {
assertThat(result.await()).isEqualTo("value-1")
}
}
@Test
fun `isolated cancel`() {
// I will confirm that cancellation in a different scope does not propagate.
val scope1 = CoroutineScope(EmptyCoroutineContext)
val result1 = scope1.async {
target.get("1", mappingFunction)
}
val scope2 = CoroutineScope(EmptyCoroutineContext)
scope2.launch {
throw IllegalArgumentException()
}
runBlocking {
assertThat(result1.await()).isEqualTo("value-1")
}
}
@Test
fun `get - check exception and cancel behavior`() {
val scope = CoroutineScope(EmptyCoroutineContext)
val job = scope.async {
try {
target.get("1", exceptionFunction)
} catch (expected: IllegalArgumentException) {
println(expected)
}
"Result"
}
val result = runBlocking { job.await() }
assertThat(result).isEqualTo("Result")
}
@Test
fun `getAll - check exception and cancel behavior`() {
val scope = CoroutineScope(EmptyCoroutineContext)
val job = scope.async {
try {
target.getAll(listOf("1", "2")) {
throw IllegalArgumentException()
}
} catch (expected: IllegalArgumentException) {
println(expected)
}
"Result"
}
val result = runBlocking { job.await() }
assertThat(result).isEqualTo("Result")
}
}
}
| 2 | null | 1 | 7 | 28a61205c6931102b8efb4eaec7cfa23f6ddad0b | 10,223 | caffeine-coroutines | MIT License |
modules/kor-repositories/src/main/kotlin/com/sefford/kor/repositories/components/CacheFolder.kt | Sefford | 20,562,081 | false | null | /*
* Copyright (C) 2017 <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.sefford.kor.repositories.components
import java.io.File
/**
* Abstraction of a Cache Folder
*
* @param <K> Type of IDs that will storaged in the CacheFolder
* @author <NAME> <<EMAIL>>
</K> */
interface CacheFolder<K> {
/**
* Retrieves all the files in this cache Folder
*
* @return All files in the folder
*/
fun files(): Array<File>
/**
* Checks if a file exists in the folder
*
* @return TRUE if exists, FALSE otherwise
*/
fun exists(): Boolean
/**
* Given an ID in the <K> type, returns its related file.
*
*
* This method works basically as a mapper between the underlying folder and the File itself.
*
* @param id ID of the element to get the file from
* @return A valid file to read the element from K
*/
fun getFile(id: K): File?
}
| 0 | Kotlin | 5 | 115 | 74ac1a1373860a470122a3149f9f297e783a2daa | 1,460 | kor | Apache License 2.0 |
plot-config-portable/src/jvmTest/kotlin/plot/config/StatKindTest.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2021. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.config
import kotlin.test.Test
import kotlin.test.assertEquals
class StatKindTest {
@Test
fun valueOf() {
assertEquals(StatKind.COUNT, StatKind.safeValueOf("count"))
}
@Test(expected = IllegalArgumentException::class)
fun unknownName() {
StatKind.safeValueOf("coun")
}
}
| 97 | null | 51 | 889 | c5c66ceddc839bec79b041c06677a6ad5f54e416 | 492 | lets-plot | MIT License |
foundation/domain-model/testFixtures/ru/pixnews/domain/model/company/company/HypixelStudiosCompanyFixture.kt | illarionov | 305,333,284 | 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 ru.pixnews.domain.model.company.company
import kotlinx.collections.immutable.persistentListOf
import kotlinx.datetime.Month
import ru.pixnews.domain.model.company.Company
import ru.pixnews.domain.model.company.CompanyFixtures
import ru.pixnews.domain.model.company.CompanyId
import ru.pixnews.domain.model.company.CompanyStatus.ACTIVE
import ru.pixnews.domain.model.datasource.DataSourceFixtures
import ru.pixnews.domain.model.datasource.igdb
import ru.pixnews.domain.model.links.ExternalLink
import ru.pixnews.domain.model.links.ExternalLinkType.OFFICIAL
import ru.pixnews.domain.model.links.ExternalLinkType.TWITTER
import ru.pixnews.domain.model.locale.LanguageCode
import ru.pixnews.domain.model.locale.Localized
import ru.pixnews.domain.model.util.ApproximateDate
import ru.pixnews.domain.model.util.CanvasSize
import ru.pixnews.domain.model.util.DefaultImageUrl
import ru.pixnews.domain.model.util.RichText
import ru.pixnews.domain.model.util.Url
private val hypixelStudiosCompanyId = CompanyId("hypixel-studios")
public val CompanyFixtures.hypixelStudios: Company
get() = Company(
id = hypixelStudiosCompanyId,
name = "Hypixel Studios",
description = Localized(value = RichText(""), language = LanguageCode.ENGLISH),
avatar = DefaultImageUrl(
rawUrl = "https://images.igdb.com/igdb/image/upload/t_logo_med/cl2n9.png",
size = CanvasSize(284U, 147U),
),
foundingDate = ApproximateDate.YearMonthDay(year = 2018, month = Month.DECEMBER, dayOfMonth = 13),
status = ACTIVE,
country = null,
parentCompany = CompanyFixtures.riotGames.id,
dataSources = DataSourceFixtures.igdb,
links = persistentListOf(
ExternalLink(OFFICIAL, Url("https://hypixelstudios.com/")),
ExternalLink(TWITTER, Url("https://twitter.com/Hypixel")),
),
)
| 0 | Kotlin | 0 | 2 | d806ee06019389c78546d946f1c20d096afc7c6e | 2,479 | Pixnews | Apache License 2.0 |
app/src/main/java/com/example/maihang/fragments/BottomSheet/MealBottomSheetFragment.kt | DevP-ai | 689,309,567 | false | {"Kotlin": 45226} | package com.example.maihang.fragments.BottomSheet
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.maihang.R
private const val MEAL_ID = "param1"
class MealBottomSheetFragment : Fragment() {
private var mealId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
mealId = it.getString(MEAL_ID)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meal_bottom_sheet, container, false)
}
companion object {
@JvmStatic
fun newInstance(param1: String) =
MealBottomSheetFragment().apply {
arguments = Bundle().apply {
putString(MEAL_ID, param1)
}
}
}
} | 0 | Kotlin | 0 | 0 | e8bdfab87fc649b90865ef9ca53aeece731572e7 | 1,083 | Maihang | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/CommentText.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
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 me.localx.icons.straight.Icons
public val Icons.Filled.CommentText: ImageVector
get() {
if (_commentText != null) {
return _commentText!!
}
_commentText = Builder(name = "CommentText", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
horizontalLineToRelative(12.0f)
lineTo(24.0f, 12.0f)
curveTo(24.0f, 5.383f, 18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(18.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.0f)
lineTo(11.0f, 9.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
lineTo(6.0f, 7.0f)
horizontalLineToRelative(12.0f)
verticalLineToRelative(4.0f)
close()
}
}
.build()
return _commentText!!
}
private var _commentText: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,365 | icons | MIT License |
compiler/testData/diagnostics/testsWithStdLib/inference/annotationsForResolve/checkLowPriorityIsResolvedSuccessfully.kt | JetBrains | 3,432,266 | false | null | // FIR_IDENTICAL
class Foo {
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
@kotlin.internal.LowPriorityInOverloadResolution
val test: Bar = Bar()
}
fun Foo.test() {}
class Bar
class Scope {
operator fun Bar.invoke(f: () -> Unit) {}
}
fun Scope.bar(e: Foo) {
e.test {}
}
| 125 | null | 4813 | 39,375 | 83d2d2cfcfc3d9903c902ca348f331f89bed1076 | 299 | kotlin | Apache License 2.0 |
app/src/main/kotlin/me/nanova/subspace/domain/repo/TorrentRepo.kt | kid1412621 | 737,778,999 | false | {"Kotlin": 117037} | package me.nanova.subspace.domain.repo
import androidx.paging.PagingData
import kotlinx.coroutines.flow.Flow
import me.nanova.subspace.domain.model.Account
import me.nanova.subspace.domain.model.QTListParams
import me.nanova.subspace.domain.model.Torrent
interface TorrentRepo {
// suspend fun apiVersion(): String
fun torrents(account: Account, filter: QTListParams): Flow<PagingData<Torrent>>
}
| 4 | Kotlin | 0 | 0 | d3a503c4e21e5f68f36c5e8249745b0b19ea6415 | 409 | subspace | MIT License |
src/main/kotlin/no/nav/helse/flex/DokumentConsumer.kt | navikt | 446,743,079 | false | {"Kotlin": 113201, "Dockerfile": 267} | package no.nav.helse.flex
import com.fasterxml.jackson.module.kotlin.readValue
import no.nav.helse.flex.journalpost.JournalpostBehandler
import no.nav.helse.flex.retry.RetryProducer
import org.apache.avro.generic.GenericRecord
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.slf4j.MDC
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.support.Acknowledgment
import org.springframework.stereotype.Component
import java.time.OffsetDateTime
import java.util.*
@Component
class DokumentConsumer(
private val journalpostBehandler: JournalpostBehandler,
private val retryProducer: RetryProducer,
) {
private val log = logger()
@KafkaListener(
topics = ["#{environmentToggles.dokumentTopic()}"],
id = "flex-joark-mottak",
idIsGroup = true,
concurrency = "3",
containerFactory = "kafkaAvroListenerContainerFactory",
properties = ["auto.offset.reset = earliest"],
)
fun listen(
cr: ConsumerRecord<String, GenericRecord>,
acknowledgment: Acknowledgment,
) {
val genericRecord = cr.value()
if (genericRecord["temaNytt"].toString() != "SYK") {
return
}
if (genericRecord["hendelsesType"].toString() !in listOf("MidlertidigJournalført", "Mottatt", "JournalpostMottatt")) {
return
}
val kafkaEvent = objectMapper.readValue<KafkaEvent>(genericRecord.toString())
try {
MDC.put(CORRELATION_ID, UUID.randomUUID().toString())
journalpostBehandler.behandleJournalpost(kafkaEvent)
} catch (e: Exception) {
log.error("Feilet på journalpost ${kafkaEvent.journalpostId}, legger på retry-topic", e)
retryProducer.send(kafkaEvent, OffsetDateTime.now().plusSeconds(1))
} finally {
MDC.clear()
}
acknowledgment.acknowledge()
}
}
data class KafkaEvent(
val hendelsesId: String,
val hendelsesType: String,
val journalpostId: String,
val temaNytt: String,
val mottaksKanal: String,
val journalpostStatus: String,
val versjon: Int = 0,
val temaGammelt: String,
val kanalReferanseId: String,
val behandlingstema: String = "",
)
| 8 | Kotlin | 0 | 0 | c5c44497c7f6a1f02b99eaea4b85444eb33d44cb | 2,272 | flex-joark-mottak | MIT License |
app/src/main/java/com/applendar/applendar/ListadoMateriasFragment.kt | UCASV | 267,764,032 | false | null | package com.applendar.applendar
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.Toolbar
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.view.MenuItemCompat
import androidx.fragment.app.Fragment
import com.applendar.applendar.adapters.MateriasAdapter
import com.applendar.applendar.domain.Materia
import com.applendar.applendar.retrofit.APIEndpoint
import com.applendar.applendar.retrofit.AsyncResponse
import com.applendar.applendar.util.GeneralGlobalVariables
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ListadoMateriasFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ListadoMateriasFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
lateinit var materiaslv: ListView;
lateinit var adapter: MateriasAdapter
lateinit var materias: ArrayList<Materia>;
lateinit var materiasPerma: ArrayList<Materia>;
lateinit var searchView: SearchView;
lateinit var loadingModal: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
var mainActivity: MainActivity = (activity as MainActivity);
(activity as MainActivity).setActionBarTitle("Materias")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val obj = object: AsyncResponse{
override fun processFinish() {
println("Entered Async Response")
loadingModal.visibility = View.GONE;
adapter = MateriasAdapter(context!!, materias);
materiaslv.adapter = adapter;
materiasPerma = ArrayList<Materia>()
materiasPerma.addAll(materias)
}
override fun alternativeFinish() {
TODO("Not yet implemented")
}
}
ClienteRequest(obj).execute()
loadingModal = view!!.findViewById(R.id.listado_materias_loading_modal)
loadingModal.visibility = View.VISIBLE
materiaslv = view!!.findViewById(R.id.fragment_listado_materias_listview)
materiaslv.setOnItemClickListener { parent, view, position, id ->
var materia: Materia = adapter.getItem(position) as Materia
var intent: Intent = Intent(context!!, MateriaActivity::class.java)
intent.putExtra("materia_nombre", materia.nombre)
intent.putExtra("materia_acronimo", materia.acronimo)
intent.putExtra("materia_catedratico", materia.catedratico)
intent.putExtra("materia_id", materia.materiaId)
startActivity(intent)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.searchbar_menu, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_buscar)
if (searchItem != null) {
searchView = MenuItemCompat.getActionView(searchItem) as SearchView
searchView.setOnCloseListener(object : SearchView.OnCloseListener {
override fun onClose(): Boolean {
return true
}
})
val searchPlate = searchView.findViewById(androidx.appcompat.R.id.search_src_text) as EditText
searchPlate.hint = "Search"
val searchPlateView: View =
searchView.findViewById(androidx.appcompat.R.id.search_plate)
searchPlateView.setBackgroundColor(
ContextCompat.getColor(
context!!,
android.R.color.transparent
)
)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
var materiaSublist = ArrayList<Materia>()
if(query!= null ) {
if( query != "") {
for (materia: Materia in materiasPerma) {
if (materia.acronimo?.toLowerCase()?.contains(query.toLowerCase())!!
|| materia.nombre?.toLowerCase()
?.contains(query.toLowerCase())!!
) {
materiaSublist.add(materia)
}
}
}
else{
materiaSublist = materiasPerma
}
}
else{
materiaSublist = materiasPerma
}
materias.clear()
materias.addAll(materiaSublist)
adapter.notifyDataSetChanged()
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
var materiaSublist = ArrayList<Materia>()
if(newText==null){
materiaSublist = materiasPerma
materias.clear()
materias.addAll(materiaSublist)
adapter.notifyDataSetChanged()
}
else if(newText==""){
materiaSublist = materiasPerma
materias.clear()
materias.addAll(materiaSublist)
adapter.notifyDataSetChanged()
}
return false
}
})
val searchManager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity!!.componentName))
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
activity!!.title = "Titulo"
return inflater.inflate(R.layout.fragment_listado_materias, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ListadoMateriasFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ListadoMateriasFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
inner class ClienteRequest(callback: AsyncResponse) :
AsyncTask<String?, Void?, ArrayList<Materia>>() {
var delegate: AsyncResponse
override fun onPostExecute(result: ArrayList<Materia>?) {
delegate.processFinish()
}
override fun doInBackground(vararg p0: String?): ArrayList<Materia>? {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder()
.addInterceptor(interceptor).build()
val BASE_URL: String = GeneralGlobalVariables.BASE_URL
val retrofit = Retrofit.Builder()
.client(client)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService: APIEndpoint = retrofit.create(APIEndpoint::class.java)
/*val encoder = Encoder()
val usuario = prefs.getString(LoginActivity.USERNAME, null)
val password = prefs.getString(LoginActivity.PASSWORD, null)
val encodedString: String = encoder.encoder64(usuario, password)*/
val request: Call<ArrayList<Materia>> =
apiService.getMaterias()
val response: Response<ArrayList<Materia>>
try {
response = request.execute()
materias = response.body()!!;
return response.body()
} catch (e: IOException) {
println(e.message)
}
return null
}
init {
delegate = callback
}
}
} | 1 | Kotlin | 0 | 0 | 493b0cc1ea5bffcafaca73e1114ad3726fb590a4 | 9,421 | entrega-de-proyecto-pdm-0120-safaera-mp3 | Apache License 2.0 |
example_cli/src/main/kotlin/org/kethereum/example_cli/ExampleCLI.kt | komputing | 92,780,266 | false | null | package org.kethereum.example_cli
import kotlinx.coroutines.flow.collect
import org.kethereum.abi.EthereumABI
import org.kethereum.abi_codegen.model.GeneratorSpec
import org.kethereum.abi_codegen.toKotlinCode
import org.kethereum.eip137.model.ENSName
import org.kethereum.eip137.toHexString
import org.kethereum.eip137.toNameHash
import org.kethereum.ens.ENS
import org.kethereum.erc55.withERC55Checksum
import org.kethereum.flows.getBlockFlow
import org.kethereum.flows.getTransactionFlow
import org.kethereum.model.Address
import org.kethereum.rpc.EthereumRPC
import org.kethereum.rpc.min3.getMin3RPC
import kotlin.system.exitProcess
val rpc : EthereumRPC = getMin3RPC()
val ens = ENS(rpc)
suspend fun main() {
showUsageAndDemoSelect()
}
private suspend fun showUsageAndDemoSelect(appendix: String = "") {
println("""What should we demo$appendix?
|
|ERC555 (1)
|EIP137 (2)
|ENS (3)
|transactionFlow (4)
|blockFlow (5)
|CodeGeneration (6)
|Exit (x)
""".trimMargin())
when (readLine()?.toUpperCase()) {
"1", "ERC55" -> demoERC55()
"2", "EIP137" -> demoEIP137()
"3", "ENS" -> demoENS()
"4", "TRANSACTIONFLOW" -> {
getTransactionFlow(rpc).collect { tx ->
println(tx)
}
}
"5", "BLOCKFLOW" -> {
getBlockFlow(rpc).collect { block ->
println(block)
}
}
"6", "CODEGENERATION" -> demoCodeGen()
"X", "EXIT" -> exitProcess(0)
else -> println("input not understood")
}
showUsageAndDemoSelect(" next")
}
fun demoENS() {
println("vitalik.eth addr -> " + ens.getAddress(ENSName("vitalik.eth")))
println("ENS reverse " + ens.reverseResolve(Address("d8da6bf26964af9d7eed9e03e53415d37aa96045")))
println("ligi.ethereum.eth node -> " + ENSName("ligi.ethereum.eth").toNameHash().toHexString())
println("ligi.ethereum.eth github username" + ens.getGithubUserName(ENSName("ligi.ethereum.eth")))
println("kevins.xyz " + ens.getAddress(ENSName("kevins.xyz")))
}
private fun demoEIP137() {
println("alice.eth -> " + ENSName("alice.eth").toNameHash().toHexString())
}
private fun demoERC55() {
val addressNoChecksum = "0x112234455c3a32fd11230c42e7bccd4a84e02010"
println(addressNoChecksum + "->" + Address(addressNoChecksum).withERC55Checksum())
}
private fun demoCodeGen() {
EthereumABI(0.javaClass.getResource("/ENSResolver.abi").readText()).toKotlinCode(GeneratorSpec("PeeETH")).writeTo(System.out)
}
| 43 | null | 82 | 333 | 1f42cede2d31cb5d3c488bd74eeb8480ec47c919 | 2,576 | KEthereum | MIT License |
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/impl/securestorage/RealSecureStorageRepositoryFactory.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2023 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.autofill.impl.securestorage
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.securestorage.store.RealSecureStorageRepository
import com.duckduckgo.securestorage.store.SecureStorageRepository
import com.duckduckgo.securestorage.store.db.SecureStorageDatabase
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
import kotlinx.coroutines.flow.firstOrNull
import timber.log.Timber
@ContributesBinding(AppScope::class)
class RealSecureStorageRepositoryFactory @Inject constructor(
private val secureStorageDatabaseFactory: SecureStorageDatabaseFactory,
) : SecureStorageRepository.Factory {
override suspend fun get(): SecureStorageRepository? {
val db = secureStorageDatabaseFactory.getDatabase()
return if (db != null && db.contentsAreReadable()) {
RealSecureStorageRepository(db.websiteLoginCredentialsDao(), db.neverSavedSitesDao())
} else {
null
}
}
private suspend fun SecureStorageDatabase.contentsAreReadable(): Boolean {
return kotlin.runCatching {
websiteLoginCredentialsDao().websiteLoginCredentials().firstOrNull()
true
}.getOrElse {
Timber.e("Secure storage database exists but is not readable")
false
}
}
}
| 67 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,936 | Android | Apache License 2.0 |
AgoraEduUIKit/src/main/java/com/agora/edu/component/whiteboard/AgoraEduPenTextComponent.kt | AgoraIO-Community | 330,886,965 | false | null | package com.agora.edu.component.whiteboard
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.view.marginEnd
import androidx.recyclerview.widget.GridLayoutManager
import com.agora.edu.component.common.IAgoraUIProvider
import com.agora.edu.component.helper.GridSpacingItemDecoration
import com.agora.edu.component.whiteboard.adpater.*
import com.agora.edu.component.whiteboard.color.AgoraEduWbColorAdapter
import com.agora.edu.component.whiteboard.data.AgoraEduApplianceData.Companion.getListColor
import com.agora.edu.component.whiteboard.data.AgoraEduApplianceData.Companion.getListPenShape
import com.agora.edu.component.whiteboard.data.AgoraEduApplianceData.Companion.getListTextSize
import com.agora.edu.component.whiteboard.data.AgoraEduApplianceData.Companion.getListThickness
import io.agora.agoraeduuikit.R
/**
* author : hefeng
* date : 2022/2/16
* description : 笔和文字大小,颜色
*/
class AgoraEduPenTextComponent : AgoraEduBaseApplianceComponent {
constructor(context: Context) : super(context)
constructor(context: Context, attr: AttributeSet) : super(context, attr)
constructor(context: Context, attr: AttributeSet, defStyleAttr: Int) : super(context, attr, defStyleAttr)
private lateinit var shapeToolsAdapter: AgoraEduToolsAdapter<AgoraEduPenShapeInfo> // 形状
private lateinit var thicknessSizeToolsAdapter: AgoraEduToolsAdapter<AgoraEduThicknessInfo> // 画笔粗细
private lateinit var textSizeToolsAdapter: AgoraEduToolsAdapter<AgoraEduTextSizeInfo> // 文字大小
private lateinit var colorToolsAdapter: AgoraEduWbColorAdapter<AgoraEduPenColorInfo> // 颜色
var onTextListener: OnAgoraEduTextListener? = null
var onPenListener: OnAgoraEduPenListener? = null
override fun initView(agoraUIProvider: IAgoraUIProvider) {
super.initView(agoraUIProvider)
}
// 记录位置
/**
* 形状的位置
*/
var shapeSelectIndex = 0
/**
* 文本大小
*/
var textSelectIndex = 2
fun showPen() {
divider2.visibility = View.VISIBLE
bottomListView.visibility = View.VISIBLE
centerListView.layoutManager = GridLayoutManager(context, LINE_SIZE_COUNT)
for (i in 0 until centerListView.itemDecorationCount) {
centerListView.removeItemDecorationAt(i)
}
centerListView.addItemDecoration(
GridSpacingItemDecoration(
LINE_SIZE_COUNT,
resources.getDimensionPixelSize(R.dimen.agora_appliance_item_margin), true
)
)
// 通过margin来对齐
centerListView.setPadding(0,0,resources.getDimensionPixelSize(R.dimen.agora_appliance_pen_m_margin),0)
// 形状
shapeToolsAdapter = AgoraEduToolsAdapter(config)
shapeToolsAdapter.setViewData(getListPenShape())
shapeToolsAdapter.operationType = 2
shapeToolsAdapter.selectPosition = shapeSelectIndex
shapeToolsAdapter.onClickItemListener = { position, info ->
shapeSelectIndex = position
// 这里不能覆盖父类型
//config.activeAppliance = info.activeAppliance
// 这里是子菜单类型
onPenListener?.onPenShapeSelected(config.activeAppliance, info.activeAppliance, info.iconRes)
}
topListView.adapter = shapeToolsAdapter
// 粗细,圆形
thicknessSizeToolsAdapter = AgoraEduToolsAdapter(config)
thicknessSizeToolsAdapter.operationType = 3
thicknessSizeToolsAdapter.selectPosition = getPenSize()
thicknessSizeToolsAdapter.setViewData(getListThickness(context))
thicknessSizeToolsAdapter.onClickItemListener = { position, info ->
config.thickSize = info.size
onPenListener?.onPenThicknessSelected(info.size, info.iconRes)
}
centerListView.adapter = thicknessSizeToolsAdapter
// 颜色
colorToolsAdapter = AgoraEduWbColorAdapter(config)
colorToolsAdapter.setViewData(getListColor(context))
colorToolsAdapter.selectPosition = getPenColorPosition()
colorToolsAdapter.onClickItemListener = { position, info ->
config.color = info.iconRes // 颜色存在iconRes
onPenListener?.onPenColorSelected(info.iconRes, R.drawable.agora_wb_pen)
// 需要更新:形状,圆圈,小矩形的颜色
shapeToolsAdapter.notifyDataSetChanged()
thicknessSizeToolsAdapter.notifyDataSetChanged()
}
bottomListView.adapter = colorToolsAdapter
}
fun showText() {
divider2.visibility = View.GONE
bottomListView.visibility = View.GONE
centerListView.setPadding(0, 0, 0, 0)
centerListView.layoutManager = GridLayoutManager(context, LINE_COUNT)
for (i in 0 until centerListView.itemDecorationCount) {
centerListView.removeItemDecorationAt(i)
}
centerListView.addItemDecoration(
GridSpacingItemDecoration(
LINE_COUNT,
resources.getDimensionPixelSize(R.dimen.agora_appliance_item_margin), true
)
)
textSelectIndex = getTSize()
// 文字大小 T
textSizeToolsAdapter = AgoraEduToolsAdapter(config)
textSizeToolsAdapter.setViewData(getListTextSize(context))
textSizeToolsAdapter.selectPosition = textSelectIndex
textSizeToolsAdapter.onClickItemListener = { position, info ->
textSelectIndex = position
textSizeToolsAdapter.notifyDataSetChanged()
config.fontSize = info.size
onTextListener?.onTextSizeSelected(info.size, R.drawable.agora_wb_text)
}
topListView.adapter = textSizeToolsAdapter
// 颜色
colorToolsAdapter = AgoraEduWbColorAdapter(config)
colorToolsAdapter.setViewData(getListColor(context))
colorToolsAdapter.onClickItemListener = { position, info ->
config.color = info.iconRes // 颜色存在iconRes
onTextListener?.onTextColorSelected(info.iconRes, R.drawable.agora_wb_text)
// 刷新 T 的颜色
textSizeToolsAdapter.notifyDataSetChanged()
}
centerListView.adapter = colorToolsAdapter
}
fun getTSize(): Int {
var pos = 2
for ((index, value) in getListTextSize(context).withIndex()) {
if (config.fontSize == value.size) {
pos = index
break
}
}
return pos
}
/**
* 选择的位置(可能没有在里面)
*/
fun getPenSize(): Int {
var pos = 1
for ((index, value) in getListThickness(context).withIndex()) {
if (config.thickSize == value.size) {
pos = index
break
}
}
return pos
}
/**
* 选择的位置(可能没有在里面)
*/
fun getPenColorPosition(): Int {
var pos = -1
for ((index, value) in getListColor(context).withIndex()) {
if (config.color == value.iconRes) {
pos = index
break
}
}
return pos
}
} | 4 | Kotlin | 19 | 8 | 9fb07495275f2da4aa0b579005c7eacfd444defb | 7,019 | CloudClass-Android | MIT License |
auth/src/main/kotlin/researchstack/auth/domain/repository/AccountRepository.kt | S-ResearchStack | 520,365,275 | false | {"Kotlin": 178868, "AIDL": 4785} | package researchstack.auth.domain.repository
import researchstack.auth.domain.model.Account
interface AccountRepository {
suspend fun getAccount(): Account?
suspend fun updateAccount(account: Account)
suspend fun clearAccount()
}
| 5 | Kotlin | 20 | 26 | e31e8055f96fa226745750b5a653e341cf5f2e6c | 244 | app-sdk | Apache License 2.0 |
src/main/kotlin/br/com/fugisawa/adopetbackendapikotlin/dto/PetsPerSizeView.kt | lucasfugisawa | 623,206,765 | false | null | package br.com.fugisawa.adopetbackendapikotlin.dto
import br.com.fugisawa.adopetbackendapikotlin.domain.pet.PetSize
data class PetsPerSizeView(
val size: PetSize,
val count: Long,
) | 0 | Kotlin | 0 | 1 | c1d08830ff0b88b158cac07236acca9c049a3c92 | 191 | adopet-backend-api-alura-challenge-semana1 | MIT License |
gymind/app/src/main/java/com/sondreweb/gymind/helpers/Utilities.kt | engson | 422,841,076 | false | {"Kotlin": 20830} | package com.sondreweb.gymind.helpers
import android.content.Context
import java.io.BufferedReader
import java.io.InputStream
class Utilities {
companion object {
fun getAssetsData(context: Context, url: String): String =
context
.assets
.open(url)
.bufferedReader()
.use(BufferedReader::readText)
}
} | 3 | Kotlin | 0 | 0 | 5be8212325d5b6ab3e42b199ade44f9930c02e6a | 395 | WorkoutApp | Apache License 2.0 |
dlt-analyzer-app/src/main/kotlin/analyzer/ui/table/DltStringRenderer.kt | froks | 772,775,135 | false | {"Kotlin": 75788} | package analyzer.ui.table
import java.awt.Component
import javax.swing.JTable
import javax.swing.table.DefaultTableCellRenderer
class DltStringRenderer : DefaultTableCellRenderer() {
private val defaultColor = this.foreground
override fun getTableCellRendererComponent(
table: JTable,
value: Any?,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int
): Component {
val model = table.model as DltTableModel
val color = model.getRowColor(row)
if (color != null) {
foreground = color
} else {
foreground = defaultColor
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column)
}
}
| 0 | Kotlin | 0 | 1 | 59ae4bb6694aa48d12767de324fd053f5fa2bc08 | 763 | dlt-tools | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/connect/CfnRuleTaskActionPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.connect
import cloudshift.awscdk.common.CdkDslMarker
import cloudshift.awscdk.common.MapBuilder
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.Map
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.connect.CfnRule
/**
* Information about the task action.
*
* This field is required if `TriggerEventSource` is one of the following values:
* `OnZendeskTicketCreate` | `OnZendeskTicketStatusUpdate` | `OnSalesforceCaseCreate`
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.connect.*;
* TaskActionProperty taskActionProperty = TaskActionProperty.builder()
* .contactFlowArn("contactFlowArn")
* .name("name")
* // the properties below are optional
* .description("description")
* .references(Map.of(
* "referencesKey", ReferenceProperty.builder()
* .type("type")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-connect-rule-taskaction.html)
*/
@CdkDslMarker
public class CfnRuleTaskActionPropertyDsl {
private val cdkBuilder: CfnRule.TaskActionProperty.Builder =
CfnRule.TaskActionProperty.builder()
/** @param contactFlowArn The Amazon Resource Name (ARN) of the flow. */
public fun contactFlowArn(contactFlowArn: String) {
cdkBuilder.contactFlowArn(contactFlowArn)
}
/**
* @param description The description. Supports variable injection. For more information, see
* [JSONPath reference](https://docs.aws.amazon.com/connect/latest/adminguide/contact-lens-variable-injection.html)
* in the *Amazon Connect Administrators Guide* .
*/
public fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param name The name. Supports variable injection. For more information, see
* [JSONPath reference](https://docs.aws.amazon.com/connect/latest/adminguide/contact-lens-variable-injection.html)
* in the *Amazon Connect Administrators Guide* .
*/
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param references Information about the reference when the `referenceType` is `URL` .
* Otherwise, null. `URL` is the only accepted type. (Supports variable injection in the
* `Value` field.)
*/
public fun references(references: MapBuilder.() -> Unit = {}) {
val builder = MapBuilder()
builder.apply(references)
cdkBuilder.references(builder.map)
}
/**
* @param references Information about the reference when the `referenceType` is `URL` .
* Otherwise, null. `URL` is the only accepted type. (Supports variable injection in the
* `Value` field.)
*/
public fun references(references: Map<String, Any>) {
cdkBuilder.references(references)
}
/**
* @param references Information about the reference when the `referenceType` is `URL` .
* Otherwise, null. `URL` is the only accepted type. (Supports variable injection in the
* `Value` field.)
*/
public fun references(references: IResolvable) {
cdkBuilder.references(references)
}
public fun build(): CfnRule.TaskActionProperty = cdkBuilder.build()
}
| 3 | null | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 3,683 | awscdk-dsl-kotlin | Apache License 2.0 |
e6/canasta/feature/grocery/create-list/src/main/java/ven/canasta/feature/grocery/grocerylist/create/mock/TitleField.kt | ernestosimionato6 | 584,044,832 | false | null |
package ven.canasta.feature.grocery.grocerylist.create.mock
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.flowlayout.FlowColumn
import com.google.accompanist.flowlayout.FlowCrossAxisAlignment.Center
import com.google.accompanist.flowlayout.FlowMainAxisAlignment
import ven.canasta.core.designsystem.theme.CanastaTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun XTitleField(s: String,
modifier: Modifier = Modifier.fillMaxWidth()
) {
var text by remember { mutableStateOf("Hello") }
OutlinedTextField(
value = text,
onValueChange = { text = it },
// modifier = Modifier.clip(RoundedCornerShape(12.dp)),
label = {}, // "", // { Text("Label") },
modifier = Modifier.border(
BorderStroke(
width = 2.dp,
color = Companion.Green
),
shape = RoundedCornerShape(50)
),
colors = TextFieldDefaults.run {
textFieldColors(
containerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
)
},
// textStyle = inputTextStyle,
)
}
@Preview(name="title-field", showBackground = true)
@Composable
fun TitleFieldPreview() {
CanastaTheme {
Box(
Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
FlowColumn(
Modifier.fillMaxWidth()
.height(200.dp),
mainAxisSpacing = 20.dp,
mainAxisAlignment = FlowMainAxisAlignment.Center,
crossAxisAlignment = Center
) {
XTitleField(
s = "hola mundo",
)
BasicTextField(
value = "12341234",
onValueChange = {},
)
}
}
}
} | 4 | Kotlin | 0 | 0 | 21b39b4b9dbd4273853fc3954f1f1fdafa056281 | 3,168 | e6-canasta | Apache License 2.0 |
apps/mobile-app/src/main/kotlin/dev/marlonlom/apps/bookbar/ui/navigation/MainNavHost.kt | marlonlom | 740,270,327 | false | {"Kotlin": 175363} | /*
* Copyright 2024 Marlonlom
* SPDX-License-Identifier: Apache-2.0
*/
package dev.marlonlom.apps.bookbar.ui.navigation
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import dev.marlonlom.apps.bookbar.domain.books.BookDetailItem
import dev.marlonlom.apps.bookbar.features.book_detail.BookDetailRoute
import dev.marlonlom.apps.bookbar.features.book_detail.BookDetailsViewModel
import dev.marlonlom.apps.bookbar.features.books_favorite.FavoriteBooksRoute
import dev.marlonlom.apps.bookbar.features.books_new.NewBooksRoute
import dev.marlonlom.apps.bookbar.ui.main.contents.BookbarAppState
import kotlinx.coroutines.ExperimentalCoroutinesApi
/**
* Main navigation host composable function.
*
* @author marlonlom
*
* @param appState App ui state.
* @param bookDetailsViewModel Book details viewmodel.
* @param onBookItemClicked Action for Book item clicked.
* @param openExternalUrl Action for opening external urls.
* @param onFavoriteBookIconClicked Action for favorite book icon clicked.
* @param onRemoveFavoriteIconClicked Action for favorite Book removal icon clicked.
* @param onShareIconClicked Action for book sharing icon clicked.
*/
@ExperimentalCoroutinesApi
@ExperimentalFoundationApi
@ExperimentalMaterial3Api
@Composable
fun MainNavHost(
appState: BookbarAppState,
bookDetailsViewModel: BookDetailsViewModel,
onBookItemClicked: (String) -> Unit,
openExternalUrl: (String) -> Unit,
onFavoriteBookIconClicked: (BookDetailItem, Boolean) -> Unit,
onRemoveFavoriteIconClicked: (String) -> Unit,
onShareIconClicked: (String) -> Unit
) {
NavHost(
navController = appState.navController,
startDestination = BookbarRoute.Home.route,
enterTransition = { EnterTransition.None },
exitTransition = { ExitTransition.None },
popEnterTransition = { EnterTransition.None },
popExitTransition = { ExitTransition.None },
) {
homeDestination(appState, onBookItemClicked)
favoritesDestination(appState, onBookItemClicked, onRemoveFavoriteIconClicked)
detailsDestination(
appState = appState,
bookDetailsViewModel = bookDetailsViewModel,
openExternalUrl = openExternalUrl,
onFavoriteBookIconClicked = onFavoriteBookIconClicked,
onShareIconClicked = onShareIconClicked
)
}
}
/**
* Home destination extension for navigation graph builder.
*
* @author marlonlom
*
* @param appState App ui state.
* @param onBookItemClicked Action for Book item clicked.
*/
@ExperimentalFoundationApi
internal fun NavGraphBuilder.homeDestination(
appState: BookbarAppState,
onBookItemClicked: (String) -> Unit
) {
composable(BookbarRoute.Home.route) {
NewBooksRoute(appState, onBookItemClicked)
}
}
/**
* Favorites destination extension for navigation graph builder.
*
* @author marlonlom
*
* @param appState App ui state.
* @param onBookItemClicked Action for Book item clicked.
* @param onRemoveFavoriteIconClicked Action for favorite Book removal icon clicked.
*/
internal fun NavGraphBuilder.favoritesDestination(
appState: BookbarAppState,
onBookItemClicked: (String) -> Unit,
onRemoveFavoriteIconClicked: (String) -> Unit
) {
composable(BookbarRoute.Favorite.route) {
FavoriteBooksRoute(appState, onBookItemClicked, onRemoveFavoriteIconClicked)
}
}
/**
* Book details destination extension for navigation graph builder.
*
* @author marlonlom
*
* @param appState App ui state.
* @param bookDetailsViewModel Book details viewmodel.
* @param openExternalUrl Action for opening external urls.
* @param onFavoriteBookIconClicked Action for favorite book button clicked.
* @param onShareIconClicked Action for opening share dialog feature.
*/
@ExperimentalCoroutinesApi
@ExperimentalFoundationApi
@ExperimentalMaterial3Api
internal fun NavGraphBuilder.detailsDestination(
appState: BookbarAppState,
bookDetailsViewModel: BookDetailsViewModel,
openExternalUrl: (String) -> Unit,
onFavoriteBookIconClicked: (BookDetailItem, Boolean) -> Unit,
onShareIconClicked: (String) -> Unit
) {
composable(
route = BookbarRoute.Details.route,
arguments = BookbarRoute.Details.navArguments
) { navBackStackEntry ->
val bookId = navBackStackEntry.arguments?.getString("bookId")
requireNotNull(bookId) { "bookId parameter wasn't found. Please make sure it's set!" }
bookDetailsViewModel.setSelectedBook(bookId)
BookDetailRoute(appState, openExternalUrl, onFavoriteBookIconClicked, onShareIconClicked)
}
}
| 0 | Kotlin | 0 | 1 | 030a0495b69edcaae9ce887c4e90e151a1c843ab | 4,805 | bookbar | Apache License 2.0 |
Meld-Module-World/src/main/kotlin/io/github/daylightnebula/meld/world/chunks/Palettes.kt | DaylightNebula | 652,923,400 | false | {"Kotlin": 199201, "Python": 792} | package io.github.daylightnebula.meld.world.chunks
import io.github.daylightnebula.meld.server.networking.common.ByteWriter
import org.cloudburstmc.math.vector.Vector3i
class FlexiblePalette(
var blockIDs: IntArray = intArrayOf(0),
var blockReferences: ByteArray = ByteArray(16 * 16 * 16) { 0 },
var startCount: Short = 0
) {
companion object {
fun filled(blockID: Int = 0) = FlexiblePalette(
blockIDs = if (blockID != 0) intArrayOf(0, blockID) else intArrayOf(0),
blockReferences = ByteArray(16 * 16 * 16) { if (blockID != 0) 1 else 0 },
startCount = if (blockID == 0) 0 else 4096
)
}
// count variable with private set
var count: Short = startCount
private set
// writer to byte writer
fun write(writer: ByteWriter) {
// if the template is filled, send a filled chunk
if ((count.toInt() == 0 || count.toInt() == blockReferences.size) && blockIDs.size < 2) {
writer.writeUByte(0u)
writer.writeVarInt(if (count.toInt() == 0) blockIDs.first() else blockIDs.last())
writer.writeVarInt(0)
return
}
// 8 bits per entry (byte per block (could this be lowered for compression?))
writer.writeUByte(8u)
// write block ids
writer.writeVarInt(blockIDs.size)
for (id in blockIDs) writer.writeVarInt(id)
// write block references
if (blockReferences.size % 8 != 0) throw IllegalArgumentException("Block references was not divisible by 8. Recommended size is 4096.")
writer.writeVarInt(blockReferences.size / 8)
writer.writeByteArray(blockReferences)
}
fun fill(from: Vector3i, to: Vector3i, newID: Int) {
// range check
if (from.x !in 0..15 || from.y !in 0 .. 15 || from.z !in 0 .. 15)
throw IllegalArgumentException("Section fill call out of range in from $from")
if (to.x !in 0..15 || to.y !in 0 .. 15 || to.z !in 0 .. 15)
throw IllegalArgumentException("Section fill call out of range in to $to")
// fill blocks
(from.x .. to.x).forEach { x ->
(from.y .. to.y).forEach { y ->
(from.z .. to.z).forEach { z ->
uncheckedSet(Vector3i.from(x, y, z), newID)
}
}
}
}
fun set(position: Vector3i, newID: Int) {
// range check
if (position.x !in 0..15 || position.y !in 0 .. 15 || position.z !in 0 .. 15)
throw IllegalArgumentException("Section set call out of range $position")
uncheckedSet(position, newID)
}
fun uncheckedSet(position: Vector3i, newID: Int) {
// get ref index
val refIndex = locationToRefIndex(position)
// get index of new id in block ids
var index = blockIDs.indexOf(newID)
// if old ref index and new ref index are equal, cancel
if (blockReferences[refIndex].toInt() == index) return
// update index if necessary
if (index == -1) {
index = blockIDs.size
blockIDs = intArrayOf(*blockIDs, newID)
}
// update block count
if (newID == 0) count-- else count++
// set block
val oldIndex = blockReferences[refIndex]
blockReferences[refIndex] = index.toByte()
// check if old index does not exist in block references anymore
if (!blockReferences.any { it == oldIndex }) {
// remove the old index
blockIDs = blockIDs.filterIndexed { index, _ -> index != oldIndex.toInt() }.toIntArray()
// any items in block references greater than old index, remove 1 from that item
for (i in blockReferences.indices) {
if (blockReferences[i] > oldIndex) blockReferences[i]--
}
}
}
fun get(position: Vector3i): Int {
val refIndex = locationToRefIndex(position)
val blockID = blockReferences[refIndex]
return blockIDs[blockID.toInt()]
}
private fun locationToRefIndex(position: Vector3i) =
(position.y * 256) + (position.z * 16) + modChunkRefIndexByX(position.x)
// why is this necessary for java edition clients? IDK
private fun modChunkRefIndexByX(index: Int) =
when (index) {
in 0 .. 7 -> 7 - index
else -> 23 - index
}
} | 0 | Kotlin | 0 | 1 | 2290a5266ae56ef2e59cad88fc1f38e825b2cc88 | 4,405 | Meld | Apache License 2.0 |
Meld-Module-World/src/main/kotlin/io/github/daylightnebula/meld/world/chunks/Palettes.kt | DaylightNebula | 652,923,400 | false | {"Kotlin": 199201, "Python": 792} | package io.github.daylightnebula.meld.world.chunks
import io.github.daylightnebula.meld.server.networking.common.ByteWriter
import org.cloudburstmc.math.vector.Vector3i
class FlexiblePalette(
var blockIDs: IntArray = intArrayOf(0),
var blockReferences: ByteArray = ByteArray(16 * 16 * 16) { 0 },
var startCount: Short = 0
) {
companion object {
fun filled(blockID: Int = 0) = FlexiblePalette(
blockIDs = if (blockID != 0) intArrayOf(0, blockID) else intArrayOf(0),
blockReferences = ByteArray(16 * 16 * 16) { if (blockID != 0) 1 else 0 },
startCount = if (blockID == 0) 0 else 4096
)
}
// count variable with private set
var count: Short = startCount
private set
// writer to byte writer
fun write(writer: ByteWriter) {
// if the template is filled, send a filled chunk
if ((count.toInt() == 0 || count.toInt() == blockReferences.size) && blockIDs.size < 2) {
writer.writeUByte(0u)
writer.writeVarInt(if (count.toInt() == 0) blockIDs.first() else blockIDs.last())
writer.writeVarInt(0)
return
}
// 8 bits per entry (byte per block (could this be lowered for compression?))
writer.writeUByte(8u)
// write block ids
writer.writeVarInt(blockIDs.size)
for (id in blockIDs) writer.writeVarInt(id)
// write block references
if (blockReferences.size % 8 != 0) throw IllegalArgumentException("Block references was not divisible by 8. Recommended size is 4096.")
writer.writeVarInt(blockReferences.size / 8)
writer.writeByteArray(blockReferences)
}
fun fill(from: Vector3i, to: Vector3i, newID: Int) {
// range check
if (from.x !in 0..15 || from.y !in 0 .. 15 || from.z !in 0 .. 15)
throw IllegalArgumentException("Section fill call out of range in from $from")
if (to.x !in 0..15 || to.y !in 0 .. 15 || to.z !in 0 .. 15)
throw IllegalArgumentException("Section fill call out of range in to $to")
// fill blocks
(from.x .. to.x).forEach { x ->
(from.y .. to.y).forEach { y ->
(from.z .. to.z).forEach { z ->
uncheckedSet(Vector3i.from(x, y, z), newID)
}
}
}
}
fun set(position: Vector3i, newID: Int) {
// range check
if (position.x !in 0..15 || position.y !in 0 .. 15 || position.z !in 0 .. 15)
throw IllegalArgumentException("Section set call out of range $position")
uncheckedSet(position, newID)
}
fun uncheckedSet(position: Vector3i, newID: Int) {
// get ref index
val refIndex = locationToRefIndex(position)
// get index of new id in block ids
var index = blockIDs.indexOf(newID)
// if old ref index and new ref index are equal, cancel
if (blockReferences[refIndex].toInt() == index) return
// update index if necessary
if (index == -1) {
index = blockIDs.size
blockIDs = intArrayOf(*blockIDs, newID)
}
// update block count
if (newID == 0) count-- else count++
// set block
val oldIndex = blockReferences[refIndex]
blockReferences[refIndex] = index.toByte()
// check if old index does not exist in block references anymore
if (!blockReferences.any { it == oldIndex }) {
// remove the old index
blockIDs = blockIDs.filterIndexed { index, _ -> index != oldIndex.toInt() }.toIntArray()
// any items in block references greater than old index, remove 1 from that item
for (i in blockReferences.indices) {
if (blockReferences[i] > oldIndex) blockReferences[i]--
}
}
}
fun get(position: Vector3i): Int {
val refIndex = locationToRefIndex(position)
val blockID = blockReferences[refIndex]
return blockIDs[blockID.toInt()]
}
private fun locationToRefIndex(position: Vector3i) =
(position.y * 256) + (position.z * 16) + modChunkRefIndexByX(position.x)
// why is this necessary for java edition clients? IDK
private fun modChunkRefIndexByX(index: Int) =
when (index) {
in 0 .. 7 -> 7 - index
else -> 23 - index
}
} | 0 | Kotlin | 0 | 1 | 2290a5266ae56ef2e59cad88fc1f38e825b2cc88 | 4,405 | Meld | Apache License 2.0 |
app/src/main/java/com/hinterlong/kevin/swishticker/data/ActionType.kt | denzelpfeifer | 179,320,631 | true | {"Kotlin": 26219, "Java": 2184} | package com.hinterlong.kevin.swishticker.data
enum class ActionType constructor(val code:Int) {
TWO_POINT(0),
THREE_POINT(1),
FREE_THROW(2),
REBOUND(3),
BLOCK(4),
STEAL(5),
ASSIST(6),
FOUL(7)
} | 0 | Kotlin | 0 | 0 | 4c08ac9dda83fcead6e35507deeb711ec7a7455d | 226 | SwishTicker | Apache License 2.0 |
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/resolve/EclipseAnalyzerFacadeForJVM.kt | wpopielarski | 163,985,792 | true | {"Kotlin": 873465, "Java": 742545, "AspectJ": 16111} | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.core.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.builtins.JvmBuiltInsPackageFragmentProvider
import org.jetbrains.kotlin.cli.jvm.compiler.CliLightClassGenerationSupport
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.container.ComponentProvider
import org.jetbrains.kotlin.container.ValueDescriptor
import org.jetbrains.kotlin.context.ContextForNewModule
import org.jetbrains.kotlin.context.MutableModuleContext
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.jetbrains.kotlin.core.model.KotlinEnvironment
import org.jetbrains.kotlin.core.model.KotlinScriptEnvironment
import org.jetbrains.kotlin.core.utils.ProjectUtils
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDependenciesImpl
import org.jetbrains.kotlin.frontend.java.di.initJvmBuiltInsForTopDownAnalysis
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.JvmBuiltIns
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer
import org.jetbrains.kotlin.resolve.TopDownAnalysisMode
import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver
import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension
import org.jetbrains.kotlin.resolve.lazy.KotlinCodeAnalyzer
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory
import org.jetbrains.kotlin.util.KotlinFrontEndException
import java.lang.reflect.Type
import java.util.ArrayList
import java.util.LinkedHashSet
import org.jetbrains.kotlin.frontend.java.di.createContainerForTopDownAnalyzerForJvm as createContainerForScript
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.SourceOrBinaryModuleClassResolver
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.load.java.sam.SamWithReceiverResolver
import org.jetbrains.kotlin.core.model.SamWithReceiverResolverExtension
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider
data class AnalysisResultWithProvider(val analysisResult: AnalysisResult, val componentProvider: ComponentProvider?) {
companion object {
val EMPTY = AnalysisResultWithProvider(AnalysisResult.EMPTY, null)
}
}
public object EclipseAnalyzerFacadeForJVM {
public fun analyzeFilesWithJavaIntegration(
environment: KotlinEnvironment,
filesToAnalyze: Collection<KtFile>): AnalysisResultWithProvider {
val filesSet = filesToAnalyze.toSet()
if (filesSet.size != filesToAnalyze.size) {
KotlinLogger.logWarning("Analyzed files have duplicates")
}
val allFiles = LinkedHashSet<KtFile>(filesSet)
val addedFiles = filesSet.map { getPath(it) }.filterNotNull().toSet()
ProjectUtils.getSourceFilesWithDependencies(environment.javaProject).filterNotTo(allFiles) {
getPath(it) in addedFiles
}
val project = environment.project
val moduleContext = createModuleContext(project, environment.configuration, true)
val storageManager = moduleContext.storageManager
val module = moduleContext.module
val providerFactory = FileBasedDeclarationProviderFactory(moduleContext.storageManager, allFiles)
val trace = CliLightClassGenerationSupport.CliBindingTrace()
val sourceScope = TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, filesToAnalyze)
val moduleClassResolver = SourceOrBinaryModuleClassResolver(sourceScope)
val languageVersionSettings = LanguageVersionSettingsImpl(
LanguageVersionSettingsImpl.DEFAULT.languageVersion,
LanguageVersionSettingsImpl.DEFAULT.apiVersion)
val optionalBuiltInsModule = JvmBuiltIns(storageManager).apply { initialize(module, true) }.builtInsModule
val dependencyModule = run {
val dependenciesContext = ContextForNewModule(
moduleContext, Name.special("<dependencies of ${environment.configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"),
module.builtIns, null
)
val dependencyScope = GlobalSearchScope.notScope(sourceScope)
val dependenciesContainer = createContainerForTopDownAnalyzerForJvm(
dependenciesContext,
trace,
DeclarationProviderFactory.EMPTY,
dependencyScope,
LookupTracker.DO_NOTHING,
KotlinPackagePartProvider(environment),
JvmTarget.DEFAULT,
languageVersionSettings,
moduleClassResolver,
environment.javaProject)
moduleClassResolver.compiledCodeResolver = dependenciesContainer.get<JavaDescriptorResolver>()
dependenciesContext.setDependencies(listOfNotNull(dependenciesContext.module, optionalBuiltInsModule))
dependenciesContext.initializeModuleContents(CompositePackageFragmentProvider(listOf(
moduleClassResolver.compiledCodeResolver.packageFragmentProvider,
dependenciesContainer.get<JvmBuiltInsPackageFragmentProvider>()
)))
dependenciesContext.module
}
val container = createContainerForTopDownAnalyzerForJvm(
moduleContext,
trace,
providerFactory,
sourceScope,
LookupTracker.DO_NOTHING,
KotlinPackagePartProvider(environment),
JvmTarget.DEFAULT,
languageVersionSettings,
moduleClassResolver,
environment.javaProject).apply {
initJvmBuiltInsForTopDownAnalysis()
}
moduleClassResolver.sourceCodeResolver = container.get<JavaDescriptorResolver>()
val additionalProviders = ArrayList<PackageFragmentProvider>()
additionalProviders.add(container.get<JavaDescriptorResolver>().packageFragmentProvider)
PackageFragmentProviderExtension.getInstances(project).mapNotNullTo(additionalProviders) { extension ->
extension.getPackageFragmentProvider(project, module, storageManager, trace, null)
}
module.setDependencies(ModuleDependenciesImpl(
listOfNotNull(module, dependencyModule, optionalBuiltInsModule),
setOf(dependencyModule)
))
module.initialize(CompositePackageFragmentProvider(
listOf(container.get<KotlinCodeAnalyzer>().packageFragmentProvider) +
additionalProviders
))
try {
container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, filesSet)
} catch(e: KotlinFrontEndException) {
// Editor will break if we do not catch this exception
// and will not be able to save content without reopening it.
// In IDEA this exception throws only in CLI
KotlinLogger.logError(e)
}
return AnalysisResultWithProvider(
AnalysisResult.success(trace.getBindingContext(), module),
container)
}
public fun analyzeScript(
environment: KotlinScriptEnvironment,
scriptFile: KtFile): AnalysisResultWithProvider {
if (environment.isInitializingScriptDefinitions) {
// We can't start resolve when script definitions are not initialized
return AnalysisResultWithProvider.EMPTY
}
val trace = CliLightClassGenerationSupport.CliBindingTrace()
val container = TopDownAnalyzerFacadeForJVM.createContainer(
environment.project,
setOf(scriptFile),
trace,
environment.configuration,
{ KotlinPackagePartProvider(environment) },
{ storageManager: StorageManager, files: Collection<KtFile> -> FileBasedDeclarationProviderFactory(storageManager, files) }
)
try {
container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, setOf(scriptFile))
} catch(e: KotlinFrontEndException) {
// Editor will break if we do not catch this exception
// and will not be able to save content without reopening it.
// In IDEA this exception throws only in CLI
KotlinLogger.logError(e)
}
return AnalysisResultWithProvider(
AnalysisResult.success(trace.getBindingContext(), container.get<ModuleDescriptor>()),
container)
}
private fun getPath(jetFile: KtFile): String? = jetFile.getVirtualFile()?.getPath()
private fun createModuleContext(
project: Project,
configuration: CompilerConfiguration,
createBuiltInsFromModule: Boolean
): MutableModuleContext {
val projectContext = ProjectContext(project)
val builtIns = JvmBuiltIns(projectContext.storageManager, !createBuiltInsFromModule)
return ContextForNewModule(
projectContext, Name.special("<${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"), builtIns, null
).apply {
if (createBuiltInsFromModule) {
builtIns.builtInsModule = module
}
}
}
} | 0 | Kotlin | 1 | 0 | daff955c817b4c88cc9f29cd923ba0be9d8044dd | 11,165 | kotlin-eclipse | Apache License 2.0 |
app/src/main/java/com/example/expandablebottomnavigationbar/SearchFragment.kt | tunahanbozkurt | 615,692,461 | false | null | package com.example.expandablebottomnavigationbar
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.expandablebottomnavigationbar.databinding.FragmentSearchBinding
class SearchFragment : Fragment() {
private var _binding: FragmentSearchBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSearchBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btDetail.setOnClickListener {
findNavController().navigate(R.id.action_searchFragment_to_detailFragment)
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
} | 0 | Kotlin | 0 | 6 | e2d4d944830935fa970debca0fc57edb597c84d5 | 1,078 | ExpandableBottomNavigationBar | The Unlicense |
app/src/main/java/com/zipdabang/zipdabang_android/module/my/data/remote/signout/SignOutTokens.kt | zipdabang | 666,457,004 | false | {"Kotlin": 1689597} | package com.zipdabang.zipdabang_android.module.my.data.remote.signout
import com.google.gson.annotations.SerializedName
import kotlinx.serialization.Serializable
data class SignOutTokens(
@SerializedName("fcmToken") val fcmToken: String,
@SerializedName("serialNumber") val serialNumber: String
)
| 8 | Kotlin | 1 | 2 | ef22f7d73c2c44065714a6cffe783250b80487c8 | 307 | android | The Unlicense |
bootstrap/src/test/kotlin/net/dontdrinkandroot/wicket/bootstrap/behavior/ToolTipBehaviorTest.kt | dontdrinkandroot | 7,002,436 | false | null | package net.dontdrinkandroot.wicket.bootstrap.behavior
import net.dontdrinkandroot.wicket.bootstrap.test.AbstractWicketTest
import org.apache.wicket.core.util.string.ComponentRenderer
import org.apache.wicket.markup.html.WebMarkupContainer
import org.apache.wicket.model.IModel
import org.apache.wicket.model.Model
import org.apache.wicket.util.tester.TagTester
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class ToolTipBehaviorTest : AbstractWicketTest() {
@Test
fun testDefaultMarkup() {
val container = WebMarkupContainer("id")
container.add(ToolTipBehavior(Model("TestText")))
val componentMarkup = ComponentRenderer.renderComponent(container)
Assertions.assertEquals(
"<wicket:container wicket:id=\"id\" title=\"TestText\" data-toggle=\"tooltip\" data-placement=\"top\" data-delay=\"0\"></wicket:container>",
componentMarkup.toString()
)
}
@Test
fun testPosition() {
val container = WebMarkupContainer("id")
val behavior = ToolTipBehavior(Model.of("TestText"))
container.add(behavior)
var tagTester: TagTester
var componentMarkup: String
val positionModel: IModel<ToolTipBehavior.Position> = Model()
positionModel.setObject(ToolTipBehavior.Position.TOP)
componentMarkup = ComponentRenderer.renderComponent(container).toString()
tagTester = TagTester.createTagByAttribute(componentMarkup, "wicket:id", "id")
tagTester.getAttributeIs("data-placement", "top")
positionModel.setObject(ToolTipBehavior.Position.RIGHT)
componentMarkup = ComponentRenderer.renderComponent(container).toString()
tagTester = TagTester.createTagByAttribute(componentMarkup, "wicket:id", "id")
tagTester.getAttributeIs("data-placement", "right")
positionModel.setObject(ToolTipBehavior.Position.BOTTOM)
componentMarkup = ComponentRenderer.renderComponent(container).toString()
tagTester = TagTester.createTagByAttribute(componentMarkup, "wicket:id", "id")
tagTester.getAttributeIs("data-placement", "bottom")
positionModel.setObject(ToolTipBehavior.Position.LEFT)
componentMarkup = ComponentRenderer.renderComponent(container).toString()
tagTester = TagTester.createTagByAttribute(componentMarkup, "wicket:id", "id")
tagTester.getAttributeIs("data-placement", "left")
}
} | 34 | Kotlin | 1 | 3 | 51fba9712321f0fdb5faa452fddc63aa9b360fe6 | 2,445 | wicket.java | Apache License 2.0 |
database/src/commonMain/kotlin/co/nestor/database/provider/builder/IDatabaseBuilderProvider.kt | kiquenet85 | 849,346,240 | false | {"Kotlin": 183158, "Swift": 621} | package co.nestor.database.provider.builder
import androidx.room.RoomDatabase
import co.nestor.database.AppDatabase
interface IDatabaseBuilderProvider {
fun getDatabaseBuilder(): RoomDatabase.Builder<AppDatabase>
}
| 0 | Kotlin | 0 | 0 | 2f000a653ddbb56f7439df4185e944fd76df6061 | 221 | kueski | Apache License 2.0 |
TemplateMethod/src/main/kotlin/impl/ClassB.kt | AaronChuang | 208,242,423 | false | null | package impl
import AbstractClass
// 實作演算法各步驟
class ClassB: AbstractClass() {
override fun primitiveOperation1() {
println("ClassB.primitiveOperation1")
}
override fun primitiveOperation2() {
println("ClassB.primitiveOperation2")
}
} | 0 | Kotlin | 0 | 0 | 9e31b8065a7b98e30d93033fae92d0381c17ef34 | 267 | Kotlin-DesignPatternExample | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/ui/components/ClickableRoute.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.components
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.LocalContentColor
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.model.Note
import com.vitorpamplona.amethyst.model.User
import com.vitorpamplona.amethyst.service.NIP30Parser
import com.vitorpamplona.amethyst.service.model.ChannelCreateEvent
import com.vitorpamplona.amethyst.service.model.PrivateDmEvent
import com.vitorpamplona.amethyst.service.nip19.Nip19
import com.vitorpamplona.amethyst.ui.actions.ImmutableListOfLists
import com.vitorpamplona.amethyst.ui.actions.toImmutableListOfLists
import com.vitorpamplona.amethyst.ui.note.LoadChannel
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun ClickableRoute(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
when (nip19.type) {
Nip19.Type.USER -> {
DisplayUser(nip19, nav)
}
Nip19.Type.ADDRESS -> {
DisplayAddress(nip19, nav)
}
Nip19.Type.NOTE -> {
DisplayNote(nip19, nav)
}
Nip19.Type.EVENT -> {
DisplayEvent(nip19, nav)
}
else -> {
Text(
remember {
"@${nip19.hex}${nip19.additionalChars} "
}
)
}
}
}
@Composable
private fun LoadNote(
hex: String,
content: @Composable (Note) -> Unit
) {
var noteBase by remember(hex) { mutableStateOf(LocalCache.getNoteIfExists(hex)) }
if (noteBase == null) {
LaunchedEffect(key1 = hex) {
launch(Dispatchers.IO) {
noteBase = LocalCache.checkGetOrCreateNote(hex)
}
}
}
noteBase?.let {
content(it)
}
}
@Composable
private fun DisplayEvent(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
LoadNote(nip19.hex) {
DisplayNoteLink(it, nip19, nav)
}
}
@Composable
private fun DisplayNote(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
LoadNote(nip19.hex) {
DisplayNoteLink(it, nip19, nav)
}
}
@Composable
private fun DisplayNoteLink(
it: Note,
nip19: Nip19.Return,
nav: (String) -> Unit
) {
val noteState by it.live().metadata.observeAsState()
val note = remember(noteState) { noteState?.note } ?: return
val channelHex = remember(noteState) { note.channelHex() }
val noteIdDisplayNote = remember(noteState) { "@${note.idDisplayNote()}" }
val addedCharts = remember { "${nip19.additionalChars} " }
if (note.event is ChannelCreateEvent || nip19.kind == ChannelCreateEvent.kind) {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Channel/${nip19.hex}" },
nav = nav
)
} else if (note.event is PrivateDmEvent || nip19.kind == PrivateDmEvent.kind) {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Room/${note.author?.pubkeyHex}" },
nav = nav
)
} else if (channelHex != null) {
LoadChannel(baseChannelHex = channelHex) { baseChannel ->
val channelState by baseChannel.live.observeAsState()
val channelDisplayName by remember(channelState) {
derivedStateOf {
channelState?.channel?.toBestDisplayName() ?: noteIdDisplayNote
}
}
CreateClickableText(
clickablePart = channelDisplayName,
suffix = addedCharts,
route = remember(noteState) { "Channel/${baseChannel.idHex}" },
nav = nav
)
}
} else {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Event/${nip19.hex}" },
nav = nav
)
}
}
@Composable
private fun DisplayAddress(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
var noteBase by remember(nip19) { mutableStateOf(LocalCache.getNoteIfExists(nip19.hex)) }
if (noteBase == null) {
LaunchedEffect(key1 = nip19.hex) {
launch(Dispatchers.IO) {
noteBase = LocalCache.checkGetOrCreateAddressableNote(nip19.hex)
}
}
}
noteBase?.let {
val noteState by it.live().metadata.observeAsState()
val route = remember(noteState) { "Note/${nip19.hex}" }
val displayName = remember(noteState) { "@${noteState?.note?.idDisplayNote()}" }
val addedCharts = remember { "${nip19.additionalChars} " }
CreateClickableText(
clickablePart = displayName,
suffix = addedCharts,
route = route,
nav = nav
)
}
if (noteBase == null) {
Text(
remember {
"@${nip19.hex}${nip19.additionalChars} "
}
)
}
}
@Composable
private fun DisplayUser(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
var userBase by remember(nip19) { mutableStateOf(LocalCache.getUserIfExists(nip19.hex)) }
if (userBase == null) {
LaunchedEffect(key1 = nip19.hex) {
launch(Dispatchers.IO) {
userBase = LocalCache.checkGetOrCreateUser(nip19.hex)
}
}
}
userBase?.let {
RenderUserAsClickableText(it, nip19, nav)
}
if (userBase == null) {
Text(
remember {
"@${nip19.hex}${nip19.additionalChars} "
}
)
}
}
@Composable
private fun RenderUserAsClickableText(
baseUser: User,
nip19: Nip19.Return,
nav: (String) -> Unit
) {
val userState by baseUser.live().metadata.observeAsState()
val route = remember { "User/${baseUser.pubkeyHex}" }
val userDisplayName by remember(userState) {
derivedStateOf {
userState?.user?.toBestDisplayName()
}
}
val userTags by remember(userState) {
derivedStateOf {
userState?.user?.info?.latestMetadata?.tags?.toImmutableListOfLists()
}
}
val addedCharts = remember(nip19) {
"${nip19.additionalChars} "
}
userDisplayName?.let {
CreateClickableTextWithEmoji(
clickablePart = it,
suffix = addedCharts,
maxLines = 1,
route = route,
nav = nav,
tags = userTags
)
}
}
@Composable
fun CreateClickableText(
clickablePart: String,
suffix: String,
maxLines: Int = Int.MAX_VALUE,
overrideColor: Color? = null,
fontWeight: FontWeight = FontWeight.Normal,
route: String,
nav: (String) -> Unit
) {
val currentStyle = LocalTextStyle.current
val primaryColor = MaterialTheme.colors.primary
val onBackgroundColor = MaterialTheme.colors.onBackground
val clickablePartStyle = remember(primaryColor, overrideColor) {
currentStyle.copy(color = overrideColor ?: primaryColor, fontWeight = fontWeight).toSpanStyle()
}
val nonClickablePartStyle = remember(onBackgroundColor, overrideColor) {
currentStyle.copy(color = overrideColor ?: onBackgroundColor, fontWeight = fontWeight).toSpanStyle()
}
val text = remember(clickablePartStyle, nonClickablePartStyle, clickablePart, suffix) {
buildAnnotatedString {
withStyle(clickablePartStyle) {
append(clickablePart)
}
withStyle(nonClickablePartStyle) {
append(suffix)
}
}
}
ClickableText(
text = text,
maxLines = maxLines,
onClick = { nav(route) }
)
}
@Composable
fun CreateTextWithEmoji(
text: String,
tags: ImmutableListOfLists<String>?,
color: Color = Color.Unspecified,
textAlign: TextAlign? = null,
fontWeight: FontWeight? = null,
fontSize: TextUnit = TextUnit.Unspecified,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
modifier: Modifier = Modifier
) {
var emojiList by remember(text) { mutableStateOf<ImmutableList<Renderable>>(persistentListOf()) }
LaunchedEffect(key1 = text) {
launch(Dispatchers.Default) {
val emojis =
tags?.lists?.filter { it.size > 2 && it[0] == "emoji" }?.associate { ":${it[1]}:" to it[2] } ?: emptyMap()
if (emojis.isNotEmpty()) {
val newEmojiList = assembleAnnotatedList(text, emojis)
if (newEmojiList.isNotEmpty()) {
emojiList = newEmojiList.toImmutableList()
}
}
}
}
val textColor = color.takeOrElse {
LocalTextStyle.current.color.takeOrElse {
LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
}
}
if (emojiList.isEmpty()) {
Text(
text = text,
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize,
maxLines = maxLines,
overflow = overflow,
modifier = modifier
)
} else {
val style = LocalTextStyle.current.merge(
TextStyle(
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize
)
).toSpanStyle()
InLineIconRenderer(emojiList, style, maxLines, overflow, modifier)
}
}
@Composable
fun CreateTextWithEmoji(
text: String,
emojis: ImmutableMap<String, String>,
color: Color = Color.Unspecified,
textAlign: TextAlign? = null,
fontWeight: FontWeight? = null,
fontSize: TextUnit = TextUnit.Unspecified,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
modifier: Modifier = Modifier
) {
var emojiList by remember(text) { mutableStateOf<ImmutableList<Renderable>>(persistentListOf()) }
if (emojis.isNotEmpty()) {
LaunchedEffect(key1 = text) {
launch(Dispatchers.Default) {
val newEmojiList = assembleAnnotatedList(text, emojis)
if (newEmojiList.isNotEmpty()) {
emojiList = newEmojiList.toImmutableList()
}
}
}
}
val textColor = color.takeOrElse {
LocalTextStyle.current.color.takeOrElse {
LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
}
}
if (emojiList.isEmpty()) {
Text(
text = text,
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize,
maxLines = maxLines,
overflow = overflow,
modifier = modifier
)
} else {
val currentStyle = LocalTextStyle.current
val style = remember(currentStyle) {
currentStyle.merge(
TextStyle(
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize
)
).toSpanStyle()
}
InLineIconRenderer(emojiList, style, maxLines, overflow, modifier)
}
}
@Composable
fun CreateClickableTextWithEmoji(
clickablePart: String,
maxLines: Int = Int.MAX_VALUE,
tags: ImmutableListOfLists<String>?,
style: TextStyle,
onClick: (Int) -> Unit
) {
var emojiList by remember(clickablePart) { mutableStateOf<ImmutableList<Renderable>>(persistentListOf()) }
LaunchedEffect(key1 = clickablePart) {
launch(Dispatchers.Default) {
val emojis =
tags?.lists?.filter { it.size > 2 && it[0] == "emoji" }?.associate { ":${it[1]}:" to it[2] } ?: emptyMap()
if (emojis.isNotEmpty()) {
val newEmojiList = assembleAnnotatedList(clickablePart, emojis)
if (newEmojiList.isNotEmpty()) {
emojiList = newEmojiList.toImmutableList()
}
}
}
}
if (emojiList.isEmpty()) {
ClickableText(
text = AnnotatedString(clickablePart),
style = style,
maxLines = maxLines,
onClick = onClick
)
} else {
ClickableInLineIconRenderer(emojiList, maxLines, style.toSpanStyle()) {
onClick(it)
}
}
}
@Immutable
data class DoubleEmojiList(
val part1: ImmutableList<Renderable>,
val part2: ImmutableList<Renderable>
)
@Composable
fun CreateClickableTextWithEmoji(
clickablePart: String,
suffix: String,
maxLines: Int = Int.MAX_VALUE,
overrideColor: Color? = null,
fontWeight: FontWeight = FontWeight.Normal,
route: String,
nav: (String) -> Unit,
tags: ImmutableListOfLists<String>?
) {
var emojiLists by remember(clickablePart) {
mutableStateOf<DoubleEmojiList?>(null)
}
LaunchedEffect(key1 = clickablePart) {
launch(Dispatchers.Default) {
val emojis =
tags?.lists?.filter { it.size > 2 && it[0] == "emoji" }?.associate { ":${it[1]}:" to it[2] } ?: emptyMap()
if (emojis.isNotEmpty()) {
val newEmojiList1 = assembleAnnotatedList(clickablePart, emojis)
val newEmojiList2 = assembleAnnotatedList(suffix, emojis)
if (newEmojiList1.isNotEmpty() || newEmojiList2.isNotEmpty()) {
emojiLists = DoubleEmojiList(newEmojiList1.toImmutableList(), newEmojiList2.toImmutableList())
}
}
}
}
if (emojiLists == null) {
CreateClickableText(clickablePart, suffix, maxLines, overrideColor, fontWeight, route, nav)
} else {
ClickableInLineIconRenderer(
emojiLists!!.part1,
maxLines,
LocalTextStyle.current.copy(color = overrideColor ?: MaterialTheme.colors.primary, fontWeight = fontWeight).toSpanStyle()
) {
nav(route)
}
InLineIconRenderer(
emojiLists!!.part2,
LocalTextStyle.current.copy(color = overrideColor ?: MaterialTheme.colors.onBackground, fontWeight = fontWeight).toSpanStyle(),
maxLines
)
}
}
suspend fun assembleAnnotatedList(text: String, emojis: Map<String, String>): ImmutableList<Renderable> {
return NIP30Parser().buildArray(text).map {
val url = emojis[it]
if (url != null) {
ImageUrlType(url)
} else {
TextType(it)
}
}.toImmutableList()
}
@Immutable
open class Renderable()
@Immutable
class TextType(val text: String) : Renderable()
@Immutable
class ImageUrlType(val url: String) : Renderable()
@Composable
fun ClickableInLineIconRenderer(
wordsInOrder: ImmutableList<Renderable>,
maxLines: Int = Int.MAX_VALUE,
style: SpanStyle,
onClick: (Int) -> Unit
) {
val inlineContent = wordsInOrder.mapIndexedNotNull { idx, value ->
if (value is ImageUrlType) {
Pair(
"inlineContent$idx",
InlineTextContent(
Placeholder(
width = 17.sp,
height = 17.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
AsyncImage(
model = value.url,
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.padding(1.dp)
)
}
)
} else {
null
}
}.associate { it.first to it.second }
val annotatedText = buildAnnotatedString {
wordsInOrder.forEachIndexed { idx, value ->
withStyle(
style
) {
if (value is TextType) {
append(value.text)
} else if (value is ImageUrlType) {
appendInlineContent("inlineContent$idx", "[icon]")
}
}
}
}
val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
val pressIndicator = Modifier.pointerInput(onClick) {
detectTapGestures { pos ->
layoutResult.value?.let { layoutResult ->
onClick(layoutResult.getOffsetForPosition(pos))
}
}
}
BasicText(
text = annotatedText,
modifier = pressIndicator,
inlineContent = inlineContent,
maxLines = maxLines,
onTextLayout = {
layoutResult.value = it
}
)
}
@Composable
fun InLineIconRenderer(
wordsInOrder: ImmutableList<Renderable>,
style: SpanStyle,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
modifier: Modifier = Modifier
) {
val inlineContent = wordsInOrder.mapIndexedNotNull { idx, value ->
if (value is ImageUrlType) {
Pair(
"inlineContent$idx",
InlineTextContent(
Placeholder(
width = 20.sp,
height = 20.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
AsyncImage(
model = value.url,
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 1.dp)
)
}
)
} else {
null
}
}.associate { it.first to it.second }
val annotatedText = buildAnnotatedString {
wordsInOrder.forEachIndexed { idx, value ->
withStyle(
style
) {
if (value is TextType) {
append(value.text)
} else if (value is ImageUrlType) {
appendInlineContent("inlineContent$idx", "[icon]")
}
}
}
}
Text(
text = annotatedText,
inlineContent = inlineContent,
maxLines = maxLines,
overflow = overflow,
modifier = modifier
)
}
| 158 | null | 144 | 995 | 0bb39f91b9dddf81dcec63f3d97674f26872fbd0 | 20,543 | amethyst | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/ui/components/ClickableRoute.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.components
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.LocalContentColor
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.model.Note
import com.vitorpamplona.amethyst.model.User
import com.vitorpamplona.amethyst.service.NIP30Parser
import com.vitorpamplona.amethyst.service.model.ChannelCreateEvent
import com.vitorpamplona.amethyst.service.model.PrivateDmEvent
import com.vitorpamplona.amethyst.service.nip19.Nip19
import com.vitorpamplona.amethyst.ui.actions.ImmutableListOfLists
import com.vitorpamplona.amethyst.ui.actions.toImmutableListOfLists
import com.vitorpamplona.amethyst.ui.note.LoadChannel
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun ClickableRoute(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
when (nip19.type) {
Nip19.Type.USER -> {
DisplayUser(nip19, nav)
}
Nip19.Type.ADDRESS -> {
DisplayAddress(nip19, nav)
}
Nip19.Type.NOTE -> {
DisplayNote(nip19, nav)
}
Nip19.Type.EVENT -> {
DisplayEvent(nip19, nav)
}
else -> {
Text(
remember {
"@${nip19.hex}${nip19.additionalChars} "
}
)
}
}
}
@Composable
private fun LoadNote(
hex: String,
content: @Composable (Note) -> Unit
) {
var noteBase by remember(hex) { mutableStateOf(LocalCache.getNoteIfExists(hex)) }
if (noteBase == null) {
LaunchedEffect(key1 = hex) {
launch(Dispatchers.IO) {
noteBase = LocalCache.checkGetOrCreateNote(hex)
}
}
}
noteBase?.let {
content(it)
}
}
@Composable
private fun DisplayEvent(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
LoadNote(nip19.hex) {
DisplayNoteLink(it, nip19, nav)
}
}
@Composable
private fun DisplayNote(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
LoadNote(nip19.hex) {
DisplayNoteLink(it, nip19, nav)
}
}
@Composable
private fun DisplayNoteLink(
it: Note,
nip19: Nip19.Return,
nav: (String) -> Unit
) {
val noteState by it.live().metadata.observeAsState()
val note = remember(noteState) { noteState?.note } ?: return
val channelHex = remember(noteState) { note.channelHex() }
val noteIdDisplayNote = remember(noteState) { "@${note.idDisplayNote()}" }
val addedCharts = remember { "${nip19.additionalChars} " }
if (note.event is ChannelCreateEvent || nip19.kind == ChannelCreateEvent.kind) {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Channel/${nip19.hex}" },
nav = nav
)
} else if (note.event is PrivateDmEvent || nip19.kind == PrivateDmEvent.kind) {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Room/${note.author?.pubkeyHex}" },
nav = nav
)
} else if (channelHex != null) {
LoadChannel(baseChannelHex = channelHex) { baseChannel ->
val channelState by baseChannel.live.observeAsState()
val channelDisplayName by remember(channelState) {
derivedStateOf {
channelState?.channel?.toBestDisplayName() ?: noteIdDisplayNote
}
}
CreateClickableText(
clickablePart = channelDisplayName,
suffix = addedCharts,
route = remember(noteState) { "Channel/${baseChannel.idHex}" },
nav = nav
)
}
} else {
CreateClickableText(
clickablePart = noteIdDisplayNote,
suffix = addedCharts,
route = remember(noteState) { "Event/${nip19.hex}" },
nav = nav
)
}
}
@Composable
private fun DisplayAddress(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
var noteBase by remember(nip19) { mutableStateOf(LocalCache.getNoteIfExists(nip19.hex)) }
if (noteBase == null) {
LaunchedEffect(key1 = nip19.hex) {
launch(Dispatchers.IO) {
noteBase = LocalCache.checkGetOrCreateAddressableNote(nip19.hex)
}
}
}
noteBase?.let {
val noteState by it.live().metadata.observeAsState()
val route = remember(noteState) { "Note/${nip19.hex}" }
val displayName = remember(noteState) { "@${noteState?.note?.idDisplayNote()}" }
val addedCharts = remember { "${nip19.additionalChars} " }
CreateClickableText(
clickablePart = displayName,
suffix = addedCharts,
route = route,
nav = nav
)
}
if (noteBase == null) {
Text(
remember {
"@${nip19.hex}${nip19.additionalChars} "
}
)
}
}
@Composable
private fun DisplayUser(
nip19: Nip19.Return,
nav: (String) -> Unit
) {
var userBase by remember(nip19) { mutableStateOf(LocalCache.getUserIfExists(nip19.hex)) }
if (userBase == null) {
LaunchedEffect(key1 = nip19.hex) {
launch(Dispatchers.IO) {
userBase = LocalCache.checkGetOrCreateUser(nip19.hex)
}
}
}
userBase?.let {
RenderUserAsClickableText(it, nip19, nav)
}
if (userBase == null) {
Text(
remember {
"@${nip19.hex}${nip19.additionalChars} "
}
)
}
}
@Composable
private fun RenderUserAsClickableText(
baseUser: User,
nip19: Nip19.Return,
nav: (String) -> Unit
) {
val userState by baseUser.live().metadata.observeAsState()
val route = remember { "User/${baseUser.pubkeyHex}" }
val userDisplayName by remember(userState) {
derivedStateOf {
userState?.user?.toBestDisplayName()
}
}
val userTags by remember(userState) {
derivedStateOf {
userState?.user?.info?.latestMetadata?.tags?.toImmutableListOfLists()
}
}
val addedCharts = remember(nip19) {
"${nip19.additionalChars} "
}
userDisplayName?.let {
CreateClickableTextWithEmoji(
clickablePart = it,
suffix = addedCharts,
maxLines = 1,
route = route,
nav = nav,
tags = userTags
)
}
}
@Composable
fun CreateClickableText(
clickablePart: String,
suffix: String,
maxLines: Int = Int.MAX_VALUE,
overrideColor: Color? = null,
fontWeight: FontWeight = FontWeight.Normal,
route: String,
nav: (String) -> Unit
) {
val currentStyle = LocalTextStyle.current
val primaryColor = MaterialTheme.colors.primary
val onBackgroundColor = MaterialTheme.colors.onBackground
val clickablePartStyle = remember(primaryColor, overrideColor) {
currentStyle.copy(color = overrideColor ?: primaryColor, fontWeight = fontWeight).toSpanStyle()
}
val nonClickablePartStyle = remember(onBackgroundColor, overrideColor) {
currentStyle.copy(color = overrideColor ?: onBackgroundColor, fontWeight = fontWeight).toSpanStyle()
}
val text = remember(clickablePartStyle, nonClickablePartStyle, clickablePart, suffix) {
buildAnnotatedString {
withStyle(clickablePartStyle) {
append(clickablePart)
}
withStyle(nonClickablePartStyle) {
append(suffix)
}
}
}
ClickableText(
text = text,
maxLines = maxLines,
onClick = { nav(route) }
)
}
@Composable
fun CreateTextWithEmoji(
text: String,
tags: ImmutableListOfLists<String>?,
color: Color = Color.Unspecified,
textAlign: TextAlign? = null,
fontWeight: FontWeight? = null,
fontSize: TextUnit = TextUnit.Unspecified,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
modifier: Modifier = Modifier
) {
var emojiList by remember(text) { mutableStateOf<ImmutableList<Renderable>>(persistentListOf()) }
LaunchedEffect(key1 = text) {
launch(Dispatchers.Default) {
val emojis =
tags?.lists?.filter { it.size > 2 && it[0] == "emoji" }?.associate { ":${it[1]}:" to it[2] } ?: emptyMap()
if (emojis.isNotEmpty()) {
val newEmojiList = assembleAnnotatedList(text, emojis)
if (newEmojiList.isNotEmpty()) {
emojiList = newEmojiList.toImmutableList()
}
}
}
}
val textColor = color.takeOrElse {
LocalTextStyle.current.color.takeOrElse {
LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
}
}
if (emojiList.isEmpty()) {
Text(
text = text,
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize,
maxLines = maxLines,
overflow = overflow,
modifier = modifier
)
} else {
val style = LocalTextStyle.current.merge(
TextStyle(
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize
)
).toSpanStyle()
InLineIconRenderer(emojiList, style, maxLines, overflow, modifier)
}
}
@Composable
fun CreateTextWithEmoji(
text: String,
emojis: ImmutableMap<String, String>,
color: Color = Color.Unspecified,
textAlign: TextAlign? = null,
fontWeight: FontWeight? = null,
fontSize: TextUnit = TextUnit.Unspecified,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
modifier: Modifier = Modifier
) {
var emojiList by remember(text) { mutableStateOf<ImmutableList<Renderable>>(persistentListOf()) }
if (emojis.isNotEmpty()) {
LaunchedEffect(key1 = text) {
launch(Dispatchers.Default) {
val newEmojiList = assembleAnnotatedList(text, emojis)
if (newEmojiList.isNotEmpty()) {
emojiList = newEmojiList.toImmutableList()
}
}
}
}
val textColor = color.takeOrElse {
LocalTextStyle.current.color.takeOrElse {
LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
}
}
if (emojiList.isEmpty()) {
Text(
text = text,
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize,
maxLines = maxLines,
overflow = overflow,
modifier = modifier
)
} else {
val currentStyle = LocalTextStyle.current
val style = remember(currentStyle) {
currentStyle.merge(
TextStyle(
color = textColor,
textAlign = textAlign,
fontWeight = fontWeight,
fontSize = fontSize
)
).toSpanStyle()
}
InLineIconRenderer(emojiList, style, maxLines, overflow, modifier)
}
}
@Composable
fun CreateClickableTextWithEmoji(
clickablePart: String,
maxLines: Int = Int.MAX_VALUE,
tags: ImmutableListOfLists<String>?,
style: TextStyle,
onClick: (Int) -> Unit
) {
var emojiList by remember(clickablePart) { mutableStateOf<ImmutableList<Renderable>>(persistentListOf()) }
LaunchedEffect(key1 = clickablePart) {
launch(Dispatchers.Default) {
val emojis =
tags?.lists?.filter { it.size > 2 && it[0] == "emoji" }?.associate { ":${it[1]}:" to it[2] } ?: emptyMap()
if (emojis.isNotEmpty()) {
val newEmojiList = assembleAnnotatedList(clickablePart, emojis)
if (newEmojiList.isNotEmpty()) {
emojiList = newEmojiList.toImmutableList()
}
}
}
}
if (emojiList.isEmpty()) {
ClickableText(
text = AnnotatedString(clickablePart),
style = style,
maxLines = maxLines,
onClick = onClick
)
} else {
ClickableInLineIconRenderer(emojiList, maxLines, style.toSpanStyle()) {
onClick(it)
}
}
}
@Immutable
data class DoubleEmojiList(
val part1: ImmutableList<Renderable>,
val part2: ImmutableList<Renderable>
)
@Composable
fun CreateClickableTextWithEmoji(
clickablePart: String,
suffix: String,
maxLines: Int = Int.MAX_VALUE,
overrideColor: Color? = null,
fontWeight: FontWeight = FontWeight.Normal,
route: String,
nav: (String) -> Unit,
tags: ImmutableListOfLists<String>?
) {
var emojiLists by remember(clickablePart) {
mutableStateOf<DoubleEmojiList?>(null)
}
LaunchedEffect(key1 = clickablePart) {
launch(Dispatchers.Default) {
val emojis =
tags?.lists?.filter { it.size > 2 && it[0] == "emoji" }?.associate { ":${it[1]}:" to it[2] } ?: emptyMap()
if (emojis.isNotEmpty()) {
val newEmojiList1 = assembleAnnotatedList(clickablePart, emojis)
val newEmojiList2 = assembleAnnotatedList(suffix, emojis)
if (newEmojiList1.isNotEmpty() || newEmojiList2.isNotEmpty()) {
emojiLists = DoubleEmojiList(newEmojiList1.toImmutableList(), newEmojiList2.toImmutableList())
}
}
}
}
if (emojiLists == null) {
CreateClickableText(clickablePart, suffix, maxLines, overrideColor, fontWeight, route, nav)
} else {
ClickableInLineIconRenderer(
emojiLists!!.part1,
maxLines,
LocalTextStyle.current.copy(color = overrideColor ?: MaterialTheme.colors.primary, fontWeight = fontWeight).toSpanStyle()
) {
nav(route)
}
InLineIconRenderer(
emojiLists!!.part2,
LocalTextStyle.current.copy(color = overrideColor ?: MaterialTheme.colors.onBackground, fontWeight = fontWeight).toSpanStyle(),
maxLines
)
}
}
suspend fun assembleAnnotatedList(text: String, emojis: Map<String, String>): ImmutableList<Renderable> {
return NIP30Parser().buildArray(text).map {
val url = emojis[it]
if (url != null) {
ImageUrlType(url)
} else {
TextType(it)
}
}.toImmutableList()
}
@Immutable
open class Renderable()
@Immutable
class TextType(val text: String) : Renderable()
@Immutable
class ImageUrlType(val url: String) : Renderable()
@Composable
fun ClickableInLineIconRenderer(
wordsInOrder: ImmutableList<Renderable>,
maxLines: Int = Int.MAX_VALUE,
style: SpanStyle,
onClick: (Int) -> Unit
) {
val inlineContent = wordsInOrder.mapIndexedNotNull { idx, value ->
if (value is ImageUrlType) {
Pair(
"inlineContent$idx",
InlineTextContent(
Placeholder(
width = 17.sp,
height = 17.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
AsyncImage(
model = value.url,
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.padding(1.dp)
)
}
)
} else {
null
}
}.associate { it.first to it.second }
val annotatedText = buildAnnotatedString {
wordsInOrder.forEachIndexed { idx, value ->
withStyle(
style
) {
if (value is TextType) {
append(value.text)
} else if (value is ImageUrlType) {
appendInlineContent("inlineContent$idx", "[icon]")
}
}
}
}
val layoutResult = remember { mutableStateOf<TextLayoutResult?>(null) }
val pressIndicator = Modifier.pointerInput(onClick) {
detectTapGestures { pos ->
layoutResult.value?.let { layoutResult ->
onClick(layoutResult.getOffsetForPosition(pos))
}
}
}
BasicText(
text = annotatedText,
modifier = pressIndicator,
inlineContent = inlineContent,
maxLines = maxLines,
onTextLayout = {
layoutResult.value = it
}
)
}
@Composable
fun InLineIconRenderer(
wordsInOrder: ImmutableList<Renderable>,
style: SpanStyle,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
modifier: Modifier = Modifier
) {
val inlineContent = wordsInOrder.mapIndexedNotNull { idx, value ->
if (value is ImageUrlType) {
Pair(
"inlineContent$idx",
InlineTextContent(
Placeholder(
width = 20.sp,
height = 20.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
AsyncImage(
model = value.url,
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 1.dp)
)
}
)
} else {
null
}
}.associate { it.first to it.second }
val annotatedText = buildAnnotatedString {
wordsInOrder.forEachIndexed { idx, value ->
withStyle(
style
) {
if (value is TextType) {
append(value.text)
} else if (value is ImageUrlType) {
appendInlineContent("inlineContent$idx", "[icon]")
}
}
}
}
Text(
text = annotatedText,
inlineContent = inlineContent,
maxLines = maxLines,
overflow = overflow,
modifier = modifier
)
}
| 158 | null | 144 | 995 | 0bb39f91b9dddf81dcec63f3d97674f26872fbd0 | 20,543 | amethyst | MIT License |
app/src/main/java/com/ku_stacks/ku_ring/data/mapper/EntityToModelMapper.kt | KU-Stacks | 412,458,697 | false | null | package com.ku_stacks.ku_ring.data.mapper
import com.ku_stacks.ku_ring.data.db.NoticeEntity
import com.ku_stacks.ku_ring.data.db.PushEntity
import com.ku_stacks.ku_ring.data.model.Notice
import com.ku_stacks.ku_ring.data.model.Push
import com.ku_stacks.ku_ring.util.WordConverter
import com.ku_stacks.ku_ring.util.isOnlyAlphabets
import timber.log.Timber
fun List<PushEntity>.toPushList(): List<Push> = map { it.toPush() }
fun PushEntity.toPush(): Push {
val subjectAndTag = splitSubjectAndTag(subject.trim())
// DO NOT ERASE: legacy version stores category to korean.
val categoryEng = if (category.isOnlyAlphabets()) {
category
} else {
WordConverter.convertKoreanToEnglish(category)
}
return Push(
articleId = articleId,
category = categoryEng,
postedDate = postedDate,
subject = subjectAndTag.first,
baseUrl = baseUrl,
isNew = isNew,
receivedDate = receivedDate,
tag = subjectAndTag.second
)
}
fun List<NoticeEntity>.toNoticeList() = map { it.toNotice() }
fun NoticeEntity.toNotice(): Notice {
if (this.subject.isEmpty()) {
Timber.e("Notice.subject is empty: $this")
}
val (subject, tag) = splitSubjectAndTag(subject)
return Notice(
postedDate = postedDate,
subject = subject,
category = category,
url = url,
articleId = articleId,
isNew = isNew,
isRead = isRead,
isSubscribing = false,
isSaved = isSaved,
isReadOnStorage = isReadOnStorage,
tag = tag
)
}
| 0 | Kotlin | 0 | 11 | b5b33f75d2373787b4b859311a2180dcf9efe75e | 1,589 | KU-Ring-Android | Apache License 2.0 |
main/src/main/java/com/oratakashi/hilt/main/ui/main/LibraryViewModel.kt | oratakashi | 341,453,675 | false | null | package com.oratakashi.hilt.main.ui.main
import android.util.Log
import androidx.lifecycle.ViewModel
import com.oratakashi.hilt.core.data.network.ApiEndpoint
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
@HiltViewModel
class LibraryViewModel @Inject constructor(
private val endpoint: ApiEndpoint
) : ViewModel() {
fun getData(){
endpoint.getHotel()
.map {
it.string()
}
.onErrorReturn {
Log.e("debug", "Error : ${it.message}")
it.message
}
.toFlowable()
.subscribe{
Log.e("debug", "Data : $it")
}
.let { return@let CompositeDisposable()::add }
}
} | 0 | Kotlin | 1 | 1 | 78392470dbb09398c4c1758bb17eb221fcf6a6f8 | 814 | Hilt-Multi-Module | MIT License |
src/main/kotlin/no/nav/kafka/KartleggingSvarProdusent.kt | navikt | 644,356,194 | false | {"Kotlin": 82238, "Dockerfile": 214} | package no.nav.kafka
import no.nav.konfigurasjon.KafkaConfig
class KartleggingSvarProdusent {
private val kafkaProdusent = KafkaProdusent(kafkaConfig = KafkaConfig())
fun sendSvar(svar: KartleggingSvar) {
val topic = Topic.KARTLEGGING_SVAR
kafkaProdusent.sendMelding(topic, svar.tilNøkkel(), svar.tilMelding())
}
}
| 0 | Kotlin | 0 | 0 | bd3aebacfa397079fc6c001393542cfb55db57d9 | 348 | fia-arbeidsgiver | MIT License |
lint-rules-rxjava2-lint/src/main/kotlin/com/vanniktech/lintrules/rxjava2/RxJava2MethodMissingCheckReturnValueDetector.kt | vanniktech | 77,383,319 | false | null | package com.vanniktech.lintrules.rxjava2
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Scope.JAVA_FILE
import com.android.tools.lint.detector.api.Severity.WARNING
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.PsiType
import java.util.EnumSet
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toUpperCaseAsciiOnly
import org.jetbrains.uast.UAnnotated
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.kotlin.declarations.KotlinUMethod
val ISSUE_METHOD_MISSING_CHECK_RETURN_VALUE = Issue.create(
"RxJava2MethodMissingCheckReturnValue",
"Method is missing the @CheckReturnValue annotation.",
"Methods returning RxJava Reactive Types should be annotated with the @CheckReturnValue annotation. Static analyze tools such as Lint or ErrorProne can detect when the return value of a method is not used. This is usually an indication of a bug. If this is done on purpose (e.g. fire & forget) it should be stated explicitly.",
CORRECTNESS, PRIORITY, WARNING,
Implementation(RxJava2MethodMissingCheckReturnValueDetector::class.java, EnumSet.of(JAVA_FILE)))
class RxJava2MethodMissingCheckReturnValueDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes() = listOf(UMethod::class.java)
override fun createUastHandler(context: JavaContext) = CheckReturnValueVisitor(context)
class CheckReturnValueVisitor(private val context: JavaContext) : UElementHandler() {
override fun visitMethod(node: UMethod) {
val returnType = node.returnType
val isPropertyFunction = node is KotlinUMethod && node.sourcePsi is KtProperty
if (returnType != null && isTypeThatRequiresAnnotation(returnType) && !isPropertyFunction) {
val hasAnnotatedMethod = context.evaluator.getAllAnnotations(node as UAnnotated, true)
.any { "io.reactivex.annotations.CheckReturnValue" == it.qualifiedName }
if (hasAnnotatedMethod) return
val hasIgnoredModifier = ignoredModifiers().any { node.hasModifier(it) }
if (hasIgnoredModifier) return
val modifier = node.modifierList.children.joinToString(separator = " ") { it.text }
val fix = LintFix.create()
.replace()
.name("Add @CheckReturnValue")
.range(context.getLocation(node))
.shortenNames()
.reformat(true)
.text(modifier)
.with("@io.reactivex.annotations.CheckReturnValue $modifier")
.autoFix()
.build()
context.report(ISSUE_METHOD_MISSING_CHECK_RETURN_VALUE, node, context.getNameLocation(node), "Method should have @CheckReturnValue annotation.", fix)
}
}
private fun isTypeThatRequiresAnnotation(psiType: PsiType): Boolean {
val canonicalText = psiType.canonicalText
.replace("<[\\w.<>]*>".toRegex(), "") // We need to remove the generics.
return canonicalText.matches("io\\.reactivex\\.[\\w]+".toRegex()) ||
"io.reactivex.disposables.Disposable" == canonicalText ||
"io.reactivex.observers.TestObserver" == canonicalText ||
"io.reactivex.subscribers.TestSubscriber" == canonicalText
}
companion object {
private const val IGNORE_MODIFIERS_PROP = "com.vanniktech.lintrules.rxjava2.RxJava2MethodMissingCheckReturnValueDetector.ignoreMethodAccessModifiers"
private fun ignoredModifiers(): List<JvmModifier> {
return System.getProperty(IGNORE_MODIFIERS_PROP)
?.split(",")
?.map { JvmModifier.valueOf(it.toUpperCaseAsciiOnly()) }
.orEmpty()
}
}
}
}
| 2 | null | 37 | 363 | 4129325aca446b470cdfa9ba04e2984e631eb988 | 4,028 | lint-rules | Apache License 2.0 |
api/src/test/kotlin/edu/wgu/osmt/elasticsearch/SearchControllerTest.kt | JohnKallies | 457,873,790 | true | {"TypeScript": 580384, "Kotlin": 430178, "HTML": 128324, "Shell": 27042, "Java": 8284, "JavaScript": 3402, "Dockerfile": 771, "CSS": 80} | package edu.wgu.osmt.elasticsearch
import edu.wgu.osmt.BaseDockerizedTest
import edu.wgu.osmt.HasDatabaseReset
import edu.wgu.osmt.HasElasticsearchReset
import edu.wgu.osmt.SpringTest
import edu.wgu.osmt.api.model.ApiAdvancedSearch
import edu.wgu.osmt.api.model.ApiSearch
import edu.wgu.osmt.collection.CollectionEsRepo
import edu.wgu.osmt.jobcode.JobCodeEsRepo
import edu.wgu.osmt.keyword.KeywordEsRepo
import edu.wgu.osmt.mockdata.MockData
import edu.wgu.osmt.richskill.RichSkillEsRepo
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.util.UriComponentsBuilder
@Transactional
internal class SearchControllerTest @Autowired constructor(
override val richSkillEsRepo: RichSkillEsRepo,
override val collectionEsRepo: CollectionEsRepo,
override val keywordEsRepo: KeywordEsRepo,
override val jobCodeEsRepo: JobCodeEsRepo
): SpringTest(), BaseDockerizedTest, HasDatabaseReset, HasElasticsearchReset {
@Autowired
lateinit var searchController: SearchController
private lateinit var mockData : MockData
val nullJwt : Jwt? = null
@BeforeAll
fun setup() {
mockData = MockData()
}
@Test
fun testSearchCollections(){
// Arrange
val collections = mockData.getCollections()
val collectionDoc = mockData.getCollectionDoc(collections[0].uuid)
collectionDoc?.let { collectionEsRepo.save(it) }
// Act
val result = searchController.searchCollections(
UriComponentsBuilder.newInstance(),
50,
0,
arrayOf("draft", "published"),
"",
ApiSearch(advanced = ApiAdvancedSearch(collectionName = collectionDoc?.name)),
nullJwt)
// Assert
assertThat(result.body?.first()?.uuid).isEqualTo(collectionDoc?.uuid)
}
@Test
fun testSearchSkills(){
// Arrange
val listOfSkills = mockData.getRichSkillDocs().filter { !it.collections.isNullOrEmpty() }
richSkillEsRepo.saveAll(listOfSkills)
val collectionDoc = mockData.getCollectionDoc(listOfSkills[0].collections[0].uuid)
collectionDoc?.let { collectionEsRepo.save(it) }
// Act
val result = searchController.searchSkills(
UriComponentsBuilder.newInstance(),
50,
0,
arrayOf("draft","published"),
"",
collectionDoc?.uuid,
ApiSearch(query=listOfSkills[0].name),
nullJwt)
// Assert
assertThat(result.body?.map { it.uuid }).contains(listOfSkills[0].uuid)
}
@Test
fun testSearchJobCodes() {
// Arrange
val listOfJobCodes = mockData.getJobCodes()
jobCodeEsRepo.saveAll(listOfJobCodes)
// Act
val result = searchController.searchJobCodes(UriComponentsBuilder.newInstance(),listOfJobCodes[0].code)
// Assert
assertThat(result.body?.map { it.targetNodeName }).contains(listOfJobCodes[0].name)
}
@Test
fun testSearchKeywords() {
// Arrange
val listOfKeywords = mockData.getKeywords()
keywordEsRepo.saveAll(listOfKeywords)
// Act
val result = searchController.searchKeywords(
UriComponentsBuilder.newInstance(),
listOfKeywords[0].value.toString(),
listOfKeywords[0].type.toString())
// Assert
assertThat(result.body?.map { it.name }).contains(listOfKeywords[0].value)
}
} | 1 | TypeScript | 0 | 0 | 8cde0a104a3a05a6a60978636325b8ffc5a719a2 | 3,825 | osmt | Apache License 2.0 |
app/src/main/java/lol/calico/uctutors/generated/api/v1/OpenChannelRequestKt.kt | calico32 | 715,594,197 | false | {"Kotlin": 456590, "TypeScript": 218807, "Java": 99962} | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: api/v1/messages.proto
// Generated files should ignore deprecation warnings
@file:Suppress("DEPRECATION")
package lol.calico.uctutors.generated.api.v1;
@kotlin.jvm.JvmName("-initializeopenChannelRequest")
public inline fun openChannelRequest(block: lol.calico.uctutors.generated.api.v1.OpenChannelRequestKt.Dsl.() -> kotlin.Unit): lol.calico.uctutors.generated.api.v1.OpenChannelRequest =
lol.calico.uctutors.generated.api.v1.OpenChannelRequestKt.Dsl._create(lol.calico.uctutors.generated.api.v1.OpenChannelRequest.newBuilder()).apply { block() }._build()
/**
* Protobuf type `api.v1.OpenChannelRequest`
*/
public object OpenChannelRequestKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
public class Dsl private constructor(
private val _builder: lol.calico.uctutors.generated.api.v1.OpenChannelRequest.Builder
) {
public companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: lol.calico.uctutors.generated.api.v1.OpenChannelRequest.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): lol.calico.uctutors.generated.api.v1.OpenChannelRequest = _builder.build()
/**
* `string channel_id = 1 [json_name = "channelId"];`
*/
public var channelId: kotlin.String
@JvmName("getChannelId")
get() = _builder.getChannelId()
@JvmName("setChannelId")
set(value) {
_builder.setChannelId(value)
}
/**
* `string channel_id = 1 [json_name = "channelId"];`
*/
public fun clearChannelId() {
_builder.clearChannelId()
}
}
}
@kotlin.jvm.JvmSynthetic
public inline fun lol.calico.uctutors.generated.api.v1.OpenChannelRequest.copy(block: `lol.calico.uctutors.generated.api.v1`.OpenChannelRequestKt.Dsl.() -> kotlin.Unit): lol.calico.uctutors.generated.api.v1.OpenChannelRequest =
`lol.calico.uctutors.generated.api.v1`.OpenChannelRequestKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 0 | Kotlin | 0 | 0 | a92325ff8dd6ce831fd230b92d3d1be288451143 | 2,159 | uctutors | MIT License |
android/app/src/main/java/com/algorand/android/modules/walletconnect/client/v2/sessionexpiration/di/WalletConnectV2SessionExpirationManagerModule.kt | perawallet | 364,359,642 | false | {"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596} | /*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.walletconnect.client.v2.sessionexpiration.di
import com.algorand.android.modules.walletconnect.client.v2.domain.WalletConnectV2SignClient
import com.algorand.android.modules.walletconnect.client.v2.mapper.WalletConnectClientV2Mapper
import com.algorand.android.modules.walletconnect.client.v2.sessionexpiration.WalletConnectV2SessionExpirationManager
import com.algorand.android.modules.walletconnect.client.v2.sessionexpiration.WalletConnectV2SessionExpirationManagerImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Named
@Module
@InstallIn(SingletonComponent::class)
object WalletConnectV2SessionExpirationManagerModule {
@Provides
@Named(WalletConnectV2SessionExpirationManager.INJECTION_NAME)
fun provideWalletConnectV2SessionExpirationManager(
signClient: WalletConnectV2SignClient,
clientV2Mapper: WalletConnectClientV2Mapper
): WalletConnectV2SessionExpirationManager {
return WalletConnectV2SessionExpirationManagerImpl(signClient, clientV2Mapper)
}
}
| 22 | Swift | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 1,726 | pera-wallet | Apache License 2.0 |
RemoveTableHeader/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.*
import javax.swing.*
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableCellRenderer
fun makeUI(): Component {
val columnNames = arrayOf("String", "Integer", "Boolean")
val data = arrayOf(
arrayOf("aaa", 12, true),
arrayOf("bbb", 5, false),
arrayOf("CCC", 92, true),
arrayOf("DDD", 0, false),
)
val model = object : DefaultTableModel(data, columnNames) {
override fun getColumnClass(column: Int) = getValueAt(0, column).javaClass
}
val table = object : JTable(model) {
private val evenColor = Color(0xF0_F0_F0)
override fun prepareRenderer(
tcr: TableCellRenderer,
row: Int,
column: Int,
): Component {
val c = super.prepareRenderer(tcr, row, column)
if (isCellSelected(row, column)) {
c.foreground = getSelectionForeground()
c.background = getSelectionBackground()
} else {
c.foreground = foreground
c.background = if (row % 2 == 0) evenColor else background
}
return c
}
}
table.autoCreateRowSorter = true
val scrollPane = JScrollPane(table)
val check = JCheckBox("JTableHeader visible: ", true)
check.addActionListener { e ->
scrollPane.columnHeader.isVisible = (e.source as? JCheckBox)?.isSelected ?: false
scrollPane.revalidate()
}
return JPanel(BorderLayout()).also {
it.add(scrollPane)
it.add(check, BorderLayout.NORTH)
it.preferredSize = Dimension(320, 240)
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 6 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 1,915 | kotlin-swing-tips | MIT License |
plugins/analysis/kotlin-plugin/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/kotlin/elements/KotlinAnnotatedExpression.kt | arrow-kt | 217,378,939 | false | null | package arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.elements
import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements.AnnotatedExpression
import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements.Expression
import arrow.meta.plugins.analysis.phases.analysis.solver.ast.kotlin.ast.model
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
class KotlinAnnotatedExpression(val impl: KtAnnotatedExpression) :
AnnotatedExpression, KotlinAnnotated, KotlinAnnotationsContainer {
override fun impl(): KtAnnotatedExpression = impl
override val baseExpression: Expression?
get() = impl().baseExpression?.model()
}
| 97 | Kotlin | 40 | 316 | 8d2a80cf3a1275a752c18baceed74cb61aa13b4d | 680 | arrow-meta | Apache License 2.0 |
app/src/main/java/com/codrutursache/casey/data/data_source/ShoppingListDao.kt | ursachecodrut | 739,025,706 | false | {"Kotlin": 205638} | package com.codrutursache.casey.data.data_source
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.codrutursache.casey.domain.model.ShoppingItemEntity
import com.google.firebase.auth.FirebaseAuth
@Dao
interface ShoppingListDao {
@Query("SELECT * FROM ShoppingItemEntity WHERE userId = :userId")
suspend fun getAllItems(userId: String): List<ShoppingItemEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertItem(item: ShoppingItemEntity): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertBatchItems(items: List<ShoppingItemEntity>)
@Query("UPDATE ShoppingItemEntity SET checked = :checked WHERE id = :id AND userId = :userId")
suspend fun toggleItem(id: Int, checked: Boolean, userId: String)
@Query("DELETE FROM ShoppingItemEntity WHERE id = :id AND userId = :userId")
suspend fun deleteItem(id: Int, userId: String)
@Query("DELETE FROM ShoppingItemEntity WHERE userId = :userId")
suspend fun deleteAllItems(userId: String)
}
| 0 | Kotlin | 0 | 1 | 82b537f401f8ac2447e571e62a94df6518acf23d | 1,108 | casey | MIT License |
app/src/main/java/com/example/lilium/Map/BookingActivity.kt | Farfive | 605,575,557 | false | null | package com.example.lilium.Map
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.example.lilium.R
class BookingActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_pick_date)
}
} | 0 | Kotlin | 0 | 0 | c554e485426abfb2081e80204b1ace518b9cbd3c | 399 | STYLEAP | MIT License |
app/src/main/java/spam/blocker/util/Schedule.kt | aj3423 | 783,998,987 | false | {"Kotlin": 382407, "Go": 6080} | package spam.blocker.util
import android.content.Context
import spam.blocker.R
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
// Serialized format: "weekdays,time range,enabled"
// e.g. "12345,00:00-01:02,true"
class Schedule {
var enabled = false
var startHour = 0
var startMin = 0
var endHour = 0
var endMin = 0
var weekdays = arrayListOf<Int>()
fun serializeToStr(): String {
val part0 = weekdays.fold("") { acc, item ->
acc + item.toString()
}
val part1 = timeRangeStr()
val part2 = enabled.toString()
return "$part0,$part1,$part2"
}
// for serialization only
private fun timeRangeStr(): String {
return String.format("%02d:%02d-%02d:%02d", startHour, startMin, endHour, endMin)
}
// for display on UI
fun timeRangeDisplayStr(ctx: Context): String {
if (startHour == 0 && startMin == 0 && endHour == 0 && endMin == 0)
return ctx.getString(R.string.entire_day)
return String.format("%02d:%02d - %02d:%02d", startHour, startMin, endHour, endMin)
}
fun toDisplayStr(ctx: Context): String {
val labels = ctx.resources.getStringArray(R.array.week)
val days = weekdays.sorted()
if (days == listOf(1,2,3,4,5,6,7) || days.isEmpty()) // every day, ignore the day string
return timeRangeDisplayStr(ctx)
if (days == listOf(2,3,4,5,6))
return ctx.getString(R.string.workday) + " " + timeRangeDisplayStr(ctx)
if (days == listOf(1, 7))
return ctx.getString(R.string.weekend) + " " + timeRangeDisplayStr(ctx)
// [1,3,5] -> "Sun,Tue,Thur"
val daysStr = days.joinToString(",") { labels[it-1] }
return daysStr + " " + timeRangeDisplayStr(ctx)
}
fun satisfyTime(timeMillis: Long): Boolean {
val t = LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), ZoneId.systemDefault())
var d = t.dayOfWeek.ordinal + 2
if (d == 8) d = 1
if (weekdays.isNotEmpty()) { // empty means everyday
if (d !in weekdays)
return false
}
// all 0s means entire day, always satisfies
if (startHour == 0 && startMin == 0 && endHour == 0 && endMin == 0)
return true
val min = startHour * 60 + startMin
val max = endHour * 60 + endMin
val v = t.hour * 60 + t.minute
return v in min..max
}
companion object {
private val regexRange = """(\d{1,2}):(\d{1,2})-(\d{1,2}):(\d{1,2})""".toRegex()
fun parseFromStr(str: String) : Schedule {
val ret = Schedule()
if (str.isEmpty())
return Schedule()
val parts = str.split(",")
if (parts.size != 3)
return Schedule()
// 1. weekdays, e.g.: "23456"
// Calendar.SUNDAY ~ Calendar.SATURDAY (1~7)
parts[0].forEach {
ret.weekdays.add(it.digitToInt())
}
// 2. time range, e.g.: "01:00-02:30"
val match = regexRange.matchEntire(parts[1]) ?: return Schedule()
val (startHour, startMinute, endHour, endMinute) = match.destructured
ret.startHour = startHour.toInt()
ret.startMin = startMinute.toInt()
ret.endHour = endHour.toInt()
ret.endMin = endMinute.toInt()
// 3. enabled
ret.enabled = parts[2].toBoolean()
return ret
}
}
}
| 5 | Kotlin | 6 | 357 | 9a650076aa485bee8bb99653f3d7256b02ec8488 | 3,561 | SpamBlocker | MIT License |
src/commonMain/kotlin/github/otisgoodman/pocketKt/services/LogService.kt | OtisGoodman | 572,316,780 | false | null | package github.otisgoodman.pocketKt.services
import github.otisgoodman.pocketKt.PocketbaseClient
import github.otisgoodman.pocketKt.PocketbaseException
import github.otisgoodman.pocketKt.dsl.query.Filter
import github.otisgoodman.pocketKt.dsl.query.SortFields
import github.otisgoodman.pocketKt.models.LogRequest
import github.otisgoodman.pocketKt.models.utils.ListResult
import github.otisgoodman.pocketKt.services.utils.BaseService
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.datetime.Instant
import kotlinx.datetime.toInstant
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
public class LogService(client: PocketbaseClient) : BaseService(client) {
@Serializable
public data class HourlyStats(val total: Int, @SerialName("date") val initialDate: String) {
@Transient
val date: Instant = initialDate.replace(" ", "T").toInstant()
}
/**
* Returns a paginated request logs list.
* @param [page] The page (aka. offset) of the paginated list.
* @param [perPage] The max returned request logs per page.
*/
public suspend fun getRequestsList(
page: Int = 1,
perPage: Int = 30,
sortBy: SortFields = SortFields(),
filterBy: Filter = Filter()
): ListResult<LogRequest> {
val params = mapOf(
"page" to page.toString(),
"perPage" to perPage.toString(),
)
val response = client.httpClient.get {
url {
path("api", "logs", "requests")
params.forEach { parameters.append(it.key, it.value) }
filterBy.addTo(parameters)
sortBy.addTo(parameters)
}
}
PocketbaseException.handle(response)
return response.body()
}
/**
* Returns a single request log by its ID.
* @param [id]
*/
public suspend fun getRequest(id: String): LogRequest {
val response = client.httpClient.get {
url {
path("api", "logs", "requests", id)
}
}
PocketbaseException.handle(response)
return response.body()
}
/**
* Returns hourly aggregated request logs statistics.
*/
public suspend fun getRequestsStats(filterBy: Filter = Filter()): List<HourlyStats> {
val response = client.httpClient.get {
url {
path("api", "logs", "requests", "stats")
filterBy.addTo(parameters)
}
}
PocketbaseException.handle(response)
return response.body()
}
} | 4 | Kotlin | 1 | 3 | 99d4c3f99cad97bd3718829628c986b06b371d89 | 2,685 | pocket-kt | MIT License |
app/src/main/java/com/elementary/tasks/core/data/dao/GoogleTaskListsDao.kt | naz013 | 165,067,747 | false | null | package com.elementary.tasks.core.data.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.elementary.tasks.core.data.models.GoogleTaskList
@Dao
interface GoogleTaskListsDao {
@Query("SELECT * FROM GoogleTaskList ORDER BY title")
fun all(): List<GoogleTaskList>
@Query("SELECT * FROM GoogleTaskList WHERE def=1")
fun defaultGoogleTaskList(): GoogleTaskList?
@Query("SELECT * FROM GoogleTaskList ORDER BY title")
fun loadAll(): LiveData<List<GoogleTaskList>>
@Query("SELECT * FROM GoogleTaskList WHERE def=1")
fun loadDefault(): LiveData<GoogleTaskList>
@Query("SELECT * FROM GoogleTaskList WHERE def=1")
fun getDefault(): List<GoogleTaskList>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(googleTaskList: GoogleTaskList)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(vararg googleTaskLists: GoogleTaskList)
@Delete
fun delete(googleTaskList: GoogleTaskList)
@Query("SELECT * FROM GoogleTaskList WHERE listId=:id")
fun loadById(id: String): LiveData<GoogleTaskList>
@Query("SELECT * FROM GoogleTaskList WHERE listId=:id")
fun getById(id: String): GoogleTaskList?
@Query("DELETE FROM GoogleTaskList")
fun deleteAll()
}
| 0 | null | 3 | 6 | a6eecfda739be05a4b84e7d47284cd9e2bc782d6 | 1,395 | reminder-kotlin | Apache License 2.0 |
src/test/kotlin/leetcode/uber/FirstAndLasPositionInSortedArrayTest.kt | Magdi | 390,731,717 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 96, "Java": 1} | package leetcode.uber
import leetcode.uber.FirstAndLasPositionInSortedArray
import org.junit.Assert.*
import org.junit.Test
internal class FirstAndLasPositionInSortedArrayTest {
@Test
fun `test case 1`() {
val nums = intArrayOf(5, 7, 7, 8, 8, 10)
val target = 8
val expected = intArrayOf(3, 4)
assertArrayEquals(expected,
FirstAndLasPositionInSortedArray().searchRange(nums, target))
}
@Test
fun `test case 2`() {
val nums = intArrayOf(5,7,7,8,8,10)
val target = 6
val expected = intArrayOf(-1, -1)
assertArrayEquals(expected,
FirstAndLasPositionInSortedArray().searchRange(nums, target))
}
@Test
fun `test case 3`() {
val nums = intArrayOf()
val target = 6
val expected = intArrayOf(-1, -1)
assertArrayEquals(expected,
FirstAndLasPositionInSortedArray().searchRange(nums, target))
}
} | 0 | Kotlin | 0 | 0 | 63bc711dc8756735f210a71454144dd033e8927d | 963 | ProblemSolving | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/modules/pin/PinViewModel.kt | 923325596 | 185,099,077 | false | null | package io.horizontalsystems.bankwallet.modules.pin
import androidx.core.hardware.fingerprint.FingerprintManagerCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.horizontalsystems.bankwallet.SingleLiveEvent
import io.horizontalsystems.bankwallet.core.IKeyStoreSafeExecute
import io.horizontalsystems.bankwallet.modules.pin.edit.EditPinModule
import io.horizontalsystems.bankwallet.modules.pin.set.SetPinModule
import io.horizontalsystems.bankwallet.modules.pin.unlock.UnlockPinModule
import java.util.*
class PinViewModel: ViewModel(), PinModule.IPinView, SetPinModule.ISetPinRouter, EditPinModule.IEditPinRouter, IKeyStoreSafeExecute, UnlockPinModule.IUnlockPinRouter {
lateinit var delegate: PinModule.IPinViewDelegate
val titleLiveDate = MutableLiveData<Int>()
val addPagesEvent = MutableLiveData<List<PinPage>>()
val showPageAtIndex = MutableLiveData<Int>()
val showError = MutableLiveData<Int>()
val showErrorForPage = MutableLiveData<Pair<Int, Int>>()
val fillPinCircles = MutableLiveData<Pair<Int, Int>>()
val navigateToMainLiveEvent = SingleLiveEvent<Unit>()
val hideToolbar = SingleLiveEvent<Unit>()
val dismissLiveEvent = SingleLiveEvent<Unit>()
val showBackButton = SingleLiveEvent<Unit>()
val showFingerprintInputLiveEvent = SingleLiveEvent<FingerprintManagerCompat.CryptoObject>()
val resetCirclesWithShakeAndDelayForPage = SingleLiveEvent<Int>()
val keyStoreSafeExecute = SingleLiveEvent<Triple<Runnable, Runnable?, Runnable?>>()
val showAttemptsLeftError = MutableLiveData<Pair<Int, Int>>()
val showLockedView = SingleLiveEvent<Date>()
val closeApplicationLiveEvent = SingleLiveEvent<Unit>()
fun init(interactionType: PinInteractionType, appStart: Boolean, showCancelButton: Boolean) {
when(interactionType) {
PinInteractionType.SET_PIN -> SetPinModule.init(this, this, this)
PinInteractionType.UNLOCK -> UnlockPinModule.init(this, this, this, appStart, showCancelButton)
PinInteractionType.EDIT_PIN -> EditPinModule.init(this, this, this)
}
delegate.viewDidLoad()
}
override fun setTitle(title: Int) {
titleLiveDate.value = title
}
override fun hideToolbar() {
hideToolbar.call()
}
override fun addPages(pages: List<PinPage>) {
addPagesEvent.value = pages
}
override fun showPage(index: Int) {
showPageAtIndex.value = index
}
override fun showErrorForPage(error: Int, pageIndex: Int) {
showErrorForPage.value = Pair(error, pageIndex)
}
override fun showError(error: Int) {
showError.value = error
}
override fun showPinWrong(pageIndex: Int) {
resetCirclesWithShakeAndDelayForPage.value = pageIndex
}
override fun showFingerprintDialog(cryptoObject: FingerprintManagerCompat.CryptoObject) {
showFingerprintInputLiveEvent.value = cryptoObject
}
override fun showBackButton() {
showBackButton.call()
}
override fun fillCircles(length: Int, pageIndex: Int) {
fillPinCircles.value = Pair(length, pageIndex)
}
override fun navigateToMain() {
navigateToMainLiveEvent.call()
}
override fun safeExecute(action: Runnable, onSuccess: Runnable?, onFailure: Runnable?) {
keyStoreSafeExecute.value = Triple(action, onSuccess, onFailure)
}
override fun closeApplication() {
closeApplicationLiveEvent.call()
}
override fun dismiss() {
dismissLiveEvent.call()
}
override fun showLockView(until: Date) {
showLockedView.postValue(until)
}
override fun showAttemptsLeft(attempts: Int?, pageIndex: Int) {
attempts?.let {
showAttemptsLeftError.postValue(Pair(attempts, pageIndex))
}
}
}
| 0 | null | 0 | 1 | 1c34db3d30f5aeddb590b55c2550dbe0da5056b8 | 3,859 | bank-wallet-android | MIT License |
src/aws/lambdas/incremental_distribution/cta/src/test/java/contract/CircuitBreakers.kt | faberga | 304,428,308 | true | {"Kotlin": 1588541, "HCL": 484131, "Ruby": 385358, "Python": 81257, "HTML": 7697, "Java": 7597, "Shell": 4822, "Dockerfile": 2996, "JavaScript": 554, "Makefile": 539} | package contract
import contract.infra.BackendContractScenario
import contract.infra.RecordingTest
import contract.infra.ReplayTest
import org.junit.jupiter.api.Test
import smoke.actors.MobileApp
import smoke.env.SmokeTests
interface CircuitBreakers : BackendContractScenario {
@Test
fun `Mobile user checks exposure circuit breaker`() {
MobileApp(mitmHttpClient(), envConfig).exposureCircuitBreaker.requestAndApproveCircuitBreak()
}
@Test
fun `Mobile user checks venue circuit breaker`() {
MobileApp(mitmHttpClient(), envConfig).venueCircuitBreaker.requestAndApproveCircuitBreak()
}
}
class RecordingCircuitBreakersTest : RecordingTest(), CircuitBreakers {
override val envConfig = SmokeTests.loadConfig()
}
class ReplayCircuitBreakersTest : ReplayTest(), CircuitBreakers {
override val envConfig = SmokeTests.loadConfig()
}
| 0 | Kotlin | 0 | 0 | 8c67d6e23c7fc79f039c4012238d82131900a4d4 | 879 | covid19-app-system-public | MIT License |
app/src/main/java/com/wreckingballsoftware/design/ui/framework/FrameworkStateItem.kt | leewaggoner | 698,812,124 | false | {"Kotlin": 60063} | package com.wreckingballsoftware.design.ui.framework
import androidx.compose.runtime.Composable
sealed class FrameworkStateItem(
val isTopBarActionAvailable: Boolean,
val isNavBarVisible: Boolean,
val fabAction: @Composable () -> Unit,
) {
class AuthFrameworkStateItem : FrameworkStateItem(
isTopBarActionAvailable = false,
isNavBarVisible = false,
fabAction = { },
)
class CampaignsFrameworkStateItem(fab: @Composable () -> Unit): FrameworkStateItem(
isTopBarActionAvailable = true,
isNavBarVisible = true,
fabAction = fab,
)
class CampaignDetailsStateItem : FrameworkStateItem(
isTopBarActionAvailable = true,
isNavBarVisible = true,
fabAction = { }
)
class MapFrameworkStateItem(fab: @Composable () -> Unit) : FrameworkStateItem(
isTopBarActionAvailable = true,
isNavBarVisible = true,
fabAction = fab,
)
class SignsFrameworkStateItem : FrameworkStateItem(
isTopBarActionAvailable = true,
isNavBarVisible = true,
fabAction = { },
)
} | 0 | Kotlin | 0 | 0 | 857d5c4584563f3e94e8682b847565fd1a4cf346 | 1,110 | design | Apache License 2.0 |
client/android/div/src/main/java/com/yandex/div/core/state/UpdateStateChangePageCallback.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.core.state
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
/**
* Save view pager position in [DivViewState]
*/
internal class UpdateStateChangePageCallback(
private val mBlockId: String,
private val mDivViewState: DivViewState
) : OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (position != RecyclerView.NO_POSITION) {
mDivViewState.putBlockState(mBlockId, PagerState(position))
}
}
}
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 549 | divkit | Apache License 2.0 |
easypublish/src/main/java/osp/leobert/maven/publish/EasyPublishPlugin.kt | leobert-lan | 365,922,895 | false | null | @file:Suppress("deprecation")
package osp.leobert.maven.publish
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.maven.Conf2ScopeMappingContainer
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.MavenPlugin.*
import org.gradle.api.plugins.MavenPluginConvention
import org.gradle.api.plugins.PluginContainer
import org.gradle.api.publication.maven.internal.MavenFactory
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.plugins.signing.SigningExtension
import osp.leobert.maven.publish.bean.EasyPublish
import java.net.URI
import java.util.*
class EasyPublishPlugin : Plugin<ProjectInternal> {
var easyPublish = EasyPublish()
var publishExtension: PublishingExtension? = null
var signExtension: SigningExtension? = null
@Suppress("PrivateApi", "Unchecked")
override fun apply(project: ProjectInternal) {
Logger.info("hello,I'am easy-publish")
project.pluginManager.apply(BasePlugin::class.java)
val mavenFactory: MavenFactory = project.services.get(MavenFactory::class.java)
val pluginConvention: MavenPluginConvention = addConventionObject(project, mavenFactory)
val plugins: PluginContainer = project.plugins
try {
val appPluginClass: Class<Plugin<*>> =
Class.forName("com.android.build.gradle.AppPlugin") as Class<Plugin<*>>
val libraryPluginClass: Class<Plugin<*>> =
Class.forName("com.android.build.gradle.LibraryPlugin") as Class<Plugin<*>>
val testPluginClass: Class<Plugin<*>> =
Class.forName("com.android.build.gradle.TestPlugin") as Class<Plugin<*>>
plugins.withType(appPluginClass) {
configureAndroidScopeMappings(project.configurations,
pluginConvention.conf2ScopeMappings)
}
plugins.withType(libraryPluginClass) {
configureAndroidScopeMappings(project.configurations,
pluginConvention.conf2ScopeMappings)
}
plugins.withType(testPluginClass) {
configureAndroidScopeMappings(project.configurations,
pluginConvention.conf2ScopeMappings)
}
} catch (ex: ClassNotFoundException) {
}
easyPublish = project.extensions.create("EasyPublish", EasyPublish::class.java)
val localProperties = Util.localProperty(project)
project.afterEvaluate { _ ->
Logger.info("find config:$easyPublish")
project.apply {
it.plugin("maven-publish")
if (easyPublish.needSign)
it.plugin("signing")
Logger.info("apply plugin 'maven-publish'${" and 'signing'".takeIf { easyPublish.needSign } ?: ""} to ${project.name}")
}
publishExtension = Util.publishingExtension(project)
signExtension = Util.signingExtension(project)
Logger.info("test:${publishExtension}${publishExtension?.publications}${publishExtension?.repositories}")
project.container(EasyPublish::class.java)
val isAndroid = Util.isAndroidModule(project)
if (isAndroid) {
addJavaDocTaskForAndroid(project)
}
val sourcesJarTask = addSourceJar(project, easyPublish)
val javadocJarTask = addJavadocJar(project)
project.tasks.withType(Javadoc::class.java) {
it.options.encoding = "UTF-8"
// it.options.addStringOption('Xdoclint:none', '-quiet')
// options.addStringOption('encoding', 'UTF-8')
// options.addStringOption('charSet', 'UTF-8')
}
configPublishing(project, localProperties, sourcesJarTask, javadocJarTask)
}
}
private fun addJavadocJar(project: Project): Task? {
val javadoc = project.tasks.findByName("javadoc").takeIfInstance<Javadoc>()
return try {
project.tasks.create(
"javadocJar", Jar::class.java
).apply {
this.classifier = "javadoc"
this.from(javadoc?.destinationDir)
this.setDependsOn(arrayListOf(javadoc))
}
} catch (e: Exception) {
Logger.error(e.message ?: "empty message", e)
null
}
}
private fun addSourceJar(project: Project, easyPublish: EasyPublish): Task? {
return try {
project.tasks.create(
"sourcesJar", Jar::class.java
).takeIfInstance<AbstractArchiveTask>()?.apply {
this.classifier = "sources"
this.from(
easyPublish.sourceSet
?: throw IllegalArgumentException("must config sourceSet in EasyPublish")
)
}
} catch (e: Exception) {
Logger.error(e.message ?: "empty message", e)
null
}
}
// task javadoc(type: Javadoc) {
// options.encoding "UTF-8"
// options.charSet 'UTF-8'
// source = android.sourceSets.main.java.srcDirs
// classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
// }
private fun addJavaDocTaskForAndroid(project: Project): Task? {
return try {
project.tasks.create(
"javadoc", Javadoc::class.java
).apply {
this.options.encoding("UTF-8")
easyPublish.docClassPathAppend?.let { docClassPathAppend ->
this.classpath.plus(docClassPathAppend)
}
easyPublish.sourceSet
?: throw IllegalArgumentException("must config sourceSet in EasyPublish")
easyPublish.docExcludes?.let { exclude ->
this.exclude(exclude)
exclude.forEach { e ->
Logger.info("exclude doc of $e")
}
}
}
} catch (e: Exception) {
Logger.error(e.message ?: "empty message", e)
null
}
}
private fun configPublishing(
project: Project,
properties: Properties?,
sourcesJarTask: Task?,
javadocJarTask: Task?,
) {
val publishingExtension = publishExtension
if (publishingExtension == null) {
Logger.error("publishingExtension is null something error")
return
}
publishingExtension.publications {
it.register<MavenPublication>(
"easyMavenPublish",
MavenPublication::class.java
) { publication ->
if (!easyPublish.notStandardJavaComponent)
publication.from(project.components.getByName("java"))
publication.groupId = Util.require("EasyPublish.groupId", easyPublish.groupId)
publication.artifactId =
Util.require("EasyPublish.artifactId", easyPublish.artifactId)
publication.version = Util.require("EasyPublish.version", easyPublish.version)
javadocJarTask?.let { t ->
Logger.info("add javadocJarTask to publication artifact")
publication.artifact(t)
}
sourcesJarTask?.let { t ->
Logger.info("add sourcesJarTask to publication artifact")
publication.artifact(t)
}
easyPublish.artifactsAppend?.forEach { a ->
Logger.info("add $a to publication artifact")
publication.artifact(a)
}
//pom config
publication.pom { pom ->
pom.packaging = Util.require("EasyPublish.packaging", easyPublish.packaging)
pom.name.set(
Util.require("EasyPublish.artifactId", easyPublish.artifactId)
)
pom.description.set(
Util.require("EasyPublish.description", easyPublish.description)
)
pom.url.set(
Util.require("EasyPublish.siteUrl", easyPublish.siteUrl)
)
pom.licenses { licenses ->
licenses.license { license ->
license.name.set(
Util.require("EasyPublish.licenseName", easyPublish.licenseName)
)
license.url.set(
Util.require("EasyPublish.licenseUrl", easyPublish.licenseUrl)
)
}
}
pom.developers { develops ->
easyPublish.mDevelopers.forEach { dev ->
develops.developer { developer ->
developer.id.set(dev.id)
developer.name.set(dev.name)
developer.email.set(dev.email)
}
}
}
pom.scm { scm ->
scm.connection.set(
Util.require("EasyPublish.siteUrl", easyPublish.siteUrl)
)
scm.developerConnection.set(
Util.require("EasyPublish.gitUrl", easyPublish.gitUrl)
)
scm.url.set(
Util.require("EasyPublish.siteUrl", easyPublish.siteUrl)
)
}
if (easyPublish.notStandardJavaComponent) {
applyPomDeps(pom = pom, project = project)
}
}
}
}
publishingExtension.repositories {
it.maven { repo ->
repo.url = URI.create(
Util.require("EasyPublish.mavenRepoUrl", easyPublish.mavenRepoUrl) ?: ""
)
val account = properties?.get("nexus_user")?.toString()
val password = properties?.get("nexus_pwd")?.toString()
repo.credentials { credential ->
credential.username = Util.require("local.properties.nexus_user", account)
credential.password = Util.require("local.properties.nexus_pwd", password)
}
}
}
signExtension?.sign(
publishingExtension.publications.findByName("easyMavenPublish")
)
}
private val scopeMapping = mapOf<String, String?>(
"api" to "compile",
"implementation" to "compile",
"compile" to "compile"
)
private fun applyPomDeps(pom: MavenPom, project: Project) {
pom.withXml { xml ->
val dependenciesNode = xml.asNode().appendNode("dependencies")
//Iterate over the compile dependencies (we don't want the test ones), adding a <dependency> node for each
scopeMapping.keys.forEach { key ->
try {
project.configurations.getByName(key).allDependencies?.forEach { dependency ->
val dependencyNode = dependenciesNode.appendNode("dependency")
dependencyNode.appendNode("groupId", dependency.group)
dependencyNode.appendNode("artifactId", dependency.name)
dependencyNode.appendNode("version", dependency.version)
dependencyNode.appendNode("scope", scopeMapping[key])
}
} catch (thr: Throwable) {
}
}
}
}
private fun configureAndroidScopeMappings(
configurations: ConfigurationContainer,
mavenScopeMappings: Conf2ScopeMappingContainer,
) {
mavenScopeMappings.addMapping(COMPILE_PRIORITY,
configurations.getByName(JavaPlugin.API_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.COMPILE)
mavenScopeMappings.addMapping(COMPILE_PRIORITY,
configurations.getByName(JavaPlugin.COMPILE_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.COMPILE)
mavenScopeMappings.addMapping(RUNTIME_PRIORITY,
configurations.getByName(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.RUNTIME)
mavenScopeMappings.addMapping(TEST_COMPILE_PRIORITY,
configurations.getByName(JavaPlugin.TEST_COMPILE_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.TEST)
mavenScopeMappings.addMapping(TEST_RUNTIME_PRIORITY,
configurations.getByName(JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.TEST)
}
private fun addConventionObject(
project: ProjectInternal,
mavenFactory: MavenFactory,
): MavenPluginConvention {
val mavenConvention = MavenPluginConvention(project, mavenFactory)
val convention = project.convention
convention.plugins.forEach { s, any ->
Logger.info(" convention.plugins$s")
}
convention.plugins["maven-publish"] = mavenConvention
return mavenConvention
}
} | 0 | Kotlin | 0 | 2 | 22ae0ac6f2ff17f0f50d65fb3617e597e0723c98 | 14,092 | EsayPublish | Apache License 2.0 |
compiler/src/main/kotlin/com/r0adkll/kimchi/annotations/ContributesSubcomponentAnnotation.kt | r0adkll | 842,714,606 | false | null | // Copyright (C) 2024 r0adkll
// SPDX-License-Identifier: Apache-2.0
package com.r0adkll.kimchi.annotations
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.r0adkll.kimchi.util.KimchiException
import com.r0adkll.kimchi.util.ksp.argumentAt
import com.r0adkll.kimchi.util.ksp.findAnnotation
import com.r0adkll.kimchi.util.ksp.valueAsClassName
import com.r0adkll.kimchi.util.ksp.valueAsClassNameList
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ksp.toClassName
class ContributesSubcomponentAnnotation private constructor(
override val scope: ClassName,
val parentScope: ClassName,
private val excludes: List<ClassName>,
override val replaces: List<ClassName>,
) : MergingAnnotation, ReplaceableAnnotation {
override fun excludes(contribution: KSClassDeclaration): Boolean {
return excludes.contains(contribution.toClassName())
}
companion object {
fun from(annotated: KSAnnotated): ContributesSubcomponentAnnotation {
val annotation = annotated.findAnnotation(ContributesSubcomponent::class)
?: throw KimchiException("Unable to find @ContributesSubcomponent annotation", annotated)
val scope = annotation.argumentAt("scope", 0)
?.valueAsClassName
?: throw KimchiException("Unable to find `scope` on @ContributesSubcomponent annotation", annotated)
val parentScope = annotation.argumentAt("parentScope", 1)
?.valueAsClassName
?: throw KimchiException("Unable to find `parentScope` on @ContributesSubcomponent annotation", annotated)
val excludes = annotation.argumentAt("excludes", 2)
?.valueAsClassNameList
?: emptyList()
val replaces = annotation.argumentAt("replaces", 3)
?.valueAsClassNameList
?: emptyList()
return ContributesSubcomponentAnnotation(scope, parentScope, excludes, replaces)
}
}
}
| 3 | null | 1 | 8 | 4c1b05096184ca4db4dac41104940ef2a70fc67a | 1,937 | kimchi | Apache License 2.0 |
ui/ui-saved-instance-state/src/commonMain/kotlin/androidx/compose/runtime/savedinstancestate/UiSavedStateRegistry.kt | Sathawale27 | 284,157,908 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime.savedinstancestate
import androidx.compose.staticAmbientOf
/**
* Allows components to save and restore their state using the saved instance state mechanism.
*/
interface UiSavedStateRegistry {
/**
* Returns the restored value for the given key.
* Once being restored the value is cleared, so you can't restore the same key twice.
*
* @param key Key used to save the value
*/
fun consumeRestored(key: String): Any?
/**
* Registers the value provider.
*
* The same [key] cannot be registered twice, if you need to update the provider call
* [unregisterProvider] first and then register again.
*
* @param key Key to use for storing the value
* @param valueProvider Provides the current value, to be executed when [performSave]
* will be triggered to collect all the registered values
*/
fun registerProvider(key: String, valueProvider: () -> Any?)
/**
* Unregisters the value provider previously registered via [registerProvider].
*
* @param key Key of the value which shouldn't be saved anymore
*/
fun unregisterProvider(key: String)
/**
* Returns true if the value can be saved using this Registry.
* The default implementation will return true if this value can be stored in Bundle.
*
* @param value The value which we want to save using this Registry
*/
fun canBeSaved(value: Any): Boolean
/**
* Executes all the registered value providers and combines these values into a key-value map.
*/
fun performSave(): Map<String, Any>
}
/**
* Creates [UiSavedStateRegistry].
*
* @param restoredValues The map of the restored values
* @param canBeSaved Function which returns true if the given value can be saved by the registry
*/
fun UiSavedStateRegistry(
restoredValues: Map<String, Any>?,
canBeSaved: (Any) -> Boolean
): UiSavedStateRegistry = UiSavedStateRegistryImpl(restoredValues, canBeSaved)
/**
* Ambient with a current [UiSavedStateRegistry] instance.
*/
val UiSavedStateRegistryAmbient = staticAmbientOf<UiSavedStateRegistry?> { null }
private class UiSavedStateRegistryImpl(
restored: Map<String, Any>?,
private val canBeSaved: (Any) -> Boolean
) : UiSavedStateRegistry {
private val restored: MutableMap<String, Any> = restored?.toMutableMap() ?: mutableMapOf()
private val valueProviders = mutableMapOf<String, () -> Any?>()
override fun canBeSaved(value: Any): Boolean = canBeSaved.invoke(value)
override fun consumeRestored(key: String): Any? = restored.remove(key)
override fun registerProvider(key: String, valueProvider: () -> Any?) {
require(key.isNotBlank()) { "Registered key is empty or blank" }
require(!valueProviders.contains(key)) {
"Key $key was already registered. Please call " +
"unregister before registering again"
}
@Suppress("UNCHECKED_CAST")
valueProviders[key] = valueProvider
}
override fun unregisterProvider(key: String) {
require(valueProviders.contains(key)) {
"Key $key wasn't registered, but unregister " +
"requested"
}
valueProviders.remove(key)
}
override fun performSave(): Map<String, Any> {
val map = restored.toMutableMap()
valueProviders.forEach {
val value = it.value()
if (value != null) {
check(canBeSaved(value))
map[it.key] = value
}
}
return map
}
} | 1 | null | 0 | 1 | 549e3e3003cd308939ff31799cf1250e86d3e63e | 4,223 | androidx | Apache License 2.0 |
src/main/kotlin/no/nav/familie/ef/personhendelse/handler/DøfødtBarnHandler.kt | navikt | 386,583,602 | false | {"Kotlin": 216367, "Dockerfile": 136, "Shell": 37} | package no.nav.familie.ef.personhendelse.handler
import no.nav.familie.ef.personhendelse.datoutil.tilNorskDatoformat
import no.nav.person.pdl.leesah.Personhendelse
import org.springframework.stereotype.Component
@Component
class DøfødtBarnHandler : PersonhendelseHandler {
override val type = PersonhendelseType.DØDFØDT_BARN
override fun lagOppgaveBeskrivelse(personhendelse: Personhendelse): OppgaveInformasjon {
return OpprettOppgave(beskrivelse = "Døfødt barn ${personhendelse.doedfoedtBarn.dato.tilNorskDatoformat()}")
}
}
| 0 | Kotlin | 0 | 0 | 2f099ec37719527d73eb0a09083f9d89169ae022 | 551 | familie-ef-personhendelse | MIT License |
4/PR4_8+/app/src/main/java/com/example/pr4_8/AlarmReceiver.kt | Purpurum | 580,288,282 | false | null | package com.example.pr4_8
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
class AlarmReceiver:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val intent = Intent(context, Exercise::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (context != null) {
context.startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | 247e216e5e3e33eb0dbb25fc4e1305036df3667e | 491 | MD-NARFU | MIT License |
core/src/commonMain/kotlin/com/xebia/functional/xef/llm/models/chat/MessageWithFunctionCall.kt | xebia-functional | 629,411,216 | false | null | package com.xebia.functional.xef.llm.models.chat
import com.xebia.functional.xef.llm.models.functions.FunctionCall
data class MessageWithFunctionCall(
val role: String,
val content: String? = null,
val functionCall: FunctionCall?,
val name: String? = Role.ASSISTANT.name
)
| 10 | Kotlin | 8 | 89 | a762a968c31778f0a314a204f6b10340cec38336 | 283 | xef | Apache License 2.0 |
kotlin-jvm/src/main/kotlin/playground/SkrapeIt.kt | LouisCAD | 295,134,297 | false | null | @file:Suppress("PackageDirectoryMismatch")
package playground.skrapeit
import it.skrape.core.htmlDocument
import it.skrape.expect
import it.skrape.matchers.ContentTypes
import it.skrape.matchers.toBe
import it.skrape.matchers.toBePresentTimes
import it.skrape.matchers.toContain
import it.skrape.selects.and
import it.skrape.selects.html5.*
import it.skrape.skrape
import playground.loadResourceFileContent
/**
* skrapeit/skrape.it
*
* [Website](https://docs.skrape.it/docs/)
* [GitHub](https://github.com/skrapeit/skrape.it)
*/
fun main() {
println()
println("# skrapeit/skrape.it")
println(
"A Kotlin-based HTML / XML deserialization library that places particular emphasis on ease of use and a " +
"high level of readability by providing an intuitive DSL."
)
println()
println("Pick Html Head Elements from a Doc")
`Pick Html Head Elements from a Doc`()
println("Pick Html Body Elements from a Doc")
`Pick Html Body Elements from a Doc`()
println("Pick Custom HTML tags")
`Pick Custom HTML tags`()
println("Build CSS selectors")
`Build CSS selectors`()
println("Parse and verify local HTML resource")
`Parse and verify local HTML resource`()
println("Parse and verify response of url")
`Parse and verify response of url`()
}
/**
* [Picking Html-Elements from a Doc](https://docs.skrape.it/docs/dsl/parsing-html#picking-html-elements-from-a-doc)
*/
private fun `Pick Html Head Elements from a Doc`() {
val mockHtmlHead =
"""
<html>
<head>
<link rel="shortcut icon" href="https://some.url/icon">
<script src="https://some.url/some-script.js"></script>
<meta name="foo" content="bar">
</head>
</html>
""".trimIndent()
htmlDocument(mockHtmlHead) {
meta {
withAttribute = "name" to "foo"
findFirst {
attribute("content") toBe "bar"
}
}
}
}
/**
* [Picking Html-Elements from a Doc](https://docs.skrape.it/docs/dsl/parsing-html#picking-html-elements-from-a-doc)
*/
private fun `Pick Html Body Elements from a Doc`() {
val mockHtmlBody =
"""
<html>
<body>
<nav>
<ol class="navigation">
<li><a href="items">List Items</a></li>
<li><a href="items/one">List Item One</a></li>
<li>Item 42</li>
</ol>
</nav>
i'm the body
<h1>i'm the headline</h1>
<main>
<p class="foo bar">i'm a paragraph</p>
<p>i'm a second paragraph</p>
<p>i'm a paragraph <wbr> with word break</p>
<p>i'm the last paragraph</p>
</main>
</body>
</html>
""".trimIndent()
htmlDocument(mockHtmlBody) {
h1 {
findFirst {
text toBe "i'm the headline"
}
}
ol {
findFirst {
className toContain "navigation"
}
}
p {
findAll {
toBePresentTimes(4)
forEach {
it.text toContain "paragraph"
}
}
}
p {
withClass = "foo" and "bar"
findFirst {
text toBe "i'm a paragraph"
}
}
}
}
/**
* [Picking Custom HTML tags](https://docs.skrape.it/docs/dsl/parsing-html#picking-custom-html-tags)
*/
private fun `Pick Custom HTML tags`() {
val someHtml = """
<body>
<a-custom-tag>foo</a-custom-tag>
<a-custom-tag class="some-style">bar</a-custom-tag>
</body>
""".trimIndent()
htmlDocument(someHtml) {
"a-custom-tag" {
withClass = "some-style"
findFirst {
text toBe "bar"
}
}
}
}
/**
* [Building CSS selectors](https://docs.skrape.it/docs/dsl/parsing-html#building-css-selectors)
*/
private fun `Build CSS selectors`() {
val complexHtmlElement = """<button class="foo bar" fizz="buzz" disabled>click me</button>"""
// terse
htmlDocument(complexHtmlElement) {
"button.foo.bar[fizz='buzz'][disabled]" {
findFirst { /* will pick first matching occurrence */ }
findAll { /* will pick all matching occurrences */ }
}
}
// more readable and less error prone
htmlDocument(complexHtmlElement) {
button {
withClass = "foo" and "bar"
withAttribute = "fizz" to "buzz"
withAttributeKey = "disabled"
findFirst { /* will pick first matching occurence */ }
findAll { /* will pick all matching occurences */ }
}
}
}
/**
* [Testing an Endpoint that is returning HTML](https://docs.skrape.it/docs/dsl/basic-test-scenario#testing-an-endpoint-that-is-returning-html)
*/
private fun `Parse and verify response of url`() {
skrape {
url = "https://github.com/skrapeit/skrape.it"
expect {
statusCode toBe 200
statusMessage toBe "OK"
contentType toBe ContentTypes.TEXT_HTML_UTF8
htmlDocument {
p {
findFirst {
text toBe "A Kotlin-based testing/scraping/parsing library providing the ability to analyze" +
" and extract data from HTML (server & client-side rendered). It places particular emphasis" +
" on ease of use and a high level of readability by providing an intuitive DSL. It aims" +
" to be a testing lib, but can also be used to scrape websites in a convenient fashion."
}
findAll {
size toBe 26
toBePresentTimes(26) // shorthand
}
}
}
}
}
}
private fun `Parse and verify local HTML resource`() {
htmlDocument(loadResourceFileContent("references/kotlinx.html/ref.html")) {
h2 {
findFirst {
text toBe "kotlinx.html"
}
}
p {
withClass = "text-center" and "mt-6"
findFirst {
text toBe "If you don't want to receive letters like this - unsubscribe here."
}
}
}
}
| 16 | null | 54 | 171 | ff3ae6af7530d3b873b79486cf6e947f1ee53aa1 | 6,452 | kotlin-libraries-playground | MIT License |
src/commonTest/kotlin/responseexpectations/ExpectedSong.kt | MrNuggelz | 866,645,099 | false | {"Kotlin": 132979} | package responseexpectations
import io.github.mrnuggelz.opensubsonic.responses.ItemGenre
import io.github.mrnuggelz.opensubsonic.responses.ReplayGain
import io.github.mrnuggelz.opensubsonic.responses.Song
internal val expectedSong = Song(
id = "a70f5f4d781dfa00020e8023698318c0",
parent = "7a234fa5fc021f53f96601568505447c",
isDir = false,
title = "Prayer For Rain Ft Ryan Herr & Lizzy Plotkin",
album = "Pushing Through The Pavement",
artist = "The Polish Ambassador",
track = 3,
year = 2014,
genre = "Electronic",
coverArt = "mf-a70f5f4d781dfa00020e8023698318c0_640a9366",
size = 6932992,
contentType = "audio/mpeg",
suffix = "mp3",
duration = 271,
bitRate = 203,
samplingRate = 44100,
channelCount = 2,
path = "The Polish Ambassador/Pushing Through The Pavement/03 - Prayer For Rain Ft Ryan Herr & Lizzy Plotkin.mp3",
isVideo = false,
userRating = 2,
playCount = 49,
created = "2023-03-10T02:18:29.29713925Z",
albumId = "7a234fa5fc021f53f96601568505447c",
artistId = "64e1f796b283545d329cdf6a31a31dbe",
type = "music",
mediaType = "song",
played = "2024-09-24T17:22:09.299Z",
bpm = 0,
comment = "http://www.jamendo.com cc_standard",
sortName = "",
musicBrainzId = "",
genres = listOf(ItemGenre(name = "Electronic")),
replayGain = ReplayGain(
trackPeak = 1.0,
albumPeak = 1.0,
)
)
| 0 | Kotlin | 0 | 1 | 0734cbd098998abd57e9210d93963dd58c1950bc | 1,437 | OpenSubsonicClient | Apache License 2.0 |
app/src/main/kotlin/com/dtz/netservice/utils/DefaultExceptionHandler.kt | arthurisaac | 590,202,437 | false | {"Kotlin": 527523, "Java": 6547} | package com.dtz.netservice.utils
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.dtz.netservice.app.ApplicationClass
import com.dtz.netservice.ui.activities.login.LoginActivity
import kotlin.system.exitProcess
class DefaultExceptionHandler(var activity: Activity) : Thread.UncaughtExceptionHandler {
@SuppressLint("UnspecifiedImmutableFlag")
override fun uncaughtException(thread: Thread, ex: Throwable) {
val intent = Intent(activity, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(
ApplicationClass.instance?.baseContext , 0, intent, PendingIntent.FLAG_ONE_SHOT
)
//Restart your app after 2 seconds
val mgr = ApplicationClass.instance?.baseContext?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
mgr[AlarmManager.RTC, System.currentTimeMillis() + 1000] = pendingIntent
//finishing the activity.
activity.finish()
//Stopping application
exitProcess(2)
}
} | 0 | Kotlin | 0 | 0 | 0e0d332896a6db60c5af57680d039f7aa08ed9cb | 1,278 | crit-app | Apache License 2.0 |
idea/tests/testData/wordSelection/ClassMember5/5.kt | JetBrains | 278,369,660 | false | null | class C {
constructor()
<selection><caret>init</selection> {
}
fun foo() {
}
// comment
val bar = 1
} | 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 133 | intellij-kotlin | Apache License 2.0 |
lib_base_framework/src/main/java/app/melon/base/framework/lifecycle/LifecycleEvent.kt | biubiubiiu | 344,728,768 | false | null | package app.melon.base.framework.lifecycle
interface LifecycleEvent | 1 | Kotlin | 1 | 2 | 6bb52f962084674ed50ffb3f8399c1b413a5a234 | 68 | Melon | Apache License 2.0 |
trixnity-client/src/commonMain/kotlin/net/folivo/trixnity/client/store/cache/DeleteByRoomIdRepositoryCoroutineCache.kt | benkuly | 330,904,570 | false | null | package net.folivo.trixnity.client.store.cache
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import net.folivo.trixnity.client.store.repository.MapDeleteByRoomIdRepository
import net.folivo.trixnity.client.store.repository.MinimalDeleteByRoomIdRepository
import net.folivo.trixnity.client.store.transaction.TransactionManager
import net.folivo.trixnity.core.model.RoomId
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
private class DeleteByRoomIdRepositoryCoroutineCacheValuesIndex<K>(
private val keyMapper: (K) -> RoomId,
) : CoroutineCacheValuesIndex<K> {
private val roomIdMapping = MutableStateFlow<Map<RoomId, Set<K>>>(emptyMap())
override suspend fun onPut(key: K): Unit =
roomIdMapping.update { mappings ->
val roomId = keyMapper(key)
mappings + (roomId to (mappings[roomId].orEmpty() + key))
}
override suspend fun onRemove(key: K) {
roomIdMapping.update { mappings ->
val roomId = keyMapper(key)
val newMapping = mappings[roomId].orEmpty() - key
if (newMapping.isEmpty()) mappings - roomId
else mappings + (roomId to newMapping)
}
}
private val zeroStateFlow = MutableStateFlow(0)
override suspend fun getSubscriptionCount(key: K): StateFlow<Int> = zeroStateFlow
fun getMapping(roomId: RoomId): Set<K> =
roomIdMapping.value[roomId].orEmpty()
}
class MinimalDeleteByRoomIdRepositoryCoroutineCache<K, V>(
private val repository: MinimalDeleteByRoomIdRepository<K, V>,
private val tm: TransactionManager,
cacheScope: CoroutineScope,
expireDuration: Duration = 1.minutes,
keyMapper: (K) -> RoomId,
) : MinimalRepositoryCoroutineCache<K, V>(
repository = repository,
tm = tm,
cacheScope = cacheScope,
expireDuration = expireDuration,
) {
private val roomIdIndex: DeleteByRoomIdRepositoryCoroutineCacheValuesIndex<K> =
DeleteByRoomIdRepositoryCoroutineCacheValuesIndex(keyMapper)
init {
addIndex(roomIdIndex)
}
suspend fun deleteByRoomId(roomId: RoomId) {
coroutineScope {
launch {
tm.writeOperation { repository.deleteByRoomId(roomId) }
}
launch {
roomIdIndex.getMapping(roomId).forEach {
updateAndGet(
key = it,
updater = { null },
get = { null },
persist = { null },
)
}
}
}
}
}
class MapDeleteByRoomIdRepositoryCoroutineCache<K1, K2, V>(
private val repository: MapDeleteByRoomIdRepository<K1, K2, V>,
private val tm: TransactionManager,
cacheScope: CoroutineScope,
expireDuration: Duration = 1.minutes,
keyMapper: (MapRepositoryCoroutinesCacheKey<K1, K2>) -> RoomId,
) : MapRepositoryCoroutineCache<K1, K2, V>(
repository = repository,
tm = tm,
cacheScope = cacheScope,
expireDuration = expireDuration,
) {
private val roomIdIndex: DeleteByRoomIdRepositoryCoroutineCacheValuesIndex<MapRepositoryCoroutinesCacheKey<K1, K2>> =
DeleteByRoomIdRepositoryCoroutineCacheValuesIndex(keyMapper)
init {
addIndex(roomIdIndex)
}
suspend fun deleteByRoomId(roomId: RoomId) {
coroutineScope {
launch {
tm.writeOperation { repository.deleteByRoomId(roomId) }
}
launch {
roomIdIndex.getMapping(roomId).forEach {
updateAndGet(
key = it,
updater = { null },
get = { null },
persist = { null },
)
}
}
}
}
} | 0 | Kotlin | 3 | 25 | 06fce82bf53d18085eb001e1b18ddc40465a46ab | 4,017 | trixnity | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.