path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
application/KotlinConcepts/app/src/main/java/com/istudio/app/modules/module_demos/flows/modules/flow_basics/ui/FlowBasics.kt
devrath
339,281,472
false
{"Kotlin": 468482, "Java": 3273}
package com.istudio.app.modules.module_demos.flows.modules.flow_basics.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import com.istudio.app.modules.module_selection.ModuleDemo import com.istudio.app.ui.composables.AppButton import com.istudio.app.ui.composables.AppText @Composable fun FlowBasics(navController: NavHostController){ val viewModel: FlowBasicsVm = hiltViewModel() Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.height(16.dp)) AppButton(text = "Flow Builders", onClick = { viewModel.flowBuilders() }) Spacer(modifier = Modifier.height(16.dp)) AppButton(text = "Flow into Mutable State Flow ", onClick = { // New composable is launched navController.navigate(ModuleDemo.DisplayDataFromServer.rout) }) Spacer(modifier = Modifier.height(16.dp)) AppText(text = "Stopping Flow - Demo") AppButton(text = "Start", onClick = { viewModel.stoppingFlowDemoStart() }) Spacer(modifier = Modifier.height(5.dp)) AppButton(text = "Cancel", onClick = { viewModel.invokeCancel() }) Spacer(modifier = Modifier.height(5.dp)) AppButton(text = "Flow Context", onClick = { viewModel.flowContextDemo() }) } }
0
Kotlin
2
15
788c8472244eaa76c0b013a9686749541885876f
1,938
KotlinAlchemy
Apache License 2.0
compiler/testData/diagnostics/tests/secondaryConstructors/headerCallChecker/propertyAccess.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// !DIAGNOSTICS: -UNUSED_PARAMETER class A { val prop = 1 constructor(x: Int) constructor(x: Int, y: Int, z: Int = x + <!INSTANCE_ACCESS_BEFORE_SUPER_CALL!>prop<!> <!OVERLOAD_RESOLUTION_AMBIGUITY!>+<!> <!INSTANCE_ACCESS_BEFORE_SUPER_CALL!>this<!>.prop) : this(x + <!INSTANCE_ACCESS_BEFORE_SUPER_CALL!>prop<!> <!OVERLOAD_RESOLUTION_AMBIGUITY!>+<!> <!INSTANCE_ACCESS_BEFORE_SUPER_CALL!>this<!>.prop) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
420
kotlin
Apache License 2.0
app/src/main/java/com/eroom/erooja/feature/ongoingGoal/OngoingGoalAdapter.kt
YAPP-16th
235,351,786
false
{"Kotlin": 606192, "Java": 100845}
package com.eroom.erooja.feature.ongoingGoal import android.graphics.Paint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewPropertyAnimator import androidx.recyclerview.widget.RecyclerView import com.eroom.data.entity.MinimalTodoListDetail import com.eroom.erooja.R import kotlinx.android.synthetic.main.item_ongoing_goal_list.view.* class OngoingGoalAdapter( val todoList: ArrayList<MinimalTodoListDetail>, private val saveAnimate: (Boolean, Long) -> Unit ) : RecyclerView.Adapter<Holder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val inflatedView = LayoutInflater.from(parent.context) .inflate(R.layout.item_ongoing_goal_list, parent, false) return Holder(inflatedView) } override fun getItemCount(): Int = todoList.size override fun onBindViewHolder(holder: Holder, position: Int) { holder.bind( todoList[position].content, todoList[position].isEnd, saveAnimate, todoList[position].id ) } } class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind( contentText: String, isEnd: Boolean, saveAnimate: (Boolean, Long) -> Unit, todoId: Long ) { itemView.ongoing_detail_checkbox.text = contentText itemView.ongoing_detail_checkbox.apply { isChecked = isEnd if (isEnd) { paintFlags = Paint.STRIKE_THRU_TEXT_FLAG setTextColor(context.getColor(R.color.grey4)) setOnClickListener { saveAnimate(false, todoId) } } else { paintFlags = 0 setTextColor(context.getColor(R.color.grey7)) setOnClickListener { saveAnimate(true, todoId) } } } } }
15
Kotlin
5
14
c762fbf4ff35bfe7a2d4a0cfc4ffb11a23fb86c0
1,897
Team_Android_1_Client
Apache License 2.0
fields/src/commonMain/kotlin/geo/LocationProvider.kt
aSoft-Ltd
695,480,107
false
{"Kotlin": 18492}
package geo interface LocationProvider { val name: String fun transform(input: String?): GeoLocation? }
0
Kotlin
0
0
b7c5704b364663fdafefdfe6a055f273eb0bd204
112
geo-client
MIT License
model/src/main/kotlin/org/digma/intellij/plugin/model/rest/tests/FilterForLatestTests.kt
digma-ai
472,408,329
false
{"Kotlin": 1315823, "Java": 697153, "C#": 114216, "FreeMarker": 13319, "HTML": 13271, "Shell": 6494}
package org.digma.intellij.plugin.model.rest.tests data class FilterForLatestTests( var environments: Set<String>, var pageNumber: Int = 1, )
390
Kotlin
6
17
55a318082a8f8b8d3a1de7d50e83af12d1ef1657
151
digma-intellij-plugin
MIT License
core_library_common/src/commonMain/kotlin/net/apptronic/core/commons/dataprovider/cache/SimpleDataProviderCacheBuilder.kt
apptronicnet
264,405,837
false
null
package net.apptronic.core.commons.dataprovider.cache import net.apptronic.core.context.di.Scope fun <K, T> Scope.simpleCache( builder: SimpleDataProviderCacheBuilder<K, T>.() -> Unit = {} ): DataProviderCache<K, T> { return SimpleDataProviderCacheBuilder<K, T>().apply(builder).build() } class SimpleDataProviderCacheBuilder<K, T> internal constructor() { var maxSize: Int = 32 var sizeFunction: (Pair<K, T>) -> Int = { 1 } fun sizeFunction(sizeFunction: (Pair<K, T>) -> Int) { this.sizeFunction = sizeFunction } internal fun build(): DataProviderCache<K, T> { return SimpleDataProviderCache( maxSize = maxSize, sizeFunction = sizeFunction ) } }
2
Kotlin
0
6
5320427ddc9dd2393f01e75564dab126fdeaac72
745
core
MIT License
libraries/tools/kotlin-gradle-plugin/src/functionalTest/kotlin/org/jetbrains/kotlin/gradle/dependencyResolutionTests/LazyResolvedConfigurationTest.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:Suppress("FunctionName") package org.jetbrains.kotlin.gradle.dependencyResolutionTests import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.component.ModuleComponentIdentifier import org.gradle.api.artifacts.component.ProjectComponentIdentifier import org.gradle.internal.component.external.model.DefaultModuleComponentSelector import org.gradle.kotlin.dsl.project import org.jetbrains.kotlin.gradle.dsl.multiplatformExtension import org.jetbrains.kotlin.gradle.plugin.kotlinToolingVersion import org.jetbrains.kotlin.gradle.plugin.mpp.internal import org.jetbrains.kotlin.gradle.util.applyMultiplatformPlugin import org.jetbrains.kotlin.gradle.util.buildProject import org.jetbrains.kotlin.gradle.util.enableDependencyVerification import org.jetbrains.kotlin.gradle.utils.LazyResolvedConfiguration import org.junit.Test import kotlin.test.assertEquals import kotlin.test.fail class LazyResolvedConfigurationTest { @Test fun `test - creating LazyResolvedConfiguration - will not resolve source configuration`() { val project = buildProject() val configuration = project.configurations.create("forTest") LazyResolvedConfiguration(configuration) assertEquals( Configuration.State.UNRESOLVED, configuration.state, "Expected construction of 'LazyResolvedConfiguration' to not cause resolution of source configuration" ) } @Test fun `test - okio - getArtifacts`() { val project = buildProject { enableDependencyVerification(false) repositories.mavenLocal { repo -> repo.mavenContent { it.includeGroupByRegex(".*jetbrains.*") } } repositories.mavenCentral() applyMultiplatformPlugin() } val kotlin = project.multiplatformExtension kotlin.jvm() kotlin.linuxX64() kotlin.sourceSets.getByName("commonMain").dependencies { implementation("com.squareup.okio:okio:3.3.0") } project.evaluate() val commonMainCompileDependencies = kotlin.metadata().compilations.getByName("commonMain") .internal.configurations.compileDependencyConfiguration val lazyCommonMainCompileDependencies = LazyResolvedConfiguration(commonMainCompileDependencies) assertEquals( commonMainCompileDependencies.incoming.resolutionResult.allDependencies, lazyCommonMainCompileDependencies.allDependencies ) assertEquals(lazyCommonMainCompileDependencies.allDependencies, lazyCommonMainCompileDependencies.allResolvedDependencies) if (lazyCommonMainCompileDependencies.allResolvedDependencies.isEmpty()) fail("Expected some resolved dependencies") /* Check stdlib-common dependency on commonMainCompileDependencies */ run { val resolvedStdlib = lazyCommonMainCompileDependencies.allResolvedDependencies.filter { dependencyResult -> dependencyResult.resolvedVariant.owner.let { id -> id is ModuleComponentIdentifier && id.module == "kotlin-stdlib" } } if (resolvedStdlib.isEmpty()) fail("Expected kotlin-stdlib in resolved dependencies") resolvedStdlib.forEach { dependencyResult -> val artifacts = lazyCommonMainCompileDependencies.getArtifacts(dependencyResult) if (artifacts.isEmpty()) fail("Expected some artifacts resolved for $dependencyResult") artifacts.forEach { artifact -> assertEquals(artifact.file.name, "kotlin-stdlib-${project.kotlinToolingVersion}-all.jar") } } } /* Check okio dependency on commonMainCompileDependencies */ run { val resolvedOkio = lazyCommonMainCompileDependencies.allResolvedDependencies.filter { dependencyResult -> dependencyResult.resolvedVariant.owner.let { id -> id is ModuleComponentIdentifier && id.module == "okio" } } if (resolvedOkio.isEmpty()) fail("Expected okio in resolved dependencies") resolvedOkio.forEach { dependencyResult -> val artifacts = lazyCommonMainCompileDependencies.getArtifacts(dependencyResult) if (artifacts.isEmpty()) fail("Expected some artifacts resolved for $dependencyResult") artifacts.forEach { artifact -> assertEquals("okio-metadata-3.3.0-all.jar", artifact.file.name) } } } /* Check okio dependency on linuxX64MainCompile */ run { val lazyLinuxX64CompileDependencies = LazyResolvedConfiguration( kotlin.linuxX64().compilations.getByName("main").internal.configurations.compileDependencyConfiguration ) val resolvedOkio = lazyLinuxX64CompileDependencies.allResolvedDependencies.filter { dependencyResult -> dependencyResult.resolvedVariant.owner.let { id -> id is ModuleComponentIdentifier && id.module == "okio" } } if (resolvedOkio.isEmpty()) fail("Expected okio in resolved dependencies") resolvedOkio.forEach { dependencyResult -> val artifacts = lazyLinuxX64CompileDependencies.getArtifacts(dependencyResult) if (artifacts.isEmpty()) fail("Expected some artifacts resolved for $dependencyResult") artifacts.forEach { artifact -> val artifactComponentIdentifier = artifact.id.componentIdentifier as ModuleComponentIdentifier assertEquals("okio-linuxx64", artifactComponentIdentifier.module, "Expected linux specific component identifier") } } } } @Test fun `test - unresolved dependency`() { val project = buildProject() val configuration = project.configurations.create("forTest") val unresolvedDependency = project.dependencies.create("unresolved:dependency") configuration.dependencies.add(unresolvedDependency) val lazyConfiguration = LazyResolvedConfiguration(configuration) if (lazyConfiguration.files.toList().isNotEmpty()) fail("Expected no files to be resolved") if (lazyConfiguration.resolvedArtifacts.toList().isNotEmpty()) fail("Expected no artifacts to be resolved") if (lazyConfiguration.allResolvedDependencies.isNotEmpty()) fail("Expected no resolved dependencies") if (lazyConfiguration.resolutionFailures.size != 1) fail("Expected one resolution failure: ${lazyConfiguration.resolutionFailures}") val failure = lazyConfiguration.resolutionFailures.first() if ("unresolved:dependency" !in failure.message.orEmpty()) fail("Expected dependency mentioned in failure: ${failure.message}") if (lazyConfiguration.allDependencies.size != 1) fail("Expected one dependency: ${lazyConfiguration.allDependencies}") val resolvedDependencyResult = lazyConfiguration.allDependencies.first() val moduleIdentifier = (resolvedDependencyResult.requested as DefaultModuleComponentSelector).moduleIdentifier assertEquals("unresolved", moduleIdentifier.group) assertEquals("dependency", moduleIdentifier.name) if (lazyConfiguration.allResolvedDependencies.isNotEmpty()) fail("Expected no resolved dependencies") } @Test fun `test - circular dependency handling`() { val project = buildProject() val configuration = project.configurations.create("forTest") configuration.isCanBeConsumed = true // add dependency to itself project.dependencies.add(configuration.name, project.dependencies.project(":", configuration = configuration.name)) project.artifacts.add(configuration.name, project.file("artifact.tmp")) val lazyConfiguration = LazyResolvedConfiguration(configuration) val dependency = lazyConfiguration.allResolvedDependencies.singleOrNull() ?: fail("Expected to have single dependency") val id = dependency.resolvedVariant.owner if (id !is ProjectComponentIdentifier || id.projectPath != ":") fail("Expected project(:) dependency") val artifactName = lazyConfiguration .resolvedArtifacts .map { it.file.name } .singleOrNull() ?: fail("Expected to have single artifact") assertEquals("artifact.tmp", artifactName) } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
8,666
kotlin
Apache License 2.0
app/src/main/java/top/itning/yunshuclassschedule/util/Glide4Modle.kt
itning
144,722,483
false
null
package top.itning.yunshuclassschedule.util import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule /** * @author itning */ @GlideModule class Glide4Modle : AppGlideModule()
0
Kotlin
10
48
7fac8219f32116334c67541a038639bdc0abccdb
219
YunShuClassSchedule
Apache License 2.0
app/src/main/java/com/ntcv4tracker/features/viewAllOrder/orderOptimized/OrderOptiCatagoryOnClick.kt
DebashisINT
598,511,717
false
{"Kotlin": 14010101, "Java": 1002677}
package com.ntcv4tracker.features.viewAllOrder.orderOptimized import com.ntcv4tracker.app.domain.NewOrderColorEntity interface OrderOptiCatagoryOnClick { fun catagoryListOnClick(objSel: CommonProductCatagory) }
0
Kotlin
0
0
ffb2507db7da2079fd47b16554179d5a5525c79a
216
NTC
Apache License 2.0
app/src/main/java/com/shehuan/wanandroid/widget/VerticalTabLayout.kt
shehuan
153,994,354
false
{"Kotlin": 176622}
package com.shehuan.wanandroid.widget import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.shehuan.wanandroid.R class VerticalTabLayout : LinearLayout { private var currentTabIndex = 0 constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { orientation = VERTICAL } fun addTabs(tabNames: List<String>) { for (tabName in tabNames) { addTab(tabName) } } private fun addTab(tabName: String) { val tab = TabItem(context, tabName) tab.tag = childCount tab.setOnClickListener { val tag: Int = it.tag as Int if (tag != currentTabIndex) { listener.onTabClick(currentTabIndex, tag) switchTab(tag) } } if (childCount == 0) tab.select() addView(tab) } private fun switchTab(destTabIndex: Int) { val destTab: TabItem = getChildAt(destTabIndex) as TabItem destTab.select() val currentTab: TabItem = getChildAt(currentTabIndex) as TabItem currentTab.unSelect() currentTabIndex = destTabIndex } interface OnTabClickListener { fun onTabClick(oldTabIndex: Int, newTabIndex: Int) } lateinit var listener: OnTabClickListener fun setOnTabClickListener(listener: OnTabClickListener) { this.listener = listener } @SuppressLint("ViewConstructor") private class TabItem(context: Context?, tabName: String) : LinearLayout(context) { private val indicatorView: View private val nameTv: TextView private val lineView: View init { val tab: LinearLayout = inflate(R.layout.tab_item_nav_layout) as LinearLayout nameTv = tab.findViewById(R.id.nameTv) nameTv.text = tabName indicatorView = tab.findViewById(R.id.indicatorView) lineView = tab.findViewById(R.id.lineView) } fun select() { nameTv.setTextColor(resources.getColor(R.color.cFE6243)) indicatorView.visibility = View.VISIBLE lineView.visibility = View.GONE } fun unSelect() { nameTv.setTextColor(resources.getColor(R.color.c2C2C2C)) indicatorView.visibility = View.INVISIBLE lineView.visibility = View.VISIBLE } private fun inflate(layoutId: Int): View = LayoutInflater.from(context).inflate(layoutId, this) } }
1
Kotlin
10
39
6d8e12117dc0b5cdf3df98f28df2e7a8dd3e03fd
2,834
WanAndroid
Apache License 2.0
src/main/kotlin/dev/mim1q/derelict/entity/boss/BigSpider.kt
mim1q
636,851,598
false
{"Kotlin": 190159, "Java": 8250}
package dev.mim1q.derelict.entity.boss import net.minecraft.entity.LivingEntity import net.minecraft.util.math.MathHelper import kotlin.math.* interface BigSpider { val bigSpiderAnimationProperties: BigSpiderAnimationProperties private val properties get() = bigSpiderAnimationProperties fun getYawChangeProgress(tickDelta: Float = 1F) = MathHelper.lerp(tickDelta, properties.prevYawChangeProgress, properties.yawChangeProgress) fun getYawChangeDelta(tickDelta: Float = 1F) = MathHelper.lerp(tickDelta, properties.prevYawChangeDelta, properties.yawChangeDelta) fun getSpeedChangeProgress(tickDelta: Float = 1F) = MathHelper.lerp(tickDelta, properties.prevSpeedChangeProgress, properties.speedChangeProgress) fun getSpeedChangeDelta(tickDelta: Float = 1F) = MathHelper.lerp(tickDelta, properties.prevSpeedChangeDelta, properties.speedChangeDelta) } class BigSpiderAnimationProperties(private val entity: LivingEntity) { var yawChangeProgress: Float = 0.0F private set var prevYawChangeProgress: Float = 0.0F private set var yawChangeDelta: Float = 0.0F private set var prevYawChangeDelta: Float = 0.0F private set var speedChangeProgress: Float = 0.0F private set var prevSpeedChangeProgress: Float = 0.0F private set var speedChangeDelta: Float = 0.0F private set var prevSpeedChangeDelta: Float = 0.0F private set fun tick() { prevYawChangeDelta = yawChangeDelta prevYawChangeProgress = yawChangeProgress prevSpeedChangeDelta = speedChangeDelta prevSpeedChangeProgress = speedChangeProgress val yawChange = abs(entity.prevBodyYaw - entity.bodyYaw) if (yawChange < 0.1F) { yawChangeDelta = max(yawChangeDelta - 0.1F, 0.0F) } else { val clampedYawChange = min(yawChange, 0.1F) yawChangeDelta = min(yawChangeDelta + clampedYawChange, 0.5F) yawChangeProgress += if (entity.prevBodyYaw > entity.bodyYaw) (-clampedYawChange * 2F) else (clampedYawChange * 2F) } val distance = (entity.x - entity.prevX).pow(2) + (entity.z - entity.prevZ).pow(2) if (distance <= 0.001) { speedChangeDelta = max(speedChangeDelta - 0.1F, 0.0F) } else { speedChangeDelta = min(speedChangeDelta + 0.1F, 1.0F) speedChangeProgress += MathHelper.clamp(sqrt(distance), 0.1, 1.0).toFloat() } } }
1
Kotlin
2
0
33f7a5b2716e15d2463ccd12f58b999205ba4993
2,342
derelict
MIT License
app/src/main/java/com/marcgdiez/jsonplaceholder/core/MvpView.kt
mgdiez
155,749,752
false
{"Kotlin": 29634}
package com.marcgdiez.jsonplaceholder.core interface MvpView
0
Kotlin
3
7
0de8487bfc59c2abc324ff9a90d4b7c34719ab05
61
ForumDB-Kotlin-MVP
Apache License 2.0
sphinx/application/common/wrappers/wrapper-contact/src/main/java/chat/sphinx/wrapper_contact/ContactKey.kt
stakwork
340,103,148
false
{"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.wrapper_contact @Suppress("NOTHING_TO_INLINE") inline fun String.toContactKey(): ContactKey? = try { ContactKey(this) } catch (e: IllegalArgumentException) { null } @JvmInline value class ContactKey(val value: String) { init { require(value.isNotEmpty()) { "ContactKey cannot be empty" } } }
96
Kotlin
8
18
4fd9556a4a34f14126681535558fe1e39747b323
378
sphinx-kotlin
MIT License
compiler/testData/codegen/box/functions/bigArity/invokeLambda.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// !LANGUAGE: +FunctionTypesWithBigArity class A(val value: Int) private fun check(actual: A, expected: Int) { if (expected != actual.value) { throw AssertionError("Expected $expected, actual ${actual.value}") } } fun box(): String { val l = { p00: A, p01: A, p02: A, p03: A, p04: A, p05: A, p06: A, p07: A, p08: A, p09: A, p10: A, p11: A, p12: A, p13: A, p14: A, p15: A, p16: A, p17: A, p18: A, p19: A, p20: A, p21: A, p22: A, p23: A, p24: A, p25: A, p26: A, p27: A, p28: A, p29: A -> check(p00, 0) check(p01, 1) check(p02, 2) check(p03, 3) check(p04, 4) check(p05, 5) check(p06, 6) check(p07, 7) check(p08, 8) check(p09, 9) check(p10, 10) check(p11, 11) check(p12, 12) check(p13, 13) check(p14, 14) check(p15, 15) check(p16, 16) check(p17, 17) check(p18, 18) check(p19, 19) check(p20, 20) check(p21, 21) check(p22, 22) check(p23, 23) check(p24, 24) check(p25, 25) check(p26, 26) check(p27, 27) check(p28, 28) check(p29, 29) "OK" } return l( A(0), A(1), A(2), A(3), A(4), A(5), A(6), A(7), A(8), A(9), A(10), A(11), A(12), A(13), A(14), A(15), A(16), A(17), A(18), A(19), A(20), A(21), A(22), A(23), A(24), A(25), A(26), A(27), A(28), A(29) ) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,478
kotlin
Apache License 2.0
compiler/testData/codegen/box/compileKotlinAgainstKotlin/inlineClasses/oldMangling/constructorWithInlineClassParametersInBinaryDependencies.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// TARGET_BACKEND: JVM // !LANGUAGE: +InlineClasses // MODULE: lib // USE_OLD_INLINE_CLASSES_MANGLING_SCHEME // FILE: A.kt package lib inline class S(val string: String) class Test(val s: S) // MODULE: main(lib) // FILE: B.kt import lib.* fun box() = Test(S("OK")).s.string
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
278
kotlin
Apache License 2.0
libraries/stdlib/wasm/src/kotlin/collections/ArraysWasm.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2022 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 kotlin.collections /** * Returns a *typed* array containing all the elements of this collection. * * Allocates an array of runtime type `T` having its size equal to the size of this collection * and populates the array with the elements of this collection. * @sample samples.collections.Collections.Collections.collectionToTypedArray */ @kotlin.internal.InlineOnly public actual inline fun <T> Collection<T>.toTypedArray(): Array<T> = copyToArray(this) @Suppress("UNCHECKED_CAST") @PublishedApi internal fun <T> copyToArray(collection: Collection<T>): Array<T> = if (collection is AbstractCollection<T>) //TODO: Find more proper way to call abstract collection's toArray @Suppress("INVISIBLE_MEMBER") collection.toArray() as Array<T> else collectionToArray(collection) as Array<T>
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,038
kotlin
Apache License 2.0
app/src/main/java/com/humboshot/koillection/destinations/AppDestination.kt
HumboShot
717,172,914
false
{"Kotlin": 25123}
package com.humboshot.koillection.destinations import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.List import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.List import androidx.compose.material.icons.filled.Menu import androidx.compose.ui.graphics.vector.ImageVector interface AppDestination { val icon: ImageVector val route: String val title: String } object MainCollection : AppDestination { override val icon: ImageVector = Icons.Default.Menu override val route: String = "main_collection" override val title: String = "Collection" } object SubCollection : AppDestination { override val icon: ImageVector = Icons.AutoMirrored.Filled.List override val route: String = "sub_collection" override val title: String = "{collection_name}" }
0
Kotlin
0
0
95916b9dc1173d0718086993a7169524b909a341
875
koillection-android
MIT License
presentation/list/src/main/kotlin/com/loukwn/gifsoundit/list/view/InfiniteScrollListener.kt
loukwn
149,398,180
false
null
package com.loukwn.gifsoundit.list.view import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class InfiniteScrollListener( val func: () -> Unit, private val layoutManager: LinearLayoutManager ) : RecyclerView.OnScrollListener() { private var previousTotal = 0 private var loading = true private var visibleThreshold = 2 private var firstVisibleItem = 0 private var visibleItemCount = 0 private var totalItemCount = 0 override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0) { visibleItemCount = recyclerView.childCount totalItemCount = layoutManager.itemCount firstVisibleItem = layoutManager.findFirstVisibleItemPosition() if (loading) { if (totalItemCount > previousTotal) { loading = false previousTotal = totalItemCount } } if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold) ) { // End has been reached func() loading = true } } } fun allowOrNotLoading(allow: Boolean) { loading = !allow } }
0
Kotlin
0
4
0715a653ab3555263a1724b880c61858da05702d
1,363
GifSound-It
MIT License
app/src/main/java/com/ricardoteixeira/app/framework/db/FutureWeatherDao.kt
ricardorochateixeira
325,117,463
false
null
package com.ricardoteixeira.app.framework.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.ricardoteixeira.app.framework.db.model.future.FutureWeatherDatabaseModel @Dao interface FutureWeatherDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertCity(city: FutureWeatherDatabaseModel): Long @Query("SELECT * FROM future_weather WHERE cityId = :cityId") fun getCityById(cityId: Int): FutureWeatherDatabaseModel? }
0
Kotlin
0
0
242e0528e3c87dd30ad25b4f167f773362669da6
538
WeatherMVVM-clean
MIT License
src/main/kotlin/world/cepi/sabre/server/ConfigurationHelper.kt
Project-Cepi
298,999,865
false
null
package world.cepi.sabre.server import kotlinx.serialization.json.Json val format = Json { encodeDefaults = true prettyPrint = true ignoreUnknownKeys = true coerceInputValues = true isLenient = true }
21
Kotlin
2
27
3e3f6847905f3e83a81d4065321f037683269430
223
Sabre
MIT License
Android/doraemonkit/src/main/java/com/didichuxing/doraemonkit/kit/core/DokitViewManager.kt
yunjianke
402,659,818
true
{"Java": 4132258, "Objective-C": 1632344, "Kotlin": 1223695, "Dart": 256321, "Vue": 149147, "JavaScript": 103564, "Swift": 39841, "C": 31160, "Objective-C++": 12589, "HTML": 10495, "Shell": 7787, "Ruby": 6648, "AIDL": 570, "Less": 372}
package com.didichuxing.doraemonkit.kit.core import android.app.Activity import android.content.Context import android.content.res.Configuration import android.graphics.Point import android.view.WindowManager import androidx.room.Room import com.didichuxing.doraemonkit.DoKit import com.didichuxing.doraemonkit.kit.network.room_db.DokitDatabase import com.didichuxing.doraemonkit.kit.network.room_db.DokitDbManager import com.didichuxing.doraemonkit.util.ScreenUtils import kotlin.reflect.KClass /** * Created by jintai on 2018/10/23. * 浮标管理类 */ internal class DokitViewManager : DokitViewManagerInterface { companion object { @JvmStatic val instance: DokitViewManager by lazy { DokitViewManager() } private const val TAG = "DokitViewManagerProxy" /** * 每个类型在页面中的位置 只保存marginLeft 和marginTop */ private val mDoKitViewPos: MutableMap<String, DoKitViewInfo> by lazy { mutableMapOf<String, DoKitViewInfo>() } } private val mLastDoKitViewPosInfoMaps: MutableMap<String, LastDokitViewPosInfo> by lazy { mutableMapOf<String, LastDokitViewPosInfo>() } private val mDoKitViewManager: AbsDokitViewManager by lazy { if (DoKitManager.IS_NORMAL_FLOAT_MODE) { NormalDoKitViewManager() } else { SystemDoKitViewManager() } } //下面注释表示允许主线程进行数据库操作,但是不推荐这样做。 //他可能造成主线程lock以及anr //所以我们的操作都是在新线程完成的 val db: DokitDatabase by lazy { Room.databaseBuilder( DoKit.APPLICATION, DokitDatabase::class.java, "dokit-database" ) //下面注释表示允许主线程进行数据库操作,但是不推荐这样做。 //他可能造成主线程lock以及anr //所以我们的操作都是在新线程完成的 .allowMainThreadQueries() .build() } fun init() { //获取所有的intercept apis DokitDbManager.getInstance().getAllInterceptApis() //获取所有的template apis DokitDbManager.getInstance().getAllTemplateApis() } /** * 当app进入后台时调用 */ override fun notifyBackground() { mDoKitViewManager.notifyBackground() } /** * 当app进入前台时调用 */ override fun notifyForeground() { mDoKitViewManager.notifyForeground() } /** * 只有普通浮标才会调用 * 保存每种类型dokitView的位置 */ fun saveDokitViewPos(tag: String, marginLeft: Int, marginTop: Int) { var orientation = -1 val portraitPoint = Point() val landscapePoint = Point() if (ScreenUtils.isPortrait()) { orientation = Configuration.ORIENTATION_PORTRAIT portraitPoint.x = marginLeft portraitPoint.y = marginTop } else { orientation = Configuration.ORIENTATION_LANDSCAPE landscapePoint.x = marginLeft landscapePoint.y = marginTop } if (mDoKitViewPos[tag] == null) { val doKitViewInfo = DoKitViewInfo(orientation, portraitPoint, landscapePoint) mDoKitViewPos[tag] = doKitViewInfo } else { val doKitViewInfo = mDoKitViewPos[tag] if (doKitViewInfo != null) { doKitViewInfo.orientation = orientation doKitViewInfo.portraitPoint = portraitPoint doKitViewInfo.landscapePoint = landscapePoint } } } /** * 只有普通的浮标才需要调用 * 获得指定dokitView的位置信息 * * @param tag * @return */ fun getDoKitViewPos(tag: String): DoKitViewInfo? { return mDoKitViewPos[tag] } /** * 只有普通的浮标才需要调用 * 添加activity关联的所有dokitView activity resume的时候回调 * * @param activity */ override fun dispatchOnActivityResumed(activity: Activity?) { activity?.let { mDoKitViewManager.dispatchOnActivityResumed(it) } } override fun onActivityPaused(activity: Activity?) { activity?.let { mDoKitViewManager.onActivityPaused(it) } } override fun onActivityStopped(activity: Activity?) { activity?.let { mDoKitViewManager.onActivityStopped(it) } } /** * 在当前Activity中添加指定悬浮窗 * * @param dokitIntent */ override fun attach(dokitIntent: DokitIntent) { mDoKitViewManager.attach(dokitIntent) } /** * 隐藏工具列表dokitView */ fun detachToolPanel() { mDoKitViewManager.detachToolPanel() } /** * 显示工具列表dokitView */ fun attachToolPanel(activity: Activity) { mDoKitViewManager.attachToolPanel(activity) } /** * 显示主图标 dokitView */ fun attachMainIcon(activity: Activity) { mDoKitViewManager.attachMainIcon(activity) } /** * 隐藏首页图标 */ fun detachMainIcon() { mDoKitViewManager.detachMainIcon() } /** * 移除每个activity指定的dokitView */ override fun detach(tag: String) { mDoKitViewManager.detach(tag) } /** * 移除每个activity指定的dokitView */ override fun detach(dokitView: AbsDokitView) { mDoKitViewManager.detach(dokitView) } override fun detach(doKitViewClass: Class<out AbsDokitView>) { mDoKitViewManager.detach(doKitViewClass) } /** * 移除所有activity的所有dokitView */ override fun detachAll() { mDoKitViewManager.detachAll() } /** * 获取页面上指定的dokitView * * @param activity 如果是系统浮标 activity可以为null * @param tag * @return */ override fun <T : AbsDokitView> getDoKitView( activity: Activity?, clazz: Class<T> ): AbsDokitView? { return if (activity != null) { mDoKitViewManager.getDoKitView(activity, clazz) } else { null } } /** * Activity销毁时调用 */ override fun onActivityDestroyed(activity: Activity?) { activity?.let { mDoKitViewManager.onActivityDestroyed(it) } } /** * @param activity * @return */ override fun getDoKitViews(activity: Activity?): Map<String, AbsDokitView>? { return if (activity != null) { mDoKitViewManager.getDoKitViews(activity) } else { null } } /** * 系统悬浮窗需要调用 */ interface DokitViewAttachedListener { fun onDokitViewAdd(dokitView: AbsDokitView?) } /** * 系统悬浮窗需要调用 * * @param listener */ fun addDokitViewAttachedListener(listener: DokitViewAttachedListener?) { if (!DoKitManager.IS_NORMAL_FLOAT_MODE && mDoKitViewManager is SystemDoKitViewManager) { (mDoKitViewManager as SystemDoKitViewManager).addListener(listener!!) } } /** * 系统悬浮窗需要调用 * * @param listener */ fun removeDokitViewAttachedListener(listener: DokitViewAttachedListener?) { if (!DoKitManager.IS_NORMAL_FLOAT_MODE && mDoKitViewManager is SystemDoKitViewManager) { (mDoKitViewManager as SystemDoKitViewManager).removeListener(listener!!) } } /** * 获取 * * @return WindowManager */ val windowManager: WindowManager get() = DoKit.APPLICATION.getSystemService(Context.WINDOW_SERVICE) as WindowManager fun saveLastDokitViewPosInfo(key: String, lastDokitViewPosInfo: LastDokitViewPosInfo) { mLastDoKitViewPosInfoMaps[key] = lastDokitViewPosInfo } fun getLastDokitViewPosInfo(key: String): LastDokitViewPosInfo? { return mLastDoKitViewPosInfoMaps[key] } fun removeLastDokitViewPosInfo(key: String) { mLastDoKitViewPosInfoMaps.remove(key) } }
0
Java
0
0
84adf606f930e1b0140da07f2d6c64503cf6d997
8,303
DoraemonKit
Apache License 2.0
test/test/TestBinarySearchPerformance.kt
AntonioNoack
266,471,164
false
{"Kotlin": 995165, "GLSL": 6755, "Java": 1308}
package test import me.anno.remsstudio.animation.AnimatedProperty import org.apache.logging.log4j.LogManager import org.joml.Vector3f import java.util.* fun main(){ val logger = LogManager.getLogger("TestBinarySearchPerformance") // java 1.8.0 build 112 // sequential 50 cycles vs random 220 cycles // random with values: 35-38ns slower -> binarySearch seems to be already optimized for sequential calls :) // random.nextDouble() = 11.5ns // small calc = 1.5ns // access + loop + small calc = 15ns val times = 1e8 val pos = AnimatedProperty.pos() pos.addKeyframe(1.0, Vector3f()) pos.addKeyframe(2.0, Vector3f(1f, 1f, 1f)) pos.addKeyframe(5.0, Vector3f()) for(i in 0 until 1000){ pos.addKeyframe(i+0.5, Vector3f(i.toFloat(), 0f, 0f)) } val random = Random() fun seq(){ val t0 = System.nanoTime() for(i in 0 until times.toLong()){ val t = i/1e9 pos[t] } val t1 = System.nanoTime() logger.info("Sequential: ${((t1-t0)/times)} ns/try") } fun rnd(){ val t2 = System.nanoTime() for(i in 0 until times.toLong()){ val t = random.nextDouble() * 10 pos[t] } val t3 = System.nanoTime() logger.info("Random: ${((t3-t2)/times)} ns/try") } seq() rnd() seq() rnd() }
2
Kotlin
3
15
f494e15a8e7fbafbe0910a1391bca20bcad0fe0d
1,389
RemsStudio
Apache License 2.0
kvision-modules/kvision-bootstrap-typeahead-remote/src/main/kotlin/pl/treksoft/kvision/form/text/TypeaheadRemoteInput.kt
joerg-rade
274,166,618
true
{"Kotlin": 2040278, "CSS": 18836, "JavaScript": 8572, "HTML": 1858}
/* * Copyright (c) 2017-present <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package pl.treksoft.kvision.form.text import kotlinx.serialization.ImplicitReflectionSerializer import kotlinx.serialization.builtins.list import kotlinx.serialization.builtins.serializer import kotlinx.serialization.stringify import org.w3c.dom.get import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.remote.JsonRpcRequest import pl.treksoft.kvision.remote.KVServiceManager import pl.treksoft.kvision.utils.JSON import kotlin.browser.window /** * The Typeahead control connected to the multiplatform service. * * @constructor * @param serviceManager multiplatform service manager * @param function multiplatform service method returning the list of options * @param stateFunction a function to generate the state object passed with the remote request * @param items the max number of items to display in the dropdown * @param minLength the minimum character length needed before triggering dropdown * @param delay a delay between lookups * @param type text input type (default "text") * @param value text input value * @param classes a set of CSS class names */ @OptIn(ImplicitReflectionSerializer::class) open class TypeaheadRemoteInput<T : Any>( serviceManager: KVServiceManager<T>, function: suspend T.(String?, String?) -> List<String>, private val stateFunction: (() -> String)? = null, items: Int? = 8, minLength: Int = 1, delay: Int = 0, type: TextInputType = TextInputType.TEXT, value: String? = null, classes: Set<String> = setOf() ) : TypeaheadInput(null, null, items, minLength, delay, type, value, classes) { private val kvUrlPrefix = window["kv_remote_url_prefix"] private val urlPrefix: String = if (kvUrlPrefix != undefined) kvUrlPrefix else "" init { val (url, method) = serviceManager.getCalls()[function.toString().replace("\\s".toRegex(), "")] ?: throw IllegalStateException("Function not specified!") this.ajaxOptions = TaAjaxOptions( urlPrefix + url, preprocessQuery = { query -> val state = stateFunction?.invoke() JSON.plain.stringify(JsonRpcRequest(0, url, listOf(query, state))) }, preprocessData = { JSON.plain.parse(String.serializer().list, it.result as String).toTypedArray() }, httpType = HttpType.valueOf(method.name) ) } } /** * DSL builder extension function. * * It takes the same parameters as the constructor of the built component. */ fun <T : Any> Container.typeaheadRemoteInput( serviceManager: KVServiceManager<T>, function: suspend T.(String?, String?) -> List<String>, stateFunction: (() -> String)? = null, items: Int? = 8, minLength: Int = 1, delay: Int = 0, type: TextInputType = TextInputType.TEXT, value: String? = null, classes: Set<String> = setOf(), init: (TypeaheadRemoteInput<T>.() -> Unit)? = null ): TypeaheadRemoteInput<T> { val typeaheadRemoteInput = TypeaheadRemoteInput( serviceManager, function, stateFunction, items, minLength, delay, type, value, classes ).apply { init?.invoke(this) } this.add(typeaheadRemoteInput) return typeaheadRemoteInput }
0
Kotlin
1
0
9fbc710662e398199ba0082cbd3add9aa22c16a3
4,365
kvision
MIT License
src/main/kotlin/me/dominaezzz/chitchat/sdk/core/internal/InternalUtils.kt
Dominaezzz
342,052,724
false
null
package me.dominaezzz.chitchat.sdk.core.internal import io.github.matrixkt.utils.MatrixJson import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.json.JsonElement internal fun <T> Flow<JsonElement?>.decodeJson(deserializationStrategy: DeserializationStrategy<T>): Flow<T?> { return map { content -> if (content != null) { try { MatrixJson.decodeFromJsonElement(deserializationStrategy, content) } catch (e: Exception) { null } } else { null } } } @ExperimentalCoroutinesApi internal fun <T> Flow<T?>.coalesce(other: Flow<T>): Flow<T> { return distinctUntilChanged { old, new -> old == null && new == null } .transformLatest { if (it != null) { // TODO: Will "Latest" wrongly cancel this branch? emit(it) } else { emitAll(other) } } }
0
Kotlin
0
12
23ff3f3a3b17db7514ea45f9a8fea9c8b421545b
905
ChitChat
Apache License 2.0
Practice/Algorithms/Warmup/BirthdayCakeCandles.kts
kukaro
352,032,273
false
null
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* /* * Complete the 'birthdayCakeCandles' function below. * * The function is expected to return an INTEGER. * The function accepts INTEGER_ARRAY candles as parameter. */ fun birthdayCakeCandles(candles: Array<Int>): Int { var mx = 0; var result = 0; for (candle in candles) { if (candle > mx) { mx = candle; result = 1; } else if (candle == mx) { result++; } } return result; } fun main(args: Array<String>) { val candlesCount = readLine()!!.trim().toInt() val candles = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray() val result = birthdayCakeCandles(candles) println(result) }
0
Kotlin
0
0
4f04ff7b605536398aecc696f644f25ee6d56637
1,135
hacker-rank-solved
MIT License
compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-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.resolve.checkers import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors.* import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext import org.jetbrains.kotlin.resolve.calls.checkers.isComputingDeferredType import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerAbiStability import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.newLinkedHashSetWithExpectedSize object MissingDependencyClassChecker : CallChecker { override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) { val resultingDescriptor = resolvedCall.resultingDescriptor for (diagnostic in collectDiagnostics(reportOn, resultingDescriptor)) { context.trace.report(diagnostic) } val containerSource = (resultingDescriptor as? DeserializedMemberDescriptor)?.containerSource incompatibilityDiagnosticFor(containerSource, reportOn)?.let(context.trace::report) } private fun diagnosticFor(descriptor: ClassifierDescriptor, reportOn: PsiElement): Diagnostic? { if (descriptor is NotFoundClasses.MockClassDescriptor) { return MISSING_DEPENDENCY_CLASS.on(reportOn, descriptor.fqNameSafe) } return incompatibilityDiagnosticFor(descriptor.source, reportOn) } private fun incompatibilityDiagnosticFor(source: SourceElement?, reportOn: PsiElement): Diagnostic? { if (source is DeserializedContainerSource) { val incompatibility = source.incompatibility if (incompatibility != null) { return INCOMPATIBLE_CLASS.on(reportOn, source.presentableString, incompatibility) } if (source.isPreReleaseInvisible) { return PRE_RELEASE_CLASS.on(reportOn, source.presentableString) } if (source.abiStability == DeserializedContainerAbiStability.UNSTABLE) { return IR_WITH_UNSTABLE_ABI_COMPILED_CLASS.on(reportOn, source.presentableString) } } return null } private fun collectDiagnostics(reportOn: PsiElement, descriptor: CallableDescriptor): Set<Diagnostic> { val result: MutableSet<Diagnostic> = newLinkedHashSetWithExpectedSize(1) fun consider(classDescriptor: ClassDescriptor) { val diagnostic = diagnosticFor(classDescriptor, reportOn) if (diagnostic != null) { result.add(diagnostic) return } (classDescriptor.containingDeclaration as? ClassDescriptor)?.let(::consider) } fun consider(type: KotlinType) { if (!isComputingDeferredType(type)) { (type.constructor.declarationDescriptor as? ClassDescriptor)?.let(::consider) } } descriptor.returnType?.let(::consider) descriptor.extensionReceiverParameter?.value?.type?.let(::consider) descriptor.valueParameters.forEach { consider(it.type) } return result } object ClassifierUsage : ClassifierUsageChecker { override fun check(targetDescriptor: ClassifierDescriptor, element: PsiElement, context: ClassifierUsageCheckerContext) { diagnosticFor(targetDescriptor, element)?.let(context.trace::report) val containerSource = (targetDescriptor as? DeserializedMemberDescriptor)?.containerSource incompatibilityDiagnosticFor(containerSource, element)?.let(context.trace::report) } } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
4,661
kotlin
Apache License 2.0
app/src/main/java/com/hits/coded/presentation/views/codeBlocks/expressions/UIExpressionBlock.kt
delet-dis
482,704,007
false
null
package com.hits.coded.presentation.views.codeBlocks.expressions import android.content.Context import android.util.AttributeSet import android.view.DragEvent import android.view.View import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.widget.addTextChangedListener import com.hits.coded.R import com.hits.coded.data.interfaces.ui.UIElementHandlesCustomRemoveViewProcessInterface import com.hits.coded.data.interfaces.ui.UIElementHandlesDragAndDropInterface import com.hits.coded.data.interfaces.ui.UIElementSavesNestedBlocksInterface import com.hits.coded.data.interfaces.ui.codeBlocks.UICodeBlockElementHandlesDragAndDropInterface import com.hits.coded.data.interfaces.ui.codeBlocks.UICodeBlockSupportsErrorDisplaying import com.hits.coded.data.interfaces.ui.codeBlocks.UICodeBlockWithCustomRemoveViewProcessInterface import com.hits.coded.data.interfaces.ui.codeBlocks.UICodeBlockWithDataInterface import com.hits.coded.data.interfaces.ui.codeBlocks.UICodeBlockWithLastTouchInformation import com.hits.coded.data.interfaces.ui.codeBlocks.UIMoveableCodeBlockInterface import com.hits.coded.data.interfaces.ui.codeBlocks.UINestedableCodeBlock import com.hits.coded.data.models.codeBlocks.bases.BlockBase import com.hits.coded.data.models.codeBlocks.dataClasses.ExpressionBlock import com.hits.coded.data.models.codeBlocks.types.subBlocks.ExpressionBlockType import com.hits.coded.databinding.ViewExpressionBlockBinding class UIExpressionBlock @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr), UIMoveableCodeBlockInterface, UICodeBlockWithDataInterface, UICodeBlockWithLastTouchInformation, UIElementHandlesDragAndDropInterface, UICodeBlockElementHandlesDragAndDropInterface, UICodeBlockWithCustomRemoveViewProcessInterface, UIElementHandlesCustomRemoveViewProcessInterface, UIElementSavesNestedBlocksInterface, UINestedableCodeBlock, UICodeBlockSupportsErrorDisplaying { private val binding: ViewExpressionBlockBinding override val nestedUIBlocks: ArrayList<View?> = arrayListOf(null, null) private var leftSide: Any? = Any() set(value) { field = value _block.leftSide = value } private var rightSide: Any? = Any() set(value) { field = value _block.rightSide = value } private var _block = ExpressionBlock() override val block: BlockBase get() = _block override var touchX: Int = 0 override var touchY: Int = 0 var blockType: ExpressionBlockType? = null set(value) { field = value value?.let { changeBlockType(it) } } init { inflate( context, R.layout.view_expression_block, this ).also { view -> binding = ViewExpressionBlockBinding.bind(view) } this.initDragAndDropGesture(this, DRAG_AND_DROP_TAG) initDragAndDropListener() initCardsTextsListeners() } private fun changeBlockType(blockType: ExpressionBlockType) { _block.expressionBlockType = blockType binding.centerText.setText(blockType.resourceId) } private fun initCardsTextsListeners() { binding.leftCardText.addTextChangedListener { leftSide = it.toString() } binding.rightCardText.addTextChangedListener { rightSide = it.toString() } } override fun initDragAndDropListener() { binding.leftCardText.setOnDragListener { _, dragEvent -> val draggableItem = dragEvent?.localState as View (draggableItem as? UINestedableCodeBlock)?.let { val itemParent = draggableItem.parent as? ViewGroup itemParent?.let { when (dragEvent.action) { DragEvent.ACTION_DRAG_STARTED, DragEvent.ACTION_DRAG_LOCATION -> return@setOnDragListener true DragEvent.ACTION_DRAG_ENTERED -> { scalePlusAnimation(binding.leftCard) return@setOnDragListener true } DragEvent.ACTION_DRAG_EXITED -> { scaleMinusAnimation(binding.leftCard) return@setOnDragListener true } DragEvent.ACTION_DROP -> { handleDropEvent(binding.leftCard, itemParent, draggableItem) return@setOnDragListener true } DragEvent.ACTION_DRAG_ENDED -> { handleDragEndedEvent(draggableItem) return@setOnDragListener true } else -> return@setOnDragListener true } } } true } binding.rightCardText.setOnDragListener { _, dragEvent -> val draggableItem = dragEvent?.localState as View (draggableItem as? UINestedableCodeBlock)?.let { val itemParent = draggableItem.parent as? ViewGroup itemParent?.let { when (dragEvent.action) { DragEvent.ACTION_DRAG_STARTED, DragEvent.ACTION_DRAG_LOCATION -> return@setOnDragListener true DragEvent.ACTION_DRAG_ENTERED -> { scalePlusAnimation(binding.rightCard) return@setOnDragListener true } DragEvent.ACTION_DRAG_EXITED -> { scaleMinusAnimation(binding.rightCard) return@setOnDragListener true } DragEvent.ACTION_DROP -> { handleDropEvent(binding.rightCard, itemParent, draggableItem) return@setOnDragListener true } DragEvent.ACTION_DRAG_ENDED -> { handleDragEndedEvent(draggableItem) return@setOnDragListener true } else -> return@setOnDragListener true } } } true } } private fun handleDropEvent( parentCard: ViewGroup, itemParent: ViewGroup, draggableItem: View ) = with(binding) { scaleMinusAnimation(parentCard) if (draggableItem != this@UIExpressionBlock) { itemParent.removeView(draggableItem) processViewWithCustomRemoveProcessRemoval(itemParent, draggableItem) val draggableBlockWithData = draggableItem as? UICodeBlockWithDataInterface if (parentCard == leftCard) { leftCardText.apply { setText("") visibility = INVISIBLE } draggableBlockWithData?.block?.let { leftSide = it } nestedUIBlocks[0] = draggableItem } if (parentCard == rightCard) { rightCardText.apply { setText("") visibility = INVISIBLE } draggableBlockWithData?.block?.let { rightSide = it } nestedUIBlocks[1] = draggableItem } parentCard.addView(draggableItem) } } private fun handleDragEndedEvent( draggableItem: View ) { draggableItem.post { draggableItem.animate().alpha(1f).duration = UIMoveableCodeBlockInterface.ITEM_APPEAR_ANIMATION_DURATION } val draggableItemBlock = (draggableItem as? UICodeBlockWithDataInterface)?.block if (draggableItemBlock == _block.leftSide || draggableItemBlock == _block.rightSide) { draggableItem.x = 0f draggableItem.y = 0f } this.invalidate() } override fun customRemoveView(view: View) { nestedUIBlocks[nestedUIBlocks.indexOf(view)] = null val removingViewBlock = (view as? UICodeBlockWithDataInterface)?.block if ((leftSide as? BlockBase) == removingViewBlock) { binding.leftCard.removeView(view) leftSide = null with(binding.leftCardText) { setText("") visibility = VISIBLE } } if ((rightSide as? BlockBase) == removingViewBlock) { binding.rightCard.removeView(view) rightSide = null with(binding.rightCardText) { setText("") visibility = VISIBLE } } } override fun hideError() = binding.backgroundImage.setImageResource(R.drawable.expression_block) override fun displayError() = binding.backgroundImage.setImageResource(R.drawable.error_small_block) private companion object { const val DRAG_AND_DROP_TAG = "EXPRESSION_BLOCK_" } }
0
Kotlin
0
0
2a9d9db6d86bcd535e24e487d1720977e596bf22
9,415
coded.
MIT License
compiler/testData/codegen/box/contracts/forLoop.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// !OPT_IN: kotlin.contracts.ExperimentalContracts // WITH_STDLIB import kotlin.contracts.* fun runOnce(action: () -> Unit) { contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } action() } fun test1(): String { var res = "" for (s in listOf("OK")) { runOnce { res += s } } return res } fun test2(): String { var res = "" for (s: String in listOf("OK")) { runOnce { res += s } } return res } fun test3(): String { var res = "" for ((s, _) in listOf("OK" to "FAIL")) { runOnce { res += s } } return res } fun test4(): String { var res = "" for ((s: String, _) in listOf("OK" to "FAIL")) { runOnce { res += s } } return res } fun box(): String { test1().let { if (it != "OK") return "FAIL 1: $it" } test2().let { if (it != "OK") return "FAIL 2: $it" } test3().let { if (it != "OK") return "FAIL 3: $it" } test4().let { if (it != "OK") return "FAIL 4: $it" } return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,103
kotlin
Apache License 2.0
native/commonizer/src/org/jetbrains/kotlin/commonizer/mergedtree/CirPackageNode.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.commonizer.mergedtree import org.jetbrains.kotlin.commonizer.cir.CirName import org.jetbrains.kotlin.commonizer.cir.CirPackage import org.jetbrains.kotlin.commonizer.cir.CirPackageName import org.jetbrains.kotlin.commonizer.utils.CommonizedGroup import org.jetbrains.kotlin.commonizer.utils.CommonizerMap import org.jetbrains.kotlin.commonizer.utils.firstNonNull import org.jetbrains.kotlin.storage.NullableLazyValue class CirPackageNode( override val targetDeclarations: CommonizedGroup<CirPackage>, override val commonDeclaration: NullableLazyValue<CirPackage> ) : CirNodeWithMembers<CirPackage, CirPackage> { override val properties: MutableMap<PropertyApproximationKey, CirPropertyNode> = CommonizerMap() override val functions: MutableMap<FunctionApproximationKey, CirFunctionNode> = CommonizerMap() override val classes: MutableMap<CirName, CirClassNode> = CommonizerMap() val typeAliases: MutableMap<CirName, CirTypeAliasNode> = CommonizerMap() val packageName: CirPackageName get() = targetDeclarations.firstNonNull().packageName override fun <T, R> accept(visitor: CirNodeVisitor<T, R>, data: T) = visitor.visitPackageNode(this, data) override fun toString() = CirNode.toString(this) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,492
kotlin
Apache License 2.0
src/main/kotlin/com/cognifide/gradle/common/file/FileUtil.kt
wttech
237,183,159
false
{"Kotlin": 198547, "Java": 24371, "Shell": 4879}
package com.cognifide.gradle.common.file import org.apache.commons.io.FilenameUtils object FileUtil { fun sanitizeName(name: String): String = name.replace("[:\\\\/*?|<> &]".toRegex(), "_") fun sanitizePath(path: String): String { val source = FilenameUtils.separatorsToUnix(path) val letter = if (source.contains(":/")) source.substringBefore(":/") else null val pathNoLetter = source.substringAfter(":/") val pathSanitized = pathNoLetter.split("/").joinToString("/") { sanitizeName(it) } return if (letter != null) "$letter:/$pathSanitized" else pathSanitized } fun systemPath(path: String) = FilenameUtils.separatorsToSystem(path) }
12
Kotlin
2
4
5200dc8e98727a3189cf78c17f21356801ae964c
697
gradle-common-plugin
Apache License 2.0
compiler/testData/diagnostics/tests/generics/suppressVarianceConflict.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FIR_IDENTICAL // !DIAGNOSTICS: -UNUSED_PARAMETER -UNUSED_VARIABLE class A<out T, in E> { fun foo(x: @UnsafeVariance T) {} fun foo(x: @UnsafeVariance T, y: List<@UnsafeVariance T>): @UnsafeVariance E = null!! fun bar(): List<@UnsafeVariance E> = null!! } fun foo(x: A<String, Any?>, cs: CharSequence, ls: List<CharSequence>) { val y: A<CharSequence, String> = x y.foo(cs) val s: String = y.foo(cs, ls) val ls2: List<String> = y.bar() }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
471
kotlin
Apache License 2.0
app/src/main/java/com/heronet/sellnetbeta/util/Resource.kt
heronet
381,562,805
false
null
package com.heronet.sellnetbeta.util sealed class Resource<T>(val data: T? = null, val message: String? = null, val messages: List<String>? = null) { class Loading<T>(): Resource<T>(null, null) class Success<T>(data: T, message: String? = null): Resource<T>(data, message) class Error<T>(message: String, messages: List<String>? = null): Resource<T>(message = message, messages = messages) }
0
Kotlin
0
0
24d1287c43631c56f96b8a89625f2af5f66b4420
405
sellnet-android
MIT License
compiler/testData/codegen/box/multiDecl/ValCapturedInObjectLiteral.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
class A { operator fun component1() = 1 operator fun component2() = 2 } fun box() : String { val (a, b) = A() val local = object { public fun run() : Int { return a } } return if (local.run() == 1 && b == 2) "OK" else "fail" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
282
kotlin
Apache License 2.0
compiler/testData/writeFlags/property/syntheticAnnotationsMethod/withGetterJvmName.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// !LANGUAGE: +UseGetterNameForPropertyAnnotationsMethodOnJvm // WITH_STDLIB class Foo { annotation class Anno @Anno @get:JvmName("jvmName") val prop: Int get() = 42 } // TESTED_OBJECT_KIND: function // TESTED_OBJECTS: Foo, jvmName$annotations // FLAGS: ACC_DEPRECATED, ACC_STATIC, ACC_SYNTHETIC, ACC_PUBLIC
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
334
kotlin
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/arguments/argumentsOfAnnotations.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
annotation class Ann(val x: Int, val y: String, val z: String = "z") @Ann(y = "y", x = 10) class A annotation class AnnVarargs(val x: Int, vararg val y: String, val z: Int) @AnnVarargs(1, "a", "b", "c", <!NO_VALUE_FOR_PARAMETER!><!ARGUMENT_TYPE_MISMATCH!>2<!>)<!> class B
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
275
kotlin
Apache License 2.0
agp-7.1.0-alpha01/tools/base/adblib/test/src/com/android/adblib/AdbLoggerTest.kt
jomof
374,736,765
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) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.adblib import org.junit.Assert import org.junit.Test import java.io.IOException class AdbLoggerTest { @Test fun simpleLoggerFunctionsWork() { // Prepare val testLogger = MyAdbLogger() // Act testLogger.debug("foo") testLogger.error(IOException(), "bar") testLogger.log(AdbLogger.Level.ERROR, "foo2%s", "bar") testLogger.log(AdbLogger.Level.ERROR, RuntimeException(), "foo3%s", "bar") // Assert Assert.assertEquals(4, testLogger.entries.size) Assert.assertEquals("foo", testLogger.entries[0].message) Assert.assertEquals(AdbLogger.Level.DEBUG, testLogger.entries[0].level) Assert.assertNull(testLogger.entries[0].exception) Assert.assertEquals("bar", testLogger.entries[1].message) Assert.assertEquals(AdbLogger.Level.ERROR, testLogger.entries[1].level) Assert.assertTrue(testLogger.entries[1].exception is IOException) Assert.assertEquals("foo2bar", testLogger.entries[2].message) Assert.assertEquals(AdbLogger.Level.ERROR, testLogger.entries[2].level) Assert.assertNull(testLogger.entries[2].exception) Assert.assertEquals("foo3bar", testLogger.entries[3].message) Assert.assertEquals(AdbLogger.Level.ERROR, testLogger.entries[3].level) Assert.assertTrue(testLogger.entries[3].exception is RuntimeException) } @Test fun allLoggerFunctionsWork() { // Prepare val loggerFunctions: List<LoggerOverloads> = listOf( LoggerOverloads( AdbLogger.Level.VERBOSE, AdbLogger::verbose, AdbLogger::verbose, AdbLogger::verbose, AdbLogger::verbose ), LoggerOverloads( AdbLogger.Level.DEBUG, AdbLogger::debug, AdbLogger::debug, AdbLogger::debug, AdbLogger::debug ), LoggerOverloads( AdbLogger.Level.INFO, AdbLogger::info, AdbLogger::info, AdbLogger::info, AdbLogger::info ), LoggerOverloads( AdbLogger.Level.WARN, AdbLogger::warn, AdbLogger::warn, AdbLogger::warn, AdbLogger::warn ), LoggerOverloads( AdbLogger.Level.ERROR, AdbLogger::error, AdbLogger::error, AdbLogger::error, AdbLogger::error ), ) val testLogger = MyAdbLogger() // Act loggerFunctions.forEach { loggerOverloads -> loggerOverloads.fun1.invoke(testLogger, "foo") loggerOverloads.fun2.invoke(testLogger, "foo2%s", arrayOf("bar")) loggerOverloads.fun3.invoke(testLogger, IOException(), "foo3") loggerOverloads.fun4.invoke(testLogger, RuntimeException(), "foo4%s", arrayOf("bar")) } // Assert Assert.assertEquals(4 * loggerFunctions.size, testLogger.entries.size) var index = 0 loggerFunctions.forEach { loggerOverloads -> Assert.assertEquals("foo", testLogger.entries[index].message) Assert.assertEquals(loggerOverloads.level, testLogger.entries[index].level) Assert.assertNull(testLogger.entries[index].exception) index++ Assert.assertEquals("foo2bar", testLogger.entries[index].message) Assert.assertEquals(loggerOverloads.level, testLogger.entries[index].level) Assert.assertNull(testLogger.entries[index].exception) index++ Assert.assertEquals("foo3", testLogger.entries[index].message) Assert.assertEquals(loggerOverloads.level, testLogger.entries[index].level) Assert.assertTrue(testLogger.entries[index].exception is IOException) index++ Assert.assertEquals("foo4bar", testLogger.entries[index].message) Assert.assertEquals(loggerOverloads.level, testLogger.entries[index].level) Assert.assertTrue(testLogger.entries[index].exception is RuntimeException) index++ } } class MyAdbLogger : AdbLogger() { val entries = ArrayList<Entry>() override fun log(level: Level, message: String) { entries.add(Entry(level, message, null)) } override fun log(level: Level, exception: Throwable, message: String) { entries.add(Entry(level, message, exception)) } data class Entry(val level: Level, val message: String, val exception: Throwable?) } class LoggerOverloads( val level: AdbLogger.Level, val fun1: AdbLogger.(String) -> Unit, val fun2: AdbLogger.(format: String, args: Array<Any?>) -> Unit, val fun3: AdbLogger.(exception: Throwable, message: String) -> Unit, val fun4: AdbLogger.(exception: Throwable, format: String, args: Array<Any?>) -> Unit, ) }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
5,741
CppBuildCacheWorkInProgress
Apache License 2.0
smartpack-compile/src/main/kotlin/com/loong/chow/smartpacket/compiler/Constant.kt
loongchow
184,882,231
false
{"Java": 112772, "Kotlin": 68964}
package com.loong.chow.smartpacket.compiler import com.google.auto.common.MoreTypes import com.loong.chow.PackHelper import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import javax.lang.model.element.Element import javax.lang.model.type.TypeMirror val PACK_HELPER: ClassName by lazy { ClassName.get(PackHelper::class.java) } const val NEW_LINE = ";\r\n"; const val PACK_INTERFACE = "ParcelHelper" fun packMethodName(enclosingElement: Element): String { return "pack${enclosingElement.simpleName}" } fun packMethodName(type: TypeMirror): String { return packMethodName(MoreTypes.asElement(type)) } fun unPackMethodName(enclosingElement: Element): String { return "unPack${enclosingElement.simpleName}" } fun unPackMethodName(type: TypeMirror): String { return unPackMethodName(MoreTypes.asElement(type)) } fun helper(_typeName: TypeName): TypeName { var clazzNameStr = (_typeName as ClassName).simpleName().toString() val packageName = (_typeName as ClassName).packageName().toString() val helperTypeName = ClassName.get(packageName, clazzNameStr + "Helper") return helperTypeName } fun packMethodName(className: ClassName): String { return "pack${className.simpleName()}" } fun unPackMethodName(className: ClassName): String { return "unPack${className.simpleName()}" }
0
Java
0
4
ba04c31ead3892c45080897b67038131770ffd8e
1,346
SmartPacket
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/BuildingRetailMore.kt
Konyaco
574,321,009
false
{"Kotlin": 11029508, "Java": 256912}
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.BuildingRetailMore: ImageVector get() { if (_buildingRetailMore != null) { return _buildingRetailMore!! } _buildingRetailMore = fluentIcon(name = "Filled.BuildingRetailMore") { fluentPath { moveTo(6.22f, 3.0f) curveToRelative(-0.52f, 0.0f, -1.01f, 0.23f, -1.35f, 0.63f) lineTo(1.3f, 7.95f) curveToRelative(-0.67f, 0.82f, -0.1f, 2.05f, 0.96f, 2.05f) horizontalLineToRelative(19.5f) curveToRelative(1.05f, 0.0f, 1.63f, -1.23f, 0.96f, -2.05f) lineToRelative(-3.58f, -4.32f) curveToRelative(-0.33f, -0.4f, -0.83f, -0.63f, -1.35f, -0.63f) lineTo(6.22f, 3.0f) close() moveTo(3.0f, 11.5f) verticalLineToRelative(7.25f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, 2.5f, 2.5f) horizontalLineToRelative(13.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, 2.5f, -2.5f) lineTo(21.0f, 11.5f) lineTo(3.0f, 11.5f) close() moveTo(9.0f, 15.25f) arcToRelative(1.25f, 1.25f, 0.0f, true, true, -2.5f, 0.0f) arcToRelative(1.25f, 1.25f, 0.0f, false, true, 2.5f, 0.0f) close() moveTo(12.0f, 16.5f) arcToRelative(1.25f, 1.25f, 0.0f, true, true, 0.0f, -2.5f) arcToRelative(1.25f, 1.25f, 0.0f, false, true, 0.0f, 2.5f) close() moveTo(17.5f, 15.25f) arcToRelative(1.25f, 1.25f, 0.0f, true, true, -2.5f, 0.0f) arcToRelative(1.25f, 1.25f, 0.0f, false, true, 2.5f, 0.0f) close() } } return _buildingRetailMore!! } private var _buildingRetailMore: ImageVector? = null
4
Kotlin
4
155
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,152
compose-fluent-ui
Apache License 2.0
compiler/testData/diagnostics/tests/inference/capturedTypes/dontCheckNewCapturedTypeSpecificChecksForOldOnes.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// FIR_IDENTICAL // WITH_STDLIB // KT-47143 interface Container<PARAM: Any> interface ContainerType<PARAM: Any, CONT: Container<PARAM>> fun <R: Any> doGet(ep: ContainerType<*, *>): String = TODO() @JvmName("name") fun <R: Any, PARAM: Any, CONT: Container<PARAM>> doGet(ep: ContainerType<PARAM, CONT>): String = TODO() fun main() {}
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
337
kotlin
Apache License 2.0
core_library_common/src/commonMain/kotlin/net/apptronic/core/base/platform/Extensions.kt
apptronicnet
264,405,837
false
null
package net.apptronic.core.base.platform const val IS_DEBUG = false fun debugError(error: Error) { if (IS_DEBUG) { throw error } else { platformLogError(error) } }
2
Kotlin
0
6
5320427ddc9dd2393f01e75564dab126fdeaac72
193
core
MIT License
feature-news-data-newsapi/build.gradle.kts
bogdanzurac
606,411,511
false
null
import dev.bogdanzurac.marp.build.projects plugins { alias(libs.plugins.marp.feature.data) } android { namespace = "dev.bogdanzurac.marp.feature.news.data.newsapi" } dependencies { implementation(project(projects.featureNewsData)) }
0
Kotlin
0
2
1b8859f92a7c20837817b0abf897530bb691caba
248
marp-app-client-android
Apache License 2.0
compiler/testData/diagnostics/testsWithStdLib/contracts/smartcasts/operatorsTests/isInstanceOperator.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// !LANGUAGE: +AllowContractsForCustomFunctions +UseReturnsEffect // !OPT_IN: kotlin.contracts.ExperimentalContracts // !DIAGNOSTICS: -INVISIBLE_REFERENCE -INVISIBLE_MEMBER import kotlin.contracts.* fun isString(x: Any?): Boolean { contract { returns(true) implies (x is String) } return x is String } fun notIsString(x: Any?): Boolean { contract { returns(false) implies (x is String) } return x !is String } fun testSimple(x: Any?) { x.<!UNRESOLVED_REFERENCE!>length<!> if (isString(x)) { x.length } else { x.<!UNRESOLVED_REFERENCE!>length<!> } } fun testSpilling(x: Any?) { x.<!UNRESOLVED_REFERENCE!>length<!> if (isString(x)) x.length x.<!UNRESOLVED_REFERENCE!>length<!> } fun testInversion(x: Any?) { if (notIsString(x)) { x.<!UNRESOLVED_REFERENCE!>length<!> } else { x.length } } fun testInversionSpilling(x: Any?) { x.<!UNRESOLVED_REFERENCE!>length<!> if (notIsString(x)) else x.length x.<!UNRESOLVED_REFERENCE!>length<!> }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,080
kotlin
Apache License 2.0
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/pragma/tableinfo/TableInfoDataSource.kt
jakoss
331,248,865
true
{"Kotlin": 356476}
package com.infinum.dbinspector.ui.pragma.indexes import com.infinum.dbinspector.domain.UseCases import com.infinum.dbinspector.domain.shared.models.Cell import com.infinum.dbinspector.domain.shared.models.parameters.PragmaParameters import com.infinum.dbinspector.ui.shared.base.BaseDataSource internal class IndexDataSource( databasePath: String, statement: String, private val getPragma: UseCases.GetIndexes ) : BaseDataSource<PragmaParameters.Indexes>() { override var parameters: PragmaParameters.Indexes = PragmaParameters.Indexes( databasePath = databasePath, statement = statement ) override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Cell> { val page = getPragma(parameters) parameters = parameters.copy(page = page.nextPage) return LoadResult.Page( data = page.cells, prevKey = null, nextKey = page.nextPage, itemsAfter = page.afterCount ) } }
0
null
0
0
f01af7a2f74ec66b6befbdf86d8ac221a550ff86
998
android_dbinspector
Apache License 2.0
publisher-sdk/src/androidTest/java/com/criteo/publisher/context/ContextProviderTest.kt
criteo
276,380,681
false
{"Java": 1087914, "Kotlin": 895885, "Groovy": 5188}
/* * Copyright 2020 Criteo * * 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.criteo.publisher.context import android.content.res.Configuration import android.content.res.Resources import android.os.LocaleList import com.criteo.publisher.mock.MockedDependenciesRule import com.criteo.publisher.mock.SpyBean import com.criteo.publisher.util.AndroidUtil import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.Rule import org.junit.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.stub import org.mockito.kotlin.whenever import java.util.Locale class ContextProviderTest { @Rule @JvmField val mockedDependenciesRule = MockedDependenciesRule() @SpyBean private lateinit var androidUtil: AndroidUtil @SpyBean private lateinit var contextProvider: ContextProvider @Test fun fetchDeviceHardwareVersion_DoesNotThrow() { assertThatCode { contextProvider.fetchDeviceModel() }.doesNotThrowAnyException() } @Test fun fetchDeviceMake_DoesNotThrow() { assertThatCode { contextProvider.fetchDeviceMake() }.doesNotThrowAnyException() } @Test fun fetchDeviceConnectionType_DoesNotThrow() { assertThatCode { contextProvider.fetchDeviceConnectionType() }.doesNotThrowAnyException() } @Test fun fetchUserCountry_GivenNoLocale_ReturnNull() { Resources.getSystem().configuration.setLocales(LocaleList()) val country = contextProvider.fetchUserCountry() assertThat(country).isNull() } @Test fun fetchUserCountry_GivenLocaleWithBlankCountry_ReturnNull() { Resources.getSystem().configuration.setLocales(LocaleList(Locale.FRENCH)) val country = contextProvider.fetchUserCountry() assertThat(country).isNull() } @Test fun fetchUserCountry_GivenLocaleWithCountry_ReturnIt() { Resources.getSystem().configuration.setLocales(LocaleList(Locale.FRANCE)) val country = contextProvider.fetchUserCountry() assertThat(country).isEqualTo("FR") } @Test fun fetchUserCountry_GivenManyLocales_ReturnFirstOneWithCountry() { Resources.getSystem().configuration.setLocales(LocaleList(Locale.FRENCH, Locale.FRANCE, Locale.CANADA)) val country = contextProvider.fetchUserCountry() assertThat(country).isEqualTo("FR") } @Test fun fetchUserLanguages_GivenNoLocale_ReturnNull() { Resources.getSystem().configuration.setLocales(LocaleList()) val country = contextProvider.fetchUserLanguages() assertThat(country).isNull() } @Test fun fetchUserLanguages_GivenLocaleWithBlankLanguage_ReturnNull() { Resources.getSystem().configuration.setLocales(LocaleList(Locale.ROOT)) val country = contextProvider.fetchUserLanguages() assertThat(country).isNull() } @Test fun fetchUserLanguages_GivenManyLocales_ReturnSetOfNonEmpty() { Resources.getSystem().configuration.setLocales( LocaleList( Locale.FRANCE, Locale.ROOT, Locale.CANADA_FRENCH, Locale.SIMPLIFIED_CHINESE ) ) val country = contextProvider.fetchUserLanguages() assertThat(country).containsExactly("fr", "zh") } @Test fun fetchDeviceWidth_ReturnStrictlyPositiveWidth() { val width = contextProvider.fetchDeviceWidth() assertThat(width).isPositive() } @Test fun fetchDeviceHeight_ReturnStrictlyPositiveHeight() { val height = contextProvider.fetchDeviceHeight() assertThat(height).isPositive() } @Test fun fetchDeviceOrientation_GivenPortrait_ReturnIt() { doReturn(Configuration.ORIENTATION_PORTRAIT).whenever(androidUtil).orientation val orientation = contextProvider.fetchDeviceOrientation() assertThat(orientation).isEqualTo("Portrait") } @Test fun fetchDeviceOrientation_GivenLandscape_ReturnIt() { doReturn(Configuration.ORIENTATION_LANDSCAPE).whenever(androidUtil).orientation val orientation = contextProvider.fetchDeviceOrientation() assertThat(orientation).isEqualTo("Landscape") } @Test fun fetchDeviceOrientation_GivenUndefined_ReturnNull() { doReturn(Configuration.ORIENTATION_UNDEFINED).whenever(androidUtil).orientation val orientation = contextProvider.fetchDeviceOrientation() assertThat(orientation).isNull() } @Test fun fetchSessionDuration_ReturnStrictlyPositive() { val duration = contextProvider.fetchSessionDuration() assertThat(duration).isGreaterThanOrEqualTo(0) } @Test fun fetchUserContext_GivenMockedData_PutThemInRightField() { contextProvider.stub { doReturn("deviceModel").whenever(mock).fetchDeviceModel() doReturn("deviceMake").whenever(mock).fetchDeviceMake() doReturn(42).whenever(mock).fetchDeviceConnectionType() doReturn("userCountry").whenever(mock).fetchUserCountry() doReturn(listOf("en", "he")).whenever(mock).fetchUserLanguages() doReturn(1337).whenever(mock).fetchDeviceWidth() doReturn(22).whenever(mock).fetchDeviceHeight() doReturn("deviceOrientation").whenever(mock).fetchDeviceOrientation() doReturn(10000).whenever(mock).fetchSessionDuration() } val expected = mapOf( "device.model" to "deviceModel", "device.make" to "deviceMake", "device.contype" to 42, "user.geo.country" to "userCountry", "data.inputLanguage" to listOf("en", "he"), "device.w" to 1337, "device.h" to 22, "data.orientation" to "deviceOrientation", "data.sessionDuration" to 10000 ) val context = contextProvider.fetchUserContext() assertThat(context).containsExactlyInAnyOrderEntriesOf(expected) } @Test fun fetchUserContext_GivenNoData_PutNothing() { contextProvider.stub { doReturn(null).whenever(mock).fetchDeviceModel() doReturn(null).whenever(mock).fetchDeviceMake() doReturn(null).whenever(mock).fetchDeviceConnectionType() doReturn(null).whenever(mock).fetchUserCountry() doReturn(null).whenever(mock).fetchUserLanguages() doReturn(null).whenever(mock).fetchDeviceWidth() doReturn(null).whenever(mock).fetchDeviceHeight() doReturn(null).whenever(mock).fetchDeviceOrientation() doReturn(null).whenever(mock).fetchSessionDuration() } val context = contextProvider.fetchUserContext() assertThat(context).isEmpty() } }
4
Java
8
11
5758799caec064ab0501bbe2052210a226abc2cd
6,927
android-publisher-sdk
Apache License 2.0
app/src/main/java/com/github/cfogrady/vitalwear/character/transformation/ExpectedTransformation.kt
cfogrady
619,941,986
false
{"Kotlin": 546579}
package com.github.cfogrady.vitalwear.character.transformation open class ExpectedTransformation(open val slotId: Int, val fusion: Boolean = false) { }
18
Kotlin
0
4
7d8da38e0cc955bc28b41cb2002ec0932e800f98
152
VitalWear
MIT License
compiler/frontend.java/src/org/jetbrains/kotlin/asJava/SyntheticElementUtils.kt
android
263,405,600
true
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.asJava import com.intellij.psi.PsiMethod import com.intellij.psi.SyntheticElement import org.jetbrains.kotlin.resolve.DescriptorUtils fun isSyntheticValuesOrValueOfMethod(method: PsiMethod): Boolean { if (method !is SyntheticElement) return false return DescriptorUtils.ENUM_VALUE_OF.asString() == method.name || DescriptorUtils.ENUM_VALUES.asString() == method.name }
15
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
618
kotlin
Apache License 2.0
app/src/main/java/com/ql/giantbomb/base/di/module/ApiModule.kt
nirukk52
522,774,137
false
{"Kotlin": 43170}
package com.ql.giantbomb.base.di.module import com.ql.giantbomb.base.api.NFTService import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import okhttp3.Call import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.create import javax.inject.Singleton /** * Created by <NAME> on 8/24/20. */ @Module object ApiModule { @Provides @JvmStatic @Singleton fun provideOkHttp(): Call.Factory { return OkHttpClient.Builder().build() } @Provides @JvmStatic @Singleton fun provideMoshi(): Moshi { return Moshi.Builder() .build() } @Provides @JvmStatic @Singleton fun provideRetrofit( moshi: Moshi, callFactory: Call.Factory ): Retrofit { return Retrofit.Builder() .baseUrl("") .callFactory(callFactory) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() } @Provides @JvmStatic @Singleton fun provideGameService(retrofit: Retrofit): NFTService { return retrofit.create() } }
1
Kotlin
0
0
a19bb2b84df799b4317b572d21045286e5987dce
1,182
metaplex
Apache License 2.0
kubernetes/src/main/kotlin/dsl/DefaultKubernetesDeployment.kt
jGleitz
291,470,605
false
{"Kotlin": 237894}
package de.joshuagleitze.gradle.kubernetes.dsl import org.gradle.api.Task import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider public abstract class DefaultKubernetesDeployment<DeployTask: Task, TeardownTask: Task>( final override val cluster: ClusterProvider, tasks: TaskContainer, override val deployment: TaskProvider<DeployTask>, override val teardown: TaskProvider<TeardownTask> ): KubernetesDeployment<DeployTask, TeardownTask> { init { tasks.clusterDeploymentTask(cluster).configure { it.dependsOn(deployment) } tasks.clusterTeardownTask(cluster).configure { it.dependsOn(teardown) } } final override fun getName(): String = cluster.name override fun toString(): String = "deployment '$name' for cluster '${cluster.name}'" }
6
Kotlin
0
1
c54c5179547dc7000e6bab142d2e2a47db9687cc
778
gradle-kubernetes
MIT License
idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/foldIndexed.kt
android
263,405,600
true
null
// WITH_RUNTIME fun test(list: List<Int>) { val foldIndexed = list.<caret>filter { it > 1 }.foldIndexed(0) { index, acc, i -> acc + i } }
15
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
142
kotlin
Apache License 2.0
app/src/test/kotlin/galaxyraiders/adapters/BasicRandomGeneratorTest.kt
galaxy-raiders
480,406,228
false
{"Kotlin": 81414, "Shell": 2563, "Dockerfile": 2318}
package galaxyraiders.adapters import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.RepeatedTest import org.junit.jupiter.api.assertAll import kotlin.random.Random import kotlin.test.assertTrue @DisplayName("Given a basic random generator") class BasicRandomGeneratorTest { private val rng = Random(seed = 42) private val generator = BasicRandomGenerator(rng) @RepeatedTest(10) fun `it generates a double within an interval`() { val min = 1.0 val max = 2.0 val generated: Double = generator.generateDoubleInInterval(min, max) assertAll( "BasicRandomGenerator creates a double with restrictions", { assertTrue(generated >= min) }, { assertTrue(generated <= max) }, ) } @RepeatedTest(10) fun `it generates an integer within a range`() { val min = 1 val max = 10 val generated: Int = generator.generateIntegerInRange(min, max) assertAll( "BasicRandomGenerator creates an integer with restrictions", { assertTrue(generated >= min) }, { assertTrue(generated <= max) }, ) } }
1
Kotlin
109
2
7c1893bea62e43cbb4e289da21713beb5a078a42
1,088
galaxy-raiders-api
MIT License
build.gradle.kts
kofftop
676,710,453
false
null
import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.gradle.tasks.KotlinCompile repositories { mavenCentral() maven("https://jitpack.io") maven("https://repo.spring.io/milestone") maven("https://repo.spring.io/snapshot") } plugins { id("org.springframework.boot") version "3.2.0-SNAPSHOT" id("io.spring.dependency-management") version "1.1.2" kotlin("jvm") version "1.9.0" kotlin("plugin.spring") version "1.9.0" } dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.jetbrains.kotlin:kotlin-reflect") implementation("io.github.kotlin-telegram-bot.kotlin-telegram-bot:telegram:6.1.0") testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation("com.google.truth:truth:1.1.3") testImplementation("io.mockk:mockk:1.13.5") } tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "19" kotlinOptions.freeCompilerArgs += listOf("-opt-in=kotlin.time.ExperimentalTime", "-Xjsr305=strict") } tasks.withType<JavaCompile> { sourceCompatibility = "19" targetCompatibility = "19" } tasks.test { useJUnitPlatform() jvmArgs("--enable-preview") } tasks.bootJar { archiveVersion.set("boot") }
0
Kotlin
0
0
e5ed158e294b71ea16b177a9ee3d28b21d6b37a4
1,224
kofftop
MIT License
src/main/java/com/mineinabyss/mobzy/ecs/components/death/MobDrop.kt
Paul1365972
327,421,137
true
{"Kotlin": 146282}
package com.mineinabyss.mobzy.ecs.components.death import com.mineinabyss.idofront.messaging.color import com.mineinabyss.idofront.recpies.addCookingRecipes import com.mineinabyss.idofront.serialization.SerializableItemStack import com.mineinabyss.mobzy.mobzy import kotlinx.serialization.Serializable import org.bukkit.ChatColor import org.bukkit.inventory.ItemStack import kotlin.math.roundToInt import kotlin.random.Random /** * A serializable class for defining an item a mob can drop. It acts as a sort of factory for [ItemStack]s that may * define rarity, how many items to spawn, etc... * * Also allows defining a cooked version of the item that will automatically be registered when the class is created. * * @param item The item to be spawned. * @param cooked The cooked version of this item. * @param cookExp The amount of exp to drop when this item is cooked. * @param cookTime How long it takes for this item to cook * @param minAmount The minimum stack size of this item. * @param maxAmount The maximum stack size of this item. * @param dropChance A chance from 0 to 1 for this item to be dropped. * */ @Serializable data class MobDrop( val item: SerializableItemStack, val cooked: SerializableItemStack? = null, val cookExp: Float = 0f, val cookTime: Int = 200, val minAmount: Int = 1, val maxAmount: Int = 1, val dropChance: Double = 1.0 ) { init { if (cooked != null) { val cookedItem = cooked.toItemStack() //TODO pretty hacky way of adding recipes. Won't reload them from config if they've changed. try { addCookingRecipes( ChatColor.stripColor(cookedItem.itemMeta!!.displayName.color('§').replace(' ', '_'))!!, item.toItemStack(), cookedItem, cookExp, cookTime, mobzy ) } catch (e: IllegalStateException) { } } } /** @return The amount of items to be dropped, or null if the drop does not succeed */ // TODO I'd like to use exactly what Minecraft's existing system is, but I can't seem to find a way to reuse that. fun chooseDrop(lootingLevel: Int, fire: Boolean): ItemStack? { val lootingPercent = lootingLevel / 100.0 val lootingMaxAmount: Int = if (dropChance >= 0.5) (maxAmount + lootingLevel * Random.nextDouble()).roundToInt() else maxAmount val lootingDropChance = if (dropChance >= 0.10) dropChance * (10.0 + lootingLevel) / 10.0 else dropChance + lootingPercent return if (Random.nextDouble() < lootingDropChance) { val drop = if (fire && cooked != null) cooked.toItemStack() else item.toItemStack() drop.amount = if (lootingMaxAmount <= minAmount) minAmount else Random.nextInt(minAmount, lootingMaxAmount) drop } else null } }
0
Kotlin
0
0
ba1cec1b06421bbfe67ea2c90bc7422a425f8a5a
3,098
Mobzy
MIT License
server/src/integrationTest/kotlin/dev/pellet/integration/IntegrationSenseCheckTest.kt
CarrotCodes
395,832,386
false
null
package dev.pellet.integration import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class IntegrationSenseCheckTest { @Test fun `sense check integration tests`() { assertTrue(true) assertFalse(false) } }
7
Kotlin
2
33
ce4f95136804fddaabaa2978b374be76ed12705e
267
Pellet
Apache License 2.0
src/test/kotlin/com/thelastpickle/tlpstress/MainArgumentsTest.kt
rustyrazorblade
250,606,150
false
{"Kotlin": 152309, "Shell": 863}
package com.thelastpickle.tlpstress import com.thelastpickle.tlpstress.commands.Run import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class MainArgumentsTest { @Test fun testPagingFlagWorks() { val run = Run("placeholder") val pageSize = 20000 run.paging = pageSize assertThat(run.options.fetchSize).isEqualTo(pageSize) } }
4
Kotlin
1
3
4338efd4697e654004bda77137249b45a043d502
412
tlp-stress
Apache License 2.0
libraries/stdlib/wasm/internal/kotlin/wasm/internal/Number2String.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2021 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 kotlin.wasm.internal private enum class CharCodes(val code: Int) { // PERCENT(0x25), PLUS(0x2B), MINUS(0x2D), DOT(0x2E), _0(0x30), // _1(0x31), // _2(0x32), // _3(0x33), // _4(0x34), // _5(0x35), // _6(0x36), // _7(0x37), // _8(0x38), // _9(0x39), // A(0x41), // B(0x42), // E(0x45), // I(0x49), // N(0x4E), // O(0x4F), // X(0x58), // Z(0x5A), // a(0x61), // b(0x62), e(0x65), // n(0x6E), // o(0x6F), // u(0x75), // x(0x78), // z(0x7A) } private fun digitToChar(input: Int): Char { assert(input in 0..9) return (CharCodes._0.code + input).toChar() } // Inspired by the AssemblyScript implementation internal fun itoa32(inputValue: Int, radix: Int): String { if (radix < 2 || radix > 36) throw IllegalArgumentException("Radix argument is unreasonable") if (radix != 10) TODO("When we need it") if (inputValue == 0) return "0" // We can't represent abs(Int.MIN_VALUE), so just hardcode it here if (inputValue == Int.MIN_VALUE) return "-2147483648" val sign = inputValue ushr 31 assert(sign == 1 || sign == 0) val absValue = if (sign == 1) -inputValue else inputValue val decimals = decimalCount32(absValue) + sign val buf = WasmCharArray(decimals) utoaDecSimple(buf, absValue, decimals) if (sign == 1) buf.set(0, CharCodes.MINUS.code.toChar()) return buf.createString() } private fun utoaDecSimple(buffer: WasmCharArray, numInput: Int, offsetInput: Int) { assert(numInput != 0) assert(buffer.len() > 0) assert(offsetInput > 0 && offsetInput <= buffer.len()) var num = numInput var offset = offsetInput do { val t = num / 10 val r = num % 10 num = t offset-- buffer.set(offset, digitToChar(r)) } while (num > 0) } private fun utoaDecSimple64(buffer: WasmCharArray, numInput: Long, offsetInput: Int) { assert(numInput != 0L) assert(buffer.len() > 0) assert(offsetInput > 0 && offsetInput <= buffer.len()) var num = numInput var offset = offsetInput do { val t = num / 10 val r = (num % 10).toInt() num = t offset-- buffer.set(offset, digitToChar(r)) } while (num > 0) } private fun Boolean.toInt() = if (this) 1 else 0 private fun Boolean.toLong() = if (this) 1L else 0L private fun decimalCount32(value: Int): Int { if (value < 100000) { if (value < 100) { return 1 + (value >= 10).toInt() } else { return 3 + (value >= 10000).toInt() + (value >= 1000).toInt() } } else { if (value < 10000000) { return 6 + (value >= 1000000).toInt() } else { return 8 + (value >= 1000000000).toInt() + (value >= 100000000).toInt() } } } internal fun itoa64(inputValue: Long, radix: Int): String { if (inputValue in Int.MIN_VALUE..Int.MAX_VALUE) return itoa32(inputValue.toInt(), radix) if (radix < 2 || radix > 36) throw IllegalArgumentException("Radix argument is unreasonable") if (inputValue == 0L) return "0" // We can't represent abs(Long.MIN_VALUE), so just hardcode it here if (inputValue == Long.MIN_VALUE) return "-9223372036854775808" if (radix != 10) { TODO("When we need it") } val sign = (inputValue ushr 63).toInt() assert(sign == 1 || sign == 0) val absValue = if (sign == 1) -inputValue else inputValue val decimals = decimalCount64High(absValue) + sign val buf = WasmCharArray(decimals) utoaDecSimple64(buf, absValue, decimals) if (sign == 1) buf.set(0, CharCodes.MINUS.code.toChar()) return buf.createString() } // Count number of decimals for u64 values // In our case input value always greater than 2^32-1 so we can skip some parts private fun decimalCount64High(value: Long): Int { if (value < 1000000000000000) { if (value < 1000000000000) { return 10 + (value >= 100000000000).toInt() + (value >= 10000000000).toInt() } else { return 13 + (value >= 100000000000000).toInt() + (value >= 10000000000000).toInt() } } else { if (value < 100000000000000000) { return 16 + (value >= 10000000000000000).toInt() } else { return 18 + (value >= 1000000000000000000).toInt() } } } private const val MAX_DOUBLE_LENGTH = 28 internal fun dtoa(value: Double): String { if (value == 0.0) return "0.0" if (!value.isFinite()) { if (value.isNaN()) return "NaN" return if (value < 0) "-Infinity" else "Infinity" } val buf = WasmCharArray(MAX_DOUBLE_LENGTH) val size = dtoaCore(buf, value) val ret = WasmCharArray(size) buf.copyInto(ret, 0, 0, size) return ret.createString() } private fun dtoaCore(buffer: WasmCharArray, valueInp: Double): Int { var value = valueInp val sign = (value < 0).toInt() if (sign == 1) { value = -value buffer.set(0, CharCodes.MINUS.code.toChar()) } var len = grisu2(value, buffer, sign) len = prettify(BufferWithOffset(buffer, sign), len - sign, _K) return len + sign } // These are needed for grisu2 implementation // TODO: What we are going to do with multiple threads? private var _K: Int = 0 private var _exp: Int = 0 private var _frc_minus: Long = 0 private var _frc_plus: Long = 0 private var _frc_pow: Long = 0 private var _exp_pow: Int = 0 private val EXP_POWERS = shortArrayOf( -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066 ) // 1e-348, 1e-340, ..., 1e340 private val FRC_POWERS = longArrayOf( 0xFA8FD5A0081C0288UL.toLong(), 0xBAAEE17FA23EBF76UL.toLong(), 0x8B16FB203055AC76UL.toLong(), 0xCF42894A5DCE35EAUL.toLong(), 0x9A6BB0AA55653B2DUL.toLong(), 0xE61ACF033D1A45DFUL.toLong(), 0xAB70FE17C79AC6CAUL.toLong(), 0xFF77B1FCBEBCDC4FUL.toLong(), 0xBE5691EF416BD60CUL.toLong(), 0x8DD01FAD907FFC3CUL.toLong(), 0xD3515C2831559A83UL.toLong(), 0x9D71AC8FADA6C9B5UL.toLong(), 0xEA9C227723EE8BCBUL.toLong(), 0xAECC49914078536DUL.toLong(), 0x823C12795DB6CE57UL.toLong(), 0xC21094364DFB5637UL.toLong(), 0x9096EA6F3848984FUL.toLong(), 0xD77485CB25823AC7UL.toLong(), 0xA086CFCD97BF97F4UL.toLong(), 0xEF340A98172AACE5UL.toLong(), 0xB23867FB2A35B28EUL.toLong(), 0x84C8D4DFD2C63F3BUL.toLong(), 0xC5DD44271AD3CDBAUL.toLong(), 0x936B9FCEBB25C996UL.toLong(), 0xDBAC6C247D62A584UL.toLong(), 0xA3AB66580D5FDAF6UL.toLong(), 0xF3E2F893DEC3F126UL.toLong(), 0xB5B5ADA8AAFF80B8UL.toLong(), 0x87625F056C7C4A8BUL.toLong(), 0xC9BCFF6034C13053UL.toLong(), 0x964E858C91BA2655UL.toLong(), 0xDFF9772470297EBDUL.toLong(), 0xA6DFBD9FB8E5B88FUL.toLong(), 0xF8A95FCF88747D94UL.toLong(), 0xB94470938FA89BCFUL.toLong(), 0x8A08F0F8BF0F156BUL.toLong(), 0xCDB02555653131B6UL.toLong(), 0x993FE2C6D07B7FACUL.toLong(), 0xE45C10C42A2B3B06UL.toLong(), 0xAA242499697392D3UL.toLong(), 0xFD87B5F28300CA0EUL.toLong(), 0xBCE5086492111AEBUL.toLong(), 0x8CBCCC096F5088CCUL.toLong(), 0xD1B71758E219652CUL.toLong(), 0x9C40000000000000UL.toLong(), 0xE8D4A51000000000UL.toLong(), 0xAD78EBC5AC620000UL.toLong(), 0x813F3978F8940984UL.toLong(), 0xC097CE7BC90715B3UL.toLong(), 0x8F7E32CE7BEA5C70UL.toLong(), 0xD5D238A4ABE98068UL.toLong(), 0x9F4F2726179A2245UL.toLong(), 0xED63A231D4C4FB27UL.toLong(), 0xB0DE65388CC8ADA8UL.toLong(), 0x83C7088E1AAB65DBUL.toLong(), 0xC45D1DF942711D9AUL.toLong(), 0x924D692CA61BE758UL.toLong(), 0xDA01EE641A708DEAUL.toLong(), 0xA26DA3999AEF774AUL.toLong(), 0xF209787BB47D6B85UL.toLong(), 0xB454E4A179DD1877UL.toLong(), 0x865B86925B9BC5C2UL.toLong(), 0xC83553C5C8965D3DUL.toLong(), 0x952AB45CFA97A0B3UL.toLong(), 0xDE469FBD99A05FE3UL.toLong(), 0xA59BC234DB398C25UL.toLong(), 0xF6C69A72A3989F5CUL.toLong(), 0xB7DCBF5354E9BECEUL.toLong(), 0x88FCF317F22241E2UL.toLong(), 0xCC20CE9BD35C78A5UL.toLong(), 0x98165AF37B2153DFUL.toLong(), 0xE2A0B5DC971F303AUL.toLong(), 0xA8D9D1535CE3B396UL.toLong(), 0xFB9B7CD9A4A7443CUL.toLong(), 0xBB764C4CA7A44410UL.toLong(), 0x8BAB8EEFB6409C1AUL.toLong(), 0xD01FEF10A657842CUL.toLong(), 0x9B10A4E5E9913129UL.toLong(), 0xE7109BFBA19C0C9DUL.toLong(), 0xAC2820D9623BF429UL.toLong(), 0x80444B5E7AA7CF85UL.toLong(), 0xBF21E44003ACDD2DUL.toLong(), 0x8E679C2F5E44FF8FUL.toLong(), 0xD433179D9C8CB841UL.toLong(), 0x9E19DB92B4E31BA9UL.toLong(), 0xEB96BF6EBADF77D9UL.toLong(), 0xAF87023B9BF0EE6BUL.toLong() ) private fun grisu2(value: Double, buffer: WasmCharArray, sign: Int): Int { // frexp routine val uv = value.toBits() var exp = ((uv and 0x7FF0000000000000) ushr 52).toInt() val sid = uv and 0x000FFFFFFFFFFFFF var frc = ((exp != 0).toLong() shl 52) + sid exp = (if (exp != 0) exp else 1) - (0x3FF + 52) normalizedBoundaries(frc, exp) getCachedPower(_exp) // normalize val off = frc.countLeadingZeroBits() frc = frc shl off exp -= off var frc_pow = _frc_pow var exp_pow = _exp_pow var w_frc = umul64f(frc, frc_pow) var wp_frc = umul64f(_frc_plus, frc_pow) - 1 var wp_exp = umul64e(_exp, exp_pow) var wm_frc = umul64f(_frc_minus, frc_pow) + 1 var delta = wp_frc - wm_frc return genDigits(buffer, w_frc, wp_frc, wp_exp, delta, sign); } private fun umul64f(u: Long, v: Long): Long { val u0 = u and 0xFFFFFFFF val v0 = v and 0xFFFFFFFF val u1 = u ushr 32 val v1 = v ushr 32 val l = u0 * v0 var t = u1 * v0 + (l ushr 32) var w = u0 * v1 + (t and 0xFFFFFFFF) w += 0x7FFFFFFF // rounding t = t ushr 32 w = w ushr 32 return u1 * v1 + t + w } private fun umul64e(e1: Int, e2: Int): Int { return e1 + e2 + 64 // where 64 is significand size } private fun normalizedBoundaries(f: Long, e: Int) { var frc = (f shl 1) + 1 var exp = e - 1 val off = frc.countLeadingZeroBits() frc = frc shl off exp -= off val m = 1 + (f == 0x0010000000000000).toInt() _frc_plus = frc _frc_minus = ((f shl m) - 1) shl e - m - exp _exp = exp } private fun getCachedPower(minExp: Int) { val c = Double.fromBits(0x3FD34413509F79FE) // 1 / lg(10) = 0.30102999566398114 val dk = (-61 - minExp) * c + 347 // dk must be positive, so can do ceiling in positive var k = dk.toInt() k += (k.toDouble() != dk).toInt() // conversion with ceil val index = (k shr 3) + 1 _K = 348 - (index shl 3) // decimal exponent no need lookup table _frc_pow = FRC_POWERS[index] _exp_pow = EXP_POWERS[index].toInt() } private fun genDigits(buffer: WasmCharArray, w_frc: Long, mp_frc: Long, mp_exp: Int, deltaInp: Long, sign: Int): Int { var delta = deltaInp val one_exp = -mp_exp val one_frc = 1L shl one_exp val mask = one_frc - 1 var wp_w_frc = mp_frc - w_frc var p1 = (mp_frc ushr one_exp).toInt() var p2 = mp_frc and mask var kappa = decimalCount32(p1) var len = sign while (kappa > 0) { var d: Int var pow10: Long when (kappa) { 0 -> { d = p1 / 1000000000; p1 %= 1000000000; pow10 = 1000000000; } 9 -> { d = p1 / 100000000; p1 %= 100000000; pow10 = 100000000; } 8 -> { d = p1 / 10000000; p1 %= 10000000; pow10 = 10000000; } 7 -> { d = p1 / 1000000; p1 %= 1000000; pow10 = 1000000; } 6 -> { d = p1 / 100000; p1 %= 100000; pow10 = 100000; } 5 -> { d = p1 / 10000; p1 %= 10000; pow10 = 10000; } 4 -> { d = p1 / 1000; p1 %= 1000; pow10 = 1000; } 3 -> { d = p1 / 100; p1 %= 100; pow10 = 100; } 2 -> { d = p1 / 10; p1 %= 10; pow10 = 10; } 1 -> { d = p1; p1 = 0; pow10 = 1; } else -> { d = 0; pow10 = 1; } } if (d or len != 0) buffer.set(len++, digitToChar(d)) --kappa val tmp = (p1.toLong() shl one_exp) + p2 if (tmp <= delta) { _K += kappa grisuRound(buffer, len, delta, tmp, pow10 shl one_exp, wp_w_frc) return len; } } var unit = 1L while (true) { p2 *= 10 delta *= 10 unit *= 10 val d = p2 ushr one_exp if (d or len.toLong() != 0L) buffer.set(len++, digitToChar(d.toInt())) p2 = p2 and mask --kappa if (p2 < delta) { _K += kappa grisuRound(buffer, len, delta, p2, one_frc, wp_w_frc * unit) return len } } } private fun grisuRound(buffer: WasmCharArray, len: Int, delta: Long, restInp: Long, ten_kappa: Long, wp_w: Long) { var rest = restInp val lastp = len - 1 var digit = buffer.get(lastp) while ( rest < wp_w && delta - rest >= ten_kappa && ( rest + ten_kappa < wp_w || wp_w - rest > rest + ten_kappa - wp_w ) ) { --digit rest += ten_kappa; } buffer.set(lastp, digit) } private fun WasmCharArray.copyInto(destination: WasmCharArray, destinationOffset: Int, sourceOffset: Int, len: Int) { var srcIndex: Int var dstIndex: Int var increment: Int if (destinationOffset <= sourceOffset) { srcIndex = sourceOffset dstIndex = destinationOffset increment = 1 } else { srcIndex = sourceOffset + len - 1 dstIndex = destinationOffset + len - 1 increment = -1 } repeat(len) { destination.set(dstIndex, this.get(srcIndex)) srcIndex += increment dstIndex += increment } } private class BufferWithOffset(val buf: WasmCharArray, val off: Int) { operator fun set(addr: Int, value: Char) { buf.set(off + addr, value) } fun memoryCopy(destAddr: Int, srcAddr: Int, len: Int) { val startIdx = off + srcAddr buf.copyInto(buf, off + destAddr, startIdx, len) } fun offsetABitMore(anotherOff: Int) = BufferWithOffset(buf, off + anotherOff) } private fun prettify(buffer: BufferWithOffset, lengthInp: Int, k: Int): Int { var length = lengthInp if (k == 0) { buffer[length] = CharCodes.DOT.code.toChar() buffer[length + 1] = CharCodes._0.code.toChar() return length + 2 } var kk = length + k if (length <= kk && kk <= 21) { // 1234e7 -> 12340000000 for (i in length until kk) { buffer[i] = CharCodes._0.code.toChar() } buffer[kk] = CharCodes.DOT.code.toChar() buffer[kk + 1] = CharCodes._0.code.toChar() return kk + 2 } else if (kk > 0 && kk <= 21) { // 1234e-2 -> 12.34 buffer.memoryCopy(kk + 1, kk, -k) buffer[kk] = CharCodes.DOT.code.toChar() return length + 1 } else if (-6 < kk && kk <= 0) { // 1234e-6 -> 0.001234 val offset = 2 - kk buffer.memoryCopy(offset, 0, length) buffer[0] = CharCodes._0.code.toChar() buffer[1] = CharCodes.DOT.code.toChar() for (i in 2 until offset) { buffer[i] = CharCodes._0.code.toChar() } return length + offset } else if (length == 1) { // 1e30 buffer[1] = CharCodes.e.code.toChar() length = genExponent(buffer.offsetABitMore(2), kk - 1) return length + 2 } else { val len = length buffer.memoryCopy(2, 1, len - 1) buffer[1] = CharCodes.DOT.code.toChar() buffer[len + 1] = CharCodes.e.code.toChar() length += genExponent(buffer.offsetABitMore(len + 2), kk - 1) return length + 2 } } private fun genExponent(buffer: BufferWithOffset, kInp: Int): Int { var k = kInp val sign = k < 0 if (sign) k = -k val kStr = k.toString() for (i in kStr.indices) buffer[i + 1] = kStr[i] buffer[0] = if (sign) CharCodes.MINUS.code.toChar() else CharCodes.PLUS.code.toChar() return kStr.length + 1 }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
16,596
kotlin
Apache License 2.0
native/commonizer/src/org/jetbrains/kotlin/descriptors/commonizer/core/PropertyCommonizer.kt
android
263,405,600
true
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.descriptors.commonizer.core import org.jetbrains.kotlin.descriptors.commonizer.cir.CirProperty import org.jetbrains.kotlin.descriptors.commonizer.cir.factory.CirPropertyFactory import org.jetbrains.kotlin.descriptors.commonizer.cir.factory.CirPropertyGetterFactory import org.jetbrains.kotlin.descriptors.commonizer.core.PropertyCommonizer.ConstCommonizationState.* import org.jetbrains.kotlin.descriptors.commonizer.mergedtree.CirClassifiersCache import org.jetbrains.kotlin.resolve.constants.ConstantValue class PropertyCommonizer(cache: CirClassifiersCache) : AbstractFunctionOrPropertyCommonizer<CirProperty>(cache) { private val setter = PropertySetterCommonizer() private var isExternal = true private lateinit var constCommonizationState: ConstCommonizationState override fun commonizationResult(): CirProperty { val setter = setter.result val constCommonizationState = constCommonizationState val constCompileTimeInitializer = (constCommonizationState as? ConstSameValue)?.compileTimeInitializer if (constCommonizationState is ConstMultipleValues) { // fix all commonized properties to make then non-const constCommonizationState.properties.forEach { it.isConst = false } } return CirPropertyFactory.create( annotations = emptyList(), name = name, typeParameters = typeParameters.result, visibility = visibility.result, modality = modality.result, containingClassDetails = null, isExternal = isExternal, extensionReceiver = extensionReceiver.result, returnType = returnType.result, kind = kind, isVar = setter != null, isLateInit = false, isConst = constCompileTimeInitializer != null, isDelegate = false, getter = CirPropertyGetterFactory.DEFAULT_NO_ANNOTATIONS, setter = setter, backingFieldAnnotations = null, delegateFieldAnnotations = null, compileTimeInitializer = constCompileTimeInitializer ) } override fun initialize(first: CirProperty) { super.initialize(first) constCommonizationState = if (first.isConst) { first.compileTimeInitializer?.let(::ConstSameValue) ?: NonConst } else { NonConst } } override fun doCommonizeWith(next: CirProperty): Boolean { if (next.isLateInit) { // expect property can't be lateinit return false } val constCommonizationState = constCommonizationState if (next.isConst) { // const properties should be lifted up // otherwise commonization should fail: expect property can't be const because expect can't have initializer when (constCommonizationState) { NonConst -> { // previous property was not constant return false } is Const -> { // previous property was constant constCommonizationState.properties += next if (constCommonizationState is ConstSameValue) { if (constCommonizationState.compileTimeInitializer != next.compileTimeInitializer) { // const properties have different constants this.constCommonizationState = ConstMultipleValues(constCommonizationState) } } } } } else if (constCommonizationState != NonConst) { // previous property was constant but this one is not return false } val result = super.doCommonizeWith(next) && setter.commonizeWith(next.setter) if (result) { isExternal = isExternal && next.isExternal } return result } private sealed class ConstCommonizationState { object NonConst : ConstCommonizationState() abstract class Const : ConstCommonizationState() { val properties: MutableList<CirProperty> = mutableListOf() } class ConstSameValue(val compileTimeInitializer: ConstantValue<*>) : Const() class ConstMultipleValues(previous: ConstSameValue) : Const() { init { properties += previous.properties } } } }
34
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
4,745
kotlin
Apache License 2.0
app/src/main/java/com/vladislav/posts/testapplication/data/repository/PostsRepositoryImpl.kt
binkos
393,090,587
false
null
package com.vladislav.posts.testapplication.data.repository import com.vladislav.posts.testapplication.data.db.dao.PostDao import com.vladislav.posts.testapplication.data.db.dao.UserDao import com.vladislav.posts.testapplication.data.mapper.mapToDomain import com.vladislav.posts.testapplication.data.mapper.toDb import com.vladislav.posts.testapplication.data.network.api.Api import com.vladislav.posts.testapplication.domain.model.Post import com.vladislav.posts.testapplication.domain.model.PostDetails import com.vladislav.posts.testapplication.domain.repository.PostsRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.flatMapConcat import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.toList import javax.inject.Inject class PostsRepositoryImpl @Inject constructor( private val api: Api, private val postDao: PostDao, private val userDao: UserDao ) : PostsRepository { override suspend fun getAllPosts(): Flow<Result<List<Post>>> = postDao .getAllPosts() .map { it.map { postEntity -> postEntity.mapToDomain() } } .flatMapConcat { flow { if (it.isEmpty()) { try { refreshPosts() } catch (ex: Exception) { emit(Result.failure<List<Post>>(ex)) } } else { emit(Result.success(it)) } } } override suspend fun refreshPostDetails(id: Long) { val post = api.getPostById(id) val user = api.getUserById(post.userId) postDao.insertPost(post.toDb()) userDao.insertUser(user.toDb()) } override suspend fun getPostDetailsById(id: Long): Flow<PostDetails> = postDao .getPostById(id) .flatMapConcat { post -> userDao.getUserById(post.userId) .map { user -> PostDetails(post.title, post.body, user.name, user.avatarUrl) } } override suspend fun refreshPosts() { val posts = api.getAllPosts() val setOfUserIdsInPosts = posts.map { post -> post.userId }.toSortedSet() setOfUserIdsInPosts .map { api.getUserById(it) } .asFlow() .catch { throw it } .map { it.toDb() } .toList() .also { userDao.insertUsers(it) } posts .map { post -> post.toDb() } .also { postDao.insertPosts(it) } } }
0
Kotlin
0
0
b58ed33f6a60d672cb79f798df7be2fd22e38d7e
2,705
Simple_posts_app
Apache License 2.0
modules/library-ui/src/main/kotlin/com/leinardi/forlago/library/ui/component/Scaffold.kt
leinardi
405,185,933
false
{"Kotlin": 594315, "Shell": 3032}
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.leinardi.forlago.library.ui.component import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.WindowInsets import androidx.compose.material3.FabPosition import androidx.compose.material3.MaterialTheme import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @Composable fun Scaffold( modifier: Modifier = Modifier, topBar: @Composable () -> Unit = {}, bottomBar: @Composable () -> Unit = {}, snackbarHost: @Composable () -> Unit = {}, floatingActionButton: @Composable () -> Unit = {}, floatingActionButtonPosition: FabPosition = FabPosition.End, containerColor: Color = MaterialTheme.colorScheme.background, contentColor: Color = contentColorFor(containerColor), contentWindowInsets: WindowInsets = WindowInsets(0, 0, 0, 0), content: @Composable (PaddingValues) -> Unit, ) { androidx.compose.material3.Scaffold( modifier = modifier, topBar = topBar, bottomBar = bottomBar, snackbarHost = snackbarHost, floatingActionButton = floatingActionButton, floatingActionButtonPosition = floatingActionButtonPosition, containerColor = containerColor, contentColor = contentColor, contentWindowInsets = contentWindowInsets, content = content, ) }
1
Kotlin
2
8
8098e124d1ae185d8777df3b5935db27bcc667f2
2,038
Forlago
Apache License 2.0
compiler/testData/diagnostics/testsWithJsStdLib/dynamicTypes/reified.fir.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// !DIAGNOSTICS: -UNUSED_PARAMETER -REIFIED_TYPE_PARAMETER_NO_INLINE fun <reified T> foo(t: T) {} class C<reified T>(t: T) fun test(d: dynamic) { foo<dynamic>(d) foo(d) C<dynamic>(d) C(d) }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
209
kotlin
Apache License 2.0
tegral-niwen/tegral-niwen-parser/src/test/kotlin/guru/zoroark/tegral/niwen/parser/ComplexStateExtractionTest.kt
utybo
491,247,680
false
{"Kotlin": 1071223, "Nix": 2449}
/* * 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 guru.zoroark.tegral.niwen.parser import guru.zoroark.tegral.niwen.lexer.matchers.matches import guru.zoroark.tegral.niwen.lexer.niwenLexer import guru.zoroark.tegral.niwen.lexer.tokenType import guru.zoroark.tegral.niwen.parser.dsl.expect import guru.zoroark.tegral.niwen.parser.dsl.niwenParser import kotlin.test.Test import kotlin.test.assertEquals class ComplexStateExtractionTest { @Test fun `Transform then store`() { val numberToken = tokenType("numberToken") val lexer = niwenLexer { default state { matches("[0-9]+") isToken numberToken } } val parser = niwenParser { IntHolder root { expect(numberToken) transform { it.toInt() } storeIn IntHolder::int } } val result = parser.parse(lexer.tokenize("1010")) assertEquals(1010, result.int) } @Test fun `Transform twice then store`() { val numberToken = tokenType("numberToken") val lexer = niwenLexer { default state { matches("[0-9]+") isToken numberToken } } val parser = niwenParser { StringHolder root { expect(numberToken) transform { it.toInt() } transform { it.toString() } storeIn StringHolder::str } } val result = parser.parse(lexer.tokenize("1010")) assertEquals("1010", result.str) } data class IntHolder(val int: Int) { companion object : ParserNodeDeclaration<IntHolder> by reflective() } data class StringHolder(val str: String) { companion object : ParserNodeDeclaration<StringHolder> by reflective() } }
21
Kotlin
3
33
eb71e752b91cac01f24ad12563c3f25d6a8f8630
2,281
Tegral
Apache License 2.0
core-ui/src/main/java/com/anytypeio/anytype/core_ui/layout/TableVerticalItemDivider.kt
anyproto
647,371,233
false
{"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276}
package com.anytypeio.anytype.core_ui.layout import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.View import androidx.recyclerview.widget.CustomGridLayoutManager import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.anytypeio.anytype.presentation.BuildConfig import kotlin.math.roundToInt class TableVerticalItemDivider( private val drawable: Drawable ) : RecyclerView.ItemDecoration() { override fun onDraw( canvas: Canvas, parent: RecyclerView, state: RecyclerView.State ) { canvas.save() val spanCount = getSpanCount(parent) val childCount = parent.childCount val itemCount = parent.adapter?.itemCount ?: 0 val rect = Rect() for (i in 0 until childCount) { val child = parent.getChildAt(i) val position = parent.getChildLayoutPosition(child) parent.getDecoratedBoundsWithMargins(child, rect) var bottom = rect.bottom + child.translationY.roundToInt() var top = bottom - drawable.intrinsicHeight if (position < itemCount) { drawable.setBounds(rect.left, top, rect.right, bottom) drawable.draw(canvas) } if (position.rem(spanCount) == 0 && position < itemCount) { bottom = child.top top = bottom - drawable.intrinsicHeight drawable.setBounds(rect.left, top, rect.right, bottom) drawable.draw(canvas) } } canvas.restore() } override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val spanCount = getSpanCount(parent) val itemCount = parent.adapter?.itemCount ?: 0 val position = parent.getChildLayoutPosition(view) outRect.bottom = drawable.intrinsicHeight if (position.rem(spanCount) == 0 && position < itemCount) { outRect.top = drawable.intrinsicHeight } } private fun getSpanCount(parent: RecyclerView): Int { return if (BuildConfig.USE_SIMPLE_TABLES_IN_EDITOR_EDDITING) { (parent.layoutManager as CustomGridLayoutManager).spanCount } else { (parent.layoutManager as GridLayoutManager).spanCount } } }
33
Kotlin
26
301
8b3b7dacae68c015fb8b1b7c9cc76e53f0706430
2,461
anytype-kotlin
RSA Message-Digest License
common/data/api/build.gradle.kts
wasabi-muffin
378,753,431
false
{"Objective-C": 1112998, "Kotlin": 144204, "Swift": 6514, "Ruby": 2369, "JavaScript": 503, "HTML": 175, "Dockerfile": 121}
buildTargets = setOf(BuildTarget.Android, BuildTarget.Ios) projectDependencies = setOf( Module.Models, Module.Repository ) setupMultiplatform() kotlin { sourceSets { commonMain { dependencies { implementation(Deps.Ktor.clientCore) implementation(Deps.Ktor.clientJson) implementation(Deps.Ktor.clientLogging) implementation(Deps.Ktor.clientSerialization) implementation(Deps.Kotlinx.coroutinesCore) implementation(Deps.Kotlinx.serializationCore) implementation(Deps.Koin.core) implementation(Deps.Kotlinx.dateTime) api(Deps.Log.kermit) } } androidMain { dependencies { implementation(Deps.Ktor.clientOkhttp) implementation(kotlin("stdlib", Versions.kotlin)) } } iosMain { dependencies { implementation(Deps.Ktor.clientIos) implementation(Deps.Kotlinx.coroutinesCore) { version { strictly(Versions.kotlinCoroutines) } } } } // jsMain { // dependencies { // implementation(Deps.Ktor.clientJs) // } // } } }
0
Objective-C
0
1
088077dc5db7245e1e116e32b8c65b74c510326f
1,384
mvi-multiplatform
Apache License 2.0
funcalk-core/src/test/kotlin/io/github/funcalk/expression/TokenizerTest.kt
funcalk
377,575,124
false
null
package io.github.funcalk.expression import org.assertj.core.api.Assertions.assertThat import io.github.funcalk.expression.TokenType.DIVIDE import io.github.funcalk.expression.TokenType.LEFT_PARENTHESIS import io.github.funcalk.expression.TokenType.MINUS import io.github.funcalk.expression.TokenType.MULTIPLY import io.github.funcalk.expression.TokenType.NUMBER import io.github.funcalk.expression.TokenType.PLUS import io.github.funcalk.expression.TokenType.POWER import io.github.funcalk.expression.TokenType.RIGHT_PARENTHESIS import io.github.funcalk.expression.TokenType.SYMBOL import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class TokenizerTest { @Test fun `tokenizer should return a token for single digit number`() { val tokenizer = Tokenizer("1") val token = Token("1") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(NUMBER) } @Test fun `tokenizer should return a token for multiple digits number`() { val tokenizer = Tokenizer("12") val token = Token("12") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(NUMBER) } @Test fun `tokenizer should return a token for fractional number`() { val tokenizer = Tokenizer("1.2") val token = Token("1.2") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(NUMBER) } @Test fun `tokenizer should be empty for an empty string`() { val tokenizer = Tokenizer("") assertThat(tokenizer.toList()).isEmpty() } @Test fun `tokenizer should be empty for a blank string`() { val tokenizer = Tokenizer(" ") assertThat(tokenizer.toList()).isEmpty() } @Test fun `tokenizer should throw IllegalArgumentException for an unknown input`() { val tokenizer = Tokenizer("#") assertThrows<IllegalArgumentException> { tokenizer.toList() } } @Test fun `tokenizer should throw IllegalArgumentException for a number using comma`() { val tokenizer = Tokenizer("1,2") assertThrows<IllegalArgumentException> { tokenizer.toList() } } @Test fun `tokenizer should throw IllegalArgumentException for a number without fractional part`() { val tokenizer = Tokenizer("1.") assertThrows<IllegalArgumentException> { tokenizer.toList() } } @Test fun `tokenizer should throw IllegalArgumentException for a number without integer part`() { val tokenizer = Tokenizer(".2") assertThrows<IllegalArgumentException> { tokenizer.toList() } } @Test fun `tokenizer should return a token for a plus`() { val tokenizer = Tokenizer("+") val token = Token("+") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(PLUS) } @Test fun `tokenizer should return a token for a minus`() { val tokenizer = Tokenizer("-") val token = Token("-") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(MINUS) } @Test fun `tokenizer should return tokens for an expression (+)`() { val tokenizer = Tokenizer(" 1 + 2 ") assertThat(tokenizer.toList().map { it.value }).containsExactly("1", "+", "2") } @Test fun `tokenizer should return tokens for an expression (-)`() { val tokenizer = Tokenizer(" 1 - 2 ") assertThat(tokenizer.toList().map { it.value }).containsExactly("1", "-", "2") } @Test fun `tokenizer should return a token for a mult`() { val tokenizer = Tokenizer("*") val token = Token("*") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(MULTIPLY) } @Test fun `tokenizer should return a token for a div`() { val tokenizer = Tokenizer("/") val token = Token("/") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(DIVIDE) } @Test fun `tokenizer should return token ^`() { val tokenizer = Tokenizer("^") val token = Token("^") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(POWER) } @Test fun `tokenizer should return tokens for left parenthesis`() { val tokenizer = Tokenizer("(") val token = Token("(") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(LEFT_PARENTHESIS) } @Test fun `tokenizer should return tokens for right parenthesis`() { val tokenizer = Tokenizer(")") val token = Token(")") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(RIGHT_PARENTHESIS) } @Test fun `tokenizer should return symbol token`() { val tokenizer = Tokenizer("pi") val token = Token("pi") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(SYMBOL) } @Test fun `tokenizer should return symbol token preserving case`() { val tokenizer = Tokenizer("PI") val token = Token("PI") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(SYMBOL) } @Test fun `tokenizer should return symbol token with digits`() { val tokenizer = Tokenizer("x2") val token = Token("x2") assertThat(tokenizer.toList()).containsExactly(token) assertThat(token.type).isEqualTo(SYMBOL) } }
12
Kotlin
0
0
73f5fc61c1dedc1b6f5eb9b10813fc7f821391b5
5,354
funcalk
Apache License 2.0
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/json/jackson/customserializersanddeserializers/MyJsonComponent.kt
spring-projects
6,296,790
false
{"Java": 24755733, "Kotlin": 451737, "HTML": 58426, "Shell": 45767, "JavaScript": 33592, "Groovy": 15015, "Ruby": 8017, "Smarty": 2882, "Batchfile": 2145, "Dockerfile": 2102, "Mustache": 449, "Vim Snippet": 135, "CSS": 117}
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.features.json.jackson.customserializersanddeserializers import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import org.springframework.boot.jackson.JsonComponent import java.io.IOException @JsonComponent class MyJsonComponent { class Serializer : JsonSerializer<MyObject>() { @Throws(IOException::class) override fun serialize(value: MyObject, jgen: JsonGenerator, serializers: SerializerProvider) { jgen.writeStartObject() jgen.writeStringField("name", value.name) jgen.writeNumberField("age", value.age) jgen.writeEndObject() } } class Deserializer : JsonDeserializer<MyObject>() { @Throws(IOException::class, JsonProcessingException::class) override fun deserialize(jsonParser: JsonParser, ctxt: DeserializationContext): MyObject { val codec = jsonParser.codec val tree = codec.readTree<JsonNode>(jsonParser) val name = tree["name"].textValue() val age = tree["age"].intValue() return MyObject(name, age) } } }
589
Java
40,158
71,299
c3b710a1f093423d6a3c8aad2a15695a2897eb57
1,994
spring-boot
Apache License 2.0
compiler/frontend.common/src/org/jetbrains/kotlin/util/CodeFragmentAdjustment.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.util @RequiresOptIn(message = "Should be used only for code fragment resolve/generation adjustments") annotation class CodeFragmentAdjustment
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
381
kotlin
Apache License 2.0
src/test/kotlin/modelo/BatallaTest.kt
joaqogomez
646,572,458
false
null
package modelo import modelo.Batalla.Batalla import modelo.Batalla.Ejercitos import modelo.JuegoYJugador.Jugador import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class BatallaTest { @Test fun ataqueEntrePaisesConElDefensorComoGanador() { val kamchatka = Ejercitos(2, Jugador(1)) val china = Ejercitos(70, Jugador(2)) val batalla = Batalla() batalla.atacar(kamchatka, china) Assertions.assertNotEquals(0, china.getCantidadEjercitos()) } @Test fun ataqueEntrePaisesConElAtacanteComoGanador() { val kamchatka = Ejercitos(70, Jugador(1)) val china = Ejercitos(1, Jugador(2)) val batalla = Batalla() batalla.atacar(kamchatka, china) while (china.getCantidadEjercitos() != 0) batalla.atacar(kamchatka, china) Assertions.assertEquals(0, china.getCantidadEjercitos()) } }
0
Kotlin
0
0
3af2d91168053940f8e9e52994da958a782bb9e8
903
75.31-TDL
MIT License
compiler/tests-spec/tests/org/jetbrains/kotlin/spec/utils/tasks/PrintSpecTestsStatistic.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2019 JetBrains s.r.o. 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.spec.utils.tasks import org.jetbrains.kotlin.spec.utils.SpecTestLinkedType import org.jetbrains.kotlin.spec.utils.SpecTestsStatElement import org.jetbrains.kotlin.spec.utils.SpecTestsStatElementType import org.jetbrains.kotlin.spec.utils.TestsStatisticCollector const val PRINT_BASE_INDENT = " " fun linkedSpecTestsPrint() { println("LINKED SPEC TESTS STATISTIC") println("--------------------------------------------------") val statistic = TestsStatisticCollector.collect(SpecTestLinkedType.LINKED) for ((areaName, areaElement) in statistic) { println("$areaName: ${areaElement.number} tests") for ((sectionName, sectionElement) in areaElement.elements) { print(" $sectionName: ${sectionElement.number} tests") notLinkedSpecTestsCategoriesPrint(sectionElement.elements) println() } } } fun notLinkedSpecTestsCategoriesPrint(elements: Map<Any, SpecTestsStatElement>, level: Int = 1) { for ((name, element) in elements) { if (element.type == SpecTestsStatElementType.TYPE) { print(" [ $name: ${element.number} ]") continue } println() print("${PRINT_BASE_INDENT.repeat(level)}$name: ${element.number} tests") notLinkedSpecTestsCategoriesPrint(element.elements, level + 1) } } fun notLinkedSpecTestsPrint() { println("NOT LINKED SPEC TESTS STATISTIC") println("--------------------------------------------------") val statistic = TestsStatisticCollector.collect(SpecTestLinkedType.NOT_LINKED) for ((areaName, areaElement) in statistic) { println("$areaName: ${areaElement.number} tests") for ((sectionName, sectionElement) in areaElement.elements) { print(" $sectionName: ${sectionElement.number} tests") notLinkedSpecTestsCategoriesPrint(sectionElement.elements) println() } } } fun main() { println("==================================================") linkedSpecTestsPrint() println("==================================================") notLinkedSpecTestsPrint() println("==================================================") }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,389
kotlin
Apache License 2.0
app/src/main/java/com/boltuix/android/NotesViewModel.kt
BoltUIX
542,468,449
false
{"Kotlin": 12601}
package com.boltuix.android import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch class NotesViewModel(application: Application) : AndroidViewModel(application) { // DataStore private val uiDataStore = UIModePreference(application) // get UI mode val getUIMode = uiDataStore.uiMode // save UI mode fun saveToDataStore(isNightMode: Boolean) { viewModelScope.launch(IO) { uiDataStore.saveToDataStore(isNightMode) } } }
0
Kotlin
0
2
e9a597922a5482b01909283832e628ee0ebbba58
617
Dark-theme-Material-Design
Apache License 2.0
mobile/src/main/java/com/sebastiansokolowski/healthguard/view/preference/CustomMultiSelectListPreference.kt
sebastiansokolowski
125,769,078
false
{"Kotlin": 277427, "Java": 1220}
package com.sebastiansokolowski.healthguard.view.preference import android.content.Context import androidx.preference.MultiSelectListPreference import android.util.AttributeSet /** * Created by <NAME> on 12.05.19. */ class CustomMultiSelectListPreference : MultiSelectListPreference { constructor(context: Context) : super(context) { setDefaultValues() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setDefaultValues() } private fun setDefaultValues() { val myEntries: MutableList<String> = mutableListOf("") val myValues: MutableList<String> = mutableListOf("") entries = myEntries.toTypedArray() entryValues = myValues.toTypedArray() } fun setValues(entryName: Array<String>, entryValue: Array<String>) { entries = entryName entryValues = entryValue } }
0
Kotlin
0
0
5c164405abb457b91f04b15ff04ef1702cee6a54
909
mHealth-Guard
Apache License 2.0
src/main/kotlin/io/github/gradlenexus/publishplugin/NexusPublishExtension.kt
gradle-nexus
208,000,474
false
{"Kotlin": 151138}
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.gradlenexus.publishplugin import org.gradle.api.Action import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import org.gradle.api.tasks.Nested import java.time.Duration abstract class NexusPublishExtension(objects: ObjectFactory) { companion object { internal const val NAME = "nexusPublishing" } abstract val useStaging: Property<Boolean> abstract val packageGroup: Property<String> abstract val repositoryDescription: Property<String> abstract val clientTimeout: Property<Duration> abstract val connectTimeout: Property<Duration> @get:Nested abstract val transitionCheckOptions: TransitionCheckOptions fun transitionCheckOptions(action: Action<in TransitionCheckOptions>) { action.execute(transitionCheckOptions) } val repositories: NexusRepositoryContainer = objects.newInstance( DefaultNexusRepositoryContainer::class.java, objects.domainObjectContainer(NexusRepository::class.java) ) fun repositories(action: Action<in NexusRepositoryContainer>) { action.execute(repositories) } }
70
Kotlin
30
374
4aa71f39171daefa47f3a5bca315c8284b350487
1,762
publish-plugin
Apache License 2.0
app/src/main/java/com/digitaldealsolution/tweeklabstask/ui/leaderboard/LeaderBoardCardViewModel.kt
harshdigi
525,768,464
false
null
package com.digitaldealsolution.tweeklabstask.ui.leaderboard import org.w3c.dom.Text data class LeaderBoardCardViewModel(val rankImg : Int, val rankTxt : String, val userImg: Int, val userName: String, val Score: String ){ }
0
Kotlin
0
0
453f585efa97e449b51b38276715dc8c24e62a5c
228
TweakLabTask
Apache License 2.0
KotlinCoroutinesExample/app/src/main/java/com/velmurugan/kotlincoroutinesexample/MainActivity.kt
velmurugan-murugesan
159,637,287
false
null
package com.velmurugan.kotlincoroutinesexample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.* /* 1. Suspend keyword 2. Scope - Global scope, Life Cycle Scope, View Model Scope 3. Launch a coroutines - Launch / Async 4. withContext 5. Dispatchers - Main Dispatchers, IO Dispatchers, Default Dispatchers, Unconfined Dispatchers */ class MainActivity : AppCompatActivity() { val TAG = MainActivity::class.java.name override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,"Before runblocking") runBlocking { delay(2000) Log.d(TAG,"Inside runblocking") } Log.d(TAG,"After runblocking") } }
0
Java
1
6
8c2e8b2a0e8f33b5e8c0ea66890756e02577fa54
894
AndriodSamples
Apache License 2.0
examples/android_kts/my-library/build.gradle.kts
johnryM
560,115,388
false
{"Kotlin": 251213}
plugins { id("com.android.library") id("org.jetbrains.kotlin.android") id ("app.cash.paparazzi") } android { namespace = "org.jetbrains.my_library" compileSdk = 32 defaultConfig { minSdk = 21 targetSdk = 32 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles("consumer-rules.pro") } buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = "1.3.1" } buildTypes { release { isMinifyEnabled = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } } dependencies { implementation("androidx.core:core-ktx:1.7.0") implementation("androidx.appcompat:appcompat:1.5.1") // implementation("com.google.android.material:material:1.7.0") api("androidx.compose.material:material:1.2.1") implementation ("androidx.compose.ui:ui-tooling-preview:1.2.1") debugImplementation ("androidx.compose.ui:ui-tooling:1.2.1") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.3") androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0") }
0
Kotlin
0
0
530186c49c9e6d10ca309c2678ac153394fef685
1,505
kover-annotation-issue-sample
Apache License 2.0
analysis/low-level-api-fir/testData/getOrBuildFir/types/typeParameterBound.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
fun <T : <expr>Number</expr>> check(t: T) { }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
46
kotlin
Apache License 2.0
build.gradle.kts
cHAuHaNz
694,451,344
false
{"Kotlin": 11835}
buildscript { } plugins { id("com.android.application") version "8.0.2" apply false id("com.android.library") version "8.0.2" apply false id("org.jetbrains.kotlin.android") version "1.8.20" apply false }
0
Kotlin
0
0
9c423926be23ab33bc284eb3b6d3621a38e6f4cd
216
Android-Library
Apache License 2.0
src/main/kotlin/com/rjs/myshows/server/service/mdb/tmdb/TmdbUrl.kt
MiseryMachine
129,748,435
false
null
package com.rjs.myshows.services.service.mdb.tmdb class TmdbUrl(var url: String = "") { fun addPath(path: String): TmdbUrl { url += path return this } }
0
Kotlin
0
0
b5679062bf7a1358b9fffbbf73469da1b71ab479
178
myshows-server-kt
MIT License
app/src/main/java/io/github/lee0701/mboard/preset/softkeyboard/RowItem.kt
Lee0701
501,429,969
false
{"Kotlin": 211361, "JavaScript": 1629}
package io.github.lee0701.mboard.preset.softkeyboard import io.github.lee0701.mboard.preset.serialization.KeyCodeSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable() sealed interface RowItem { val width: Float } @SerialName("spacer") @Serializable data class Spacer( @Serializable override val width: Float = 1f, ): RowItem @SerialName("key") @Serializable data class Key( @Serializable(with = KeyCodeSerializer::class) val code: Int = 0, val output: String? = null, val label: String? = output, val backgroundType: KeyBackgroundType? = null, val iconType: KeyIconType? = null, override val width: Float = 1f, val repeatable: Boolean = false, val type: KeyType = KeyType.Alphanumeric, ): RowItem @SerialName("include") @Serializable data class Include( val name: String, ): RowItem { override val width: Float = 0f }
0
Kotlin
0
0
5283f398559b4536e2fbb6eaa36cabb0b6072e99
925
mBoard
Apache License 2.0
kexp-runtime/src/commonMain/kotlin/hu/simplexion/kotlin/kexp/runtime/KeUnpackException.kt
spxbhuhb
634,056,804
false
null
package hu.simplexion.kotlin.kexp.runtime @Suppress("unused") class KeUnpackException( id: Long, ) : IllegalArgumentException("id: $id")
0
Kotlin
0
0
7ca91217fe19a7692adc7bc14ffcb857cbc8809a
141
kexp
Apache License 2.0
agp-7.1.0-alpha01/tools/base/wizard/template-impl/src/com/android/tools/idea/wizard/template/impl/activities/loginActivity/res/layout_w936dp/activityLoginXml.kt
jomof
374,736,765
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) 2019 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.tools.idea.wizard.template.impl.activities.loginActivity.res.layout import com.android.tools.idea.wizard.template.getMaterialComponentName fun activityLoginXml( activityClass: String, packageName: String, useAndroidX: Boolean, minApiLevel: Int): String { return """<?xml version="1.0" encoding="utf-8"?> <${getMaterialComponentName("android.support.constraint.ConstraintLayout", useAndroidX)} xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="${packageName}.ui.login.${activityClass}"> ${activityLoginXmlContent(minApiLevel)} </${getMaterialComponentName("android.support.constraint.ConstraintLayout", useAndroidX)}> """ }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
1,772
CppBuildCacheWorkInProgress
Apache License 2.0
trace-plugin/src/main/java/com/dorck/android/trace/plugin/visitor/TimeTraceClassVisitor.kt
Moosphan
613,749,197
false
null
package com.dorck.android.trace.plugin.visitor import org.objectweb.asm.ClassVisitor import org.objectweb.asm.MethodVisitor import org.objectweb.asm.Opcodes import java.util.concurrent.atomic.AtomicInteger /** * The ClassVisitor decorator to track method time cost. * @author Dorck * @since 2023/04/13 */ class TimeTraceClassVisitor( private val api: Int, private val visitor: ClassVisitor, private val counter: AtomicInteger, ) : ClassVisitor(api, visitor) { private var isAbsClz = false private var className = "" override fun visit( version: Int, access: Int, name: String?, signature: String?, superName: String?, interfaces: Array<out String>? ) { super.visit(version, access, name, signature, superName, interfaces) className = name ?: "" if ((access and Opcodes.ACC_ABSTRACT) > 0 || (access and Opcodes.ACC_INTERFACE) > 0) { isAbsClz = true } } override fun visitMethod( access: Int, name: String?, descriptor: String?, signature: String?, exceptions: Array<out String>? ): MethodVisitor { val curMethodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions) if (!isAbsClz) { val curMethodCount = counter.incrementAndGet() //println("You have tracked method [$className$name], total methods: [$curMethodCount]") return TimeTraceMethodVisitor(api, curMethodVisitor, access, name ?: "", descriptor ?: "", className, name ?: "") } return curMethodVisitor } }
0
Kotlin
0
0
d734e49d984c8b13aea9c51258286bf4c22e9756
1,640
GeekTimeCoursesTraining
MIT License
app/src/main/java/com/onemb/myshoppinglistapp/database/ShoppingListEntity.kt
one-mb-rai
748,596,581
false
{"Kotlin": 36055}
package com.onemb.myshoppinglistapp.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class ShoppingListEntity( @PrimaryKey val id: Int, @ColumnInfo(name = "itemName") val itemName: String, @ColumnInfo(name = "itemQuantity") val itemQuantity: String, @ColumnInfo(name = "itemEditedOn") val itemEditedOn: String, @ColumnInfo(name = "markCompleted") val markCompleted: Boolean )
0
Kotlin
0
0
7db9137197eb903b0492066be0a6f5c034127357
462
MyShoppingListApp
Apache License 2.0
trixnity-core/src/commonMain/kotlin/net/folivo/trixnity/core/model/events/m/SigningKeyUpdateDataUnitContent.kt
benkuly
330,904,570
false
{"Kotlin": 4132578, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1275}
package net.folivo.trixnity.core.model.events.m import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import net.folivo.trixnity.core.model.UserId import net.folivo.trixnity.core.model.events.EphemeralDataUnitContent import net.folivo.trixnity.core.model.keys.SignedCrossSigningKeys /** * @see <a href="https://spec.matrix.org/v1.7/server-server-api/#end-to-end-encryption">matrix spec</a> */ @Serializable data class SigningKeyUpdateDataUnitContent( @SerialName("master_key") val masterKey: SignedCrossSigningKeys? = null, @SerialName("self_signing_key") val selfSigningKey: SignedCrossSigningKeys? = null, @SerialName("user_id") val userId: UserId, ) : EphemeralDataUnitContent
0
Kotlin
3
27
645fc08a4aa5a119ca336678ecde33f4bd7aa3e0
735
trixnity
Apache License 2.0
compiler/testData/codegen/box/reflection/functions/simpleGetFunctions.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
// TARGET_BACKEND: JVM // WITH_REFLECT import kotlin.reflect.full.* open class A { fun mem() {} fun Int.memExt() {} } class B : A() fun box(): String { val all = A::class.functions.map { it.name }.sorted() assert(all == listOf("equals", "hashCode", "mem", "memExt", "toString")) { "Fail A functions: ${A::class.functions}" } val declared = A::class.declaredFunctions.map { it.name }.sorted() assert(declared == listOf("mem", "memExt")) { "Fail A declaredFunctions: ${A::class.declaredFunctions}" } val declaredSubclass = B::class.declaredFunctions.map { it.name }.sorted() assert(declaredSubclass.isEmpty()) { "Fail B declaredFunctions: ${B::class.declaredFunctions}" } return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
727
kotlin
Apache License 2.0
src/controller/java/generated/java/matter/controller/cluster/structs/GeneralDiagnosticsClusterNetworkInterface.kt
project-chip
244,694,174
false
{"C++": 24146071, "Kotlin": 8227006, "Java": 7134698, "Python": 3866042, "C": 2280568, "Objective-C": 1373765, "ZAP": 824658, "Objective-C++": 764141, "Shell": 298232, "CMake": 175247, "Jinja": 144691, "Dockerfile": 72039, "Swift": 29310, "JavaScript": 2484, "Emacs Lisp": 1042, "Tcl": 311}
/* * * Copyright (c) 2023 Project CHIP Authors * * 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 matter.controller.cluster.structs import matter.controller.cluster.* import matter.tlv.AnonymousTag import matter.tlv.ContextSpecificTag import matter.tlv.Tag import matter.tlv.TlvReader import matter.tlv.TlvWriter class GeneralDiagnosticsClusterNetworkInterface( val name: String, val isOperational: Boolean, val offPremiseServicesReachableIPv4: Boolean?, val offPremiseServicesReachableIPv6: Boolean?, val hardwareAddress: ByteArray, val IPv4Addresses: List<ByteArray>, val IPv6Addresses: List<ByteArray>, val type: UByte ) { override fun toString(): String = buildString { append("GeneralDiagnosticsClusterNetworkInterface {\n") append("\tname : $name\n") append("\tisOperational : $isOperational\n") append("\toffPremiseServicesReachableIPv4 : $offPremiseServicesReachableIPv4\n") append("\toffPremiseServicesReachableIPv6 : $offPremiseServicesReachableIPv6\n") append("\thardwareAddress : $hardwareAddress\n") append("\tIPv4Addresses : $IPv4Addresses\n") append("\tIPv6Addresses : $IPv6Addresses\n") append("\ttype : $type\n") append("}\n") } fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) { tlvWriter.apply { startStructure(tlvTag) put(ContextSpecificTag(TAG_NAME), name) put(ContextSpecificTag(TAG_IS_OPERATIONAL), isOperational) if (offPremiseServicesReachableIPv4 != null) { put( ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV4), offPremiseServicesReachableIPv4 ) } else { putNull(ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV4)) } if (offPremiseServicesReachableIPv6 != null) { put( ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV6), offPremiseServicesReachableIPv6 ) } else { putNull(ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV6)) } put(ContextSpecificTag(TAG_HARDWARE_ADDRESS), hardwareAddress) startArray(ContextSpecificTag(TAG_I_PV4_ADDRESSES)) for (item in IPv4Addresses.iterator()) { put(AnonymousTag, item) } endArray() startArray(ContextSpecificTag(TAG_I_PV6_ADDRESSES)) for (item in IPv6Addresses.iterator()) { put(AnonymousTag, item) } endArray() put(ContextSpecificTag(TAG_TYPE), type) endStructure() } } companion object { private const val TAG_NAME = 0 private const val TAG_IS_OPERATIONAL = 1 private const val TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV4 = 2 private const val TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV6 = 3 private const val TAG_HARDWARE_ADDRESS = 4 private const val TAG_I_PV4_ADDRESSES = 5 private const val TAG_I_PV6_ADDRESSES = 6 private const val TAG_TYPE = 7 fun fromTlv(tlvTag: Tag, tlvReader: TlvReader): GeneralDiagnosticsClusterNetworkInterface { tlvReader.enterStructure(tlvTag) val name = tlvReader.getString(ContextSpecificTag(TAG_NAME)) val isOperational = tlvReader.getBoolean(ContextSpecificTag(TAG_IS_OPERATIONAL)) val offPremiseServicesReachableIPv4 = if (!tlvReader.isNull()) { tlvReader.getBoolean(ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV4)) } else { tlvReader.getNull(ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV4)) null } val offPremiseServicesReachableIPv6 = if (!tlvReader.isNull()) { tlvReader.getBoolean(ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV6)) } else { tlvReader.getNull(ContextSpecificTag(TAG_OFF_PREMISE_SERVICES_REACHABLE_I_PV6)) null } val hardwareAddress = tlvReader.getByteArray(ContextSpecificTag(TAG_HARDWARE_ADDRESS)) val IPv4Addresses = buildList<ByteArray> { tlvReader.enterArray(ContextSpecificTag(TAG_I_PV4_ADDRESSES)) while (!tlvReader.isEndOfContainer()) { add(tlvReader.getByteArray(AnonymousTag)) } tlvReader.exitContainer() } val IPv6Addresses = buildList<ByteArray> { tlvReader.enterArray(ContextSpecificTag(TAG_I_PV6_ADDRESSES)) while (!tlvReader.isEndOfContainer()) { add(tlvReader.getByteArray(AnonymousTag)) } tlvReader.exitContainer() } val type = tlvReader.getUByte(ContextSpecificTag(TAG_TYPE)) tlvReader.exitContainer() return GeneralDiagnosticsClusterNetworkInterface( name, isOperational, offPremiseServicesReachableIPv4, offPremiseServicesReachableIPv6, hardwareAddress, IPv4Addresses, IPv6Addresses, type ) } } }
1,443
C++
1,769
6,671
420e6d424c00aed3ead4015eafd71a1632c5e540
5,385
connectedhomeip
Apache License 2.0
app/src/main/java/com/cyberknights4911/scouting/GamePiece.kt
Krylez
692,210,890
false
{"Kotlin": 84897, "PowerShell": 862}
package com.cyberknights4911.scouting enum class GamePiece(value: String) { CONE("cone"), CUBE("cube"), NONE("none") }
0
Kotlin
0
0
889cde5140d27d2c7ecc6c20ff6c588e3fff9880
131
FRC-2023-scouting-app-sample
Apache License 2.0
tooling-country/src/commonMain/kotlin/dev/datlag/tooling/country/Bermuda.kt
DatL4g
739,165,922
false
{"Kotlin": 253599}
package dev.datlag.tooling.country data object Bermuda : Country { override val codeAlpha2: Country.Code.Alpha2 = Country.Code.Alpha2("BM") override val codeAlpha3: Country.Code.Alpha3 = Country.Code.Alpha3("BMU") override val codeNumeric: Country.Code.Numeric = Country.Code.Numeric(60) }
0
Kotlin
0
1
e23d0489c713dcdce25e65ca1664398a98480362
303
tooling
Apache License 2.0
swipy/src/main/java/com/dotloop/swipy/SwipableCellHandler.kt
dotloop
155,626,492
false
null
package com.dotloop.swipy import com.dotloop.swipy.SwipableCellHandler.Mode.Single import java.util.* class SwipableCellHandler { private val openPositions: MutableSet<Int> = HashSet() private var mode = Single fun bindSwipableCell(swipeLayout: SwipeLayout, position: Int) { swipeLayout.tag = position swipeLayout.onSwipeListeners = (object : OnSwipeListener { override fun onClose(layout: SwipeLayout) { openPositions.remove(layout.tag as Int) } override fun onStartOpen(layout: SwipeLayout) { val position = layout.tag as Int /**if (mode == Attributes.Mode.Single && * !openPositions.isEmpty() && * !openPositions.contains(position)) * adapter.notifyItemChanged(position); */ } override fun onOpen(layout: SwipeLayout) { openPositions.add(layout.tag as Int) } }) swipeLayout.simpleOnLayoutChangeListenerListener = (object : SimpleOnLayoutChangeListener { override fun onLayoutChange(layout: SwipeLayout) = if (isOpen(layout.tag as Int)) layout.open(false, false) else layout.close(false, false) }) } @JvmOverloads fun reset(position: Int? = null) { when (position) { null -> openPositions.clear() else -> openPositions.remove(position) } } fun isOpen(position: Int): Boolean { return openPositions.contains(position) } fun setMode(mode: Mode) { this.mode = mode } enum class Mode { Single, Multiple } }
1
Kotlin
0
3
b2fb32b6b7bb046078ebe79df49dd61d3d4bb169
1,705
swipy
Apache License 2.0
app/src/main/java/no/bakkenbaeck/kotlinnativetest/MainActivity.kt
designatednerd
153,112,398
false
null
package no.bakkenbaeck.kotlinnativetest import android.os.Bundle import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.android.material.button.MaterialButton import no.bakkenbaeck.mpp.mobile.DayOfWeek import no.bakkenbaeck.mpp.mobile.HoursOfOperation import no.bakkenbaeck.mpp.mobile.HttpBinClient import no.bakkenbaeck.mpp.mobile.createApplicationScreenMessage import no.bakkenbaeck.mpp.mobile.localization.Localized import no.bakkenbaeck.mpp.mobile.styles.ButtonStyle import no.bakkenbaeck.mpp.mobile.styles.StaticTextStyle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) println("Current value: ${Localized.helloWorld}") HttpBinClient().runGet() HttpBinClient().runPost("HELLO ANDROID") setContentView(R.layout.activity_main) findViewById<TextView>(R.id.main_text).apply { text = createApplicationScreenMessage() applyStyle(StaticTextStyle.Headline()) } findViewById<TextView>(R.id.is_open_text).apply { applyStyle(StaticTextStyle.TextCaption()) } val dayHeader = findViewById<TextView>(R.id.day_header) dayHeader.text = HoursOfOperation.dayHeaderTitle() val openingHeader = findViewById<TextView>(R.id.opening_header) openingHeader.text = HoursOfOperation.openingHeaderTitle() val closingHeader = findViewById<TextView>(R.id.closing_header) closingHeader.text = HoursOfOperation.closingHeaderTitle() val headers = listOf(dayHeader, openingHeader, closingHeader) headers.forEach { it.applyStyle(StaticTextStyle.HeadlineSecondary()) } val hours = HoursOfOperation.Weekdays(8.0f, 20.0f) findViewById<TextView>(R.id.is_open_text).text = hours.isOpenText(DayOfWeek.Saturday, 21.5f) val hoursLayout = findViewById<LinearLayout>(R.id.hours_layout) hours.hours.forEach { val layoutForDay = LinearLayout(baseContext) val layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) layoutParams.setMargins(0, 4, 0, 0) layoutForDay.layoutParams = layoutParams val dayTextView = textPrimaryView(it.dayString) layoutForDay.addView(dayTextView) val openingTextView = textPrimaryView(it.startHourString) layoutForDay.addView(openingTextView) val closingTextView = textPrimaryView(it.endHourString) layoutForDay.addView(closingTextView) hoursLayout.addView(layoutForDay) } hoursLayout.requestLayout() findViewById<MaterialButton>(R.id.disable_button).apply { applyStyle(ButtonStyle.CallToAction()) } findViewById<MaterialButton>(R.id.enable_button).apply { applyStyle(ButtonStyle.Destructive()) } } private fun textPrimaryView(withText: String): TextView { val textView = TextView(baseContext) textView.applyStyle(StaticTextStyle.TextPrimary()) val layoutParams = LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT ) layoutParams.weight = 1.0f/3.0f textView.layoutParams = layoutParams textView.textAlignment = TextView.TEXT_ALIGNMENT_CENTER textView.text = withText return textView } }
0
Objective-C
3
13
055fdfc1bbaf85e2096cd24ebcdcae5bf4b74abe
3,609
KotlinNativeTest
MIT License
app/src/main/java/dev/sebastiano/bundel/ui/NavTransitions.kt
ZianeA
413,987,023
true
{"Kotlin": 252478}
package dev.sebastiano.bundel.ui import androidx.compose.animation.AnimatedContentScope import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.navigation.NavBackStackEntry import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph // Note: these transitions have been kindly donated by <NAME>, and are the // same you can find in his app Tivi https://github.com/chrisbanes/tivi @ExperimentalAnimationApi internal fun AnimatedContentScope<*>.defaultEnterTransition( initial: NavBackStackEntry, target: NavBackStackEntry, ): EnterTransition { val initialNavGraph = initial.destination.hostNavGraph val targetNavGraph = target.destination.hostNavGraph // If we're crossing nav graphs (bottom navigation graphs), we crossfade if (initialNavGraph.id != targetNavGraph.id) { return fadeIn() } // Otherwise we're in the same nav graph, we can imply a direction return fadeIn() + slideIntoContainer(AnimatedContentScope.SlideDirection.Start) } @ExperimentalAnimationApi internal fun AnimatedContentScope<*>.defaultExitTransition( initial: NavBackStackEntry, target: NavBackStackEntry, ): ExitTransition { val initialNavGraph = initial.destination.hostNavGraph val targetNavGraph = target.destination.hostNavGraph // If we're crossing nav graphs (bottom navigation graphs), we crossfade if (initialNavGraph.id != targetNavGraph.id) { return fadeOut() } // Otherwise we're in the same nav graph, we can imply a direction return fadeOut() + slideOutOfContainer(AnimatedContentScope.SlideDirection.Start) } private val NavDestination.hostNavGraph: NavGraph get() = hierarchy.first { it is NavGraph } as NavGraph @ExperimentalAnimationApi internal fun AnimatedContentScope<*>.defaultPopEnterTransition(): EnterTransition = fadeIn() + slideIntoContainer(AnimatedContentScope.SlideDirection.End) @ExperimentalAnimationApi internal fun AnimatedContentScope<*>.defaultPopExitTransition(): ExitTransition = fadeOut() + slideOutOfContainer(AnimatedContentScope.SlideDirection.End)
0
null
0
0
dbe9546104622f357643e75f65a4243d320a628e
2,357
bundel
Apache License 2.0
src/LearnVar.kt
hanks-zyh
45,084,033
false
null
/** * Created by hanks on 15-10-28. */ fun main(args: Array<String>) { val a = 1 val b: Int = 2 val c: Int c = 1 println(a) println(b) println(c) var x = 5 x += 1 println(x) }
0
Kotlin
0
0
04dc4c824887135836fa519f0bc5fb1feacae527
218
KotlinExample
Apache License 2.0
demo/src/main/java/com/angcyo/behavior/demo/fragment/BackgroundScaleTouchFragment.kt
angcyo
259,872,337
false
null
package com.angcyo.behavior.demo.fragment import android.os.Bundle import android.view.View import com.angcyo.behavior.behavior import com.angcyo.behavior.demo.BaseDslFragment import com.angcyo.behavior.demo.R import com.angcyo.behavior.demo.dslitem.AppUserInfoTouchItem import com.angcyo.behavior.refresh.IRefreshContentBehavior import com.angcyo.behavior.refresh.ScaleHeaderRefreshEffectConfig import com.angcyo.dsladapter.DslAdapter /** * * Email:<EMAIL> * @author angcyo * @date 2020/05/06 * Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved. */ class BackgroundScaleTouchFragment : BaseDslFragment() { init { fragmentLayoutId = R.layout.fragment_background_scale_touch } override fun initBaseView(rootView: View, savedInstanceState: Bundle?) { super.initBaseView(rootView, savedInstanceState) rootView.findViewById<View>(R.id.recycler_view)?.behavior()?.apply { if (this is IRefreshContentBehavior) { this.refreshBehaviorConfig = ScaleHeaderRefreshEffectConfig().apply { targetViewIdInContent = R.id.image_view } } } } override fun renderDslAdapter(adapter: DslAdapter) { adapter.apply { AppUserInfoTouchItem()() } super.renderDslAdapter(adapter) } }
1
Kotlin
5
23
6f06f225e0eae1f42184e4bd5d8428561a17ba67
1,350
DslBehavior
MIT License
compiler/tests-spec/testData/diagnostics/helpers/interfaces.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
interface EmptyInterface interface Interface1 { fun itest() {} fun itest1() {} fun itest0(): String fun itest00(): Interface1 fun itest000(): Int? fun itest0000(): Int fun itest00000(): Int } interface Interface2 { fun itest() {} fun itest2() {} fun itest0(): CharSequence fun itest00(): Interface2 fun itest000(): Nothing? fun itest0000(): Nothing fun itest00000(): String } interface Interface3 { fun itest() {} fun itest3() {} } interface InterfaceWithOutParameter<out T> interface InterfaceWithTypeParameter1<T> { fun ip1test1(): T? = null as T? } interface InterfaceWithTypeParameter2<T> { fun ip1test2(): T? = null as T? } interface InterfaceWithTypeParameter3<T> { fun ip1test3(): T? = null as T? } interface InterfaceWithFiveTypeParameters1<T1, T2, T3, T4, T5> { fun itest() {} fun itest1() {} } interface InterfaceWithFiveTypeParameters2<T1, T2, T3, T4, T5> { fun itest() {} fun itest2() {} } interface InterfaceWithFiveTypeParameters3<T1, T2, T3, T4, T5> { fun itest() {} fun itest3() {} } interface InterfaceWithTwoTypeParameters<T, K> { fun ip2test(): T? = null as T? }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,197
kotlin
Apache License 2.0
native/native.tests/testData/codegen/initializers/static_kType.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2021 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. */ import kotlin.test.* import kotlin.native.internal.* import kotlin.reflect.* fun box(): String { val ktype = typeOf<Map<in String?, out List<*>>?>() assertTrue(ktype.isPermanent()) assertEquals("Map", (ktype.classifier as? KClass<*>)?.simpleName) assertSame(Map::class, ktype.classifier) assertTrue(ktype.isMarkedNullable) assertTrue(ktype.arguments.isPermanent()) assertEquals(2, ktype.arguments.size) assertSame(KVariance.IN, ktype.arguments[0].variance) assertSame(KVariance.OUT, ktype.arguments[1].variance) val arg0type = ktype.arguments[0].type!! assertTrue(arg0type.isPermanent()) assertEquals("String", (arg0type.classifier as? KClass<*>)?.simpleName) assertSame(String::class, arg0type.classifier) assertTrue(arg0type.isMarkedNullable) assertTrue(arg0type.arguments.isPermanent()) assertTrue(arg0type.arguments.isEmpty()) val arg1type = ktype.arguments[1].type!! assertTrue(arg1type.isPermanent()) assertEquals("List", (arg1type.classifier as? KClass<*>)?.simpleName) assertSame(List::class, arg1type.classifier) assertFalse(arg1type.isMarkedNullable) assertTrue(arg1type.arguments.isPermanent()) assertTrue(arg1type.arguments.size == 1) assertSame(null, arg1type.arguments[0].variance) assertSame(null, arg1type.arguments[0].type) return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,573
kotlin
Apache License 2.0
native/commonizer/tests/org/jetbrains/kotlin/commonizer/hierarchical/HierarchicalTypeAliasCommonizationTest.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2021 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.commonizer.hierarchical import org.jetbrains.kotlin.commonizer.AbstractInlineSourcesCommonizationTest import org.jetbrains.kotlin.commonizer.assertCommonized class HierarchicalTypeAliasCommonizationTest : AbstractInlineSourcesCommonizationTest() { fun `test simple type alias`() { val result = commonize { outputTarget("(a, b)", "(c, d)", "(a, b, c, d)") simpleSingleSourceTarget("a", "typealias X = Int") simpleSingleSourceTarget("b", "typealias X = Int") simpleSingleSourceTarget("c", "typealias X = Int") simpleSingleSourceTarget("d", "typealias X = Int") } result.assertCommonized("((a,b), (c,d))", "typealias X = Int") result.assertCommonized("(a,b)", "typealias X = Int") result.assertCommonized("(c, d)", "typealias X = Int") } /** * See: https://youtrack.jetbrains.com/issue/KT-45992 */ fun `test typealias and class`() { val result = commonize { outputTarget("(a,b)") simpleSingleSourceTarget("a", """class X """) simpleSingleSourceTarget( "b", """ class B typealias X = B """ ) } result.assertCommonized("(a,b)", "expect class X()") } fun `test typealias to different classes`() { val result = commonize { outputTarget("(a, b)", "(c, d)", "(e, f)", "(a, b, c, d)", "(a, b, c, d, e, f)") simpleSingleSourceTarget( "a", """ class AB typealias x = AB """ ) simpleSingleSourceTarget( "b", """ class AB typealias x = AB """ ) simpleSingleSourceTarget( "c", """ class CD typealias x = CD """ ) simpleSingleSourceTarget( "d", """ class CD typealias x = CD """ ) simpleSingleSourceTarget("e", """class x""") simpleSingleSourceTarget("f", """class x""") } result.assertCommonized( "(a,b)", """ expect class AB() typealias x = AB """ ) result.assertCommonized( "(c,d)", """ expect class CD() typealias x = CD """ ) result.assertCommonized( "(c,d)", """ expect class CD() typealias x = CD """ ) result.assertCommonized( "(e,f)", """expect class x()""" ) result.assertCommonized("(a, b, c, d)", """expect class x()""") result.assertCommonized("(a, b, c, d, e, f)", """expect class x()""") } fun `test typealias chain`() { val result = commonize { outputTarget("(a, b)") simpleSingleSourceTarget( "a", """ typealias A<N, M> = Map<N, M> typealias B = A<String, Int> """.trimIndent() ) simpleSingleSourceTarget( "b", """ typealias A<N, M> = Map<N, M> typealias B = A<String, Int> """.trimIndent() ) } result.assertCommonized( "(a, b)", """ typealias A<N, M> = Map<N, M> typealias B = A<String, Int> """.trimIndent() ) } fun `test long typealias chain`() { val result = commonize { outputTarget("(a, b)") simpleSingleSourceTarget( "a", """ typealias A<N, M> = Map<N, M> typealias B<N, M> = A<N, M> typealias C<N> = B<N, Int> typealias D = C<String> """.trimIndent() ) simpleSingleSourceTarget( "b", """ typealias A<N, M> = Map<N, M> typealias B<N, M> = A<N, M> typealias C<N> = B<N, Int> typealias D = C<String> """.trimIndent() ) } result.assertCommonized( "(a, b)", """ typealias A<N, M> = Map<N, M> typealias B<N, M> = A<N, M> typealias C<N> = B<N, Int> typealias D = C<String> """.trimIndent() ) } fun `test typealias with phantom type`() { val result = commonize { outputTarget("(a, b)") simpleSingleSourceTarget( "a", """ typealias A<N, M> = Map<N, M> typealias B<N, Phantom, M> = A<N, M> typealias X<T> = B<T, String, Long> fun x(x: X<Int>) = Unit """.trimIndent() ) simpleSingleSourceTarget( "b", """ typealias A<N, M> = Map<N, M> typealias B<N, Phantom, M> = A<N, M> typealias X<T> = B<T, String, Long> typealias Y<T> = X<T> fun x(x: Y<Int>) = Unit """.trimIndent() ) } result.assertCommonized( "(a, b)", """ typealias A<N, M> = Map<N, M> typealias B<N, Phantom, M> = A<N, M> typealias X<T> = B<T, String, Long> expect fun x(x: X<Int>) """.trimIndent() ) } }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
6,030
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/collectionLiterals/collectionLiteralsOutsideOfAnnotations.fir.kt
android
263,405,600
true
null
// !LANGUAGE: +NewInference // !WITH_NEW_INFERENCE // !DIAGNOSTICS: -UNUSED_VARIABLE -UNUSED_PARAMETER fun takeArray(array: Array<String>) {} fun test() { "foo bar".<!UNRESOLVED_REFERENCE!>split<!>([""]) <!UNRESOLVED_REFERENCE!>unresolved<!>([""]) takeArray([""]) val v = [""] [""] [1, 2, 3].<!UNRESOLVED_REFERENCE!>size<!> } fun baz(arg: Array<Int> = []) { if (true) ["yes"] else {["no"]} } class Foo( val v: Array<Int> = [] )
34
Kotlin
49
316
74126637a097f5e6b099a7b7a4263468ecfda144
464
kotlin
Apache License 2.0
src/main/kotlin/top/plutomc/plutolands/PlutoLands.kt
plutosmp
594,989,254
false
null
package top.plutomc.plutolands import org.bukkit.plugin.java.JavaPlugin import java.util.concurrent.ExecutorService import java.util.concurrent.Executors @Suppress("unused") class PlutoLands : JavaPlugin() { companion object { private lateinit var instance: JavaPlugin private lateinit var executor: ExecutorService fun instance() : JavaPlugin = instance fun executor() : ExecutorService = executor } override fun onEnable() { instance = this executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) } override fun onDisable() { executor.shutdownNow() } }
0
Kotlin
0
0
66fa29e2785d33c224a3d1c44242faf2a78d9252
667
PlutoLands
MIT License
src/main/java/io/sc3/plethora/util/LivingEntityInventoryWrapper.kt
SwitchCraftCC
491,699,521
false
{"Kotlin": 383687, "Java": 259087}
package io.sc3.plethora.util import io.sc3.plethora.Plethora import io.sc3.plethora.api.reference.IReference import net.minecraft.entity.LivingEntity import net.minecraft.inventory.Inventory abstract class LivingEntityInventoryWrapper<T : LivingEntity>( private val entityReference: IReference<T> ) { val safeInv: Inventory? get() { val inv = try { val entity = entityReference.get() provideInventory(entity) } catch (e: Exception) { Plethora.log.error("Error getting inventory for RangedInventoryWrapper", e) null } return inv } val inv: Inventory get() = safeInv ?: throw IllegalStateException("The inventory could not be provided") abstract fun provideInventory(entity: T): Inventory? }
26
Kotlin
8
16
1309c51911a9b146218e5dae65a16dc8f932b23e
771
Plethora-Fabric
MIT License
datacapture/src/main/java/com/google/android/fhir/datacapture/views/QuestionnaireItemDropDownViewHolderFactory.kt
RaaziaTarique
470,648,312
true
{"Kotlin": 1720513, "Shell": 1101}
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.android.fhir.datacapture.views import android.content.Context import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.displayString import com.google.android.fhir.datacapture.localizedFlyoverSpanned import com.google.android.fhir.datacapture.validation.ValidationResult import com.google.android.fhir.datacapture.validation.getSingleStringValidationMessage import com.google.android.material.textfield.TextInputLayout import org.hl7.fhir.r4.model.QuestionnaireResponse internal object QuestionnaireItemDropDownViewHolderFactory : QuestionnaireItemViewHolderFactory(R.layout.questionnaire_item_drop_down_view) { override fun getQuestionnaireItemViewHolderDelegate() = object : QuestionnaireItemViewHolderDelegate { private lateinit var header: QuestionnaireItemHeaderView private lateinit var textInputLayout: TextInputLayout private lateinit var autoCompleteTextView: AutoCompleteTextView override lateinit var questionnaireItemViewItem: QuestionnaireItemViewItem private lateinit var context: Context override fun init(itemView: View) { header = itemView.findViewById(R.id.header) textInputLayout = itemView.findViewById(R.id.text_input_layout) autoCompleteTextView = itemView.findViewById(R.id.auto_complete) context = itemView.context } override fun bind(questionnaireItemViewItem: QuestionnaireItemViewItem) { header.bind(questionnaireItemViewItem.questionnaireItem) textInputLayout.hint = questionnaireItemViewItem.questionnaireItem.localizedFlyoverSpanned val answerOptionString = this.questionnaireItemViewItem.answerOption.map { it.displayString }.toMutableList() answerOptionString.add(0, context.getString(R.string.hyphen)) val adapter = ArrayAdapter(context, R.layout.questionnaire_item_drop_down_list, answerOptionString) autoCompleteTextView.setText( questionnaireItemViewItem.singleAnswerOrNull?.valueCoding?.display ?: "" ) autoCompleteTextView.setAdapter(adapter) autoCompleteTextView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> if (position == 0) { questionnaireItemViewItem.singleAnswerOrNull = null } else { questionnaireItemViewItem.singleAnswerOrNull = QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent() .setValue(questionnaireItemViewItem.answerOption[position - 1].valueCoding) } onAnswerChanged(autoCompleteTextView.context) } } override fun displayValidationResult(validationResult: ValidationResult) { textInputLayout.error = if (validationResult.getSingleStringValidationMessage() == "") null else validationResult.getSingleStringValidationMessage() } override fun setReadOnly(isReadOnly: Boolean) { textInputLayout.isEnabled = !isReadOnly } } }
2
Kotlin
0
1
6ca7104d3cc3fed81a5da9266a3e71228aec2d5d
3,801
android-fhir
Apache License 2.0
agp-7.1.0-alpha01/tools/base/testutils/src/main/java/com/android/testutils/MockitoKt.kt
jomof
374,736,765
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) 2019 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.testutils import org.junit.rules.ExternalResource import org.mockito.ArgumentMatchers import org.mockito.MockedStatic import org.mockito.Mockito import org.mockito.invocation.InvocationOnMock import kotlin.reflect.KMutableProperty object MockitoKt { /** * Wrapper around [Mockito.any] that doesn't return null. * If used with Kotlin functions that do not accept nullable types it causes a "must not be null" exception. * * Using the not-null assertion operator (!!) doesn't work because the result of the method call is recorded internally by Mockito. * @see Mockito.any */ fun <T> any(type: Class<T>): T = Mockito.any(type) /** * Wrapper around [Mockito.any] for generic types. */ inline fun <reified T> any() = any(T::class.java) /** * Wrapper around [Mockito.argThat] that doesn't return null. * If used with Kotlin functions that do not accept nullable types it causes a "must not be null" exception. * * Using the not-null assertion operator (!!) doesn't work because the result of the method call is recorded internally by Mockito. * @see Mockito.argThat */ fun <T> argThat(arg: (T) -> Boolean): T = Mockito.argThat(arg) /** * Convenience wrapper around [Mockito.mock] that allows the type to be inferred. */ inline fun <reified T> mock(): T = Mockito.mock(T::class.java) /** * Convenience wrapper around [Mockito.mockStatic] that allows the type to be inferred. */ inline fun <reified T> mockStatic(): MockedStatic<T> = Mockito.mockStatic(T::class.java) /** * Convenience wrapper around [InvocationOnMock.getArgument] that allows the type to be inferred. */ inline fun <reified T> InvocationOnMock.getTypedArgument(i: Int): T = getArgument(i, T::class.java) /** * Wrapper around [Mockito.eq] that doesn't return null. * If used with Kotlin functions that do not accept nullable types it causes a "must not be null" exception. * * Using the not-null assertion operator (!!) doesn't work because the result of the method call is recorded internally by Mockito. * @see Mockito.eq */ fun <T> eq(arg: T): T { Mockito.eq(arg) return arg } /** * Wrapper around [Mockito.refEq] that doesn't return null. * If used with Kotlin functions that do not accept nullable types it causes a "must not be null" exception. * * Using the not-null assertion operator (!!) doesn't work because the result of the method call is recorded internally by Mockito. * @see Mockito.refEq */ fun <T> refEq(arg: T): T = ArgumentMatchers.refEq(arg) } /** * Sets the given [property] to [newValue] before the test, and puts the original value back after. */ class PropertySetterRule<T: Any>(val newValue: T, val property: KMutableProperty<T>) : ExternalResource() { var oldValue: T? = null override fun before() { oldValue = property.getter.call() property.setter.call(newValue) } override fun after() { property.setter.call(oldValue) oldValue = null } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
3,668
CppBuildCacheWorkInProgress
Apache License 2.0
vk-api-kotlin-client/src/main/kotlin/tk/skeptick/vk/apiclient/methods/messages/MessagesApi.kt
Skeptick
139,193,533
false
{"Kotlin": 488939}
package tk.skeptick.vk.apiclient.methods.messages import io.ktor.util.date.GMTDate import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.builtins.MapSerializer import kotlinx.serialization.builtins.list import kotlinx.serialization.builtins.serializer import tk.skeptick.vk.apiclient.* import tk.skeptick.vk.apiclient.domain.* import tk.skeptick.vk.apiclient.domain.models.Chat import tk.skeptick.vk.apiclient.domain.models.Conversation import tk.skeptick.vk.apiclient.domain.models.Message import tk.skeptick.vk.apiclient.methods.ConversationFilter import tk.skeptick.vk.apiclient.methods.DefaultListResponse import tk.skeptick.vk.apiclient.methods.ExtendedListResponse import tk.skeptick.vk.apiclient.methods.ObjectField class MessagesApi(override val client: ApiClient) : MessagesApiUser, MessagesApiCommunity, MethodsContext { override fun addChatUser( chatId: Int, userId: Int ): VkApiRequest<BooleanInt> = Methods.addChatUser.httpGet(BooleanInt.serializer()) { append("chat_id", chatId) append("user_id", userId) } override fun allowMessagesFromGroup( groupId: Int, key: String? ): VkApiRequest<BooleanInt> = Methods.allowMessagesFromGroup.httpGet(BooleanInt.serializer()) { append("group_id", groupId) append("key", key) } override fun createChat( userIds: List<Int>, title: String ): VkApiRequest<Int> = Methods.createChat.httpPost(Int.serializer()) { append("user_ids", userIds.joinToString(",")) append("title", title) } override fun delete( messageIds: List<Int>, markAsSpam: Boolean, deleteForAll: Boolean, groupId: Int? ): VkApiRequest<Map<Int, BooleanInt>> = Methods.delete.httpPost(MapSerializer(Int.serializer(), BooleanInt.serializer())) { append("message_ids", messageIds.joinToString(",")) append("spam", markAsSpam.asInt()) append("delete_for_all", deleteForAll.asInt()) append("group_id", groupId) } override fun delete( messageIds: List<Int>, markAsSpam: Boolean, deleteForAll: Boolean ): VkApiRequest<Map<Int, BooleanInt>> = delete( messageIds = messageIds, markAsSpam = markAsSpam, deleteForAll = deleteForAll, groupId = null ) override fun deleteChatPhoto( chatId: Int, groupId: Int? ): VkApiRequest<ChatChangePhotoResponse> = Methods.deleteChatPhoto.httpGet(ChatChangePhotoResponse.serializer()) { append("chat_id", chatId) append("group_id", groupId) } override fun deleteChatPhoto( chatId: Int ): VkApiRequest<ChatChangePhotoResponse> = deleteChatPhoto( chatId = chatId, groupId = null ) override fun deleteConversation( peerId: Int, groupId: Int? ): VkApiRequest<DeleteConversationResponse> = Methods.deleteConversation.httpGet(DeleteConversationResponse.serializer()) { append("peer_id", peerId) append("group_id", groupId) } override fun deleteConversation( peerId: Int ): VkApiRequest<DeleteConversationResponse> = deleteConversation( peerId = peerId, groupId = null ) override fun denyMessagesFromGroup( groupId: Int ): VkApiRequest<BooleanInt> = Methods.denyMessagesFromGroup.httpGet(BooleanInt.serializer()) { append("group_id", groupId) } override fun edit( peerId: Int, messageId: Int, message: String?, latitude: Int?, longitude: Int?, attachments: List<MessageAttachment>?, keepForwardMessages: Boolean, keepSnippets: Boolean, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.edit.httpPost(BooleanInt.serializer()) { append("peer_id", peerId) append("message_id", messageId) append("message", message) append("lat", latitude) append("long", longitude) append("attachment", attachments?.joinToString(",", transform = MessageAttachment::attachmentString)) append("keep_forward_messages", keepForwardMessages.asInt()) append("keep_snippets", keepSnippets.asInt()) append("group_id", groupId) } override fun edit( peerId: Int, messageId: Int, message: String?, latitude: Int?, longitude: Int?, attachments: List<MessageAttachment>?, keepForwardMessages: Boolean, keepSnippets: Boolean ): VkApiRequest<BooleanInt> = edit( peerId = peerId, messageId = messageId, message = message, latitude = latitude, longitude = longitude, attachments = attachments, keepForwardMessages = keepForwardMessages, keepSnippets = keepSnippets, groupId = null ) override fun editChat( chatId: Int, title: String, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.editChat.httpGet(BooleanInt.serializer()) { append("chat_id", chatId) append("title", title) append("group_id", groupId) } override fun editChat( chatId: Int, title: String ): VkApiRequest<BooleanInt> = editChat( chatId = chatId, title = title, groupId = null ) override fun getByConversationMessageId( peerId: Int, conversationMessageIds: List<Int>, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ExtendedListResponse<Message>> = Methods.getByConversationMessageId.httpPost(extendedList(Message.serializer())) { append("peer_id", peerId) append("conversation_message_ids", conversationMessageIds.joinToString(",")) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getByConversationMessageId( peerId: Int, conversationMessageIds: List<Int>, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<Message>> = getByConversationMessageId( peerId = peerId, conversationMessageIds = conversationMessageIds, extended = extended, fields = fields, groupId = null ) override fun getById( messageIds: List<Int>, previewLength: Int, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ExtendedListResponse<Message>> = Methods.getById.httpPost(extendedList(Message.serializer())) { append("message_ids", messageIds.joinToString(",")) append("preview_length", previewLength) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getById( messageIds: List<Int>, previewLength: Int, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<Message>> = getById( messageIds = messageIds, previewLength = previewLength, extended = extended, fields = fields, groupId = null ) override fun getChat( chatIds: List<Int> ): VkApiRequest<List<Chat>> = Methods.getChat.httpPost(ListSerializer(Chat.serializer())) { append("chat_ids", chatIds.joinToString(",")) } override fun getChatPreview( link: String, fields: List<ObjectField> ): VkApiRequest<ChatPreview> = Methods.getChatPreview.httpPost(ChatPreview.serializer()) { append("link", link) append("fields", fields.joinToString(",") { it.value }) } override fun getConversationMembers( peerId: Int, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ExtendedListResponse<ConversationMember>> = Methods.getConversationMembers.httpPost(extendedList(ConversationMember.serializer())) { append("peer_id", peerId) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getConversationMembers( peerId: Int, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<ConversationMember>> = getConversationMembers( peerId = peerId, fields = fields, groupId = null ) override fun getConversations( offset: Int, count: Int, filter: ConversationFilter, startMessageId: Int?, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ConversationsListResponse> = Methods.getConversations.httpPost(ConversationsListResponse.serializer()) { append("offset", offset) append("count", count) append("filter", filter.value) append("start_message_id", startMessageId) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getConversations( offset: Int, count: Int, filter: ConversationFilter, startMessageId: Int?, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<ConversationsListResponse> = getConversations( offset = offset, count = count, filter = filter, startMessageId = startMessageId, extended = extended, fields = fields, groupId = null ) override fun getConversationsById( peerIds: List<Int>, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ExtendedListResponse<Conversation>> = Methods.getConversationsById.httpPost(extendedList(Conversation.serializer())) { append("peer_ids", peerIds.joinToString(",")) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getConversationsById( peerIds: List<Int>, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<Conversation>> = getConversationsById( peerIds = peerIds, extended = extended, fields = fields, groupId = null ) override fun getHistory( peerId: Int, offset: Int, count: Int, startMessageId: Int?, reverse: Boolean, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<HistoryMessagesListResponse> = Methods.getHistory.httpPost(HistoryMessagesListResponse.serializer()) { append("peer_id", peerId) append("offset", offset) append("count", count) append("start_message_id", startMessageId) append("rev", reverse.asInt()) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getHistory( peerId: Int, offset: Int, count: Int, startMessageId: Int?, reverse: Boolean, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<HistoryMessagesListResponse> = getHistory( peerId = peerId, offset = offset, count = count, startMessageId = startMessageId, reverse = reverse, extended = extended, fields = fields, groupId = null ) override fun getHistoryAttachments( peerId: Int, mediaType: AttachmentType, startFrom: Int?, count: Int, withPhotoSizes: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<HistoryAttachmentsResponse> = Methods.getHistoryAttachments.httpPost(HistoryAttachmentsResponse.serializer()) { append("peer_id", peerId) append("media_type", mediaType.value) append("start_from", startFrom) append("count", count) append("photo_sizes", withPhotoSizes.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getHistoryAttachments( peerId: Int, mediaType: AttachmentType, startFrom: Int?, count: Int, withPhotoSizes: Boolean, fields: List<ObjectField> ): VkApiRequest<HistoryAttachmentsResponse> = getHistoryAttachments( peerId = peerId, mediaType = mediaType, startFrom = startFrom, count = count, withPhotoSizes = withPhotoSizes, fields = fields, groupId = null ) override fun getImportantMessages( count: Int, offset: Int, startMessageId: Int?, previewLength: Int, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ImportantMessagesResponse> = Methods.getImportantMessages.httpPost(ImportantMessagesResponse.serializer()) { append("count", count) append("offset", offset) append("start_message_id", startMessageId) append("preview_length", previewLength) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun getImportantMessages( count: Int, offset: Int, startMessageId: Int?, previewLength: Int, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<ImportantMessagesResponse> = getImportantMessages( count = count, offset = offset, startMessageId = startMessageId, previewLength = previewLength, extended = extended, fields = fields, groupId = null ) override fun getInviteLink( peerId: Int, generateNewLink: Boolean, groupId: Int? ): VkApiRequest<ChatInviteLink> = Methods.getInviteLink.httpGet(ChatInviteLink.serializer()) { append("peer_id", peerId) append("reset", generateNewLink.asInt()) append("group_id", groupId) } override fun getInviteLink( peerId: Int, generateNewLink: Boolean ): VkApiRequest<ChatInviteLink> = getInviteLink( peerId = peerId, generateNewLink = generateNewLink, groupId = null ) override fun getLastActivity( userId: Int ): VkApiRequest<LastActivityResponse> = Methods.getLastActivity.httpGet(LastActivityResponse.serializer()) { append("user_id", userId) } override fun getLongPollHistory( ts: Long, pts: Long, previewLength: Int, withOnlineStatuses: Boolean, userFields: List<ObjectField>, eventsLimit: Int, messagesLimit: Int, maxMessageId: Int?, longPollVersion: Int, groupId: Int? ): VkApiRequest<LongPollHistoryResponse> = Methods.getLongPollHistory.httpPost(LongPollHistoryResponse.serializer()) { append("ts", ts) append("pts", pts) append("preview_length", previewLength) append("onlines", withOnlineStatuses.asInt()) append("fields", userFields.joinToString(",") { it.value }) append("events_limit", eventsLimit) append("msgs_limit", messagesLimit) append("max_msg_id", maxMessageId) append("lp_version", longPollVersion) append("group_id", groupId) } override fun getLongPollHistory( ts: Long, pts: Long, previewLength: Int, withOnlineStatuses: Boolean, userFields: List<ObjectField>, eventsLimit: Int, messagesLimit: Int, maxMessageId: Int?, longPollVersion: Int ): VkApiRequest<LongPollHistoryResponse> = getLongPollHistory( ts = ts, pts = pts, previewLength = previewLength, withOnlineStatuses = withOnlineStatuses, userFields = userFields, eventsLimit = eventsLimit, messagesLimit = messagesLimit, maxMessageId = maxMessageId, longPollVersion = longPollVersion, groupId = null ) override fun getLongPollServer( needPts: Boolean, longPollVersion: Int, groupId: Int? ): VkApiRequest<LongPollServerResponse> = Methods.getLongPollServer.httpGet(LongPollServerResponse.serializer()) { append("need_pts", needPts.asInt()) append("lp_version", longPollVersion) append("group_id", groupId) } override fun getLongPollServer( needPts: Boolean, longPollVersion: Int ): VkApiRequest<LongPollServerResponse> = getLongPollServer( needPts = needPts, longPollVersion = longPollVersion, groupId = null ) override fun getRecentCalls( count: Int, startMessageId: Int?, fields: List<ObjectField>, extended: Boolean ): VkApiRequest<ExtendedListResponse<RecentCall>> = Methods.getRecentCalls.httpPost(extendedList(RecentCall.serializer())) { append("count", count) append("start_message_id", startMessageId) append("fields", fields.joinToString(",") { it.value }) append("extended", extended.asInt()) } override fun isMessagesFromGroupAllowed( groupId: Int, userId: Int ): VkApiRequest<MessagesFromGroupAllowedResponse> = Methods.isMessagesFromGroupAllowed.httpGet(MessagesFromGroupAllowedResponse.serializer()) { append("group_id", groupId) append("user_id", userId) } override fun joinChatByInviteLink( link: String ): VkApiRequest<JoinChatByLinkResponse> = Methods.joinChatByInviteLink.httpGet(JoinChatByLinkResponse.serializer()) { append("link", link) } override fun markAsAnsweredConversation( peerId: Int, isAnswered: Boolean ): VkApiRequest<BooleanInt> = Methods.markAsAnsweredConversation.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("answered", isAnswered.asInt()) } override fun markAsAnsweredConversation( peerId: Int, isAnswered: Boolean, groupId: Int ): VkApiRequest<BooleanInt> = Methods.markAsAnsweredConversation.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("answered", isAnswered.asInt()) append("group_id", groupId) } override fun markAsImportant( messageIds: List<Int>, markAsImportant: Boolean ): VkApiRequest<List<Int>> = Methods.markAsImportant.httpPost(ListSerializer(Int.serializer())) { append("message_ids", messageIds.joinToString(",")) append("important", markAsImportant.asInt()) } override fun markAsImportantConversation( peerId: Int, isImportant: Boolean ): VkApiRequest<BooleanInt> = Methods.markAsImportantConversation.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("important", isImportant.asInt()) } override fun markAsImportantConversation( peerId: Int, isImportant: Boolean, groupId: Int ): VkApiRequest<BooleanInt> = Methods.markAsImportantConversation.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("important", isImportant.asInt()) append("group_id", groupId) } override fun markAsRead( peerId: Int, startMessageId: Int?, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.markAsRead.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("start_message_id", startMessageId) append("group_id", groupId) } override fun markAsRead( peerId: Int, startMessageId: Int? ): VkApiRequest<BooleanInt> = markAsRead( peerId = peerId, startMessageId = startMessageId, groupId = null ) override fun pin( peerId: Int, messageId: Int, groupId: Int? ): VkApiRequest<Message.Pinned> = Methods.pin.httpGet(Message.Pinned.serializer()) { append("peer_id", peerId) append("message_id", messageId) append("group_id", groupId) } override fun pin( peerId: Int, messageId: Int ): VkApiRequest<Message.Pinned> = pin( peerId = peerId, messageId = messageId, groupId = null ) override fun removeChatUser( chatId: Int, memberId: Int, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.removeChatUser.httpGet(BooleanInt.serializer()) { append("chat_id", chatId) append("member_id", memberId) append("group_id", groupId) } override fun removeChatUser( chatId: Int, memberId: Int ): VkApiRequest<BooleanInt> = removeChatUser( chatId = chatId, memberId = memberId, groupId = null ) override fun restore( messageId: Int, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.restore.httpGet(BooleanInt.serializer()) { append("message_id", messageId) append("group_id", groupId) } override fun restore( messageId: Int ): VkApiRequest<BooleanInt> = restore( messageId = messageId, groupId = null ) override fun search( query: String, peerId: Int?, maxDate: GMTDate?, previewLength: Int, offset: Int, count: Int, groupId: Int? ): VkApiRequest<DefaultListResponse<Message>> = Methods.search.httpGet(list(Message.serializer())) { append("q", query) append("peer_id", peerId) append("date", maxDate?.toDMYString()) append("preview_length", previewLength) append("offset", offset) append("count", count) append("group_id", groupId) } override fun search( query: String, peerId: Int?, maxDate: GMTDate?, previewLength: Int, offset: Int, count: Int ): VkApiRequest<DefaultListResponse<Message>> = search( query = query, peerId = peerId, maxDate = maxDate, previewLength = previewLength, offset = offset, count = count, groupId = null ) override fun searchExtended( query: String, peerId: Int?, maxDate: GMTDate?, previewLength: Int, offset: Int, count: Int, groupId: Int?, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<Message>> = Methods.search.httpGet(extendedList(Message.serializer())) { append("q", query) append("peer_id", peerId) append("date", maxDate?.toDMYString()) append("preview_length", previewLength) append("offset", offset) append("count", count) append("extended", 1) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun searchExtended( query: String, peerId: Int?, maxDate: GMTDate?, previewLength: Int, offset: Int, count: Int, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<Message>> = searchExtended( query = query, peerId = peerId, maxDate = maxDate, previewLength = previewLength, offset = offset, count = count, fields = fields, groupId = null ) override fun searchConversations( query: String, count: Int, extended: Boolean, fields: List<ObjectField>, groupId: Int? ): VkApiRequest<ExtendedListResponse<Conversation>> = Methods.searchConversations.httpPost(extendedList(Conversation.serializer())) { append("q", query) append("count", count) append("extended", extended.asInt()) append("fields", fields.joinToString(",") { it.value }) append("group_id", groupId) } override fun searchConversations( query: String, count: Int, extended: Boolean, fields: List<ObjectField> ): VkApiRequest<ExtendedListResponse<Conversation>> = searchConversations( query = query, count = count, extended = extended, fields = fields, groupId = null ) override fun send( peerId: Int, randomId: Int, message: String?, latitude: Int?, longitude: Int?, attachments: List<MessageAttachment>?, replyToMessageId: Int?, forwardedMessages: List<Int>?, stickerId: Int?, keyboard: Keyboard?, payload: MessagePayload?, dontParseLink: Boolean, disableMentions: Boolean ): VkApiRequest<Int> = Methods.send.httpPost(Int.serializer()) { append("peer_id", peerId) append("random_id", randomId) append("message", message) append("lat", latitude) append("long", longitude) append("attachment", attachments?.joinToString(",", transform = MessageAttachment::attachmentString)) append("reply_to", replyToMessageId) append("forward_messages", forwardedMessages?.joinToString(",")) append("sticker_id", stickerId) append("keyboard", keyboard?.serialize()) append("payload", payload?.value) append("dont_parse_links", dontParseLink.asInt()) append("disable_mentions", disableMentions.asInt()) } override fun send( peerId: Int, randomId: Int, message: String?, latitude: Int?, longitude: Int?, attachments: List<MessageAttachment>?, replyToMessageId: Int?, forwardedMessages: List<Int>?, stickerId: Int?, dontParseLink: Boolean, disableMentions: Boolean, groupId: Int? ): VkApiRequest<Int> = Methods.send.httpPost(Int.serializer()) { append("peer_id", peerId) append("random_id", randomId) append("message", message) append("lat", latitude) append("long", longitude) append("attachment", attachments?.joinToString(",", transform = MessageAttachment::attachmentString)) append("reply_to", replyToMessageId) append("forward_messages", forwardedMessages?.joinToString(",")) append("sticker_id", stickerId) append("dont_parse_links", dontParseLink.asInt()) append("disable_mentions", disableMentions.asInt()) append("group_id", groupId) } override fun sendBulk( userIds: List<Int>, randomId: Int, message: String?, latitude: Int?, longitude: Int?, attachments: List<MessageAttachment>?, forwardedMessages: List<Int>?, stickerId: Int?, keyboard: Keyboard?, payload: MessagePayload?, dontParseLink: Boolean ): VkApiRequest<List<SendBulkMessageResponse>> = Methods.send.httpPost(ListSerializer(SendBulkMessageResponse.serializer())) { append("user_ids", userIds.joinToString(",")) append("random_id", randomId) append("message", message) append("lat", latitude) append("long", longitude) append("attachment", attachments?.joinToString(",", transform = MessageAttachment::attachmentString)) append("forward_messages", forwardedMessages?.joinToString(",")) append("sticker_id", stickerId) append("keyboard", keyboard?.serialize()) append("payload", payload?.value) append("dont_parse_links", dontParseLink.asInt()) } override fun setActivity( peerId: Int, type: String, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.setActivity.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("type", type) } override fun setActivity( peerId: Int, type: String ): VkApiRequest<BooleanInt> = setActivity( peerId = peerId, type = type, groupId = null ) override fun setChatPhoto( file: String, groupId: Int? ): VkApiRequest<ChatChangePhotoResponse> = Methods.setChatPhoto.httpGet(ChatChangePhotoResponse.serializer()) { append("file", file) append("group_id", groupId) } override fun setChatPhoto( file: String ): VkApiRequest<ChatChangePhotoResponse> = setChatPhoto( file = file, groupId = null ) override fun unpin( peerId: Int, groupId: Int? ): VkApiRequest<BooleanInt> = Methods.unpin.httpGet(BooleanInt.serializer()) { append("peer_id", peerId) append("group_id", groupId) } override fun unpin( peerId: Int ): VkApiRequest<BooleanInt> = unpin( peerId = peerId, groupId = null ) private companion object { fun GMTDate.toDMYString(): String = buildString { append(dayOfMonth.toString().padStart(2, '0')) append((month.ordinal + 1).toString().padStart(2, '0')) append(year.toString().padStart(4, '0')) } } private object Methods { private const val it = "messages." const val addChatUser = it + "addChatUser" const val allowMessagesFromGroup = it + "allowMessagesFromGroup" const val createChat = it + "createChat" const val delete = it + "delete" const val deleteChatPhoto = it + "deleteChatPhoto" const val deleteConversation = it + "deleteConversation" const val denyMessagesFromGroup = it + "denyMessagesFromGroup" const val edit = it + "edit" const val editChat = it + "editChat" const val getByConversationMessageId = it + "getByConversationMessageId" const val getById = it + "getById" const val getChat = it + "getChat" const val getChatPreview = it + "getChatPreview" const val getConversationMembers = it + "getConversationMembers" const val getConversations = it + "getConversations" const val getConversationsById = it + "getConversationsById" const val getHistory = it + "getHistory" const val getHistoryAttachments = it + "getHistoryAttachments" const val getImportantMessages = it + "getImportantMessages" const val getInviteLink = it + "getInviteLink" const val getLastActivity = it + "getLastActivity" const val getLongPollHistory = it + "getLongPollHistory" const val getLongPollServer = it + "getLongPollServer" const val getRecentCalls = it + "getRecentCalls" const val isMessagesFromGroupAllowed = it + "isMessagesFromGroupAllowed" const val joinChatByInviteLink = it + "joinChatByInviteLink" const val markAsAnsweredConversation = it + "markAsAnsweredConversation" const val markAsImportant = it + "markAsImportant" const val markAsImportantConversation = it + "markAsImportantConversation" const val markAsRead = it + "markAsRead" const val pin = it + "pin" const val removeChatUser = it + "removeChatUser" const val restore = it + "restore" const val search = it + "search" const val searchConversations = it + "searchConversations" const val send = it + "send" const val setActivity = it + "setActivity" const val setChatPhoto = it + "setChatPhoto" const val unpin = it + "unpin" } }
0
Kotlin
1
9
f8c6604a1dd604ed9cd674db9d3c3070ac558b3c
33,638
vk-api-kotlin-client
Apache License 2.0