path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/dependency/SourceSetManager.kt
RivanParmar
526,653,590
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.dependency import com.android.build.gradle.api.AndroidSourceSet import com.android.build.gradle.internal.services.DslServices import com.android.build.gradle.internal.dsl.AndroidSourceSetFactory import com.android.build.gradle.internal.errors.DeprecationReporter import com.android.build.gradle.internal.scope.DelayedActionsExecutor import com.android.builder.errors.IssueReporter import org.gradle.api.Action import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.ConfigurationContainer import org.gradle.api.artifacts.Dependency import org.gradle.api.logging.Logger import org.gradle.api.logging.Logging class SourceSetManager( project: Project, private val publishPackage: Boolean, private val dslServices : DslServices, private val buildArtifactActions: DelayedActionsExecutor) { val sourceSetsContainer: NamedDomainObjectContainer<AndroidSourceSet> = project.container( AndroidSourceSet::class.java, AndroidSourceSetFactory(project, publishPackage, dslServices)) private val configurations: ConfigurationContainer = project.configurations private val logger: Logger = Logging.getLogger(this.javaClass) private val configuredSourceSets = mutableSetOf<String>() fun setUpTestSourceSet(name: String): AndroidSourceSet { return setUpSourceSet(name, true) } @JvmOverloads fun setUpSourceSet(name: String, isTestComponent: Boolean = false): AndroidSourceSet { val sourceSet = sourceSetsContainer.maybeCreate(name) if (!configuredSourceSets.contains(name)) { createConfigurationsForSourceSet(sourceSet, isTestComponent) configuredSourceSets.add(name) } return sourceSet } private fun createConfigurationsForSourceSet( sourceSet: AndroidSourceSet, isTestComponent: Boolean) { val apiName = sourceSet.apiConfigurationName val implementationName = sourceSet.implementationConfigurationName val runtimeOnlyName = sourceSet.runtimeOnlyConfigurationName val compileOnlyName = sourceSet.compileOnlyConfigurationName val api = if (!isTestComponent) { createConfiguration(apiName, getConfigDesc("API", sourceSet.name)) } else { null } val implementation = createConfiguration( implementationName, getConfigDesc("Implementation only", sourceSet.name)) api?.let { implementation.extendsFrom(it) } createConfiguration(runtimeOnlyName, getConfigDesc("Runtime only", sourceSet.name)) createConfiguration(compileOnlyName, getConfigDesc("Compile only", sourceSet.name)) // then the secondary configurations. createConfiguration( sourceSet.wearAppConfigurationName, "Link to a wear app to embed for object '" + sourceSet.name + "'.") createConfiguration( sourceSet.annotationProcessorConfigurationName, "Classpath for the annotation processor for '" + sourceSet.name + "'.") } /** * Creates a Configuration for a given source set. * * @param name the name of the configuration to create. * @param description the configuration description. * @param canBeResolved Whether the configuration can be resolved directly. * @return the configuration * @see Configuration.isCanBeResolved */ private fun createConfiguration( name: String, description: String, canBeResolved: Boolean = false): Configuration { logger.debug("Creating configuration {}", name) val configuration = configurations.maybeCreate(name) configuration.isVisible = false configuration.description = description configuration.isCanBeConsumed = false configuration.isCanBeResolved = canBeResolved return configuration } private fun getConfigDesc(name: String, sourceSetName: String): String { return "$name dependencies for '$sourceSetName' sources." } // Check that all sourceSets in the container have been set up with configurations. // This will alert users who accidentally mistype the name of a sourceSet in their buildscript fun checkForUnconfiguredSourceSets() { sourceSetsContainer.forEach { sourceSet -> if (!configuredSourceSets.contains(sourceSet.name)) { val message = ("The SourceSet '${sourceSet.name}' is not recognized " + "by the Android Gradle Plugin. Perhaps you misspelled something?") dslServices.issueReporter.reportError(IssueReporter.Type.GENERIC, message) } } } fun executeAction(action: Action<NamedDomainObjectContainer<AndroidSourceSet>>) { action.execute(sourceSetsContainer) } fun executeAction(action: NamedDomainObjectContainer<AndroidSourceSet>.() -> Unit) { action.invoke(sourceSetsContainer) } fun runBuildableArtifactsActions() { buildArtifactActions.runAll() } }
1
null
2
17
a497291d77bba1aa34271808088fe1e8aab5efe2
5,851
androlabs
Apache License 2.0
app/src/main/java/com/consistence/pinyin/domain/Database.kt
memtrip
137,037,911
false
null
package com.consistence.pinyin.domain import android.app.Application import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.consistence.pinyin.domain.pinyin.db.PinyinDao import com.consistence.pinyin.domain.pinyin.db.PinyinEntity import com.consistence.pinyin.domain.study.db.StudyDao import com.consistence.pinyin.domain.study.db.StudyEntity import dagger.Module import dagger.Provides import javax.inject.Singleton @Database(entities = [PinyinEntity::class, StudyEntity::class], version = 3, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun pinyinDao(): PinyinDao abstract fun studyDao(): StudyDao } @Module class DatabaseModule { @Provides @Singleton fun appDatabase(application: Application): AppDatabase { return Room.databaseBuilder(application, AppDatabase::class.java, "pingyin") .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun pinyinDao(appDatabase: AppDatabase): PinyinDao { return appDatabase.pinyinDao() } @Provides @Singleton fun studoDao(appDatabase: AppDatabase): StudyDao { return appDatabase.studyDao() } }
0
Kotlin
9
58
7df0b28a89a1bf778b118e4c35274d89b0600161
1,229
android-mvi
Apache License 2.0
app/src/main/java/br/com/movieapp/movie_popular_feature/domain/usecase/GetMoviesPopularUseCase.kt
PedroTeloeken
739,474,504
false
{"Kotlin": 58374}
package br.com.movieapp.movie_popular_feature.domain.usecase import androidx.paging.PagingConfig import androidx.paging.PagingData import br.com.movieapp.core.domain.Movie import br.com.movieapp.movie_popular_feature.domain.repository.MoviePopularRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject interface GetMoviesPopularUseCase { operator fun invoke(): Flow<PagingData<Movie>> } class GetMoviesPopularUseCaseImpl @Inject constructor( private val repository: MoviePopularRepository ) : GetMoviesPopularUseCase { override fun invoke(): Flow<PagingData<Movie>> { return repository.getPopularMovies( pagingConfig = PagingConfig( pageSize = 20, initialLoadSize = 20 ) ) } }
0
Kotlin
0
0
8dea28efcad878bdc3a46d653e99ac75d82137e8
788
MovieApp
MIT License
compose/compiler/compiler-hosted/integration-tests/src/jvmTest/kotlin/androidx/compose/compiler/plugins/kotlin/FunctionBodySkippingTransformTests.kt
androidx
256,589,781
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin import org.intellij.lang.annotations.Language import org.jetbrains.kotlin.config.CompilerConfiguration import org.junit.Ignore import org.junit.Test abstract class FunctionBodySkippingTransformTestsBase( useFir: Boolean ) : AbstractIrTransformTest(useFir) { protected fun comparisonPropagation( @Language("kotlin") unchecked: String, @Language("kotlin") checked: String, dumpTree: Boolean = false ) = verifyGoldenComposeIrTransform( """ import androidx.compose.runtime.Composable import androidx.compose.runtime.NonRestartableComposable import androidx.compose.runtime.ReadOnlyComposable $checked """.trimIndent(), """ import androidx.compose.runtime.Composable $unchecked fun used(x: Any?) {} """.trimIndent(), dumpTree = dumpTree ) } class FunctionBodySkippingTransformTests( useFir: Boolean ) : FunctionBodySkippingTransformTestsBase(useFir) { @Test fun testIfInLambda(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0) {} @Composable fun Wrap(content: @Composable () -> Unit) { content() } """, """ @Composable fun Test(x: Int = 0, y: Int = 0) { used(y) Wrap { if (x > 0) { A(x) } else { A(x) } } } """ ) @Ignore("ui/foundation dependency is not supported for now") @Test fun testBasicText(): Unit = comparisonPropagation( """ """, """ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextLayoutResult @Composable fun BasicText( style: TextStyle = TextStyle.Default, onTextLayout: (TextLayoutResult) -> Unit = {}, overflow: TextOverflow = TextOverflow.Clip, ) { used(style) used(onTextLayout) used(overflow) } """ ) @Ignore("ui/foundation dependency is not supported for now") @Test fun testArrangement(): Unit = comparisonPropagation( """ """, """ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement.Vertical @Composable fun A( arrangement: Vertical = Arrangement.Top ) { used(arrangement) } """ ) @Test fun testComposableSingletonsAreStatic(): Unit = comparisonPropagation( """ """, """ @Composable fun Example( content: @Composable () -> Unit = {} ) { content() } """ ) @Test fun testFunInterfaces(): Unit = comparisonPropagation( """ fun interface A { @Composable fun compute(value: Int): Unit } """, """ fun Example(a: A) { used(a) Example { it -> a.compute(it) } } """ ) @Test fun testFunInterfaces2(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable @Stable fun Color(color: Long): Color { return Color((color shl 32).toULong()) } @Immutable @kotlin.jvm.JvmInline value class Color(val value: ULong) { companion object { @Stable val Red = Color(0xFFFF0000) @Stable val Blue = Color(0xFF0000FF) @Stable val Transparent = Color(0x00000000) } } @Composable public fun Text( text: String, color: Color = Color.Transparent, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, minLines: Int = 1, ) {} @Composable fun condition(): Boolean = true fun interface ButtonColors { @Composable fun getColor(): Color } """, """ @Composable fun Button(colors: ButtonColors) { Text("hello world", color = colors.getColor()) } @Composable fun Test() { Button { if (condition()) Color.Red else Color.Blue } } """ ) @Test fun testSimpleColumn(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Stable import androidx.compose.runtime.Immutable @Stable interface Modifier { companion object : Modifier { } } @Immutable interface Arrangement { @Immutable interface Vertical : Arrangement object Top : Vertical } enum class LayoutOrientation { Horizontal, Vertical } enum class SizeMode { Wrap, Expand } @Immutable data class Alignment( val verticalBias: Float, val horizontalBias: Float ) { @Immutable data class Horizontal(val bias: Float) companion object { val Start = Alignment.Horizontal(-1f) } } """, """ @Composable fun RowColumnImpl( orientation: LayoutOrientation, modifier: Modifier = Modifier, arrangement: Arrangement.Vertical = Arrangement.Top, crossAxisAlignment: Alignment.Horizontal = Alignment.Start, crossAxisSize: SizeMode = SizeMode.Wrap, content: @Composable() ()->Unit ) { used(orientation) used(modifier) used(arrangement) used(crossAxisAlignment) used(crossAxisSize) content() } @Composable fun Column( modifier: Modifier = Modifier, verticalArrangement: Arrangement.Vertical = Arrangement.Top, horizontalGravity: Alignment.Horizontal = Alignment.Start, content: @Composable() ()->Unit ) { RowColumnImpl( orientation = LayoutOrientation.Vertical, arrangement = verticalArrangement, crossAxisAlignment = horizontalGravity, crossAxisSize = SizeMode.Wrap, modifier = modifier, content = content ) } """ ) @Test fun testSimplerBox(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Stable @Stable interface Modifier { companion object : Modifier { } } """, """ @Composable fun SimpleBox(modifier: Modifier = Modifier) { used(modifier) } """ ) @Test fun testDefaultSkipping(): Unit = comparisonPropagation( """ fun newInt(): Int = 123 """, """ @Composable fun Example(a: Int = newInt()) { print(a) } """ ) @Test fun testLocalComposableFunctions(): Unit = comparisonPropagation( """ @Composable fun A(a: Int) {} """, """ @Composable fun Example(a: Int) { @Composable fun Inner() { A(a) } Inner() } """ ) @Test fun testLoopWithContinueAndCallAfter(): Unit = comparisonPropagation( """ @Composable fun Call() {} fun condition(): Boolean = true """, """ @Composable @NonRestartableComposable fun Example() { Call() for (index in 0..1) { Call() if (condition()) continue Call() } } """ ) @Test fun testSimpleBoxWithShape(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Stable @Stable interface Modifier { companion object : Modifier { } } interface Shape { } val RectangleShape = object : Shape { } """, """ @Composable fun SimpleBox(modifier: Modifier = Modifier, shape: Shape = RectangleShape) { used(modifier) used(shape) } """ ) @Test fun testSimpleBox(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Stable @Stable interface Modifier { companion object : Modifier { } } """, """ @Composable fun SimpleBox(modifier: Modifier = Modifier, content: @Composable() () -> Unit = {}) { used(modifier) content() } """ ) @Test fun testComposableLambdaWithStableParams(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Immutable @Immutable class Foo @Composable fun A(x: Int) {} @Composable fun B(y: Foo) {} """, """ val foo = @Composable { x: Int, y: Foo -> A(x) B(y) } """ ) @Test fun testComposableLambdaWithUnstableParams(): Unit = comparisonPropagation( """ class Foo(var value: Int = 0) @Composable fun A(x: Int) {} @Composable fun B(y: Foo) {} """, """ val foo = @Composable { x: Int, y: Foo -> A(x) B(y) } """ ) @Test fun testComposableLambdaWithStableParamsAndReturnValue(): Unit = comparisonPropagation( """ """, """ @Composable fun SomeThing(content: @Composable() () -> Unit) { content() } @Composable fun Example() { SomeThing { val id = object {} } } """ ) @Test fun testPrimitiveVarargParams(): Unit = comparisonPropagation( """ """, """ @Composable fun B(vararg values: Int) { print(values) } """ ) @Test fun testStableVarargParams(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Immutable @Immutable class Foo """, """ @Composable fun B(vararg values: Foo) { print(values) } """ ) @Test fun testUnstableVarargParams(): Unit = comparisonPropagation( """ class Foo(var value: Int = 0) """, """ @Composable fun B(vararg values: Foo) { print(values) } """ ) @Test fun testReceiverParamSkippability(): Unit = comparisonPropagation( """ """, """ class Foo { var counter: Int = 0 @Composable fun A() { print("hello world") } @Composable fun B() { print(counter) } } """ ) @Test fun testComposableParameter(): Unit = comparisonPropagation( """ @Composable fun makeInt(): Int = 10 """, """ @Composable fun Example(a: Int = 0, b: Int = makeInt(), c: Int = 0) { used(a) used(b) used(c) } """ ) @Test fun testComposableWithAndWithoutDefaultParams(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0) {} """, """ @Composable fun Wrap(y: Int, content: @Composable (x: Int) -> Unit) { content(y) } @Composable fun Test(x: Int = 0, y: Int = 0) { used(y) Wrap(10) { used(it) A(x) } } """ ) @Test fun testComposableWithReturnValue(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0) {} """, """ @Composable fun Test(x: Int = 0, y: Int = 0): Int { A(x, y) return x + y } """ ) @Test fun testComposableLambda(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0) {} """, """ val test = @Composable { x: Int -> A(x) } """ ) @Test fun testComposableFunExprBody(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0): Int { return 10 } """, """ @Composable fun Test(x: Int) = A() """ ) @Test fun testParamReordering(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0): Int { return 10 } """, """ @Composable fun Test(x: Int, y: Int) { A(y = y, x = x) } """ ) @Test fun testStableUnstableParams(): Unit = comparisonPropagation( """ @Composable fun A(x: Int = 0, y: Int = 0): Int { return 10 } class Foo(var value: Int = 0) """, """ @Composable fun CanSkip(a: Int = 0, b: Foo = Foo()) { used(a) used(b) } @Composable fun CannotSkip(a: Int, b: Foo) { used(a) used(b) print("Hello World") } @Composable fun NoParams() { print("Hello World") } """ ) @Test fun testOptionalUnstableWithStableExtensionReceiver(): Unit = comparisonPropagation( """ class Foo(var value: Int = 0) class Bar """, """ @Composable fun Bar.CanSkip(b: Foo = Foo()) { print("Hello World") } """ ) @Test fun testNoParams(): Unit = comparisonPropagation( """ @Composable fun A() {} """, """ @Composable fun Test() { A() } """ ) @Test fun testSingleStableParam(): Unit = comparisonPropagation( """ @Composable fun A(x: Int) {} """, """ @Composable fun Test(x: Int) { A(x) } """ ) @Test fun testInlineClassDefaultParameter(): Unit = comparisonPropagation( """ inline class Color(val value: Int) { companion object { val Unset = Color(0) } } """, """ @Composable fun A(text: String) { B(text) } @Composable fun B(text: String, color: Color = Color.Unset) { used(text) used(color) } """ ) @Test fun testStaticDetection(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Stable enum class Foo { Bar, Bam } const val constInt: Int = 123 val normInt = 345 val stableTopLevelProp: Modifier = Modifier @Composable fun C(x: Any?) {} @Stable interface Modifier { companion object : Modifier { } } inline class Dp(val value: Int) @Stable fun stableFun(x: Int): Int = x * x @Stable operator fun Dp.plus(other: Dp): Dp = Dp(this.value + other.value) @Stable val Int.dp: Dp get() = Dp(this) @Composable fun D(content: @Composable() () -> Unit) {} """, """ // all of these should result in 0b0110 @Composable fun A() { val x = 123 D {} C({}) C(stableFun(123)) C(16.dp + 10.dp) C(Dp(16)) C(16.dp) C(normInt) C(Int.MAX_VALUE) C(stableTopLevelProp) C(Modifier) C(Foo.Bar) C(constInt) C(123) C(123 + 345) C(x) C(x * 123) } // all of these should result in 0b0000 @Composable fun B() { C(Math.random()) C(Math.random() / 100f) } """ ) @Test fun testAnnotationChecker(): Unit = comparisonPropagation( """ @Composable fun D(content: @Composable() () -> Unit) {} """, """ @Composable fun Example() { D {} } """ ) @Test fun testSingleStableParamWithDefault(): Unit = comparisonPropagation( """ @Composable fun A(x: Int) {} """, """ @Composable fun Test(x: Int = 0) { A(x) } """ ) @Test fun testSingleStableParamWithComposableDefault(): Unit = comparisonPropagation( """ @Composable fun A(x: Int) {} @Composable fun I(): Int { return 10 } """, """ @Composable fun Test(x: Int = I()) { A(x) } """ ) @Test fun testSingleUnstableParam(): Unit = comparisonPropagation( """ @Composable fun A(x: Foo) {} class Foo(var value: Int = 0) """, """ @Composable fun Test(x: Foo) { A(x) } """ ) @Test fun testSingleUnstableParamWithDefault(): Unit = comparisonPropagation( """ @Composable fun A(x: Foo) {} class Foo """, """ @Composable fun Test(x: Foo = Foo()) { A(x) } """ ) @Test fun testManyNonOptionalParams(): Unit = comparisonPropagation( """ @Composable fun A(a: Int, b: Boolean, c: Int, d: Foo, e: List<Int>) {} class Foo """, """ @Composable fun Test(a: Int, b: Boolean, c: Int = 0, d: Foo = Foo(), e: List<Int> = emptyList()) { A(a, b, c, d, e) } """ ) @Test fun testRecursiveCall(): Unit = comparisonPropagation( """ """, """ @Composable fun X(x: Int) { X(x + 1) X(x) } """ ) @Test fun testLambdaSkipping(): Unit = comparisonPropagation( """ import androidx.compose.runtime.* data class User( val id: Int, val name: String ) interface LazyPagingItems<T> { val itemCount: Int operator fun get(index: Int): State<T?> } @Stable interface LazyListScope { fun items(itemCount: Int, itemContent: @Composable LazyItemScope.(Int) -> Unit) } @Stable interface LazyItemScope public fun <T : Any> LazyListScope.itemsIndexed( lazyPagingItems: LazyPagingItems<T>, itemContent: @Composable LazyItemScope.(Int, T?) -> Unit ) { items(lazyPagingItems.itemCount) { index -> val item = lazyPagingItems[index].value itemContent(index, item) } } """, """ fun LazyListScope.Example(items: LazyPagingItems<User>) { itemsIndexed(items) { index, user -> print("Hello World") } } """ ) @Test fun testPassedExtensionWhenExtensionIsPotentiallyUnstable(): Unit = comparisonPropagation( """ interface Unstable """, """ @Composable fun Unstable.Test() { doSomething(this) // does this reference %dirty without %dirty } @Composable fun doSomething(x: Unstable) {} """ ) @Test fun testReceiverIssue(): Unit = comparisonPropagation( """ class Foo """, """ import androidx.compose.runtime.ExplicitGroupsComposable @Composable @ExplicitGroupsComposable fun A(foo: Foo) { foo.b() } @Composable @ExplicitGroupsComposable inline fun Foo.b(label: String = "") { c(this, label) } @Composable @ExplicitGroupsComposable inline fun c(foo: Foo, label: String) { print(label) } """ ) @Test fun testDifferentParameters(): Unit = comparisonPropagation( """ @Composable fun B(a: Int, b: Int, c: Int, d: Int) {} val fooGlobal = 10 """, """ @Composable fun A(x: Int) { B( // direct parameter x, // transformation x + 1, // literal 123, // expression with no parameter fooGlobal ) } """ ) @Test fun testReceiverLambdaCall(): Unit = comparisonPropagation( """ import androidx.compose.runtime.Stable interface Foo { val x: Int } @Stable interface StableFoo { val x: Int } """, """ val unstableUnused: @Composable Foo.() -> Unit = { } val unstableUsed: @Composable Foo.() -> Unit = { used(x) } val stableUnused: @Composable StableFoo.() -> Unit = { } val stableUsed: @Composable StableFoo.() -> Unit = { used(x) } """ ) @Test fun testNestedCalls(): Unit = comparisonPropagation( """ @Composable fun B(a: Int = 0, b: Int = 0, c: Int = 0) {} @Composable fun Provide(content: @Composable (Int) -> Unit) {} """, """ @Composable fun A(x: Int) { Provide { y -> Provide { z -> B(x, y, z) } B(x, y) } B(x) } """ ) @Test fun testLocalFunction(): Unit = comparisonPropagation( """ @Composable fun B(a: Int, b: Int) {} """, """ @Composable fun A(x: Int) { @Composable fun foo(y: Int) { B(x, y) } foo(x) } """ ) @Test fun test15Parameters(): Unit = comparisonPropagation( """ """, """ @Composable fun Example( a00: Int = 0, a01: Int = 0, a02: Int = 0, a03: Int = 0, a04: Int = 0, a05: Int = 0, a06: Int = 0, a07: Int = 0, a08: Int = 0, a09: Int = 0, a10: Int = 0, a11: Int = 0, a12: Int = 0, a13: Int = 0, a14: Int = 0 ) { // in order Example( a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14 ) // in opposite order Example( a14, a13, a12, a11, a10, a09, a08, a07, a06, a05, a04, a03, a02, a01, a00 ) } """ ) @Test fun test16Parameters(): Unit = comparisonPropagation( """ """, """ @Composable fun Example( a00: Int = 0, a01: Int = 0, a02: Int = 0, a03: Int = 0, a04: Int = 0, a05: Int = 0, a06: Int = 0, a07: Int = 0, a08: Int = 0, a09: Int = 0, a10: Int = 0, a11: Int = 0, a12: Int = 0, a13: Int = 0, a14: Int = 0, a15: Int = 0 ) { // in order Example( a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14, a15 ) // in opposite order Example( a15, a14, a13, a12, a11, a10, a09, a08, a07, a06, a05, a04, a03, a02, a01, a00 ) } """ ) @Test fun testGrouplessProperty(): Unit = comparisonPropagation( """ """, """ import androidx.compose.runtime.currentComposer open class Foo { inline val current: Int @Composable @ReadOnlyComposable get() = currentComposer.hashCode() @ReadOnlyComposable @Composable fun getHashCode(): Int = currentComposer.hashCode() } @ReadOnlyComposable @Composable fun getHashCode(): Int = currentComposer.hashCode() """ ) @Test fun testStaticAndNonStaticDefaultValueSkipping(): Unit = comparisonPropagation( """ import androidx.compose.runtime.compositionLocalOf val LocalColor = compositionLocalOf { 123 } @Composable fun A(a: Int) {} """, """ @Composable fun Example( wontChange: Int = 123, mightChange: Int = LocalColor.current ) { A(wontChange) A(mightChange) } """ ) @Test fun testComposableLambdaInvoke(): Unit = comparisonPropagation( """ """, """ @Composable fun Example(content: @Composable() () -> Unit) { content.invoke() } """ ) @Test fun testComposableLambdasWithReturnGetGroups(): Unit = comparisonPropagation( """ """, """ fun A(factory: @Composable () -> Int): Unit {} fun B() = A { 123 } """ ) @Ignore("ui/foundation dependency is not supported for now") @Test fun testDefaultsIssue(): Unit = comparisonPropagation( """ """, """ import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp @Composable fun Box2( modifier: Modifier = Modifier, paddingStart: Dp = Dp.Unspecified, content: @Composable () -> Unit = {} ) { used(modifier) used(paddingStart) content() } """ ) @Test fun testSiblingIfsWithoutElseHaveUniqueKeys(): Unit = comparisonPropagation( """ @Composable fun A(){} @Composable fun B(){} """, """ @Composable fun Test(cond: Boolean) { if (cond) { A() } if (cond) { B() } } """ ) @Test fun testUnusedParameters(): Unit = comparisonPropagation( """ class Unstable(var count: Int) class Stable(val count: Int) interface MaybeStable """, """ @Composable fun Unskippable(a: Unstable, b: Stable, c: MaybeStable) { used(a) } @Composable fun Skippable1(a: Unstable, b: Stable, c: MaybeStable) { used(b) } @Composable fun Skippable2(a: Unstable, b: Stable, c: MaybeStable) { used(c) } @Composable fun Skippable3(a: Unstable, b: Stable, c: MaybeStable) { } """ ) @Test fun testExtensionReceiver(): Unit = comparisonPropagation( """ interface MaybeStable """, """ @Composable fun MaybeStable.example(x: Int) { used(this) used(x) } val example: @Composable MaybeStable.(Int) -> Unit = { used(this) used(it) } """ ) @Test fun testArrayDefaultArgWithState(): Unit = comparisonPropagation( """ """, """ import androidx.compose.runtime.MutableState @Composable fun VarargComposable(state: MutableState<Int>, vararg values: String = Array(1) { "value " + it }) { state.value } """ ) @Test // regression test for 204897513 fun test_InlineForLoop() = verifyGoldenComposeIrTransform( source = """ import androidx.compose.runtime.* @Composable fun Test() { Bug(listOf(1, 2, 3)) { Text(it.toString()) } } @Composable inline fun <T> Bug(items: List<T>, content: @Composable (item: T) -> Unit) { for (item in items) content(item) } """, extra = """ import androidx.compose.runtime.* @Composable fun Text(value: String) {} """ ) } class FunctionBodySkippingTransformTestsNoSource( useFir: Boolean ) : FunctionBodySkippingTransformTestsBase(useFir) { override fun CompilerConfiguration.updateConfiguration() { put(ComposeConfiguration.SOURCE_INFORMATION_ENABLED_KEY, false) put(ComposeConfiguration.TRACE_MARKERS_ENABLED_KEY, false) } @Test fun testGrouplessProperty(): Unit = comparisonPropagation( """ """, """ import androidx.compose.runtime.currentComposer open class Foo { inline val current: Int @Composable @ReadOnlyComposable get() = currentComposer.hashCode() @ReadOnlyComposable @Composable fun getHashCode(): Int = currentComposer.hashCode() } @ReadOnlyComposable @Composable fun getHashCode(): Int = currentComposer.hashCode() """ ) @Test // regression test for 204897513 fun test_InlineForLoop_no_source_info() = verifyGoldenComposeIrTransform( source = """ import androidx.compose.runtime.* @Composable private fun Test() { Bug(listOf(1, 2, 3)) { Text(it.toString()) } } @Composable private inline fun <T> Bug(items: List<T>, content: @Composable (item: T) -> Unit) { for (item in items) content(item) } """, extra = """ import androidx.compose.runtime.* @Composable fun Text(value: String) {} """ ) @Test fun test_InlineSkipping() = verifyGoldenComposeIrTransform( source = """ import androidx.compose.runtime.* @Composable fun Test() { InlineWrapperParam { Text("Function ${'$'}it") } } """, extra = """ import androidx.compose.runtime.* @Composable inline fun InlineWrapperParam(content: @Composable (Int) -> Unit) { content(100) } @Composable fun Text(text: String) { } """ ) @Test fun test_ComposableLambdaWithUnusedParameter() = verifyGoldenComposeIrTransform( source = """ import androidx.compose.runtime.* val layoutLambda = @Composable { _: Int -> Layout() } """, extra = """ import androidx.compose.runtime.* @Composable inline fun Layout() {} """ ) @Test fun testNonSkippableComposable() = comparisonPropagation( "", """ import androidx.compose.runtime.NonSkippableComposable @Composable @NonSkippableComposable fun Test(i: Int) { used(i) } """.trimIndent() ) @Test fun testComposable() = verifyGoldenComposeIrTransform( source = """ interface NewProfileOBViewModel { fun overrideMe(): @Type () -> Unit } class ReturningProfileObViewModel : NewProfileOBViewModel { override fun overrideMe(): @Type () -> Unit = {} } @Target(AnnotationTarget.TYPE) annotation class Type """ ) }
28
null
945
5,125
55c737bfb7a7320ac5b43787306f0c3af169f420
36,779
androidx
Apache License 2.0
plugins/toolkit/jetbrains-core/src/software/aws/toolkits/jetbrains/core/explorer/cwqTab/CwQTreeRootNode.kt
aws
91,485,909
false
null
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.core.explorer.cwqTab import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import software.aws.toolkits.jetbrains.core.explorer.cwqTab.nodes.CwQServiceNode class CwQTreeRootNode(private val nodeProject: Project) : AbstractTreeNode<Any>(nodeProject, Object()) { override fun update(presentation: PresentationData) {} override fun getChildren(): Collection<AbstractTreeNode<*>> = EP_NAME.extensionList .filter { it.enabled() } .map { it.buildServiceRootNode(nodeProject).also { node -> node.parent = this } } companion object { val EP_NAME = ExtensionPointName<CwQServiceNode>("aws.toolkit.cwq.serviceNode") } }
419
null
184
721
cf124aa847231402fc483c02223850644b3b749e
1,013
aws-toolkit-jetbrains
Apache License 2.0
src/generated/kotlin/de/lancom/openapi/entity/XML.kt
lancomsystems
733,524,954
false
{"Kotlin": 769728, "Mustache": 12392}
/***************************************************************************** ** C A U T I O N ** ** This file is auto-generated! ** ** If you want to make changes, please see the README.md file. ** ** Please do not edit this file directly! ** *****************************************************************************/ package de.lancom.openapi.entity import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonSerialize import de.lancom.openapi.field.Field import de.lancom.openapi.jackson.EntityDeserializer import de.lancom.openapi.jackson.EntitySerializer import de.lancom.openapi.jackson.Parser import de.lancom.openapi.jackson.Wrapper import de.lancom.openapi.tools.toYamlString // hint:9A1BF04C @Suppress("PropertyName") @JsonSerialize(using = DefaultJson.Companion.Serializer::class) @JsonDeserialize(using = DefaultJson.Companion.Deserializer::class) data class DefaultJson( val _jsonNode: Field<JsonNode> = Field.unset(), ) : Entity { /////////////////////// // // jsonNode // /////////////////////// // hint:3A7F9B2E val jsonNode: JsonNode get() = _jsonNode.getOrError() // hint:F0C48D71 fun setJsonNodeField(jsonNode: Field<JsonNode>): DefaultJson { return copy(_jsonNode = jsonNode) } // hint:8E56A4D9 fun updateJsonNodeField(updater: (Field<JsonNode>) -> Field<JsonNode>): DefaultJson { return setJsonNodeField(updater(_jsonNode)) } // hint:B1D730FC fun updateJsonNode(updater: (JsonNode) -> JsonNode): DefaultJson { return updateJsonNodeField { field -> field.flatMap { value -> Field(updater(value)) } } } // hint:6542E98A fun mergeJsonNodeField(jsonNodeFieldToMerge: Field<JsonNode>): DefaultJson { return mergeJsonNode(jsonNodeFieldToMerge.orNull) } // hint:A8BC6F23 fun mergeJsonNode(jsonNodeToMerge: JsonNode?): DefaultJson { return if (jsonNodeToMerge == null) { this } else { val oldJsonNode = _jsonNode.orNull if (oldJsonNode == null) { setJsonNodeField(Field(jsonNodeToMerge)) } else { // hint:2F684DAC setJsonNode(jsonNodeToMerge) } } } // hint:87B3E19C fun setJsonNode(jsonNode: JsonNode): DefaultJson { return setJsonNodeField(Field(jsonNode)) } // hint:D465F782 fun unsetJsonNode(): DefaultJson { return setJsonNodeField(Field.unset()) } // hint:47C9A0F6 fun addJsonNode(jsonNode: JsonNode): DefaultJson { return setJsonNode(jsonNode) } // hint:6A81E3FD override val entityDescriptor: EntityDescriptor by lazy { EntityDescriptor( entity = this, jsonNode = _jsonNode, map = mapOf( ), flatMap = listOf( ), flatten = listOf( ), ) } override fun toString(): String { return this.toYamlString() } // hint:A0E5F382 override fun mergeEntity(other: Entity?): DefaultJson { return when (other) { null -> this is DefaultJson -> merge(other) else -> TODO() } } // hint:716BFD54 fun merge(other: DefaultJson?): DefaultJson { if (other == null) return this return this .mergeJsonNodeField(other._jsonNode) } companion object : JsonEntityFactory<DefaultJson> { class Serializer : EntitySerializer<DefaultJson>(DefaultJson::class.java, DefaultJson) class Deserializer : EntityDeserializer<DefaultJson>(DefaultJson::class.java, DefaultJson) // hint:5F72B6D8 override fun parseWrapper(wrapper: Wrapper): DefaultJson { return DefaultJson( _jsonNode = wrapper.jsonNodeFieldOrUnsetIfEmpty, ) } } }
1
Kotlin
0
1
be448682a5ce7441fb04f7a888cab903dcedacbb
4,240
openapi-parser
Apache License 2.0
script-generator/src/test/kotlin/generated/UpdateGradleWrapper.kt
krzema12
439,670,569
false
null
package generated import it.krzeminski.githubactions.domain.actions.CustomAction import it.krzeminski.githubactions.actions.actions.CheckoutV3 import it.krzeminski.githubactions.actions.gradleupdate.UpdateGradleWrapperActionV1 import it.krzeminski.githubactions.domain.RunnerType import it.krzeminski.githubactions.domain.Workflow import it.krzeminski.githubactions.domain.triggers.Cron import it.krzeminski.githubactions.domain.triggers.Schedule import it.krzeminski.githubactions.domain.triggers.WorkflowDispatch import it.krzeminski.githubactions.dsl.workflow import java.nio.`file`.Paths import kotlin.collections.mapOf public val workflowUpdateGradleWrapper: Workflow = workflow( name = "Update Gradle Wrapper", on = listOf( Schedule(listOf( Cron("0 0 * * *"), )), WorkflowDispatch(), ), sourceFile = Paths.get(".github/workflows/update-gradle-wrapper.main.kts"), ) { job( id = "check_yaml_consistency", name = "Check YAML consistency", runsOn = RunnerType.UbuntuLatest, ) { uses( name = "Check out", action = CheckoutV3(), condition = "true", ) run( name = "Install Kotlin", command = "sudo snap install --classic kotlin", ) run( name = "Consistency check", command = "diff -u '.github/workflows/update-gradle-wrapper.yml' <('.github/workflows/update-gradle-wrapper.main.kts')", ) } job( id = "update-gradle-wrapper", runsOn = RunnerType.UbuntuLatest, _customArguments = mapOf( "needs" to listOf("check_yaml_consistency"), ) ) { uses( name = "Checkout", action = CheckoutV3(), ) uses( name = "Update Gradle Wrapper", action = UpdateGradleWrapperActionV1(), ) uses( name = "Latex", action = CustomAction( actionOwner = "xu-cheng", actionName = "latex-action", actionVersion = "v2", inputs = mapOf( "root_file" to "report.tex", "compiler" to "latexmk", ) ), ) } }
33
null
12
317
d00c239f914719be3a7bfd9b02e06f65b8a45b7c
2,278
github-workflows-kt
Apache License 2.0
plugins/kotlin/highlighting/highlighting-k1/src/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingVisitorExtension.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.highlighter import com.intellij.codeInsight.daemon.impl.HighlightInfoType import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall abstract class KotlinHighlightingVisitorExtension { abstract fun highlightDeclaration(elementToHighlight: PsiElement, descriptor: DeclarationDescriptor): HighlightInfoType? open fun highlightCall(elementToHighlight: PsiElement, resolvedCall: ResolvedCall<*>): HighlightInfoType? { return highlightDeclaration(elementToHighlight, resolvedCall.resultingDescriptor) } companion object { val EP_NAME = ExtensionPointName.create<KotlinHighlightingVisitorExtension>("org.jetbrains.kotlin.highlighterExtension") } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
995
intellij-community
Apache License 2.0
app/src/main/java/com/concordium/wallet/ui/bakerdelegation/baker/BakerRegisterAmountActivity.kt
Concordium
358,250,608
false
null
package com.concordium.wallet.ui.bakerdelegation.baker import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.view.View import android.view.inputmethod.EditorInfo import androidx.core.widget.doOnTextChanged import com.concordium.wallet.R import com.concordium.wallet.data.backend.repository.ProxyRepository.Companion.REGISTER_BAKER import com.concordium.wallet.data.util.CurrencyUtil import com.concordium.wallet.databinding.ActivityBakerRegistrationAmountBinding import com.concordium.wallet.ui.bakerdelegation.common.BaseDelegationBakerRegisterAmountActivity import com.concordium.wallet.ui.bakerdelegation.common.DelegationBakerViewModel import com.concordium.wallet.ui.bakerdelegation.common.StakeAmountInputValidator import com.concordium.wallet.ui.common.BackendErrorHandler import com.concordium.wallet.ui.common.GenericFlowActivity import com.concordium.wallet.util.toBigInteger import java.math.BigInteger class BakerRegisterAmountActivity : BaseDelegationBakerRegisterAmountActivity() { private var minFee: BigInteger? = null private var maxFee: BigInteger? = null private var singleFee: BigInteger? = null companion object { private const val RANGE_MIN_FEE = 1 private const val RANGE_MAX_FEE = 2 private const val SINGLE_FEE = 3 } private lateinit var binding: ActivityBakerRegistrationAmountBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityBakerRegistrationAmountBinding.inflate(layoutInflater) setContentView(binding.root) setupActionBar( binding.toolbarLayout.toolbar, binding.toolbarLayout.toolbarTitle, R.string.baker_registration_amount_title ) initViews() } override fun initViews() { super.initViews() super.initReStakeOptionsView(binding.restakeOptions) if (viewModel.bakerDelegationData.isUpdateBaker()) { setActionBarTitle(R.string.baker_registration_update_amount_title) viewModel.bakerDelegationData.oldStakedAmount = viewModel.bakerDelegationData.account?.accountBaker?.stakedAmount?.toBigInteger() viewModel.bakerDelegationData.oldRestake = viewModel.bakerDelegationData.account?.accountBaker?.restakeEarnings binding.amount.setText( CurrencyUtil.formatGTU( viewModel.bakerDelegationData.account?.accountBaker?.stakedAmount ?: "0", true ) ) binding.amountDesc.text = getString(R.string.baker_update_enter_new_stake) } binding.balanceAmount.text = CurrencyUtil.formatGTU(viewModel.getAvailableBalance(), true) binding.bakerAmount.text = CurrencyUtil.formatGTU( viewModel.bakerDelegationData.account?.accountBaker?.stakedAmount ?: "0", true ) viewModel.transactionFeeLiveData.observe(this) { response -> response?.second?.let { requestId -> when (requestId) { SINGLE_FEE -> { singleFee = response.first validateFee = response.first } RANGE_MIN_FEE -> minFee = response.first RANGE_MAX_FEE -> { maxFee = response.first validateFee = response.first } } singleFee?.let { binding.poolEstimatedTransactionFee.visibility = View.VISIBLE binding.poolEstimatedTransactionFee.text = getString( R.string.baker_registration_update_amount_estimated_transaction_fee_single, CurrencyUtil.formatGTU(singleFee ?: BigInteger.ZERO) ) } ?: run { if (minFee != null && maxFee != null) { binding.poolEstimatedTransactionFee.visibility = View.VISIBLE binding.poolEstimatedTransactionFee.text = getString( R.string.baker_registration_update_amount_estimated_transaction_fee_range, CurrencyUtil.formatGTU(minFee ?: BigInteger.ZERO), CurrencyUtil.formatGTU(maxFee ?: BigInteger.ZERO) ) } } } } viewModel.chainParametersPassiveDelegationBakerPoolLoaded.observe(this) { success -> success?.let { updateViews() showWaiting(binding.includeProgress.progressLayout, false) } } showWaiting(binding.includeProgress.progressLayout, true) loadTransactionFee() try { viewModel.loadChainParametersPassiveDelegationAndPossibleBakerPool() } catch (ex: Exception) { handleBackendError(ex) } } private fun handleBackendError(throwable: Throwable) { val stringRes = BackendErrorHandler.getExceptionStringRes(throwable) runOnUiThread { popup.showSnackbar(binding.root, stringRes) } } private fun updateViews() { binding.amount.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { onContinueClicked() } false } setAmountHint(binding.amount) binding.amount.doOnTextChanged { _, _, _, _ -> validateAmountInput(binding.amount, binding.amountError) } binding.amount.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> if (hasFocus && binding.amount.text.isEmpty()) binding.amount.hint = "" else setAmountHint(binding.amount) } binding.bakerRegistrationContinue.setOnClickListener { onContinueClicked() } if (viewModel.isInCoolDown()) { binding.amountLocked.visibility = View.VISIBLE binding.amount.isEnabled = false } } override fun loadTransactionFee() { when (viewModel.bakerDelegationData.type) { REGISTER_BAKER -> { viewModel.loadTransactionFee( true, requestId = RANGE_MIN_FEE, metadataSizeForced = 0 ) viewModel.loadTransactionFee( true, requestId = RANGE_MAX_FEE, metadataSizeForced = 2048 ) } else -> viewModel.loadTransactionFee( true, requestId = SINGLE_FEE, metadataSizeForced = viewModel.bakerDelegationData.account?.accountBaker?.bakerPoolInfo?.metadataUrl?.length ) } } override fun getStakeAmountInputValidator(): StakeAmountInputValidator { return StakeAmountInputValidator( minimumValue = viewModel.bakerDelegationData.chainParameters?.minimumEquityCapital, maximumValue = viewModel.getStakeInputMax(), balance = viewModel.bakerDelegationData.account?.finalizedBalance ?: BigInteger.ZERO, atDisposal = viewModel.atDisposal(), currentPool = viewModel.bakerDelegationData.bakerPoolStatus?.delegatedCapital, poolLimit = null, previouslyStakedInPool = viewModel.bakerDelegationData.account?.accountDelegation?.stakedAmount, isInCoolDown = viewModel.isInCoolDown(), oldPoolId = viewModel.bakerDelegationData.account?.accountDelegation?.delegationTarget?.bakerId, newPoolId = viewModel.bakerDelegationData.poolId ) } override fun showError(stakeError: StakeAmountInputValidator.StakeError?) { binding.amount.setTextColor(getColor(R.color.text_pink)) binding.amountError.visibility = View.VISIBLE } override fun hideError() { binding.amount.setTextColor(getColor(R.color.theme_blue)) binding.amountError.visibility = View.INVISIBLE } override fun errorLiveData(value: Int) { } private fun onContinueClicked() { if (!binding.bakerRegistrationContinue.isEnabled) return val stakeAmountInputValidator = getStakeAmountInputValidator() val stakeError = stakeAmountInputValidator.validate( CurrencyUtil.toGTUValue(binding.amount.text.toString())?.toString(), validateFee ) if (stakeError != StakeAmountInputValidator.StakeError.OK) { binding.amountError.text = stakeAmountInputValidator.getErrorText(this, stakeError) showError(stakeError) return } val amountToStake = getAmountToStake() if (viewModel.bakerDelegationData.isUpdateBaker()) { when { amountToStake == viewModel.bakerDelegationData.oldStakedAmount && viewModel.bakerDelegationData.restake == viewModel.bakerDelegationData.oldRestake -> showNoChange() moreThan95Percent(amountToStake) -> show95PercentWarning() else -> gotoNextPage() } } else { when { moreThan95Percent(amountToStake) -> show95PercentWarning() else -> gotoNextPage() } } } private fun getAmountToStake(): BigInteger { return CurrencyUtil.toGTUValue(binding.amount.text.toString()) ?: BigInteger.ZERO } private fun show95PercentWarning() { val builder = AlertDialog.Builder(this) builder.setTitle(R.string.baker_more_than_95_title) builder.setMessage(getString(R.string.baker_more_than_95_message)) builder.setPositiveButton(getString(R.string.baker_more_than_95_continue)) { _, _ -> gotoNextPage() } builder.setNegativeButton(getString(R.string.baker_more_than_95_new_stake)) { dialog, _ -> dialog.dismiss() } builder.create().show() } private fun gotoNextPage() { viewModel.bakerDelegationData.amount = CurrencyUtil.toGTUValue(binding.amount.text.toString()) val intent = if (viewModel.bakerDelegationData.isUpdateBaker()) Intent(this, BakerRegistrationConfirmationActivity::class.java) else Intent(this, BakerRegistrationActivity::class.java) intent.putExtra(GenericFlowActivity.EXTRA_IGNORE_BACK_PRESS, false) intent.putExtra( DelegationBakerViewModel.EXTRA_DELEGATION_BAKER_DATA, viewModel.bakerDelegationData ) startActivityForResultAndHistoryCheck(intent) } }
6
Kotlin
3
9
ff6970fca016387fc0ecaade085a6f2dabbaa18e
10,739
concordium-reference-wallet-android
Apache License 2.0
core/src/main/kotlin/com/piotrwalkusz/smartlaw/core/model/element/implementation/PropertyImplementation.kt
piotrwalkusz1
293,285,610
false
null
package com.piotrwalkusz.smartlaw.core.model.element.implementation import com.piotrwalkusz.smartlaw.annotationprocessor.GenerateTemplate import com.piotrwalkusz.smartlaw.core.model.element.function.statement.Statement import com.piotrwalkusz.smartlaw.core.model.element.interfaces.InterfacePropertyType @GenerateTemplate data class PropertyImplementation( val name: String, val type: InterfacePropertyType, val body: Statement )
0
Kotlin
0
0
235354ac0469d5ba9630b91124f6fcc4481dad34
455
SmartLaw
MIT License
context/src/main/java/dev/funkymuse/context/ContextDialogs.kt
FunkyMuse
168,687,007
false
null
package com.crazylegend.kotlinextensions.context import android.content.Context import androidx.appcompat.app.AlertDialog /** * Created by hristijan on 3/1/19 to long live and prosper ! */ /** * There is No Such Thing name Hard Toast, Its just an AlertDialog which will the [msg] you passed until user cancels it. */ fun Context.showToastHard(msg: String) = AlertDialog.Builder(this).setMessage(msg).show() /** * Want to Confirm the User Action? Just call showConfirmationDialog with required + optional params to do so. */ fun Context.showConfirmationDialog(msg: String, onResponse: (result: Boolean) -> Unit, positiveText: String = "Yes", negativeText: String = "No", cancelable: Boolean = false) = AlertDialog.Builder(this).setMessage(msg).setPositiveButton(positiveText) { _, _ -> onResponse(true) }.setNegativeButton( negativeText ) { _, _ -> onResponse(false) }.setCancelable(cancelable).show() /** * Want your user to choose Single thing from a bunch? call showSinglePicker and provide your options to choose from */ fun Context.showSinglePicker(choices: Array<String>, onResponse: (index: Int) -> Unit, checkedItemIndex: Int = -1) = AlertDialog.Builder(this).setSingleChoiceItems(choices, checkedItemIndex) { dialog, which -> onResponse(which) dialog.dismiss() }.show() /** * Want your user to choose Multiple things from a bunch? call showMultiPicker and provide your options to choose from */ fun Context.showMultiPicker(choices: Array<String>, onResponse: (index: Int, isChecked: Boolean) -> Unit, checkedItems: BooleanArray? = null) = AlertDialog.Builder(this).setMultiChoiceItems(choices, checkedItems) { _, which, isChecked -> onResponse( which, isChecked ) }.setPositiveButton("Done", null).show()
6
null
92
818
fe984e6bdeb95fb5819f27dcb12001dcfd911819
1,882
KAHelpers
MIT License
androidkeystore/src/main/java/com/mutualmobile/androidkeystore/android/crypto/ciper/CipherMM.kt
mutualmobile
141,567,313
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Text": 1, "YAML": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 13, "XML": 12, "Java": 2}
/* * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mutualmobile.androidkeystore.android.crypto.ciper import java.security.NoSuchAlgorithmException import java.security.NoSuchProviderException import javax.crypto.NoSuchPaddingException /** * Return a [javax.crypto.Cipher] that works for the API 18. */ object CipherJB { @Throws(NoSuchPaddingException::class, NoSuchAlgorithmException::class, NoSuchProviderException::class) fun get(): javax.crypto.Cipher { return javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL") } }
0
Kotlin
3
13
6c082078781c782c9232ebfdeba5db14ba62ce73
1,115
MMKeystore
Apache License 2.0
src/main/kotlin/io/layercraft/packetlib/packets/v1_19_3/login/clientbound/EncryptionBeginPacket.kt
Layercraft
531,857,310
false
null
package io.layercraft.packetlib.packets.v1_19_2.login.clientbound import io.layercraft.packetlib.packets.* import io.layercraft.packetlib.serialization.MinecraftProtocolDeserializeInterface import io.layercraft.packetlib.serialization.MinecraftProtocolSerializeInterface /** * Encryption Request | 0x01 | login | clientbound * * @param serverId serverId * @param publicKey publicKey * @param verifyToken verifyToken * @see <a href="https://wiki.vg/index.php?title=Protocol&oldid=17873#Encryption_Request">https://wiki.vg/Protocol#Encryption_Request</a> */ @MinecraftPacket(id = 0x01, state = PacketState.LOGIN, direction = PacketDirection.CLIENTBOUND) data class EncryptionBeginPacket( val serverId: String, val publicKey: ByteArray, val verifyToken: ByteArray, ) : ClientBoundPacket { companion object : PacketSerializer<EncryptionBeginPacket> { override fun deserialize(input: MinecraftProtocolDeserializeInterface<*>): EncryptionBeginPacket { val serverId = input.readString() val publicKey = input.readVarIntByteArray() val verifyToken = input.readVarIntByteArray() return EncryptionBeginPacket(serverId, publicKey, verifyToken) } override fun serialize(output: MinecraftProtocolSerializeInterface<*>, value: EncryptionBeginPacket) { output.writeString(value.serverId) output.writeVarIntByteArray(value.publicKey) output.writeVarIntByteArray(value.verifyToken) } } }
0
Kotlin
1
4
3491d690689369264101853861e1d5a572cde24f
1,518
PacketLib
MIT License
app/app/src/main/java/com/example/party_lojo_game/ui/adapter/EditYourQuestionsGridAdapter.kt
ajloinformatico
381,492,665
false
null
package com.example.party_lojo_game.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.example.party_lojo_game.databinding.RowSingleQuestionBinding import com.example.party_lojo_game.databinding.RowTitleEditYourQuestionBinding import com.example.party_lojo_game.databinding.RowUnknownBinding import com.example.party_lojo_game.ui.viewholders.EditYourQuestionsGridViewHolder import com.example.party_lojo_game.ui.vo.AskTypeVO import com.example.party_lojo_game.ui.vo.AsksVO import com.example.party_lojo_game.ui.vo.EditYourQuestionsEvents class EditYourQuestionsGridAdapter( private val event: (EditYourQuestionsEvents) -> Unit ) : ListAdapter<AsksVO, EditYourQuestionsGridViewHolder>(EditYourQuestionsDiffUtils()) { private var previousType: Int = -1 override fun getItem(position: Int): AsksVO? = currentList.getOrNull(position) override fun getItemViewType(position: Int): Int { return getItem(position)?.type?.ordinal ?: AskTypeVO.UNKNONW.ordinal } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): EditYourQuestionsGridViewHolder { val layoutInflater = LayoutInflater.from(parent.context) return when (viewType) { AskTypeVO.YO_NUNCA.ordinal, AskTypeVO.VERDAD_O_RETO.ordinal, AskTypeVO.BEBE_QUIEN.ordinal -> EditYourQuestionsGridViewHolder.SingleQuestionViewHolder( // Update with correct binding RowSingleQuestionBinding.inflate(layoutInflater, parent, false) ) AskTypeVO.TITLE.ordinal -> EditYourQuestionsGridViewHolder.TitleGroupViewHolder( RowTitleEditYourQuestionBinding.inflate(layoutInflater, parent, false) ) AskTypeVO.UNKNONW.ordinal -> EditYourQuestionsGridViewHolder.UnknownViewHolder( RowUnknownBinding.inflate(layoutInflater, parent, false) ) else -> { EditYourQuestionsGridViewHolder.UnknownViewHolder( RowUnknownBinding.inflate(layoutInflater, parent, false) ) } } } override fun onBindViewHolder(holder: EditYourQuestionsGridViewHolder, position: Int) { when (holder) { is EditYourQuestionsGridViewHolder.UnknownViewHolder -> { /*ignore*/ } is EditYourQuestionsGridViewHolder.SingleQuestionViewHolder -> { (getItem(position) as? AsksVO)?.let { holder.bind( ask = it, event = event ) } } is EditYourQuestionsGridViewHolder.TitleGroupViewHolder -> { (getItem(position) as? AsksVO.TitleAskVO)?.title?.let(holder::bind) } } } class EditYourQuestionsDiffUtils : DiffUtil.ItemCallback<AsksVO>() { override fun areItemsTheSame(oldItem: AsksVO, newItem: AsksVO): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: AsksVO, newItem: AsksVO): Boolean = oldItem == newItem } }
0
Kotlin
0
0
dc0b3f5b64110f2e528020d1851a73031fb25871
3,246
party-lojo-game
MIT License
compiler/testData/diagnostics/tests/inline/recursion.kt
JakeWharton
99,388,807
false
null
// FIR_IDENTICAL // CHECK_TYPE // DIAGNOSTICS: -NOTHING_TO_INLINE -UNUSED_PARAMETER -UNUSED_VARIABLE -NOTHING_TO_INLINE -VARIABLE_EXPECTED inline fun inlineFun(s: (p: Int) -> Unit) { <!RECURSION_IN_INLINE!>inlineFun<!>(s) } inline fun <T> inlineFun(s: T) { <!RECURSION_IN_INLINE!>inlineFun<!><Int>(11) } inline fun <T> Function0<T>.inlineExt() { (checkSubtype<Function0<Int>>({11})).<!RECURSION_IN_INLINE!>inlineExt<!>(); {11}.<!RECURSION_IN_INLINE!>inlineExt<!>() } inline operator fun <T, V> Function1<T, V>.not() : Boolean { return <!RECURSION_IN_INLINE!>!<!>this } inline operator fun <T, V> Function1<T, V>.inc() : Function1<T, V> { return this<!RECURSION_IN_INLINE!>++<!> }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
709
kotlin
Apache License 2.0
xml-parser-api/src/main/kotlin/com/valb3r/bpmn/intellij/plugin/bpmn/api/bpmn/elements/types/IntermediateThrowingEventAlike.kt
valb3r
261,109,342
false
null
package com.valb3r.bpmn.intellij.plugin.bpmn.api.bpmn.elements.types interface IntermediateThrowingEventAlike
76
Kotlin
20
81
760efb3d7e48970545d0d7622687d67c2b9b9693
110
flowable-bpmn-intellij-plugin
MIT License
src/backend/src/main/kotlin/org/icpclive/service/ScoreboardService.kt
icpc
447,849,919
false
null
package org.icpclive.service import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.icpclive.api.* import org.icpclive.data.DataBus import org.icpclive.scoreboard.getScoreboardCalculator import org.icpclive.util.getLogger class ScoreboardService(val optimismLevel: OptimismLevel) { suspend fun run( runsFlow: Flow<RunInfo>, contestInfoFlow: Flow<ContestInfo>, ) { logger.info("Scoreboard service for optimismLevel=${optimismLevel} started") coroutineScope { var info: ContestInfo? = null val runs = mutableMapOf<Int, RunInfo>() // We need mutex, as conflate runs part of flow before and after it in different coroutines // So we make part before as lightweight as possible, and just drops intermediate values val mutex = Mutex() merge(runsFlow, contestInfoFlow).mapNotNull { update -> when (update) { is RunInfo -> { mutex.withLock { val oldRun = runs[update.id] runs[update.id] = update if (oldRun != null && oldRun.result == update.result) { return@mapNotNull null } } } is ContestInfo -> { info = update } } // It would be nice to copy runs here to avoid mutex, but it is too slow info } .conflate() .map { getScoreboardCalculator(it, optimismLevel).getScoreboard(it, mutex.withLock { runs.values.toList() }) } .stateIn(this) .let { DataBus.setScoreboardEvents(optimismLevel, it) } } } companion object { val logger = getLogger(ScoreboardService::class) } }
14
Kotlin
7
25
097ca5e9f6dcac7175d7242579a44dde723bd772
2,052
live-v3
MIT License
downloader/src/funTest/kotlin/DownloaderTest.kt
andreas-bauer
165,835,940
false
null
/* * Copyright (C) 2017-2019 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package com.here.ort.downloader import com.here.ort.model.HashAlgorithm import com.here.ort.model.Identifier import com.here.ort.model.Package import com.here.ort.model.RemoteArtifact import com.here.ort.model.VcsInfo import com.here.ort.utils.safeDeleteRecursively import com.here.ort.utils.test.ExpensiveTag import io.kotlintest.TestCase import io.kotlintest.TestResult import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.kotlintest.shouldThrow import io.kotlintest.specs.StringSpec import java.io.File class DownloaderTest : StringSpec() { private lateinit var outputDir: File override fun beforeTest(testCase: TestCase) { outputDir = createTempDir() } override fun afterTest(testCase: TestCase, result: TestResult) { outputDir.safeDeleteRecursively(force = true) } init { "Downloads and unpacks JAR source package".config(tags = setOf(ExpensiveTag)) { val pkg = Package( id = Identifier( type = "Maven", namespace = "junit", name = "junit", version = "4.12" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = "https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12-sources.jar", hash = "a6c32b40bf3d76eca54e3c601e5d1470c86fcdfa", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo.EMPTY ) val downloadResult = Downloader().download(pkg, outputDir) downloadResult.vcsInfo shouldBe null downloadResult.sourceArtifact shouldNotBe null downloadResult.sourceArtifact!!.url shouldBe pkg.sourceArtifact.url downloadResult.sourceArtifact!!.hash shouldBe pkg.sourceArtifact.hash downloadResult.sourceArtifact!!.hashAlgorithm shouldBe pkg.sourceArtifact.hashAlgorithm val licenseFile = File(downloadResult.downloadDirectory, "LICENSE-junit.txt") licenseFile.isFile shouldBe true licenseFile.length() shouldBe 11376L downloadResult.downloadDirectory.walkTopDown().count() shouldBe 234 } "Download of JAR source package fails when hash is incorrect".config(tags = setOf(ExpensiveTag)) { val pkg = Package( id = Identifier( type = "Maven", namespace = "junit", name = "junit", version = "4.12" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = "https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12-sources.jar", hash = "0123456789abcdef0123456789abcdef01234567", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo.EMPTY ) val exception = shouldThrow<DownloadException> { Downloader().download(pkg, outputDir) } exception.cause shouldNotBe null exception.cause!!.message shouldBe "Source artifact does not match expected SHA-1 hash " + "'0123456789abcdef0123456789abcdef01234567'." } "Falls back to downloading source package when download from VCS fails".config(tags = setOf(ExpensiveTag)) { val pkg = Package( id = Identifier( type = "Maven", namespace = "junit", name = "junit", version = "4.12" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = "https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12-sources.jar", hash = "a6c32b40bf3d76eca54e3c601e5d1470c86fcdfa", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo( type = "Git", url = "https://example.com/invalid-repo-url", revision = "8964880d9bac33f0a7f030a74c7c9299a8f117c8" ) ) val downloadResult = Downloader().download(pkg, outputDir) downloadResult.vcsInfo shouldBe null downloadResult.sourceArtifact shouldNotBe null downloadResult.sourceArtifact!!.url shouldBe pkg.sourceArtifact.url downloadResult.sourceArtifact!!.hash shouldBe pkg.sourceArtifact.hash downloadResult.sourceArtifact!!.hashAlgorithm shouldBe pkg.sourceArtifact.hashAlgorithm val licenseFile = File(downloadResult.downloadDirectory, "LICENSE-junit.txt") licenseFile.isFile shouldBe true licenseFile.length() shouldBe 11376L downloadResult.downloadDirectory.walkTopDown().count() shouldBe 234 } "Can download source artifact from SourceForce".config(tags = setOf(ExpensiveTag)) { val url = "https://master.dl.sourceforge.net/project/tyrex/tyrex/Tyrex%201.0.1/tyrex-1.0.1-src.tgz" val pkg = Package( id = Identifier( type = "Maven", namespace = "tyrex", name = "tyrex", version = "1.0.1" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = url, hash = "49fe486f44197c8e5106ed7487526f77b597308f", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo.EMPTY ) val downloadResult = Downloader().download(pkg, outputDir) downloadResult.vcsInfo shouldBe null downloadResult.sourceArtifact shouldNotBe null downloadResult.sourceArtifact!!.url shouldBe pkg.sourceArtifact.url downloadResult.sourceArtifact!!.hash shouldBe pkg.sourceArtifact.hash downloadResult.sourceArtifact!!.hashAlgorithm shouldBe pkg.sourceArtifact.hashAlgorithm val tyrexDir = File(downloadResult.downloadDirectory, "tyrex-1.0.1") tyrexDir.isDirectory shouldBe true tyrexDir.walkTopDown().count() shouldBe 409 } } }
0
null
0
1
b0b8117a5eccc8c4c2833a1089c91c7eb0c2dcc9
8,015
oss-review-toolkit
Apache License 2.0
downloader/src/funTest/kotlin/DownloaderTest.kt
andreas-bauer
165,835,940
false
null
/* * Copyright (C) 2017-2019 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package com.here.ort.downloader import com.here.ort.model.HashAlgorithm import com.here.ort.model.Identifier import com.here.ort.model.Package import com.here.ort.model.RemoteArtifact import com.here.ort.model.VcsInfo import com.here.ort.utils.safeDeleteRecursively import com.here.ort.utils.test.ExpensiveTag import io.kotlintest.TestCase import io.kotlintest.TestResult import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.kotlintest.shouldThrow import io.kotlintest.specs.StringSpec import java.io.File class DownloaderTest : StringSpec() { private lateinit var outputDir: File override fun beforeTest(testCase: TestCase) { outputDir = createTempDir() } override fun afterTest(testCase: TestCase, result: TestResult) { outputDir.safeDeleteRecursively(force = true) } init { "Downloads and unpacks JAR source package".config(tags = setOf(ExpensiveTag)) { val pkg = Package( id = Identifier( type = "Maven", namespace = "junit", name = "junit", version = "4.12" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = "https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12-sources.jar", hash = "a6c32b40bf3d76eca54e3c601e5d1470c86fcdfa", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo.EMPTY ) val downloadResult = Downloader().download(pkg, outputDir) downloadResult.vcsInfo shouldBe null downloadResult.sourceArtifact shouldNotBe null downloadResult.sourceArtifact!!.url shouldBe pkg.sourceArtifact.url downloadResult.sourceArtifact!!.hash shouldBe pkg.sourceArtifact.hash downloadResult.sourceArtifact!!.hashAlgorithm shouldBe pkg.sourceArtifact.hashAlgorithm val licenseFile = File(downloadResult.downloadDirectory, "LICENSE-junit.txt") licenseFile.isFile shouldBe true licenseFile.length() shouldBe 11376L downloadResult.downloadDirectory.walkTopDown().count() shouldBe 234 } "Download of JAR source package fails when hash is incorrect".config(tags = setOf(ExpensiveTag)) { val pkg = Package( id = Identifier( type = "Maven", namespace = "junit", name = "junit", version = "4.12" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = "https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12-sources.jar", hash = "0123456789abcdef0123456789abcdef01234567", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo.EMPTY ) val exception = shouldThrow<DownloadException> { Downloader().download(pkg, outputDir) } exception.cause shouldNotBe null exception.cause!!.message shouldBe "Source artifact does not match expected SHA-1 hash " + "'0123456789abcdef0123456789abcdef01234567'." } "Falls back to downloading source package when download from VCS fails".config(tags = setOf(ExpensiveTag)) { val pkg = Package( id = Identifier( type = "Maven", namespace = "junit", name = "junit", version = "4.12" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = "https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12-sources.jar", hash = "a6c32b40bf3d76eca54e3c601e5d1470c86fcdfa", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo( type = "Git", url = "https://example.com/invalid-repo-url", revision = "8964880d9bac33f0a7f030a74c7c9299a8f117c8" ) ) val downloadResult = Downloader().download(pkg, outputDir) downloadResult.vcsInfo shouldBe null downloadResult.sourceArtifact shouldNotBe null downloadResult.sourceArtifact!!.url shouldBe pkg.sourceArtifact.url downloadResult.sourceArtifact!!.hash shouldBe pkg.sourceArtifact.hash downloadResult.sourceArtifact!!.hashAlgorithm shouldBe pkg.sourceArtifact.hashAlgorithm val licenseFile = File(downloadResult.downloadDirectory, "LICENSE-junit.txt") licenseFile.isFile shouldBe true licenseFile.length() shouldBe 11376L downloadResult.downloadDirectory.walkTopDown().count() shouldBe 234 } "Can download source artifact from SourceForce".config(tags = setOf(ExpensiveTag)) { val url = "https://master.dl.sourceforge.net/project/tyrex/tyrex/Tyrex%201.0.1/tyrex-1.0.1-src.tgz" val pkg = Package( id = Identifier( type = "Maven", namespace = "tyrex", name = "tyrex", version = "1.0.1" ), declaredLicenses = sortedSetOf(), description = "", homepageUrl = "", binaryArtifact = RemoteArtifact.EMPTY, sourceArtifact = RemoteArtifact( url = url, hash = "49fe486f44197c8e5106ed7487526f77b597308f", hashAlgorithm = HashAlgorithm.SHA1 ), vcs = VcsInfo.EMPTY ) val downloadResult = Downloader().download(pkg, outputDir) downloadResult.vcsInfo shouldBe null downloadResult.sourceArtifact shouldNotBe null downloadResult.sourceArtifact!!.url shouldBe pkg.sourceArtifact.url downloadResult.sourceArtifact!!.hash shouldBe pkg.sourceArtifact.hash downloadResult.sourceArtifact!!.hashAlgorithm shouldBe pkg.sourceArtifact.hashAlgorithm val tyrexDir = File(downloadResult.downloadDirectory, "tyrex-1.0.1") tyrexDir.isDirectory shouldBe true tyrexDir.walkTopDown().count() shouldBe 409 } } }
0
null
0
1
b0b8117a5eccc8c4c2833a1089c91c7eb0c2dcc9
8,015
oss-review-toolkit
Apache License 2.0
src/main/kotlin/jetbrains/buildServer/server/querylang/ast/Filter.kt
JetBrains
285,547,183
false
null
package jetbrains.buildServer.server.querylang.ast interface Filter<in FObject> : FilterBuilder<FObject>, Named, Printable { fun toCondition(): RealConditionAST<*> = FilterConditionNode(this) }
3
Kotlin
5
3
cb59d0c832c69d896e56baf814c45c34eb16f832
198
teamcity-search-ql
Apache License 2.0
unique-sdk/src/openApiGenerator/src/main/kotlin/network/unique/model/AllowedResponse.kt
UniqueNetwork
555,353,838
false
null
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package network.unique.model import com.squareup.moshi.Json /** * * * @param isAllowed */ data class AllowanceResultResponse ( @Json(name = "isAllowed") val isAllowed: kotlin.Boolean )
0
null
0
3
0f5afacd0cb7b7411bc78307f3a22c8d02a14e69
479
unique-sdk-kotlin
MIT License
feature/core/src/main/kotlin/com/masselis/tpmsadvanced/core/feature/interfaces/viewmodel/CurrentVehicleDropdownViewModel.kt
VincentMasselis
501,773,706
false
{"Kotlin": 382337}
package com.masselis.tpmsadvanced.core.feature.interfaces.viewmodel import android.os.Parcelable import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.masselis.tpmsadvanced.core.feature.usecase.CurrentVehicleUseCase import com.masselis.tpmsadvanced.core.feature.usecase.VehicleListUseCase import com.masselis.tpmsadvanced.core.ui.asMutableStateFlow import com.masselis.tpmsadvanced.data.car.model.Vehicle import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.parcelize.Parcelize @OptIn(ExperimentalCoroutinesApi::class) internal class CurrentVehicleDropdownViewModel @AssistedInject constructor( private val currentVehicleUseCase: CurrentVehicleUseCase, vehicleListUseCase: VehicleListUseCase, @Assisted savedStateHandle: SavedStateHandle, ) : ViewModel() { @AssistedFactory interface Factory { fun build(savedStateHandle: SavedStateHandle): CurrentVehicleDropdownViewModel } sealed class State : Parcelable { @Parcelize object Loading : State() @Parcelize data class Vehicles( val current: Vehicle, val list: List<Vehicle>, ) : State() } private val mutableStateFlow = savedStateHandle .getLiveData<State>("STATE", State.Loading) .asMutableStateFlow() val stateFlow = mutableStateFlow.asStateFlow() init { combine( currentVehicleUseCase.flow.flatMapLatest { it.carFlow }, vehicleListUseCase.vehicleListFlow ) { current, list -> State.Vehicles(current, list.sortedBy { it.name }) }.onEach { mutableStateFlow.value = it } .launchIn(viewModelScope) } fun setCurrent(vehicle: Vehicle) = viewModelScope.launch { currentVehicleUseCase.setAsCurrent(vehicle) } fun insert(carName: String, kind: Vehicle.Kind) = viewModelScope.launch { currentVehicleUseCase.insertAsCurrent(carName, kind) } }
6
Kotlin
1
1
6c0624dc94da5a1ce54c03eb156aa8f489ebf82f
2,371
TPMS-advanced
Apache License 2.0
livekit-android-sdk/src/main/java/io/livekit/android/LiveKit.kt
livekit
339,892,560
false
null
/* * Copyright 2023 LiveKit, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.livekit.android import android.app.Application import android.content.Context import io.livekit.android.dagger.DaggerLiveKitComponent import io.livekit.android.dagger.RTCModule import io.livekit.android.dagger.create import io.livekit.android.room.ProtocolVersion import io.livekit.android.room.Room import io.livekit.android.room.RoomListener import io.livekit.android.util.LKLog import io.livekit.android.util.LoggingLevel import timber.log.Timber class LiveKit { companion object { /** * [LoggingLevel] to use for Livekit logs. Set to [LoggingLevel.OFF] to turn off logs. * * Defaults to [LoggingLevel.OFF] */ @JvmStatic var loggingLevel: LoggingLevel get() = LKLog.loggingLevel set(value) { LKLog.loggingLevel = value // Plant debug tree if needed. if (value != LoggingLevel.OFF) { val forest = Timber.forest() val needsPlanting = forest.none { it is Timber.DebugTree } if (needsPlanting) { Timber.plant(Timber.DebugTree()) } } } /** * Enables logs for the underlying WebRTC sdk logging. Used in conjunction with [loggingLevel]. * * Note: WebRTC logging is very noisy and should only be used to diagnose native WebRTC issues. */ @JvmStatic var enableWebRTCLogging: Boolean = false /** * Certain WebRTC classes need to be initialized prior to use. * * This does not need to be called under normal circumstances, as [LiveKit.create] * will handle this for you. */ fun init(appContext: Context) { RTCModule.libWebrtcInitialization(appContext) } /** * Create a Room object. */ fun create( appContext: Context, options: RoomOptions = RoomOptions(), overrides: LiveKitOverrides = LiveKitOverrides(), ): Room { val ctx = appContext.applicationContext if (ctx !is Application) { LKLog.w { "Application context was not found, this may cause memory leaks." } } val component = DaggerLiveKitComponent .factory() .create(ctx, overrides) val room = component.roomFactory().create(ctx) options.audioTrackCaptureDefaults?.let { room.audioTrackCaptureDefaults = it } options.videoTrackCaptureDefaults?.let { room.videoTrackCaptureDefaults = it } options.audioTrackPublishDefaults?.let { room.audioTrackPublishDefaults = it } options.videoTrackPublishDefaults?.let { room.videoTrackPublishDefaults = it } room.adaptiveStream = options.adaptiveStream room.dynacast = options.dynacast return room } /** * Connect to a LiveKit room * @param url URL to LiveKit server (i.e. ws://mylivekitdeploy.io) * @param listener Listener to Room events. LiveKit interactions take place with these callbacks */ @Deprecated("Use LiveKit.create and Room.connect instead. This is limited to max protocol 7.") suspend fun connect( appContext: Context, url: String, token: String, options: ConnectOptions = ConnectOptions(), roomOptions: RoomOptions = RoomOptions(), listener: RoomListener? = null, overrides: LiveKitOverrides = LiveKitOverrides(), ): Room { val room = create(appContext, roomOptions, overrides) room.listener = listener val protocolVersion = maxOf(options.protocolVersion, ProtocolVersion.v7) val connectOptions = options.copy(protocolVersion = protocolVersion) room.connect(url, token, connectOptions) return room } } }
62
null
69
176
41e5aa67852e79939ec196586039b6de477d5cc1
4,765
client-sdk-android
Apache License 2.0
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/context/DokumentContext.kt
navikt
487,246,438
false
{"Kotlin": 946725, "Shell": 1318, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.vedtak.context import no.nav.tiltakspenger.meldekort.ports.DokumentGateway import no.nav.tiltakspenger.vedtak.Configuration import no.nav.tiltakspenger.vedtak.auth.AzureTokenProvider import no.nav.tiltakspenger.vedtak.clients.dokument.DokumentHttpClient @Suppress("unused") open class DokumentContext { private val tokenProviderDokument by lazy { AzureTokenProvider(config = Configuration.oauthConfigDokument()) } open val dokumentGateway: DokumentGateway by lazy { DokumentHttpClient( baseUrl = Configuration.dokumentClientConfig().baseUrl, getToken = tokenProviderDokument::getToken, ) } }
9
Kotlin
0
1
61d70015b3dcd251a3286f634c9c8f77013449b3
675
tiltakspenger-vedtak
MIT License
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/kotlin/views/AnyViewProp.kt
derekstavis
184,342,737
true
{"Objective-C": 20602533, "Java": 13690880, "C++": 11626391, "Kotlin": 5359352, "TypeScript": 4619500, "Objective-C++": 4368983, "Swift": 1078083, "JavaScript": 1013246, "Starlark": 712574, "Ruby": 519774, "C": 282818, "Makefile": 193716, "Shell": 54009, "Assembly": 46734, "HTML": 36667, "CMake": 26275, "CSS": 1306, "Batchfile": 89}
package abi44_0_0.expo.modules.kotlin.views import android.view.View import abi44_0_0.com.facebook.react.bridge.Dynamic abstract class AnyViewProp( val name: String ) { abstract fun set(prop: Dynamic, onView: View) }
1
Objective-C
1
2
e377f0cd22db5cd7feb8e80348cd7064db5429b1
223
expo
MIT License
src/org/ice1000/tt/editing/mlang/folding.kt
owo-lang
174,763,486
false
null
package org.ice1000.tt.editing.mlang import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilderEx import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.ice1000.tt.FOLDING_PLACEHOLDER import org.ice1000.tt.MlangFile import org.ice1000.tt.editing.collectFoldRegions import org.ice1000.tt.psi.* import org.ice1000.tt.psi.mlang.* class MlangFoldingBuilder : FoldingBuilderEx(), DumbAware { override fun getPlaceholderText(node: ASTNode) = when (node.elementType) { MlangTypes.LET_EXPR, MlangTypes.RECORD_EXPR, MlangTypes.SUM_EXPR, MlangTypes.PARAMETERS -> "{$FOLDING_PLACEHOLDER}" MlangTokenType.LINE_COMMENT -> "//..." MlangTokenType.BLOCK_COMMENT -> "/***/" else -> FOLDING_PLACEHOLDER } override fun isCollapsedByDefault(node: ASTNode) = false override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> { if (root !is MlangFile) return emptyArray() return collectFoldRegions(root) { FoldingVisitor(it, document) } } } private class FoldingVisitor( private val descriptors: MutableList<FoldingDescriptor>, private val document: Document ) : MlangVisitor() { override fun visitComment(comment: PsiComment) { descriptors += FoldingDescriptor(comment, comment.textRange) } override fun visitLetExpr(o: MlangLetExpr) = foldBetweenBraces(o) override fun visitRecordExpr(o: MlangRecordExpr) = foldBetweenBraces(o) override fun visitSumExpr(o: MlangSumExpr) = foldBetweenBraces(o) override fun visitParameters(o: MlangParameters) = foldBetweenBraces(o) private fun foldBetweenBraces(o: PsiElement) { val lBrace = o.childrenWithLeaves.firstOrNull { it.elementType == MlangTypes.LBRACE } ?: return val rBrace = lBrace.rightSiblings.firstOrNull { it.elementType == MlangTypes.RBRACE } ?: return descriptors += FoldingDescriptor(o, TextRange(lBrace.startOffset, rBrace.endOffset)) } }
5
null
5
35
7e601041978a0497db7d4cf3bcf4971f532235cd
2,099
intellij-dtlc
Apache License 2.0
lib/src/main/kotlin/inc/kaizen/service/sprout/generator/impl/ModelConverterClassGenerator.kt
kaizen-inc
857,464,993
false
{"Kotlin": 76712}
package inc.kaizen.service.sprout.generator.impl import com.google.devtools.ksp.symbol.KSClassDeclaration import inc.kaizen.service.sprout.extension.capitalizeFirstLetter import inc.kaizen.service.sprout.extension.findComplexType import inc.kaizen.service.sprout.extension.toCamelCase import inc.kaizen.service.sprout.generator.* class ModelConverterClassGenerator: IClassContentGenerator { override fun generateContent(extensions: Map<String, Any>) = buildString { val packageName = extensions[PACKAGE_NAME] val serviceName = extensions[SERVICE_NAME] as String val className = extensions[CLASS_NAME] val modelPackageName = extensions[MODEL_PACKAGE_NAME] val basePackaageName = extensions[BASE_PACKAGE_NAME] val capitalizeServiceName = serviceName.capitalizeFirstLetter() val modelClass = extensions["model"] as KSClassDeclaration val complexFields = modelClass.findComplexType() appendLine("package $packageName") appendLine() appendLine("import org.springframework.stereotype.Component") appendLine("import java.util.UUID") appendLine("import org.mapstruct.Mapper") appendLine("import org.mapstruct.Mapping") appendLine("import org.mapstruct.Mappings") appendLine("import org.springframework.core.convert.converter.Converter") appendLine("import $modelPackageName.$capitalizeServiceName") appendLine("import $basePackaageName.$serviceName.model.entity.${capitalizeServiceName}Entity") complexFields.iterator().forEach { appendLine("import $modelPackageName.${it.type}") appendLine("import $basePackaageName.${it.type.toString().toCamelCase()}.model.entity.${it.type}Entity") } appendLine() appendLine("@Mapper(componentModel = \"spring\"/*, config = MappingConfiguration::class*/)") appendLine("abstract class ${className}: Converter<${capitalizeServiceName}Entity, ${capitalizeServiceName}> {") appendLine() complexFields.asIterable().forEach { appendLine(" @Mappings(") appendLine(" Mapping(target = \"${it}\", expression = \"java(fetch${it.type}(entity.get${it.type}()))\")") appendLine(" )") } appendLine(" abstract override fun convert(entity: ${capitalizeServiceName}Entity): $capitalizeServiceName") appendLine() complexFields.iterator().forEach { appendLine(" protected fun fetch${it.type}(entity: ${it.type}Entity) = entity.id") appendLine() } appendLine("}") } override fun classNameSuffix() = "Converter" override fun packageName(basePackageName: String, serviceName: String) = "$basePackageName.$serviceName.converter" }
0
Kotlin
0
0
d0d922506cd337e717fa1091fa2065eea4bc3e9f
2,809
Sprout
MIT License
app/src/main/java/com/justin/huang/maskmap/viewModel/DrugStoreViewModel.kt
justin74
244,567,887
false
{"Kotlin": 23014}
package com.justin.huang.maskmap.viewModel import androidx.lifecycle.* import com.justin.huang.maskmap.db.DrugStore import com.justin.huang.maskmap.repository.MaskPointsRepository import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject class DrugStoreViewModel @Inject constructor(private val repository: MaskPointsRepository) : ViewModel() { val drugStores: LiveData<List<DrugStore>> = repository.getDrugStoreList() init { viewModelScope.launch { Timber.d("viewModel init") repository.fetchMaskPoints() } } }
0
Kotlin
0
0
2297ef5d72751431e0b7ecf6e7d46cf5b158d333
597
MaskMap
Apache License 2.0
src/main/kotlin/br/com/webbudget/application/payloads/StateFilter.kt
web-budget
354,665,828
false
null
package br.com.webbudget.application.payloads.support enum class StateFilter(val value: Boolean?) { ALL(null), ACTIVE(true), INACTIVE(false) }
4
null
1
1
0407ee25f55f74dfa11c4806e560a7589cba37ca
148
back-end
Apache License 2.0
features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemEventRowTimestampPreview.kt
element-hq
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.messages.impl.timeline.components import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.features.messages.impl.timeline.aTimelineItemReactions import io.element.android.features.messages.impl.timeline.model.TimelineItem import io.element.android.features.messages.impl.timeline.model.event.TimelineItemTextContent import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight @PreviewsDayNight @Composable internal fun TimelineItemEventRowTimestampPreview( @PreviewParameter(TimelineItemEventForTimestampViewProvider::class) event: TimelineItem.Event ) = ElementPreview { Column { val oldContent = event.content as TimelineItemTextContent listOf( "Text", "Text longer, displayed on 1 line", "Text which should be rendered on several lines", ).forEach { str -> ATimelineItemEventRow( event = event.copy( content = oldContent.copy( body = str, ), reactionsState = aTimelineItemReactions(count = 0), ), ) } } }
263
null
94
955
31d0621fa15fe153bfd36104e560c9703eabe917
1,977
element-x-android
Apache License 2.0
objects/src/commonMain/kotlin/ru/krindra/vkkt/objects/users/UsersUser.kt
krindra
780,080,411
false
{"Kotlin": 1336107}
package ru.krindra.vkkt.objects.users import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import ru.krindra.vkkt.objects.base.BaseBoolInt import ru.krindra.vkkt.objects.base.BaseSex import ru.krindra.vkkt.objects.friends.FriendsRequestsMutual import ru.krindra.vkkt.objects.friends.FriendsFriendStatusStatus /** * * @param sex User sex * @param screenName Domain name of the user's page * @param photo50 URL of square photo of the user with 50 pixels in width * @param photo100 URL of square photo of the user with 100 pixels in width * @param onlineInfo * @param online Information whether the user is online * @param onlineMobile Information whether the user is online in mobile site or application * @param onlineApp Application ID * @param verified Information whether the user is verified * @param trending Information whether the user has a "fire" pictogram. * @param friendStatus * @param mutual * @param deactivated Returns if a profile is deleted or blocked * @param firstName User first name * @param hidden Returns if a profile is hidden. * @param id User ID * @param lastName User last name * @param canAccessClosed * @param isClosed */ @Serializable data class UsersUser ( @SerialName("id") val id: Int, @SerialName("sex") val sex: BaseSex? = null, @SerialName("hidden") val hidden: Int? = null, @SerialName("photo_50") val photo50: String? = null, @SerialName("online_app") val onlineApp: Int? = null, @SerialName("last_name") val lastName: String? = null, @SerialName("online") val online: BaseBoolInt? = null, @SerialName("photo_100") val photo100: String? = null, @SerialName("is_closed") val isClosed: Boolean? = null, @SerialName("first_name") val firstName: String? = null, @SerialName("screen_name") val screenName: String? = null, @SerialName("trending") val trending: BaseBoolInt? = null, @SerialName("verified") val verified: BaseBoolInt? = null, @SerialName("deactivated") val deactivated: String? = null, @SerialName("mutual") val mutual: FriendsRequestsMutual? = null, @SerialName("online_info") val onlineInfo: UsersOnlineInfo? = null, @SerialName("online_mobile") val onlineMobile: BaseBoolInt? = null, @SerialName("can_access_closed") val canAccessClosed: Boolean? = null, @SerialName("friend_status") val friendStatus: FriendsFriendStatusStatus? = null, )
0
Kotlin
0
1
58407ea02fc9d971f86702f3b822b33df65dd3be
2,421
VKKT
MIT License
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/shadow/ShadowTargetInspection.kt
Earthcomputer
240,984,777
true
{"Gradle Kotlin DSL": 2, "Markdown": 2, "YAML": 3, "Text": 16, "Java Properties": 3, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "XML": 28, "INI": 6, "Java": 3, "Groovy": 4, "HAProxy": 2, "Kotlin": 554, "SVG": 1, "HTML": 39, "JFlex": 4}
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.shadow import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.demonwav.mcdev.platform.mixin.util.resolveShadowTargets import com.demonwav.mcdev.util.ifEmpty import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.RemoveAnnotationQuickFix import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiMember import com.intellij.psi.PsiModifierList class ShadowTargetInspection : MixinInspection() { override fun getStaticDescription() = "Validates targets of @Shadow members" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitAnnotation(annotation: PsiAnnotation) { if (annotation.qualifiedName != SHADOW) { return } val modifierList = annotation.owner as? PsiModifierList ?: return val member = modifierList.parent as? PsiMember ?: return val psiClass = member.containingClass ?: return val targetClasses = psiClass.mixinTargets.ifEmpty { return } val targets = resolveShadowTargets(annotation, targetClasses, member) ?: return if (targets.size >= targetClasses.size) { // Everything is fine, bye return } // Oh :(, maybe we can help? (TODO: Maybe later) // Write quick fix and apply it for OverwriteTargetInspection and ShadowTargetInspection holder.registerProblem(annotation, "Cannot resolve member '${member.name}' in target class", RemoveAnnotationQuickFix(annotation, member)) } } }
1
Kotlin
2
23
ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5
2,135
MinecraftDev
MIT License
app/src/main/java/com/liorhass/android/medsstocktracker/eventlist/EventListViewModelFactory.kt
liorhass
268,994,559
false
null
package com.liorhass.android.medsstocktracker.eventlist import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.liorhass.android.medsstocktracker.database.LoggedEventsDao // Boilerplate code of a ViewModel-factory - provides the DAO and app context to the ViewModel class EventListViewModelFactory( private val dataSource: LoggedEventsDao ) : ViewModelProvider.Factory { @Suppress("unchecked_cast") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(EventListViewModel::class.java)) { return EventListViewModel(dataSource) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
Kotlin
0
0
27ef2050e0d959e3b5ae280b8e198fa905f7e21e
727
MedsStockTracker
MIT License
coil-core/src/androidMain/kotlin/coil3/target/ImageViewTarget.kt
coil-kt
201,684,760
false
{"Kotlin": 955603, "Shell": 2360, "JavaScript": 209}
package coil3.target import android.graphics.drawable.Drawable import android.widget.ImageView import coil3.annotation.Data /** * A [Target] that handles setting images on an [ImageView]. */ @Data open class ImageViewTarget( override val view: ImageView, ) : GenericViewTarget<ImageView>() { override var drawable: Drawable? get() = view.drawable set(value) = view.setImageDrawable(value) }
39
Kotlin
626
9,954
9b3f851b2763b4c72a3863f8273b8346487b363b
420
coil
Apache License 2.0
core/ui/src/main/java/com/msg/ui/util/timeFormatter.kt
School-of-Company
700,744,250
false
null
package com.msg.ui.util import java.time.LocalTime import java.time.format.DateTimeFormatter fun LocalTime.toLocalTimeFormat(): String { val formatter = DateTimeFormatter.ofPattern("HH:mm:ss") return this.format(formatter) } fun LocalTime.toKoreanFormat(): String { val dateTimeFormatter = DateTimeFormatter.ofPattern("HH시 mm분") return this.format(dateTimeFormatter) }
7
null
1
22
358bf40188fa2fc2baf23aa6b308b039cb3fbc8c
388
Bitgoeul-Android
MIT License
domain/src/main/java/com/yablunin/shopnstock/domain/repositories/ShoppingListHandlerRepository.kt
yabluninn
702,962,028
false
{"Kotlin": 126063}
package com.yablunin.shopnstock.domain.repositories import com.yablunin.shopnstock.domain.constants.ListConstants import com.yablunin.shopnstock.domain.models.ShoppingList import com.yablunin.shopnstock.domain.models.User import kotlin.random.Random class ShoppingListHandlerRepository: ListHandlerRepository { override fun addList(list: ShoppingList, user: User) { user.shoppingLists.add(list) } override fun removeList(list: ShoppingList, user: User) { user.shoppingLists.remove(list) } override fun getListById(user: User, id: Int): ShoppingList? { return user.shoppingLists.find {it.id == id} } override fun generateListId(user: User): Int { val randomId: Int = Random.nextInt(0, 100000) if (getListById(user, randomId) == null){ return randomId } else{ return generateListId(user) } } override fun copyList(copyAction: Int, list: ShoppingList, user: User): ShoppingList { var copiedListName = "" if (list.name.endsWith("(copy)")){ copiedListName = list.name } else{ copiedListName = list.name + " (copy)" } val copiedList = ShoppingList(generateListId(user), copiedListName) when(copyAction){ ListConstants.COPY_WHOLE_LIST -> { for (item in list.list){ copiedList.list.add(item) } } ListConstants.COPY_PURCHASED_ITEMS_LIST -> { for (item in list.list){ if (item.purchased){ copiedList.list.add(item) } } } ListConstants.COPY_UNPURCHASED_ITEMS_LIST -> { for (item in list.list){ if (!item.purchased){ copiedList.list.add(item) } } } } return copiedList } override fun renameList(list: ShoppingList, newName: String, user: User) { user.shoppingLists.find { it.id == list.id }!!.name = newName } }
0
Kotlin
0
3
eb1b9e2f0ceda62b0cc57173034b3186aef7e3e2
2,165
shopnstock
MIT License
src/commonTest/kotlin/nl/jacobras/humanreadable/HumanReadableRelativeTimeTests.kt
jacobras
696,961,730
false
{"Kotlin": 15061}
package nl.jacobras.humanreadable import assertk.assertThat import assertk.assertions.isEqualTo import io.github.skeptick.libres.LibresSettings import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlin.test.Test import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds class HumanReadableRelativeTimeTests { init { LibresSettings.languageCode = "en" } private val now: Instant get() = Clock.System.now() @Test fun inFuture() { assertThat(HumanReadable.timeAgo(now + 200.seconds)).isEqualTo("in 3 minutes") } @Test fun now() { assertThat(HumanReadable.timeAgo(now)).isEqualTo("now") } @Test fun inPast() { assertThat(HumanReadable.timeAgo(now - 3.days)).isEqualTo("3 days ago") } }
4
Kotlin
7
96
2598757f57081807cedda6195681f5adb9da6c5e
871
Human-Readable
MIT License
app/src/main/java/com/example/philosophyquotes/data/data_source/QuotesDAO.kt
WillACosta
536,141,267
false
{"Kotlin": 38147}
package com.example.philosophyquotes.data.data_source import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.example.philosophyquotes.data.model.Quote @Dao interface QuotesDAO { @Insert fun save(quote: Quote): Long @Query("DELETE from QUOTE WHERE id = :id") fun delete(id: Int) @Query("SELECT * FROM QUOTE") fun getAll(): List<Quote> @Query("SELECT * FROM QUOTE WHERE id = :id") fun getByID(id: Int): Quote? }
0
Kotlin
0
0
6dced3869dbae7ff1deddf04c0e6903804d964e1
511
philosophy_quotes
Apache License 2.0
app/src/main/java/com/petrulak/cleankotlin/ui/base/BaseFragment.kt
Petrulak
104,648,833
false
null
package com.petrulak.cleankotlin.ui.base import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.petrulak.cleankotlin.platform.bus.event.EventBus import javax.inject.Inject abstract class BaseFragment : Fragment() { @Inject lateinit var eventBus: EventBus open fun initializeDependencies() {} @LayoutRes protected abstract fun layoutId(): Int override fun onCreate(savedInstanceState: Bundle?) { initializeDependencies() super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater!!.inflate(layoutId(), container, false) } }
0
null
10
111
51033f30ecdb9573000454f1b8890d20c2438002
841
android-kotlin-mvp-clean-architecture
MIT License
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/frontend/fir/Fir2IrJvmResultsConverter.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "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.test.frontend.fir import org.jetbrains.kotlin.backend.common.IrSpecialAnnotationsProvider import org.jetbrains.kotlin.backend.common.actualizer.IrExtraActualDeclarationExtractor import org.jetbrains.kotlin.backend.jvm.* import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace import org.jetbrains.kotlin.codegen.ClassBuilderFactories import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector import org.jetbrains.kotlin.fir.backend.Fir2IrComponents import org.jetbrains.kotlin.fir.backend.Fir2IrVisibilityConverter import org.jetbrains.kotlin.fir.backend.jvm.* import org.jetbrains.kotlin.fir.backend.utils.extractFirDeclarations import org.jetbrains.kotlin.fir.pipeline.Fir2IrActualizedResult import org.jetbrains.kotlin.fir.pipeline.Fir2KlibMetadataSerializer import org.jetbrains.kotlin.ir.IrBuiltIns import org.jetbrains.kotlin.ir.backend.jvm.serialization.JvmIrMangler import org.jetbrains.kotlin.ir.types.IrTypeSystemContext import org.jetbrains.kotlin.ir.util.KotlinMangler import org.jetbrains.kotlin.library.metadata.KlibMetadataFactories import org.jetbrains.kotlin.library.metadata.resolver.KotlinResolvedLibrary import org.jetbrains.kotlin.test.backend.ir.IrBackendInput import org.jetbrains.kotlin.test.model.TestModule import org.jetbrains.kotlin.test.services.TestServices import org.jetbrains.kotlin.test.services.compilerConfigurationProvider @InternalFir2IrConverterAPI internal class Fir2IrJvmResultsConverter(testServices: TestServices) : AbstractFir2IrResultsConverter(testServices) { override fun createIrMangler(): KotlinMangler.IrMangler = JvmIrMangler override fun createFir2IrExtensions(compilerConfiguration: CompilerConfiguration): JvmFir2IrExtensions { return JvmFir2IrExtensions(compilerConfiguration, JvmIrDeserializerImpl()) } override fun createFir2IrVisibilityConverter(): Fir2IrVisibilityConverter { return FirJvmVisibilityConverter } override fun createTypeSystemContextProvider(): (IrBuiltIns) -> IrTypeSystemContext { return ::JvmIrTypeSystemContext } override fun createSpecialAnnotationsProvider(): IrSpecialAnnotationsProvider { return JvmIrSpecialAnnotationSymbolProvider } override fun createExtraActualDeclarationExtractorInitializer(): (Fir2IrComponents) -> List<IrExtraActualDeclarationExtractor> { return { listOfNotNull( FirJvmBuiltinProviderActualDeclarationExtractor.initializeIfNeeded(it), FirDirectJavaActualDeclarationExtractor.initializeIfNeeded(it) ) } } override fun resolveLibraries(module: TestModule, compilerConfiguration: CompilerConfiguration): List<KotlinResolvedLibrary> { val compilerConfigurationProvider = testServices.compilerConfigurationProvider // Create and initialize the module and its dependencies compilerConfigurationProvider.getProject(module) return emptyList() } override val klibFactories: KlibMetadataFactories get() = error("Should not be called") override fun createBackendInput( module: TestModule, compilerConfiguration: CompilerConfiguration, diagnosticReporter: BaseDiagnosticsCollector, inputArtifact: FirOutputArtifact, fir2IrResult: Fir2IrActualizedResult, fir2KlibMetadataSerializer: Fir2KlibMetadataSerializer, ): IrBackendInput { val phaseConfig = compilerConfiguration.get(CLIConfigurationKeys.PHASE_CONFIG) // TODO: handle fir from light tree val sourceFiles = inputArtifact.mainFirFiles.mapNotNull { it.value.sourceFile } val backendInput = JvmIrCodegenFactory.JvmIrBackendInput( fir2IrResult.irModuleFragment, fir2IrResult.symbolTable, phaseConfig, fir2IrResult.components.irProviders, createFir2IrExtensions(compilerConfiguration), FirJvmBackendExtension( fir2IrResult.components, fir2IrResult.irActualizedResult?.actualizedExpectDeclarations?.extractFirDeclarations(), ), fir2IrResult.pluginContext, notifyCodegenStart = {}, ) val project = testServices.compilerConfigurationProvider.getProject(module) val codegenFactory = JvmIrCodegenFactory(compilerConfiguration, phaseConfig) val generationState = GenerationState.Builder( project, ClassBuilderFactories.TEST, fir2IrResult.irModuleFragment.descriptor, NoScopeRecordCliBindingTrace(project).bindingContext, compilerConfiguration ).isIrBackend( true ).jvmBackendClassResolver( FirJvmBackendClassResolver(fir2IrResult.components) ).diagnosticReporter( diagnosticReporter ).build() return IrBackendInput.JvmIrBackendInput( generationState, codegenFactory, backendInput, sourceFiles, descriptorMangler = null, irMangler = fir2IrResult.components.irMangler, ) } }
184
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
5,513
kotlin
Apache License 2.0
idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggester.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.core import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.lexer.KotlinLexer import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getOutermostParenthesizerOrThis import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getParentResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeSmart import java.util.* object KotlinNameSuggester { fun suggestNamesByExpressionAndType( expression: KtExpression, type: KotlinType?, bindingContext: BindingContext?, validator: (String) -> Boolean, defaultName: String? ): Collection<String> { val result = LinkedHashSet<String>() result.addNamesByExpression(expression, bindingContext, validator) (type ?: bindingContext?.getType(expression))?.let { result.addNamesByType(it, validator) } if (result.isEmpty()) { result.addName(defaultName, validator) } return result } fun suggestNamesByType(type: KotlinType, validator: (String) -> Boolean, defaultName: String? = null): List<String> { val result = ArrayList<String>() result.addNamesByType(type, validator) if (result.isEmpty()) { result.addName(defaultName, validator) } return result } fun suggestNamesByExpressionOnly( expression: KtExpression, bindingContext: BindingContext?, validator: (String) -> Boolean, defaultName: String? = null): List<String> { val result = ArrayList<String>() result.addNamesByExpression(expression, bindingContext, validator) if (result.isEmpty()) { result.addName(defaultName, validator) } return result } fun suggestIterationVariableNames( collection: KtExpression, elementType: KotlinType, bindingContext: BindingContext?, validator: (String) -> Boolean, defaultName: String?): Collection<String> { val result = LinkedHashSet<String>() suggestNamesByExpressionOnly(collection, bindingContext, { true }) .mapNotNull { StringUtil.unpluralize(it) } .mapTo(result) { suggestNameByName(it, validator) } result.addNamesByType(elementType, validator) if (result.isEmpty()) { result.addName(defaultName, validator) } return result } private val COMMON_TYPE_PARAMETER_NAMES = listOf("T", "U", "V", "W", "X", "Y", "Z") fun suggestNamesForTypeParameters(count: Int, validator: (String) -> Boolean): List<String> { val result = ArrayList<String>() for (i in 0..count - 1) { result.add(suggestNameByMultipleNames(COMMON_TYPE_PARAMETER_NAMES, validator)) } return result } /** * Validates name, and slightly improves it by adding number to name in case of conflicts * @param name to check it in scope * @return name or nameI, where I is number */ fun suggestNameByName(name: String, validator: (String) -> Boolean): String { if (validator(name)) return name var i = 1 while (!validator(name + i)) { ++i } return name + i } /** * Validates name using set of variants which are tried in succession (and extended with suffixes if necessary) * For example, when given sequence of a, b, c possible names are tried out in the following order: a, b, c, a1, b1, c1, a2, b2, c2, ... * @param names to check it in scope * @return name or nameI, where name is one of variants and I is a number */ fun suggestNameByMultipleNames(names: Collection<String>, validator: (String) -> Boolean): String { var i = 0 while (true) { for (name in names) { val candidate = if (i > 0) name + i else name if (validator(candidate)) return candidate } i++ } } private fun MutableCollection<String>.addNamesByType(type: KotlinType, validator: (String) -> Boolean) { var type = TypeUtils.makeNotNullable(type) // wipe out '?' val builtIns = type.builtIns val typeChecker = KotlinTypeChecker.DEFAULT if (ErrorUtils.containsErrorType(type)) return if (typeChecker.equalTypes(builtIns.booleanType, type)) { addName("b", validator) } else if (typeChecker.equalTypes(builtIns.intType, type)) { addName("i", validator) } else if (typeChecker.equalTypes(builtIns.byteType, type)) { addName("byte", validator) } else if (typeChecker.equalTypes(builtIns.longType, type)) { addName("l", validator) } else if (typeChecker.equalTypes(builtIns.floatType, type)) { addName("fl", validator) } else if (typeChecker.equalTypes(builtIns.doubleType, type)) { addName("d", validator) } else if (typeChecker.equalTypes(builtIns.shortType, type)) { addName("sh", validator) } else if (typeChecker.equalTypes(builtIns.charType, type)) { addName("c", validator) } else if (typeChecker.equalTypes(builtIns.stringType, type)) { addName("s", validator) } else if (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) { val elementType = builtIns.getArrayElementType(type) if (typeChecker.equalTypes(builtIns.booleanType, elementType)) { addName("booleans", validator) } else if (typeChecker.equalTypes(builtIns.intType, elementType)) { addName("ints", validator) } else if (typeChecker.equalTypes(builtIns.byteType, elementType)) { addName("bytes", validator) } else if (typeChecker.equalTypes(builtIns.longType, elementType)) { addName("longs", validator) } else if (typeChecker.equalTypes(builtIns.floatType, elementType)) { addName("floats", validator) } else if (typeChecker.equalTypes(builtIns.doubleType, elementType)) { addName("doubles", validator) } else if (typeChecker.equalTypes(builtIns.shortType, elementType)) { addName("shorts", validator) } else if (typeChecker.equalTypes(builtIns.charType, elementType)) { addName("chars", validator) } else if (typeChecker.equalTypes(builtIns.stringType, elementType)) { addName("strings", validator) } else { val classDescriptor = TypeUtils.getClassDescriptor(elementType) if (classDescriptor != null) { val className = classDescriptor.name addName("arrayOf" + StringUtil.capitalize(className.asString()) + "s", validator) } } } else if (type.isFunctionType) { addName("function", validator) } else { val descriptor = type.constructor.declarationDescriptor if (descriptor != null) { val className = descriptor.name if (!className.isSpecial) { addCamelNames(className.asString(), validator) } } } } private val ACCESSOR_PREFIXES = arrayOf("get", "is", "set") fun getCamelNames(name: String, validator: (String) -> Boolean, startLowerCase: Boolean): List<String> { val result = ArrayList<String>() result.addCamelNames(name, validator, startLowerCase) return result } private fun MutableCollection<String>.addCamelNames(name: String, validator: (String) -> Boolean, startLowerCase: Boolean = true) { if (name === "") return var s = extractIdentifiers(name) for (prefix in ACCESSOR_PREFIXES) { if (!s.startsWith(prefix)) continue val len = prefix.length if (len < s.length && Character.isUpperCase(s[len])) { s = s.substring(len) break } } var upperCaseLetterBefore = false for (i in 0..s.length - 1) { val c = s[i] val upperCaseLetter = Character.isUpperCase(c) if (i == 0) { addName(if (startLowerCase) s.decapitalizeSmart() else s, validator) } else { if (upperCaseLetter && !upperCaseLetterBefore) { val substring = s.substring(i) addName(if (startLowerCase) substring.decapitalizeSmart() else substring, validator) } } upperCaseLetterBefore = upperCaseLetter } } private fun extractIdentifiers(s: String): String { return buildString { val lexer = KotlinLexer() lexer.start(s) while (lexer.tokenType != null) { if (lexer.tokenType == KtTokens.IDENTIFIER) { append(lexer.tokenText) } lexer.advance() } } } private fun MutableCollection<String>.addNamesByExpressionPSI(expression: KtExpression?, validator: (String) -> Boolean) { if (expression == null) return val deparenthesized = KtPsiUtil.safeDeparenthesize(expression) when (deparenthesized) { is KtSimpleNameExpression -> addCamelNames(deparenthesized.getReferencedName(), validator) is KtQualifiedExpression -> addNamesByExpressionPSI(deparenthesized.selectorExpression, validator) is KtCallExpression -> addNamesByExpressionPSI(deparenthesized.calleeExpression, validator) is KtPostfixExpression -> addNamesByExpressionPSI(deparenthesized.baseExpression, validator) } } private fun MutableCollection<String>.addNamesByExpression( expression: KtExpression?, bindingContext: BindingContext?, validator: (String) -> Boolean ) { if (expression == null) return addNamesByValueArgument(expression, bindingContext, validator) addNamesByExpressionPSI(expression, validator) } private fun MutableCollection<String>.addNamesByValueArgument( expression: KtExpression, bindingContext: BindingContext?, validator: (String) -> Boolean ) { if (bindingContext == null) return val argumentExpression = expression.getOutermostParenthesizerOrThis() val valueArgument = argumentExpression.parent as? KtValueArgument ?: return val resolvedCall = argumentExpression.getParentResolvedCall(bindingContext) ?: return val argumentMatch = resolvedCall.getArgumentMapping(valueArgument) as? ArgumentMatch ?: return val parameter = argumentMatch.valueParameter if (parameter.containingDeclaration.hasStableParameterNames()) { addName(parameter.name.asString(), validator) } } private fun MutableCollection<String>.addName(name: String?, validator: (String) -> Boolean) { if (name == null) return val correctedName = when { isIdentifier(name) -> name name == "class" -> "clazz" else -> return } add(suggestNameByName(correctedName, validator)) } fun isIdentifier(name: String?): Boolean { if (name == null || name.isEmpty()) return false val lexer = KotlinLexer() lexer.start(name, 0, name.length) if (lexer.tokenType !== KtTokens.IDENTIFIER) return false lexer.advance() return lexer.tokenType == null } }
186
null
4323
83
4383335168338df9bbbe2a63cb213a68d0858104
13,081
kotlin
Apache License 2.0
android/src/main/kotlin/com/hellobike/flutter/thrio/navigator/PageObservers.kt
hellobike
237,804,349
false
null
/** * The MIT License (MIT) * * Copyright (c) 2019 Hellobike Group * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.hellobike.flutter.thrio.module import com.hellobike.flutter.thrio.navigator.* import com.hellobike.flutter.thrio.registry.RegistrySet internal object ModulePageObservers : PageObserver { private const val TAG = "ModulePageObservers" val observers by lazy { RegistrySet<PageObserver>() } init { observers.registry(FlutterEngineFactory) } override fun willAppear(routeSettings: RouteSettings) { observers.forEach { it.willAppear(routeSettings) } Log.i( TAG, "willAppear: url->${routeSettings.url} " + "index->${routeSettings.index} " ) } override fun didAppear(routeSettings: RouteSettings) { observers.forEach { it.didAppear(routeSettings) } Log.i( TAG, "didAppear: url->${routeSettings.url} " + "index->${routeSettings.index} " ) PageRoutes.lastRouteHolder(routeSettings.url, routeSettings.index)?.activity?.get()?.apply { NavigationController.Notify.doNotify(this) } } override fun willDisappear(routeSettings: RouteSettings) { observers.forEach { it.willDisappear(routeSettings) } Log.i( TAG, "willDisappear: url->${routeSettings.url} " + "index->${routeSettings.index} " ) } override fun didDisappear(routeSettings: RouteSettings) { observers.forEach { it.didDisappear(routeSettings) } Log.i( TAG, "didDisappear: url->${routeSettings.url} " + "index->${routeSettings.index} " ) } }
8
null
77
739
7d47dd231e68dfa8e952691ec5e974b0663ff00e
2,839
flutter_thrio
MIT License
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustTraitTypeMemberImplMixin.kt
nicompte
60,753,746
true
{"Git Config": 1, "Gradle": 2, "Markdown": 8, "Java Properties": 2, "Shell": 1, "Text": 70, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Rust": 387, "XML": 34, "HTML": 18, "RenderScript": 2, "TOML": 7, "Kotlin": 295, "Java": 5, "JFlex": 1}
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import org.rust.lang.core.psi.RustTraitTypeMemberElement import org.rust.lang.core.psi.impl.RustNamedElementImpl abstract class RustTraitTypeMemberImplMixin(node: ASTNode) : RustNamedElementImpl(node) , RustTraitTypeMemberElement { }
0
Kotlin
0
0
283f8ac1b441147c1227ebc5992b7dc75fbbacb0
370
intellij-rust
MIT License
coil-base/src/test/java/coil/fetch/HttpUriFetcherTest.kt
coil-kt
201,684,760
false
null
package coil.fetch import android.content.Context import android.os.NetworkOnMainThreadException import android.webkit.MimeTypeMap import androidx.core.net.toUri import androidx.test.core.app.ApplicationProvider import coil.ImageLoader import coil.decode.DataSource import coil.decode.FileImageSource import coil.decode.SourceImageSource import coil.disk.DiskCache import coil.request.CachePolicy import coil.request.Options import coil.util.Time import coil.util.createMockWebServer import coil.util.createTestMainDispatcher import coil.util.enqueueImage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import okhttp3.Call import okhttp3.Headers import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okio.blackholeSink import okio.buffer import okio.sink import okio.source import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows import java.io.File import java.net.HttpURLConnection.HTTP_NOT_MODIFIED import java.util.UUID import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) @OptIn(ExperimentalCoroutinesApi::class) class HttpUriFetcherTest { private lateinit var context: Context private lateinit var mainDispatcher: TestCoroutineDispatcher private lateinit var server: MockWebServer private lateinit var diskCache: DiskCache private lateinit var callFactory: Call.Factory private lateinit var imageLoader: ImageLoader @Before fun before() { context = ApplicationProvider.getApplicationContext() mainDispatcher = createTestMainDispatcher() server = createMockWebServer() diskCache = DiskCache.Builder(context) .directory(File("build/cache")) .maxSizeBytes(10L * 1024 * 1024) // 10MB .build() callFactory = OkHttpClient() imageLoader = ImageLoader.Builder(context) .callFactory(callFactory) .diskCache(diskCache) .build() } @After fun after() { Dispatchers.resetMain() Time.reset() server.shutdown() imageLoader.shutdown() diskCache.clear() diskCache.directory.deleteRecursively() // Ensure we start fresh. } @Test fun `basic network fetch`() { val expectedSize = server.enqueueImage(IMAGE) val url = server.url(IMAGE).toString() val result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } @Test fun `mime type is parsed correctly from content type`() { val fetcher = HttpUriFetcher("error", Options(context), lazyOf(callFactory), lazyOf(diskCache), true) // https://android.googlesource.com/platform/frameworks/base/+/61ae88e/core/java/android/webkit/MimeTypeMap.java#407 Shadows.shadowOf(MimeTypeMap.getSingleton()) .addExtensionMimeTypMapping("svg", "image/svg+xml") val url1 = "https://www.example.com/image.jpg" val type1 = "image/svg+xml".toMediaType() assertEquals("image/svg+xml", fetcher.getMimeType(url1, type1)) val url2 = "https://www.example.com/image.svg" val type2: MediaType? = null assertEquals("image/svg+xml", fetcher.getMimeType(url2, type2)) val url3 = "https://www.example.com/image" val type3 = "image/svg+xml;charset=utf-8".toMediaType() assertEquals("image/svg+xml", fetcher.getMimeType(url3, type3)) val url4 = "https://www.example.com/image.svg" val type4 = "text/plain".toMediaType() assertEquals("image/svg+xml", fetcher.getMimeType(url4, type4)) val url5 = "https://www.example.com/image" val type5: MediaType? = null assertNull(fetcher.getMimeType(url5, type5)) } @Test fun `request on main thread throws NetworkOnMainThreadException`() { server.enqueueImage(IMAGE) val url = server.url(IMAGE).toString() val fetcher = newFetcher(url) runBlocking(Dispatchers.Main.immediate) { assertFailsWith<NetworkOnMainThreadException> { fetcher.fetch() } } } @Test fun `no disk cache - fetcher returns a source result`() { val expectedSize = server.enqueueImage(IMAGE) val url = server.url(IMAGE).toString() val result = runBlocking { newFetcher(url, diskCache = null).fetch() } assertTrue(result is SourceResult) assertTrue(result.source is SourceImageSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } @Test fun `request on main thread with network cache policy disabled executes without throwing`() { val expectedSize = server.enqueueImage(IMAGE) val url = server.url(IMAGE).toString() // Write the image in the disk cache. val editor = diskCache.edit(url)!! editor.data.sink().buffer().use { it.writeAll(context.assets.open(IMAGE).source()) } editor.commit() // Load it from the disk cache on the main thread. val result = runBlocking(Dispatchers.Main.immediate) { newFetcher(url, options = Options(context, networkCachePolicy = CachePolicy.DISABLED)).fetch() } assertTrue(result is SourceResult) assertNotNull(result.source.fileOrNull()) assertEquals(DataSource.DISK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } @Test fun `no cached file - fetcher returns the file`() { val expectedSize = server.enqueueImage(IMAGE) val url = server.url(IMAGE).toString() val result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) val source = result.source assertTrue(source is FileImageSource) // Ensure we can read the source. assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) // Ensure the result file is present. diskCache[url]!!.use { snapshot -> assertTrue(snapshot.data in diskCache.directory.listFiles().orEmpty()) assertEquals(snapshot.data, source.file) } } @Test fun `existing cached file - fetcher returns the file`() { val url = server.url(IMAGE).toString() // Run the fetcher once to create the disk cache file. var expectedSize = server.enqueueImage(IMAGE) var result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertTrue(result.source is FileImageSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) // Run the fetcher a second time. expectedSize = server.enqueueImage(IMAGE) result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertTrue(result.source is FileImageSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) // Ensure the result file is present. val expected = diskCache[url]?.data assertTrue(expected in diskCache.directory.listFiles().orEmpty()) assertEquals(expected, (result.source as FileImageSource).file) } @Test fun `cache control - empty metadata is always returned`() { val url = server.url(IMAGE).toString() val editor = diskCache.edit(url)!! editor.data.sink().buffer().use { it.writeAll(context.assets.open(IMAGE).source()) } editor.commit() val result = runBlocking { newFetcher(url).fetch() } assertEquals(0, server.requestCount) assertTrue(result is SourceResult) assertEquals(DataSource.DISK, result.dataSource) } @Test fun `cache control - no-store is never cached or returned`() { val url = server.url(IMAGE).toString() val headers = Headers.Builder() .set("Cache-Control", "no-store") .build() var expectedSize = server.enqueueImage(IMAGE, headers) var result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) diskCache[url].use(::assertNull) expectedSize = server.enqueueImage(IMAGE, headers) result = runBlocking { newFetcher(url).fetch() } assertEquals(2, server.requestCount) assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } @Test fun `cache control - respectCacheHeaders=false is always cached and returned`() { val url = server.url(IMAGE).toString() val headers = Headers.Builder() .set("Cache-Control", "no-store") .build() var expectedSize = server.enqueueImage(IMAGE, headers) var result = runBlocking { newFetcher(url, respectCacheHeaders = false).fetch() } assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) diskCache[url].use(::assertNotNull) expectedSize = server.enqueueImage(IMAGE, headers) result = runBlocking { newFetcher(url, respectCacheHeaders = false).fetch() } assertEquals(1, server.requestCount) assertTrue(result is SourceResult) assertEquals(DataSource.DISK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } @Test fun `cache control - cached response is verified and returned from the cache`() { val url = server.url(IMAGE).toString() val etag = UUID.randomUUID().toString() val headers = Headers.Builder() .set("Cache-Control", "no-cache") .set("ETag", etag) .build() val expectedSize = server.enqueueImage(IMAGE, headers) var result = runBlocking { newFetcher(url).fetch() } assertEquals(1, server.requestCount) server.takeRequest() // Discard the first request. assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) diskCache[url].use(::assertNotNull) // Don't set a response body as it should be read from the cache. server.enqueue(MockResponse().setResponseCode(HTTP_NOT_MODIFIED)) result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) // Ensure we passed the correct etag. assertEquals(2, server.requestCount) assertEquals(etag, server.takeRequest().headers["If-None-Match"]) } @Test fun `cache control - unexpired max-age is returned from cache`() { val url = server.url(IMAGE).toString() val headers = Headers.Builder() .set("Cache-Control", "max-age=60") .build() var expectedSize = server.enqueueImage(IMAGE, headers) var result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) diskCache[url].use(::assertNotNull) expectedSize = server.enqueueImage(IMAGE, headers) result = runBlocking { newFetcher(url).fetch() } assertEquals(1, server.requestCount) assertTrue(result is SourceResult) assertEquals(DataSource.DISK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } @Test fun `cache control - expired max-age is not returned from cache`() { val url = server.url(IMAGE).toString() val now = System.currentTimeMillis() val headers = Headers.Builder() .set("Cache-Control", "max-age=60") .build() var expectedSize = server.enqueueImage(IMAGE, headers) var result = runBlocking { newFetcher(url).fetch() } assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) diskCache[url].use(::assertNotNull) // Increase the current time. Time.setCurrentMillis(now + 65_000) expectedSize = server.enqueueImage(IMAGE, headers) result = runBlocking { newFetcher(url).fetch() } assertEquals(2, server.requestCount) assertTrue(result is SourceResult) assertEquals(DataSource.NETWORK, result.dataSource) assertEquals(expectedSize, result.source.use { it.source().readAll(blackholeSink()) }) } private fun newFetcher( url: String, options: Options = Options(context), respectCacheHeaders: Boolean = true, diskCache: DiskCache? = this.diskCache ): Fetcher { val factory = HttpUriFetcher.Factory(lazyOf(callFactory), lazyOf(diskCache), respectCacheHeaders) return checkNotNull(factory.create(url.toUri(), options, imageLoader)) { "fetcher == null" } } companion object { private const val IMAGE = "normal.jpg" } }
43
null
620
9,812
051e0b20969ff695d69b06cd72a1fdc9e504bf68
14,399
coil
Apache License 2.0
Others/kt_misc/pkt_9/LayoutInts.kt
duangsuse-valid-projects
163,751,200
false
null
val item = RepeatUn(asInt(), digitFor('0'..'9')) { i -> i.toString().map { it - '0' } } val tail = Seq(::CharTuple, item('-'),item('>')).toStringPat() val layout = Convert(Repeat(asString(), item(' ')).Many() prefix item('\n'), { it.length }, { "".padStart(it) }) val p = LayoutPattern(item, tail, layout) val slash = item('/') val comment = Seq(::StringTuple, elementIn('#', ';').toStringPat(), *anyChar until newlineChar) val field = Repeat(asString(), !slash).clamWhile(!slash, "") {"empty field"} val line = JoinBy(slash, field).mergeConstantJoin() val record = Decide(comment, line).mergeFirst { if (it is StringTuple) 0 else 1 } val slashSepValues = JoinBy(newlineChar, record)
4
null
1
4
e89301b326713bf949bcf9fbaa3992e83c2cba88
685
Share
MIT License
app/src/main/java/com/thenetcircle/dinoandroidframework/fragment/TNCRoomListFragment.kt
thenetcircle
116,897,773
false
null
/* * Copyright 2018 The NetCircle * * 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.thenetcircle.dinoandroidframework.fragment import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.text.TextUtils import android.util.Base64 import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import com.thenetcircle.dino.model.results.RequestRoomListResult import com.thenetcircle.dino.model.results.RoomObject import com.thenetcircle.dinoandroidframework.R import kotlinx.android.synthetic.main.fragment_room_list.* import java.nio.charset.Charset /** * Created by aaron on 16/01/2018. */ class TNCRoomListFragment : Fragment(), View.OnClickListener { interface RoomListListener { fun createRoom(roomName: String, toUserID: Int) fun joinRoom(roomID: String) } var roomListInterface: RoomListListener? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_room_list, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) create_room.setOnClickListener { if (!TextUtils.isEmpty(room_name.text) && !TextUtils.isEmpty(user_id.text)) { roomListInterface?.createRoom(room_name.text.toString(), user_id.text.toString().toInt()) } } loadingRooms() } override fun onAttach(context: Context?) { super.onAttach(context) roomListInterface = context as RoomListListener } fun loadingRooms() { progress_wheel.visibility = View.VISIBLE room_list_container.removeAllViews() } fun listRooms(roomList: RequestRoomListResult) { room_list_container.removeAllViews() progress_wheel.visibility = View.GONE for (ob: RoomObject in roomList.data!!.objectX.attachments) { val b = Button(activity) b.text = String(Base64.decode(ob.displayName, Base64.NO_WRAP), Charset.defaultCharset()) b.tag = ob.id b.setOnClickListener(this) room_list_container.addView(b) } } override fun onClick(v: View) { roomListInterface?.joinRoom(v.tag as String) } }
0
null
1
3
2d8849eead991147243746f34f95c9d6d5d4557e
2,942
dino-android-framework
Apache License 2.0
core/src/main/java/com/peterfarlow/core/service/HttpClient.kt
prfarlow1
808,781,012
false
{"Kotlin": 21118}
package com.peterfarlow.core.service import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.engine.okhttp.OkHttp import io.ktor.client.plugins.ResponseException import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.serialization.kotlinx.json.json import io.ktor.util.reflect.TypeInfo import kotlinx.serialization.json.Json import okhttp3.logging.HttpLoggingInterceptor import timber.log.Timber class HttpClient( private val apiKey: String ) { private val httpClient = HttpClient(OkHttp) { engine { config { addInterceptor(HttpLoggingInterceptor { Timber.tag("Http").d(it) }.apply { level = HttpLoggingInterceptor.Level.BODY redactHeader("x-api-key") }) } } expectSuccess = true install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } } suspend fun <T> get(url: String, typeInfo: TypeInfo): T? { val response = try { httpClient.get(url) { header("x-api-key", apiKey) } } catch (exception: ResponseException) { Timber.e(exception, "Failed to get cats") null } return response?.body(typeInfo) } }
0
Kotlin
0
0
85f4df26576bb98187fe16d76f3064f31230b7e0
1,515
SentryAndroidCodeownersDemo
The Unlicense
compiler/testData/codegen/box/primitiveTypes/nullAsNullableIntIsNull.kt
BradOselo
367,097,840
false
null
// DONT_TARGET_EXACT_BACKEND: WASM // WASM_MUTE_REASON: EXCEPTIONS_NOT_IMPLEMENTED fun box(): String { try { if ((null as Int?)!! == 10) return "Fail #1" return "Fail #2" } catch (e: Exception) { return "OK" } }
0
null
0
3
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
252
kotlin
Apache License 2.0
platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/log/AttributesLogInterceptor.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vfs.newvfs.persistent.log import com.intellij.openapi.vfs.newvfs.AttributeOutputStream import com.intellij.openapi.vfs.newvfs.FileAttribute import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSConnection import com.intellij.openapi.vfs.newvfs.persistent.intercept.AttributesInterceptor import com.intellij.openapi.vfs.newvfs.persistent.log.VfsLogOperationTrackingContext.Companion.trackOperation import com.intellij.openapi.vfs.newvfs.persistent.log.VfsLogOperationTrackingContext.Companion.trackPlainOperation class AttributesLogInterceptor( private val context: VfsLogOperationTrackingContext, private val interceptMask: VfsOperationTagsMask = VfsOperationTagsMask.AttributesMask ) : AttributesInterceptor { override fun onWriteAttribute(underlying: (connection: PersistentFSConnection, fileId: Int, attribute: FileAttribute) -> AttributeOutputStream): (connection: PersistentFSConnection, fileId: Int, attribute: FileAttribute) -> AttributeOutputStream = if (VfsOperationTag.ATTR_WRITE_ATTR !in interceptMask) underlying else { connection, fileId, attribute -> context.trackOperation(VfsOperationTag.ATTR_WRITE_ATTR) { val aos = underlying(connection, fileId, attribute) object : AttributeOutputStream(aos) { private var wasClosed: Boolean = false override fun writeEnumeratedString(str: String?) = aos.writeEnumeratedString(str) override fun close() { if (wasClosed) { super.close() return } else { wasClosed = true val data = aos.asByteArraySequence().toBytes(); { super.close() } catchResult { completeTracking { val payloadRef = context.payloadWriter(data) val attrIdEnumerated = context.enumerateAttribute(attribute) VfsOperation.AttributesOperation.WriteAttribute(fileId, attrIdEnumerated, payloadRef, it) } } } } } } } override fun onDeleteAttributes(underlying: (connection: PersistentFSConnection, fileId: Int) -> Unit): (connection: PersistentFSConnection, fileId: Int) -> Unit = if (VfsOperationTag.ATTR_DELETE_ATTRS !in interceptMask) underlying else { connection, fileId -> context.trackPlainOperation(VfsOperationTag.ATTR_DELETE_ATTRS, { VfsOperation.AttributesOperation.DeleteAttributes(fileId, it) }) { underlying(connection, fileId) } } override fun onSetVersion(underlying: (version: Int) -> Unit): (version: Int) -> Unit = if (VfsOperationTag.ATTR_SET_VERSION !in interceptMask) underlying else { version -> context.trackPlainOperation(VfsOperationTag.ATTR_SET_VERSION, { VfsOperation.AttributesOperation.SetVersion(version, it) }) { underlying(version) } } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,014
intellij-community
Apache License 2.0
src/main/kotlin/jp/co/youmeee/app/Result.kt
youmitsu
124,651,300
false
null
package jp.co.youmeee.app class Result(val arr: Array<SourceList>, val sizeAll: Int)
0
Kotlin
1
2
7c5dff343bc49e658419aa23fc75508ca1fd8cc8
98
KotlinReplaceSupporter
MIT License
util/src/main/java/com/jokubas/mmdb/util/extensions/WindowExtensions.kt
Jokubas126
235,866,403
false
null
package com.jokubas.mmdb.util.extensions import android.os.Build import android.view.View import android.view.Window import android.view.WindowInsetsController import androidx.annotation.ColorRes import androidx.core.content.ContextCompat fun Window.adjustStatusBar(@ColorRes colorRes: Int) { statusBarColor = ContextCompat.getColor(context, colorRes) setLightStatusBar(true) } fun Window.setLightStatusBar(light: Boolean) { when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { val appearance = if (light) WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS else WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS.inv() decorView.windowInsetsController?.setSystemBarsAppearance(appearance, appearance) } Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> { var flags = decorView.systemUiVisibility flags = if (light) { flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } decorView.systemUiVisibility = flags } } }
0
Kotlin
1
1
96500633698bc414d433547f9b3ebdb456ab1f46
1,172
MobileMovieDatabase
MIT License
gradle/build-logic/convention/src/main/kotlin/dev/chrisbanes/gradle/Android.kt
chrisbanes
710,434,447
false
{"Kotlin": 71417, "Shell": 1077}
// Copyright 2023, <NAME> and the Haze project contributors // SPDX-License-Identifier: Apache-2.0 package dev.chrisbanes.gradle import com.android.build.gradle.BaseExtension import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.kotlin.dsl.configure fun Project.configureAndroid() { android { compileSdkVersion(Versions.COMPILE_SDK) defaultConfig { minSdk = Versions.MIN_SDK targetSdk = Versions.TARGET_SDK } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } } } private fun Project.android(action: BaseExtension.() -> Unit) = extensions.configure<BaseExtension>(action)
7
Kotlin
12
611
8001574e5ab02786cd963fe9e7ed6851812cb7b4
712
haze
Apache License 2.0
zip/src/test/java/com/microsoft/zip/Resources.kt
sayan-chaliha
359,348,228
false
null
/* * Copyright (c) 2021 Microsoft Corporation. * All Rights Reserved * * MIT License * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.microsoft.zip import java.io.File object Resources { private val classLoader: ClassLoader = Resources::class.java.classLoader!! fun file(name: String): File = File(classLoader.getResource(name).toURI()) }
0
Kotlin
0
0
f094180ec28140cde8e6dec34654e07c4704adc8
1,394
remote-zip-android
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/auth/TLAuthorization.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api.auth import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32 import com.github.badoualy.telegram.tl.api.TLAbsUser import com.github.badoualy.telegram.tl.api.TLUserEmpty import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * auth.authorization#cd050916 * * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLAuthorization() : TLAbsAuthorization() { var tmpSessions: Int? = null var user: TLAbsUser = TLUserEmpty() private val _constructor: String = "auth.authorization#cd050916" override val constructorId: Int = CONSTRUCTOR_ID constructor(tmpSessions: Int?, user: TLAbsUser) : this() { this.tmpSessions = tmpSessions this.user = user } override fun computeFlags() { _flags = 0 updateFlags(tmpSessions, 1) } @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { computeFlags() writeInt(_flags) doIfMask(tmpSessions, 1) { writeInt(it) } writeTLObject(user) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { _flags = readInt() tmpSessions = readIfMask(1) { readInt() } user = readTLObject<TLAbsUser>() } override fun computeSerializedSize(): Int { computeFlags() var size = SIZE_CONSTRUCTOR_ID size += SIZE_INT32 size += getIntIfMask(tmpSessions, 1) { SIZE_INT32 } size += user.computeSerializedSize() return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLAuthorization) return false if (other === this) return true return _flags == other._flags && tmpSessions == other.tmpSessions && user == other.user } companion object { const val CONSTRUCTOR_ID: Int = 0xcd050916.toInt() } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
2,278
kotlogram-resurrected
MIT License
backend.native/tests/codegen/classDelegation/method.kt
JetBrains
58,957,623
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.classDelegation.method import kotlin.test.* interface A<T> { fun foo(): T } class B : A<String> { override fun foo() = "OK" } class C(a: A<String>) : A<String> by a fun box(): String { val c = C(B()) val a: A<String> = c return c.foo() + a.foo() } @Test fun runTest() { println(box()) }
0
Kotlin
625
7,100
9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa
484
kotlin-native
Apache License 2.0
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/download/ui/DownloadView.kt
BioforestChain
594,577,896
false
{"Kotlin": 2673868, "TypeScript": 704141, "Swift": 350138, "Vue": 146618, "SCSS": 39016, "Objective-C": 17350, "Shell": 11193, "HTML": 10807, "JavaScript": 3998, "CSS": 818}
package org.dweb_browser.browser.download.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import org.dweb_browser.browser.BrowserI18nResource import org.dweb_browser.browser.common.CommonSimpleTopBar import org.dweb_browser.browser.download.DownloadState import org.dweb_browser.browser.download.model.DownloadTab import org.dweb_browser.browser.download.model.LocalDownloadModel import org.dweb_browser.helper.compose.LazySwipeColumn @Composable fun DownloadView() { DownloadHistory() DecompressView() } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DownloadHistory() { val viewModel = LocalDownloadModel.current val scope = rememberCoroutineScope() Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) ) { CommonSimpleTopBar(title = BrowserI18nResource.top_bar_title_download()) { scope.launch { viewModel.close() } } SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { viewModel.tabItems.forEachIndexed { index, downloadTab -> SegmentedButton( selected = index == viewModel.tabIndex.value, onClick = { viewModel.tabIndex.value = index }, shape = RoundedCornerShape(16.dp), icon = { Icon( imageVector = downloadTab.vector, contentDescription = downloadTab.title() ) }, label = { Text(text = downloadTab.title()) } ) } } DownloadTabView() } } @Composable fun DownloadTabView() { val viewModel = LocalDownloadModel.current val decompressModel = LocalDecompressModel.current val downloadTab = viewModel.tabItems[viewModel.tabIndex.value] val list = viewModel.downloadController.downloadList.filter { downloadTab == DownloadTab.Downloads || it.status.state == DownloadState.Completed } LazySwipeColumn( items = list, key = { item -> item.id }, onRemove = { item -> viewModel.removeDownloadTask(item)}, noDataValue = BrowserI18nResource.no_download_links() ) { downloadTask -> DownloadItem(downloadTask) { decompressModel.show(it) } } }
54
Kotlin
4
11
2a129afdf353564b3dd93ad2ad6dd6528c43413b
2,863
dweb_browser
MIT License
app/shared/feature-flag/public/src/commonMain/kotlin/build/wallet/feature/flags/UtxoConsolidationFeatureFlag.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.feature.flags import build.wallet.feature.FeatureFlag import build.wallet.feature.FeatureFlagDao import build.wallet.feature.FeatureFlagValue.BooleanFlag /** * Flag determining whether a customer can use UTXO consolidation feature (aka self send). */ class UtxoConsolidationFeatureFlag( featureFlagDao: FeatureFlagDao, ) : FeatureFlag<BooleanFlag>( identifier = "mobile-utxo-consolidation-is-enabled", title = "UTXO Consolidation", description = "Allows to consolidate UTXOs", defaultFlagValue = BooleanFlag(false), featureFlagDao = featureFlagDao, type = BooleanFlag::class )
3
C
16
113
694c152387c1fdb2b6be01ba35e0a9c092a81879
630
bitkey
MIT License
maverics/src/test/kotlin/com/example/services/uservalidation/UserNameTest.kt
3Anushka
598,963,822
false
null
package com.example.services.uservalidation import com.example.services.createUser import com.example.validations.checkUserName import com.example.validations.isUniqueUsername import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class UserNameTest { @Test fun `Valid username`() { // Arrange val userNames: List<String> = listOf( "satyam", "SatBal", "Satttt", "bbc" ) for (userName in userNames) { // Act val userNameValidation = checkUserName(userName) assertFalse(userNameValidation) } } @Test fun `username containing @ & slash # is invalid`() { // Arrange val userNames: List<String> = listOf( "sat@yam", "&SatBal", "Sat#", "/" ) for (userName in userNames) { // Act val userNameValidation = checkUserName(userName) assertTrue(userNameValidation) } } @Test fun `username already exists in invalid`() { // Arrange val userName = "sat" createUser("Satyam", "Baldawa", "8983517226", "<EMAIL>", userName) val userNameValidation = isUniqueUsername(userName) assertFalse(userNameValidation) } @Test fun `username if not already exists in valid`() { // Arrange val userName = "sat" val userName2 = "yam" createUser("Satyam", "Baldawa", "8983517226", "<EMAIL>", userName) val userNameValidation = isUniqueUsername(userName2) assertTrue(userNameValidation) } }
0
Kotlin
0
0
0d75917ba64dbf30d7bc010b48ae839b86aab70e
1,666
mavericks-anushka-pair
Apache License 2.0
language-markdown/src/main/kotlin/com/blacksquircle/ui/language/markdown/lexer/MarkdownToken.kt
massivemadness
608,535,719
false
null
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.language.markdown.lexer enum class MarkdownToken { HEADER, UNORDERED_LIST_ITEM, ORDERED_LIST_ITEM, BOLDITALIC1, BOLDITALIC2, BOLD1, BOLD2, ITALIC1, ITALIC2, STRIKETHROUGH, CODE, CODE_BLOCK, LT, GT, EQ, NOT, DIV, MINUS, LPAREN, RPAREN, LBRACE, RBRACE, LBRACK, RBRACK, URL, IDENTIFIER, WHITESPACE, BAD_CHARACTER, EOF }
45
null
46
5
ff4ca02822671ec25f7da374283b253716ec4509
1,074
EditorKit
Apache License 2.0
src/main/kotlin/com/github/quanticheart/intellijplugincleantree/wizard/cleanArch/recipes/data/DataRecipe.kt
quanticheart
519,671,971
false
{"Kotlin": 115237, "Java": 237}
package com.github.quanticheart.intellijplugincleantree.wizard.cleanArch.recipes.data import com.android.tools.idea.wizard.template.ModuleTemplateData import com.android.tools.idea.wizard.template.RecipeExecutor import com.github.quanticheart.intellijplugincleantree.wizard.cleanArch.data.* import java.util.* fun RecipeExecutor.dataRecipe( moduleData: ModuleTemplateData, featureName: String, packageName: String ) { val (_, srcOut, _) = moduleData /** * Packages */ val featurePackage = "${packageName}.${featureName.toLowerCase()}" //data val repositoryImplName = "${featureName}RepositoryImpl" val endPointsName = "${featureName}EndPoints" /** * Paths */ val basePath = featureName.toLowerCase(Locale.getDefault()) /** * Create Files */ /** * Data */ val repositoryImpl = cleanArchRepositoryImplSimple( featurePackage = featurePackage, endPointsName = endPointsName, repositoryImplName = repositoryImplName ) save( repositoryImpl, srcOut.resolve("$basePath/${repositoryImplName}.kt") ) val endpoints = cleanArchEndPointsSimple( featurePackage = featurePackage, endPointsName = endPointsName ) save( endpoints, srcOut.resolve("$basePath/${endPointsName}.kt") ) }
0
Kotlin
0
0
92dfc1c111b991296c4575daa23522f4bc381339
1,371
intellij-plugin-cleantree
Apache License 2.0
spring-app/src/test/kotlin/pl/starchasers/up/DatabaseCleaner.kt
Starchasers
255,645,145
false
null
package pl.starchasers.up import org.junit.jupiter.api.extension.BeforeTestExecutionCallback import org.junit.jupiter.api.extension.ExtensionContext import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Component import pl.starchasers.up.util.initializer.Initializer import javax.sql.DataSource @Component class DatabaseCleaner( private val repositories: List<JpaRepository<*, *>>, private val initializers: List<Initializer>, private val dataSource: DataSource ) : BeforeTestExecutionCallback { fun reset() { clean() initialize() } private fun clean() { val connection = dataSource.connection connection.prepareStatement("set foreign_key_checks = 0").execute() repositories.forEach { it.deleteAllInBatch() } connection.prepareStatement("set foreign_key_checks = 1").execute() connection.close() } private fun initialize() { initializers.forEach { it.initialize() } } override fun beforeTestExecution(context: ExtensionContext?) { clean() initialize() } }
57
Kotlin
0
9
90759d835f3be8fbcb9403dd20ca0e13f18bcfbc
1,152
up
MIT License
fsmlib/src/test/kotlin/org/suggs/fsm/behavior/TransitionTest.kt
suggitpe
158,869,057
false
null
package org.suggs.fsm.behavior import io.kotest.matchers.shouldBe import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.MockitoAnnotations.initMocks import org.suggs.fsm.behavior.TransitionKind.EXTERNAL import org.suggs.fsm.behavior.TransitionKind.INTERNAL import org.suggs.fsm.behavior.builders.EventBuilder.Companion.anEventCalled import org.suggs.fsm.behavior.builders.RegionBuilder.Companion.aRegionCalled import org.suggs.fsm.behavior.builders.TransitionBuilder.Companion.aTransitionCalled import org.suggs.fsm.behavior.builders.TriggerBuilder.Companion.aTriggerCalled import org.suggs.fsm.behavior.builders.VertexBuilder.Companion.aSimpleStateCalled import org.suggs.fsm.execution.BusinessEvent import org.suggs.fsm.execution.BusinessObjectReference import org.suggs.fsm.execution.FsmExecutionContext import org.suggs.fsm.stubs.RegionContainerStub.Companion.aRegionContainerStub import org.suggs.fsm.stubs.StubFsmStateManager class TransitionTest { private lateinit var testRegion: Region @Mock private lateinit var sourceState: State @Mock private lateinit var targetState: State private var event = aBusinessEventCalled("testEvent") private var fsmStateManager = StubFsmStateManager() private var fsmExecutionContext = FsmExecutionContext(fsmStateManager) @BeforeEach fun `initialise region`() { initMocks(this) testRegion = aRegionCalled("region") .withVertices( aSimpleStateCalled("state1"), aSimpleStateCalled("state2") ) .withTransitions( aTransitionCalled("transition").startingAt("state1").endingAt("state2").triggeredBy( aTriggerCalled("trigger").firedWith(anEventCalled("event")) ) ) .build(aRegionContainerStub()) } @Test fun `external transitions fire exit and entry behaviours`() { val externalTransition = Transition("T1", EXTERNAL, sourceState, targetState) externalTransition.fire(event, fsmExecutionContext) verify(sourceState, times(1)).doExitAction(event, fsmExecutionContext) verify(targetState, times(1)).doEntryAction(event, fsmExecutionContext) } @Test fun `internal transitions do not fire exit and entry behaviors`() { val internalTransition = Transition("T1", INTERNAL, sourceState, targetState) internalTransition.fire(event, fsmExecutionContext) verify(sourceState, never()).doExitAction(event, fsmExecutionContext) verify(targetState, never()).doEntryAction(event, fsmExecutionContext) } @Test fun `can tell you if they are fireable for an event`() { val transition = testRegion.findTransitionCalled("transition") transition.isFireableFor(aBusinessEventCalled("event")) shouldBe true } @Test fun `can tell you if they are not firable for an event`() { val transition = testRegion.findTransitionCalled("transition") transition.isFireableFor(aBusinessEventCalled("irrelevantEvent")) shouldBe false } private fun aBusinessEventCalled(name: String): BusinessEvent { return BusinessEvent(name, BusinessObjectReference("", "", 0)) } }
0
Kotlin
0
0
6e9a247e1354354f04219a6b0062eeffad2e611b
3,329
fsm
Apache License 2.0
app/src/androidTest/java/com/alexzh/medicationreminder/data/ReminderDaoTest.kt
AlexZhukovich
107,887,396
false
null
package com.alexzh.medicationreminder.data import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.alexzh.medicationreminder.TestData import com.alexzh.medicationreminder.data.local.MedicationReminderDatabase import com.alexzh.medicationreminder.data.local.PillDao import com.alexzh.medicationreminder.data.local.ReminderDao import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ReminderDaoTest { private lateinit var mReminderDao : ReminderDao private lateinit var mPillDao : PillDao @Before fun setUp() { val context = InstrumentationRegistry.getContext() val database = Room.inMemoryDatabaseBuilder(context, MedicationReminderDatabase::class.java) .allowMainThreadQueries() .build() mReminderDao = database.reminderDao() mPillDao = database.pillDao() } @Test fun should_getEmpyListOfReminders_fromEmptyTable() { mReminderDao.getReminders() .test() .assertValue(TestData.EMPTY_LIST_OF_REMINDERS) } @Test fun should_getEmptyListOfReminder_forNonExistingPill() { val reminders = mReminderDao.getRemindersByPillId(TestData.INVALID_ID) assertEquals(TestData.EMPTY_LIST_OF_REMINDERS, reminders) } @Test fun should_getListOfReminders_forExistingPill() { val pillId = mPillDao.insert(TestData.getFirstPill()) mReminderDao.insert(TestData.getFirstReminder()) val reminders = mReminderDao.getRemindersByPillId(pillId) assertEquals(listOf(TestData.getFirstReminder()), reminders) } @Test fun should_getEmptyListOfReminders_forExistingPillWithoutReminders() { val pillId = mPillDao.insert(TestData.getFirstPill()) val reminders = mReminderDao.getRemindersByPillId(pillId) assertEquals(TestData.EMPTY_LIST_OF_REMINDERS, reminders) } @Test fun should_insert_newReminder() { mPillDao.insert(TestData.getFirstPill()) val reminderId = mReminderDao.insert(TestData.getFirstReminder()) assertEquals(TestData.FIRST_REMINDER_ID, reminderId) mReminderDao.getReminders() .test() .assertValue(listOf(TestData.getFirstReminder())) } @Test fun should_notInsert_theSameReminderTwice() { mPillDao.insert(TestData.getFirstPill()) mReminderDao.insert(TestData.getFirstReminder()) mReminderDao.insert(TestData.getFirstReminder()) mReminderDao.getReminders() .test() .assertValue(listOf(TestData.getFirstReminder())) } @Test fun should_insert_listOfReminders() { mPillDao.insert(TestData.getPills()) val expectedIds = listOf(TestData.FIRST_REMINDER_ID, TestData.SECOND_REMINDER_ID) val ids = mReminderDao.insert(TestData.getReminders()) assertEquals(expectedIds, ids) mReminderDao.getReminders() .test() .assertValue(TestData.getReminders()) } @Test fun should_notInsert_listOfRemindersTwice() { mPillDao.insert(TestData.getPills()) mReminderDao.insert(TestData.getReminders()) mReminderDao.insert(TestData.getReminders()) mReminderDao.getReminders() .test() .assertValue(TestData.getReminders()) } @Test fun should_notUpdate_nonExistingReminder() { val count = mReminderDao.update(TestData.getFirstReminder()) assertEquals(0, count) mReminderDao.getReminders() .test() .assertValue(TestData.EMPTY_LIST_OF_REMINDERS) } @Test fun should_update_existingReminder() { mPillDao.insert(TestData.getFirstPill()) mReminderDao.insert(TestData.getFirstReminder()) val count = mReminderDao.update(TestData.getFirstUpdatedReminder()) assertEquals(1, count) mReminderDao.getReminders() .test() .assertValue(listOf(TestData.getFirstUpdatedReminder())) } @Test fun should_notDelete_reminderFromEmptyTable() { val count = mReminderDao.delete(TestData.getFirstReminder()) assertEquals(0, count) mReminderDao.getReminders() .test() .assertValue(TestData.EMPTY_LIST_OF_REMINDERS) } @Test fun should_delete_existingReminder() { mPillDao.insert(TestData.getPills()) mReminderDao.insert(TestData.getReminders()) val count = mReminderDao.delete(TestData.getFirstReminder()) assertEquals(1, count) mReminderDao.getReminders() .test() .assertValue(listOf(TestData.getSecondReminder())) } @Test fun should_notDelete_ListOfRemindersFromEmptyTable() { val count = mReminderDao.delete(TestData.getReminders()) assertEquals(0, count) mReminderDao.getReminders() .test() .assertValue(TestData.EMPTY_LIST_OF_REMINDERS) } @Test fun should_delete_existingReminders() { mPillDao.insert(TestData.getPills()) mReminderDao.insert(TestData.getReminders()) val count = mReminderDao.delete(listOf(TestData.getFirstReminder())) assertEquals(1, count) mReminderDao.getReminders() .test() .assertValue(listOf(TestData.getSecondReminder())) } @Test fun should_notDelete_allRemindersFromEmptyTable() { mReminderDao.deleteAll() mReminderDao.getReminders() .test() .assertValue(TestData.EMPTY_LIST_OF_REMINDERS) } @Test fun should_delete_allRemindersFromFilledTable() { mPillDao.insert(TestData.getPills()) mReminderDao.insert(TestData.getReminders()) mReminderDao.deleteAll() mReminderDao.getReminders() .test() .assertValue(TestData.EMPTY_LIST_OF_REMINDERS) } }
0
Kotlin
0
1
fa71281518d20d0432ba96d3c301b1488cc6c1e8
6,169
MedicationReminder
MIT License
viz-common/src/main/kotlin/com/majaku/viz/common/config/OkHttpHeaderInterceptor.kt
Prime1Code
418,252,999
false
{"Kotlin": 9874}
package com.majaku.viz.common.config import okhttp3.Interceptor import okhttp3.Response import org.springframework.beans.factory.InitializingBean import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import org.springframework.util.StringUtils @Component class OkHttpHeaderInterceptor @Autowired constructor( private val applicationUtils: ApplicationUtils ) : Interceptor, InitializingBean { @Value("\${server.port:error}") private lateinit var serverPort: String private var applicationName: String? = null override fun intercept(chain: Interceptor.Chain): Response { if (!StringUtils.hasText(applicationName)) { applicationName = applicationUtils.getApplicationName() } val request = chain.request() val newRequest = request.newBuilder() .addHeader("MS-Port", serverPort) .addHeader("MS-Name", applicationName!!) .build() return chain.proceed(newRequest) } override fun afterPropertiesSet() { if (!StringUtils.hasText(serverPort)) { throw IllegalArgumentException("serverPort is null") } } }
0
Kotlin
0
1
caf81bbb7bc7b726c5ed968c7287957caa4f915a
1,261
viz-common
MIT License
src/main/kotlin/mcx/pass/backend/Stage.kt
mcenv
558,700,207
false
null
package mcx.pass.backend import kotlinx.collections.immutable.plus import mcx.ast.Core.Definition import mcx.ast.Core.Pattern import mcx.ast.Core.Term import mcx.ast.Lvl import mcx.ast.Modifier import mcx.ast.toIdx import mcx.ast.toLvl import mcx.pass.* import mcx.util.mapWith @Suppress("NAME_SHADOWING") class Stage private constructor() { private fun stageDefinition( definition: Definition, ): Definition? { return when (definition) { is Definition.Def -> { if (Modifier.CONST in definition.modifiers) { null } else { val type = stageTerm(definition.type) val body = definition.body?.let { stageTerm(it) } Definition.Def(definition.doc, definition.annotations, definition.modifiers, definition.name, type, body) } } } } private fun stageTerm( term: Term, ): Term { return emptyEnv().normalizeTerm(term, Phase.WORLD) } private fun Env.normalizeTerm( term: Term, phase: Phase, ): Term { return next().quoteValue(evalTerm(term, phase), phase) } private fun Env.evalTerm( term: Term, phase: Phase, ): Value { return when (term) { is Term.Tag -> { requireConst(term, phase) Value.Tag } is Term.TagOf -> { requireConst(term, phase) Value.TagOf(term.value) } is Term.Type -> { val tag = lazy { evalTerm(term.element, Phase.CONST) } Value.Type(tag) } is Term.Bool -> Value.Bool is Term.BoolOf -> Value.BoolOf(term.value) is Term.If -> { val condition = evalTerm(term.condition, phase) when { phase == Phase.CONST && condition is Value.BoolOf -> { if (condition.value) { evalTerm(term.thenBranch, phase) } else { evalTerm(term.elseBranch, phase) } } else -> { val thenBranch = lazy { evalTerm(term.thenBranch, phase) } val elseBranch = lazy { evalTerm(term.elseBranch, phase) } Value.If(condition, thenBranch, elseBranch) } } } is Term.Is -> { val scrutinee = lazy { evalTerm(term.scrutinee, phase) } val scrutineer = evalPattern(term.scrutineer, phase) when (phase) { Phase.WORLD -> Value.Is(scrutinee, scrutineer) Phase.CONST -> { when (val result = scrutineer matches scrutinee) { null -> Value.Is(scrutinee, scrutineer) else -> Value.BoolOf(result) } } } } is Term.Byte -> Value.Byte is Term.ByteOf -> Value.ByteOf(term.value) is Term.Short -> Value.Short is Term.ShortOf -> Value.ShortOf(term.value) is Term.Int -> Value.Int is Term.IntOf -> Value.IntOf(term.value) is Term.Long -> Value.Long is Term.LongOf -> Value.LongOf(term.value) is Term.Float -> Value.Float is Term.FloatOf -> Value.FloatOf(term.value) is Term.Double -> Value.Double is Term.DoubleOf -> Value.DoubleOf(term.value) is Term.String -> Value.String is Term.StringOf -> Value.StringOf(term.value) is Term.ByteArray -> Value.ByteArray is Term.ByteArrayOf -> { val elements = term.elements.map { lazy { evalTerm(it, phase) } } Value.ByteArrayOf(elements) } is Term.IntArray -> Value.IntArray is Term.IntArrayOf -> { val elements = term.elements.map { lazy { evalTerm(it, phase) } } Value.IntArrayOf(elements) } is Term.LongArray -> Value.LongArray is Term.LongArrayOf -> { val elements = term.elements.map { lazy { evalTerm(it, phase) } } Value.LongArrayOf(elements) } is Term.List -> { val element = lazy { evalTerm(term.element, phase) } Value.List(element) } is Term.ListOf -> { val elements = term.elements.map { lazy { evalTerm(it, phase) } } Value.ListOf(elements) } is Term.Compound -> { val elements = term.elements.mapValuesTo(linkedMapOf()) { lazy { evalTerm(it.value, phase) } } Value.Compound(elements) } is Term.CompoundOf -> { val elements = term.elements.mapValuesTo(linkedMapOf()) { lazy { evalTerm(it.value, phase) } } Value.CompoundOf(elements) } is Term.Point -> { val element = lazy { evalTerm(term.element, phase) } val elementType = evalTerm(term.elementType, phase) Value.Point(element, elementType) } is Term.Union -> { val elements = term.elements.map { lazy { evalTerm(it, phase) } } Value.Union(elements) } is Term.Func -> { val (binders, params) = term.params.mapWith(this) { modify, (param, type) -> val type = lazyOf(evalTerm(type, phase)) val param = evalPattern(param, phase) modify(this + next().collect(listOf(param))) param to type }.unzip() val result = Closure(this, binders, term.result) Value.Func(term.open, params, result) } is Term.FuncOf -> { val binders = term.params.map { evalPattern(it, phase) } val result = Closure(this, binders, term.result) Value.FuncOf(term.open, result) } is Term.Apply -> { val func = evalTerm(term.func, phase) val args = term.args.map { lazy { evalTerm(it, phase) } } when (phase) { Phase.WORLD -> null Phase.CONST -> { when (func) { is Value.FuncOf -> func.result(args, phase) is Value.Def -> lookupBuiltin(func.def.name)!!.eval(args) else -> null } } } ?: run { val type = evalTerm(term.type) Value.Apply(term.open, func, args, type) } } is Term.Code -> { requireConst(term, phase) val element = lazy { evalTerm(term.element, Phase.WORLD) } Value.Code(element) } is Term.CodeOf -> { requireConst(term, phase) val element = lazy { evalTerm(term.element, Phase.WORLD) } Value.CodeOf(element) } is Term.Splice -> { requireWorld(term, phase) val element = evalTerm(term.element, Phase.CONST) as Value.CodeOf element.element.value } is Term.Command -> { requireWorld(term, phase) val element = lazy { evalTerm(term.element, Phase.CONST) } val type = evalTerm(term.type, Phase.CONST) Value.Command(element, type) } is Term.Let -> { when (phase) { Phase.WORLD -> { val binder = evalPattern(term.binder, phase) val init = lazy { evalTerm(term.init, phase) } val body = lazy { evalTerm(term.body, phase) } Value.Let(binder, init, body) } Phase.CONST -> { val init = lazy { evalTerm(term.init, phase) } val binder = evalPattern(term.binder, phase) (this + (binder binds init)).evalTerm(term.body, phase) } } } is Term.Var -> { val lvl = next().toLvl(term.idx) when (phase) { Phase.WORLD -> { val type = evalTerm(term.type, phase) Value.Var(term.name, lvl, type) } Phase.CONST -> this[lvl.value].value } } is Term.Def -> { when (phase) { Phase.WORLD -> null Phase.CONST -> term.def.body?.let { evalTerm(it, phase) } } ?: Value.Def(term.def) } is Term.Meta -> unexpectedTerm(term) is Term.Hole -> unexpectedTerm(term) } } private fun Lvl.quoteValue( value: Value, phase: Phase, ): Term { return when (value) { is Value.Tag -> Term.Tag is Value.TagOf -> Term.TagOf(value.value) is Value.Type -> { val tag = quoteValue(value.element.value, Phase.CONST) Term.Type(tag) } is Value.Bool -> Term.Bool is Value.BoolOf -> Term.BoolOf(value.value) is Value.If -> { val condition = quoteValue(value.condition, phase) val thenBranch = quoteValue(value.thenBranch.value, phase) val elseBranch = quoteValue(value.elseBranch.value, phase) Term.If(condition, thenBranch, elseBranch) } is Value.Is -> { val scrutinee = quoteValue(value.scrutinee.value, phase) val scrutineer = quotePattern(value.scrutineer, phase) Term.Is(scrutinee, scrutineer) } is Value.Byte -> Term.Byte is Value.ByteOf -> Term.ByteOf(value.value) is Value.Short -> Term.Short is Value.ShortOf -> Term.ShortOf(value.value) is Value.Int -> Term.Int is Value.IntOf -> Term.IntOf(value.value) is Value.Long -> Term.Long is Value.LongOf -> Term.LongOf(value.value) is Value.Float -> Term.Float is Value.FloatOf -> Term.FloatOf(value.value) is Value.Double -> Term.Double is Value.DoubleOf -> Term.DoubleOf(value.value) is Value.String -> Term.String is Value.StringOf -> Term.StringOf(value.value) is Value.ByteArray -> Term.ByteArray is Value.ByteArrayOf -> { val elements = value.elements.map { quoteValue(it.value, phase) } Term.ByteArrayOf(elements) } is Value.IntArray -> Term.IntArray is Value.IntArrayOf -> { val elements = value.elements.map { quoteValue(it.value, phase) } Term.IntArrayOf(elements) } is Value.LongArray -> Term.LongArray is Value.LongArrayOf -> { val elements = value.elements.map { quoteValue(it.value, phase) } Term.LongArrayOf(elements) } is Value.List -> { val element = quoteValue(value.element.value, phase) Term.List(element) } is Value.ListOf -> { val elements = value.elements.map { quoteValue(it.value, phase) } Term.ListOf(elements) } is Value.Compound -> { val elements = value.elements.mapValuesTo(linkedMapOf()) { quoteValue(it.value.value, phase) } Term.Compound(elements) } is Value.CompoundOf -> { val elements = value.elements.mapValuesTo(linkedMapOf()) { quoteValue(it.value.value, phase) } Term.CompoundOf(elements) } is Value.Point -> { val element = quoteValue(value.element.value, phase) val elementType = quoteValue(value.elementType, phase) Term.Point(element, elementType) } is Value.Union -> { val elements = value.elements.map { quoteValue(it.value, phase) } Term.Union(elements) } is Value.Func -> { // TODO: fix offsets val params = (value.result.binders zip value.params).map { (binder, param) -> val binder = quotePattern(binder, phase) val param = quoteValue(param.value, phase) binder to param } val result = quoteClosure(value.result, phase) Term.Func(value.open, params, result) } is Value.FuncOf -> { // TODO: fix offsets val params = value.result.binders.map { quotePattern(it, phase) } val result = quoteClosure(value.result, phase) Term.FuncOf(value.open, params, result) } is Value.Apply -> { val func = quoteValue(value.func, phase) val args = value.args.map { quoteValue(it.value, phase) } val type = quoteValue(value.type, phase) Term.Apply(value.open, func, args, type) } is Value.Code -> { val element = quoteValue(value.element.value, Phase.WORLD) Term.Code(element) } is Value.CodeOf -> { val element = quoteValue(value.element.value, Phase.WORLD) Term.CodeOf(element) } is Value.Splice -> { val element = quoteValue(value.element, Phase.CONST) Term.Splice(element) } is Value.Command -> { val element = quoteValue(value.element.value, Phase.CONST) val type = quoteValue(value.type, Phase.CONST) Term.Command(element, type) } is Value.Let -> { val binder = quotePattern(value.binder, phase) val init = quoteValue(value.init.value, phase) val body = quoteValue(value.body.value, phase) Term.Let(binder, init, body) } is Value.Var -> { val type = quoteValue(value.type, phase) Term.Var(value.name, toIdx(value.lvl), type) } is Value.Def -> Term.Def(value.def) is Value.Meta -> Term.Meta(value.index, value.source) is Value.Hole -> Term.Hole } } private fun Env.evalPattern( pattern: Pattern<Term>, phase: Phase, ): Pattern<Value> { return when (pattern) { is Pattern.IntOf -> pattern is Pattern.CompoundOf -> { val elements = pattern.elements.mapValuesTo(linkedMapOf()) { (_, element) -> evalPattern(element, phase) } Pattern.CompoundOf(elements) } is Pattern.Var -> { val type = evalTerm(pattern.type, phase) Pattern.Var(pattern.name, type) } is Pattern.Drop -> { val type = evalTerm(pattern.type, phase) Pattern.Drop(type) } is Pattern.Hole -> unexpectedPattern(pattern) } } private fun Lvl.quotePattern( pattern: Pattern<Value>, phase: Phase, ): Pattern<Term> { return when (pattern) { is Pattern.IntOf -> pattern is Pattern.CompoundOf -> { val elements = pattern.elements.mapValuesTo(linkedMapOf()) { (_, element) -> quotePattern(element, phase) } Pattern.CompoundOf(elements) } is Pattern.Var -> { val type = quoteValue(pattern.type, phase) Pattern.Var(pattern.name, type) } is Pattern.Drop -> { val type = quoteValue(pattern.type, phase) Pattern.Drop(type) } is Pattern.Hole -> unexpectedPattern(pattern) } } private fun Lvl.quoteClosure( closure: Closure, phase: Phase, ): Term { return collect(closure.binders).let { (this + it.size).quoteValue(closure(it, phase), phase) } } operator fun Closure.invoke( args: List<Lazy<Value>>, phase: Phase, ): Value { return (env + (binders zip args).flatMap { (binder, value) -> binder binds value }).evalTerm(body, phase) } companion object { private fun requireWorld( term: Term, phase: Phase, ) { if (phase != Phase.WORLD) { unexpectedTerm(term) } } private fun requireConst( term: Term, phase: Phase, ) { if (phase != Phase.CONST) { unexpectedTerm(term) } } private fun unexpectedTerm(term: Term): Nothing { error("unexpected term: ${prettyTerm(term)}") } private fun unexpectedPattern(pattern: Pattern<*>): Nothing { error("unexpected term: ${prettyPattern(pattern)}") } operator fun invoke( context: Context, definition: Definition, ): Definition? { return Stage().stageDefinition(definition) } } }
74
Kotlin
0
4
9c0991d3041340cc28981afc61377f5e36a90997
15,630
mcx
MIT License
zoomimage-compose-sketch/src/main/kotlin/com/github/panpf/zoomimage/SingletonSketchZoomAsyncImage.kt
panpf
647,222,866
false
null
/* * Copyright (C) 2024 panpf <[email protected]> * Copyright 2023 Coil Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.zoomimage import androidx.compose.runtime.Composable import androidx.compose.runtime.NonRestartableComposable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.DefaultAlpha import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import coil3.SingletonImageLoader import coil3.compose.AsyncImagePainter import coil3.compose.AsyncImagePainter.State import coil3.compose.LocalPlatformContext import coil3.request.ImageRequest import com.github.panpf.zoomimage.compose.zoom.ScrollBarSpec /** * An image component that integrates the Coil image loading framework that zoom and subsampling huge images * * Example usages: * * ```kotlin * CoilZoomAsyncImage( * model = ImageRequest.Builder(LocalContext.current).apply { * data("https://sample.com/sample.jpeg") * placeholder(R.drawable.placeholder) * crossfade(true) * }.build(), * contentDescription = "view image", * modifier = Modifier.fillMaxSize(), * ) * ``` * * @param model Either an [ImageRequest] or the [ImageRequest.data] value. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param placeholder A [Painter] that is displayed while the image is loading. * @param error A [Painter] that is displayed when the image request is unsuccessful. * @param fallback A [Painter] that is displayed when the request's [ImageRequest.data] is null. * @param onLoading Called when the image request begins loading. * @param onSuccess Called when the image request completes successfully. * @param onError Called when the image request completes unsuccessfully. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. * @param zoomState The state to control zoom * @param scrollBar Controls whether scroll bars are displayed and their style * @param onLongPress Called when the user long presses the image * @param onTap Called when the user taps the image * @see com.github.panpf.zoomimage.compose.coil.test.SingletonCoilZoomAsyncImageTest.testCoilZoomAsyncImage1 */ @Composable @NonRestartableComposable fun CoilZoomAsyncImage( model: Any?, contentDescription: String?, modifier: Modifier = Modifier, placeholder: Painter? = null, error: Painter? = null, fallback: Painter? = error, onLoading: ((State.Loading) -> Unit)? = null, onSuccess: ((State.Success) -> Unit)? = null, onError: ((State.Error) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DrawScope.DefaultFilterQuality, zoomState: CoilZoomState = rememberCoilZoomState(), scrollBar: ScrollBarSpec? = ScrollBarSpec.Default, onLongPress: ((Offset) -> Unit)? = null, onTap: ((Offset) -> Unit)? = null, ) = CoilZoomAsyncImage( model = model, contentDescription = contentDescription, imageLoader = SingletonImageLoader.get(LocalPlatformContext.current), modifier = modifier, placeholder = placeholder, error = error, fallback = fallback, onLoading = onLoading, onSuccess = onSuccess, onError = onError, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, zoomState = zoomState, scrollBar = scrollBar, onLongPress = onLongPress, onTap = onTap, ) /** * An image component that integrates the Coil image loading framework that zoom and subsampling huge images * * Example usages: * * ```kotlin * CoilZoomAsyncImage( * model = ImageRequest.Builder(LocalContext.current).apply { * data("https://sample.com/sample.jpeg") * placeholder(R.drawable.placeholder) * crossfade(true) * }.build(), * contentDescription = "view image", * modifier = Modifier.fillMaxSize(), * ) * ``` * * @param model Either an [ImageRequest] or the [ImageRequest.data] value. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param transform A callback to transform a new [State] before it's applied to the * [AsyncImagePainter]. Typically this is used to modify the state's [Painter]. * @param onState Called when the state of this painter changes. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. * @param zoomState The state to control zoom * @param scrollBar Controls whether scroll bars are displayed and their style * @param onLongPress Called when the user long presses the image * @param onTap Called when the user taps the image * @see com.github.panpf.zoomimage.compose.coil.test.SingletonCoilZoomAsyncImageTest.testCoilZoomAsyncImage2 */ @Composable fun CoilZoomAsyncImage( model: Any?, contentDescription: String?, modifier: Modifier = Modifier, transform: (State) -> State = AsyncImagePainter.DefaultTransform, onState: ((State) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DrawScope.DefaultFilterQuality, zoomState: CoilZoomState = rememberCoilZoomState(), scrollBar: ScrollBarSpec? = ScrollBarSpec.Default, onLongPress: ((Offset) -> Unit)? = null, onTap: ((Offset) -> Unit)? = null, ) = CoilZoomAsyncImage( model = model, contentDescription = contentDescription, imageLoader = SingletonImageLoader.get(LocalPlatformContext.current), modifier = modifier, transform = transform, onState = onState, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, zoomState = zoomState, scrollBar = scrollBar, onLongPress = onLongPress, onTap = onTap, )
8
null
7
98
bdc00e862498830df39a205de5d3d490a5f04444
8,610
zoomimage
Apache License 2.0
flutter_learn/android/app/src/main/kotlin/cn/orangelab/flutter_learn/MainActivity.kt
DDYFlutter
206,050,782
false
{"Dart": 70927, "JavaScript": 790, "Shell": 782, "Swift": 404, "Kotlin": 131, "Objective-C": 38}
package cn.orangelab.flutter_learn import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
1
8c6f7e357b94abaea145b5cdffc46c5f19214e64
131
flutter_test
MIT License
sample/src/main/java/com/evo/composetoedge/components/Message.kt
Leo00001
307,006,119
true
{"Kotlin": 3397}
/* * Copyright 2020 <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.evo.composetoedge.components import androidx.compose.foundation.Image import androidx.compose.foundation.Text import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.ui.tooling.preview.Preview import com.evo.composetoedge.data.androidPost import com.evo.composetoedge.data.initialPosts /** * Created by <NAME> on 23/10/2020 */ @Composable fun Messages(posts: List<Post>, modifier: Modifier) { repeat(4) { repeat: Int -> posts.forEachIndexed { index, post -> val topPadding = if (index != 0 || repeat != 0) 16.dp else 8.dp Message(post = post, modifier = Modifier.padding(top = topPadding).then(modifier)) } } } @Composable fun Message( post: Post, modifier: Modifier = Modifier ) { val bubbleColor = if (MaterialTheme.colors.isLight) Color(0xFFF5F5F5) else Color(0xFF222222) ConstraintLayout(Modifier.fillMaxWidth().then(modifier)) { // Declaring them separately for visibility val (avatar, username) = createRefs() val (message, moreOptions) = createRefs() Avatar( name = post.username, modifier = Modifier.constrainAs(avatar) { start.linkTo(parent.start) top.linkTo(parent.top) } ) Text( text = post.username, style = MaterialTheme.typography.body1, fontWeight = FontWeight.Medium, color = MaterialTheme.colors.onBackground, modifier = Modifier.constrainAs(username) { start.linkTo(avatar.end, 12.dp) } ) // Message bubble Surface( color = bubbleColor, shape = RoundedCornerShape(0.dp, 8.dp, 8.dp, 8.dp), modifier = Modifier.constrainAs(message) { width = Dimension.preferredWrapContent.atMostWrapContent top.linkTo(username.bottom, 4.dp) linkTo(username.start, moreOptions.start, endMargin = 16.dp, bias = 0f) } ) { Text( text = post.message, style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(8.dp) ) } // More Options Surface( color = bubbleColor, shape = RoundedCornerShape(50), modifier = Modifier.size(32.dp).constrainAs(moreOptions) { end.linkTo(parent.end, 16.dp) centerVerticallyTo(message) } ) { Image( asset = Icons.Filled.MoreVert, modifier = Modifier.size(24.dp), colorFilter = ColorFilter.tint(MaterialTheme.colors.onBackground.copy(alpha = 0.60f)) ) } } } @Preview @Composable fun PreviewMesssage() { Surface(color = Color.White) { Message(androidPost) } } data class Post(val username: String, val message: String)
0
null
0
0
66a6260abc37320feea9f04ad76d734b4bc9f175
3,925
compose-to-edge
Apache License 2.0
app/src/main/java/me/luowl/wan/ui/account/MineViewModel.kt
chenyao1208
205,293,578
true
{"Kotlin": 187951, "Java": 38899, "HTML": 2838}
package me.luowl.wan.ui.account import com.jeremyliao.liveeventbus.LiveEventBus import me.luowl.wan.AppConfig import me.luowl.wan.base.BaseViewModel import me.luowl.wan.data.WanRepository import me.luowl.wan.event.LoginEvent import me.luowl.wan.util.logDebug /* * * Created by luowl * Date: 2019/8/4 * Desc: */ class MineViewModel constructor(private val repository: WanRepository) : BaseViewModel() { fun isLogin(): Boolean { return AppConfig.isLogin() } fun logout() { launch({ repository.logout() clearData() }, { clearData() }) } private fun clearData() { AppConfig.clearLoginInfo() LiveEventBus.get().with(AppConfig.LOGIN_KEY).post(LoginEvent(false)) } }
0
Kotlin
0
0
fa951c6dac69ad2944f0c881c3a5ddcc39781203
781
WanAndroid
Apache License 2.0
core/src/commonMain/kotlin/com/maxkeppeker/sheets/core/icons/twotone/Tune.kt
maxkeppeler
523,345,776
false
{"Kotlin": 1337179, "Python": 4978, "Shell": 645}
package com.maxkeppeker.sheets.core.icons.twotone import androidx.compose.material.icons.materialIcon import androidx.compose.material.icons.materialPath import androidx.compose.ui.graphics.vector.ImageVector public val Tune: ImageVector get() { if (_tune != null) { return _tune!! } _tune = materialIcon(name = "TwoTone.Tune") { materialPath { moveTo(3.0f, 5.0f) horizontalLineToRelative(10.0f) verticalLineToRelative(2.0f) lineTo(3.0f, 7.0f) close() moveTo(7.0f, 11.0f) lineTo(3.0f, 11.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(4.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(2.0f) lineTo(9.0f, 9.0f) lineTo(7.0f, 9.0f) close() moveTo(13.0f, 15.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(6.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(8.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(-8.0f) close() moveTo(3.0f, 17.0f) horizontalLineToRelative(6.0f) verticalLineToRelative(2.0f) lineTo(3.0f, 19.0f) close() moveTo(11.0f, 11.0f) horizontalLineToRelative(10.0f) verticalLineToRelative(2.0f) lineTo(11.0f, 13.0f) close() moveTo(17.0f, 3.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(6.0f) horizontalLineToRelative(2.0f) lineTo(17.0f, 7.0f) horizontalLineToRelative(4.0f) lineTo(21.0f, 5.0f) horizontalLineToRelative(-4.0f) close() } } return _tune!! } private var _tune: ImageVector? = null
14
Kotlin
38
816
2af41f317228e982e261522717b6ef5838cd8b58
2,162
sheets-compose-dialogs
Apache License 2.0
app/src/main/java/com/egoriku/ladyhappy/mainscreen/presentation/search/SearchFragment.kt
egorikftp
102,286,802
false
{"Kotlin": 477671, "JavaScript": 3040, "Shell": 289}
package com.egoriku.ladyhappy.mainscreen.presentation.search import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import com.egoriku.ladyhappy.R import com.egoriku.ladyhappy.extensions.extraNotNull import com.google.android.material.textfield.TextInputEditText private const val SEARCH_QUERY_EXTRA = "SEARCH_QUERY_EXTRA" class SearchFragment : Fragment(R.layout.fragment_search) { private val searchQuery: String by extraNotNull(SEARCH_QUERY_EXTRA) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<TextInputEditText>(R.id.searchInput).setText(searchQuery) } companion object { fun newInstance(searchQuery: String?) = SearchFragment().apply { arguments = bundleOf(SEARCH_QUERY_EXTRA to searchQuery) } } }
12
Kotlin
22
261
da53bf026e104b84eebb7c2660c2feae26c6d965
927
Lady-happy-Android
Apache License 2.0
src/main/kotlin/api/KotlinMetadataSignature.kt
Kotlin
238,709,060
false
null
/* * Copyright 2016-2023 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package kotlinx.validation.api import kotlinx.metadata.jvm.* import kotlinx.validation.* import org.objectweb.asm.* import org.objectweb.asm.tree.* @ExternalApi // Only name is part of the API, nothing else is used by stdlib public data class ClassBinarySignature internal constructor( internal val name: String, internal val superName: String, internal val outerName: String?, internal val supertypes: List<String>, internal val memberSignatures: List<MemberBinarySignature>, internal val access: AccessFlags, internal val isEffectivelyPublic: Boolean, internal val isNotUsedWhenEmpty: Boolean, internal val annotations: List<AnnotationNode> ) { internal val signature: String get() = "${access.getModifierString()} class $name" + if (supertypes.isEmpty()) "" else " : ${supertypes.joinToString()}" } internal interface MemberBinarySignature { val jvmMember: JvmMemberSignature val name: String get() = jvmMember.name val desc: String get() = jvmMember.desc val access: AccessFlags val isPublishedApi: Boolean val annotations: List<AnnotationNode> fun isEffectivelyPublic(classAccess: AccessFlags, classVisibility: ClassVisibility?) = access.isPublic && !(access.isProtected && classAccess.isFinal) && (findMemberVisibility(classVisibility)?.isPublic(isPublishedApi) ?: true) fun findMemberVisibility(classVisibility: ClassVisibility?): MemberVisibility? { return classVisibility?.findMember(jvmMember) } val signature: String } internal data class MethodBinarySignature( override val jvmMember: JvmMethodSignature, override val isPublishedApi: Boolean, override val access: AccessFlags, override val annotations: List<AnnotationNode>, private val alternateDefaultSignature: JvmMethodSignature? ) : MemberBinarySignature { override val signature: String get() = "${access.getModifierString()} fun $name $desc" override fun isEffectivelyPublic(classAccess: AccessFlags, classVisibility: ClassVisibility?) = super.isEffectivelyPublic(classAccess, classVisibility) && !isAccessOrAnnotationsMethod() && !isDummyDefaultConstructor() override fun findMemberVisibility(classVisibility: ClassVisibility?): MemberVisibility? { return super.findMemberVisibility(classVisibility) ?: classVisibility?.let { alternateDefaultSignature?.let(it::findMember) } } private fun isAccessOrAnnotationsMethod() = access.isSynthetic && (name.startsWith("access\$") || name.endsWith("\$annotations")) private fun isDummyDefaultConstructor() = access.isSynthetic && name == "<init>" && desc == "(Lkotlin/jvm/internal/DefaultConstructorMarker;)V" } /** * Calculates the signature of this method without default parameters * * Returns `null` if this method isn't an entry point of a function * or a constructor with default parameters. * Returns an incorrect result, if there are more than 31 default parameters. */ internal fun MethodNode.alternateDefaultSignature(className: String): JvmMethodSignature? { return when { access and Opcodes.ACC_SYNTHETIC == 0 -> null name == "<init>" && "ILkotlin/jvm/internal/DefaultConstructorMarker;" in desc -> JvmMethodSignature(name, desc.replace("ILkotlin/jvm/internal/DefaultConstructorMarker;", "")) name.endsWith("\$default") && "ILjava/lang/Object;)" in desc -> JvmMethodSignature( name.removeSuffix("\$default"), desc.replace("ILjava/lang/Object;)", ")").replace("(L$className;", "(") ) else -> null } } internal fun MethodNode.toMethodBinarySignature( /* * Extra annotations are: * * Annotations from the original method for synthetic `$default` method * * Annotations from getter, setter or field for synthetic `$annotation` method * * Annotations from a field for getter and setter */ extraAnnotations: List<AnnotationNode>, alternateDefaultSignature: JvmMethodSignature? ): MethodBinarySignature { val allAnnotations = visibleAnnotations.orEmpty() + invisibleAnnotations.orEmpty() + extraAnnotations return MethodBinarySignature( JvmMethodSignature(name, desc), allAnnotations.isPublishedApi(), AccessFlags(access), allAnnotations, alternateDefaultSignature ) } internal data class FieldBinarySignature( override val jvmMember: JvmFieldSignature, override val isPublishedApi: Boolean, override val access: AccessFlags, override val annotations: List<AnnotationNode> ) : MemberBinarySignature { override val signature: String get() = "${access.getModifierString()} field $name $desc" override fun findMemberVisibility(classVisibility: ClassVisibility?): MemberVisibility? { return super.findMemberVisibility(classVisibility) ?: takeIf { access.isStatic }?.let { super.findMemberVisibility(classVisibility?.companionVisibilities) } } } internal fun FieldNode.toFieldBinarySignature(extraAnnotations: List<AnnotationNode>): FieldBinarySignature { val allAnnotations = visibleAnnotations.orEmpty() + invisibleAnnotations.orEmpty() + extraAnnotations return FieldBinarySignature( JvmFieldSignature(name, desc), allAnnotations.isPublishedApi(), AccessFlags(access), allAnnotations ) } private val MemberBinarySignature.kind: Int get() = when (this) { is FieldBinarySignature -> 1 is MethodBinarySignature -> 2 else -> error("Unsupported $this") } internal val MEMBER_SORT_ORDER = compareBy<MemberBinarySignature>( { it.kind }, { it.name }, { it.desc } ) internal data class AccessFlags(val access: Int) { val isPublic: Boolean get() = isPublic(access) val isProtected: Boolean get() = isProtected(access) val isStatic: Boolean get() = isStatic(access) val isFinal: Boolean get() = isFinal(access) val isSynthetic: Boolean get() = isSynthetic(access) val isAbstract: Boolean get() = isAbstract(access) val isInterface: Boolean get() = isInterface(access) private fun getModifiers(): List<String> = ACCESS_NAMES.entries.mapNotNull { if (access and it.key != 0) it.value else null } fun getModifierString(): String = getModifiers().joinToString(" ") } internal fun FieldNode.isCompanionField(outerClassMetadata: KotlinClassMetadata?): Boolean { val access = AccessFlags(access) if (!access.isFinal || !access.isStatic) return false val metadata = outerClassMetadata ?: return false // Non-classes are not affected by the problem if (metadata !is KotlinClassMetadata.Class) return false return metadata.toKmClass().companionObject == name } internal fun ClassNode.companionName(outerClassMetadata: KotlinClassMetadata?): String { val outerKClass = (outerClassMetadata as KotlinClassMetadata.Class).toKmClass() return name + "$" + outerKClass.companionObject }
67
null
55
753
3a7003363502236e64bbf044540e569b3eb808a4
7,223
binary-compatibility-validator
Apache License 2.0
src/main/kotlin/top/lanscarlos/vulpecula/bacikal/action/internal/ActionVulpecula.kt
Lanscarlos
517,897,387
false
null
package top.lanscarlos.vulpecula.bacikal.action.internal import top.lanscarlos.vulpecula.bacikal.BacikalParser import top.lanscarlos.vulpecula.bacikal.bacikal /** * Vulpecula * top.lanscarlos.vulpecula.bacikal.action.internal * * @author Lanscarlos * @since 2023-03-25 00:29 */ object ActionVulpecula { @BacikalParser("vulpecula") fun parser() = bacikal { when (val next = this.nextToken()) { "dispatcher" -> ActionVulpeculaDispatcher.resolve(this) "schedule" -> ActionVulpeculaSchedule.resolve(this) "script" -> ActionVulpeculaScript.resolve(this) else -> error("Unknown sub action \"$next\" at vulpecula action.") } } }
1
null
5
30
b07e79c505ebd953535b8c059144baa5482807d8
706
Vulpecula
MIT License
app/src/main/java/org/stepic/droid/di/routing/RoutingModule.kt
Ujjawal-Anand
142,415,269
true
{"Java": 1818802, "Kotlin": 1403557, "CSS": 3790, "Shell": 618, "Prolog": 98}
package org.stepic.droid.di.routing import dagger.Binds import dagger.Module import org.stepic.droid.base.Client import org.stepic.droid.base.ClientImpl import org.stepic.droid.base.ListenerContainer import org.stepic.droid.base.ListenerContainerImpl import org.stepic.droid.core.routing.RoutingPosterImpl import org.stepic.droid.core.routing.contract.RoutingListener import org.stepic.droid.core.routing.contract.RoutingPoster @Module interface RoutingModule { @Binds @RoutingScope fun bindsRoutingClient(routingConsumerImpl: ClientImpl<RoutingListener>): Client<RoutingListener> @Binds @RoutingScope fun bindListenerContainer(routingListenerContainer: ListenerContainerImpl<RoutingListener>): ListenerContainer<RoutingListener> @Binds @RoutingScope fun bindsRoutingPoster(routingPosterImpl: RoutingPosterImpl): RoutingPoster }
0
Java
0
1
256a90051eefe8db83f7053914004905bbb1f8d0
870
stepik-android
Apache License 2.0
src/testFixtures/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/resource/model/induction/FutureWorkInterestsResponseBuilder.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1266220, "Mustache": 2705, "Dockerfile": 1375}
package uk.gov.justice.digital.hmpps.educationandworkplanapi.resource.model.induction import uk.gov.justice.digital.hmpps.educationandworkplanapi.resource.model.FutureWorkInterest import uk.gov.justice.digital.hmpps.educationandworkplanapi.resource.model.FutureWorkInterestsResponse import java.time.OffsetDateTime import java.util.UUID fun aValidFutureWorkInterestsResponse( reference: UUID = UUID.randomUUID(), interests: List<FutureWorkInterest> = listOf(aValidFutureWorkInterest()), createdBy: String = "asmith_gen", createdByDisplayName: String = "<NAME>", createdAt: OffsetDateTime = OffsetDateTime.now(), createdAtPrison: String = "BXI", updatedBy: String = "asmith_gen", updatedByDisplayName: String = "<NAME>", updatedAt: OffsetDateTime = OffsetDateTime.now(), updatedAtPrison: String = "BXI", ): FutureWorkInterestsResponse = FutureWorkInterestsResponse( reference = reference, interests = interests, createdBy = createdBy, createdByDisplayName = createdByDisplayName, createdAt = createdAt, createdAtPrison = createdAtPrison, updatedBy = updatedBy, updatedByDisplayName = updatedByDisplayName, updatedAt = updatedAt, updatedAtPrison = updatedAtPrison, )
4
Kotlin
0
2
fe41f71d0d2ffa0e5c0e371490c792b0c6238967
1,231
hmpps-education-and-work-plan-api
MIT License
impl/java/server/src/test/kotlin/br/com/guiabolso/events/server/exception/handler/BypassExceptionHandlerTest.kt
GuiaBolso
102,665,880
false
null
package br.com.guiabolso.events.server.exception.handler import br.com.guiabolso.events.model.RequestEvent import br.com.guiabolso.events.server.exception.BypassedException import io.mockk.mockk import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class BypassExceptionHandlerTest { @Test fun `should only throws the exception`(): Unit = runBlocking { val handler = BypassExceptionHandler(false) val exception = TestException() assertThrows<TestException> { runBlocking { handler.handleException(exception, mockk(), mockk()) } } } @Test fun `should throws the exception wrapped`(): Unit = runBlocking { val handler = BypassExceptionHandler(true) val exception = TestException() val event: RequestEvent = mockk() val ex = assertThrows<BypassedException> { runBlocking { handler.handleException(exception, event, mockk()) } } assertEquals(exception, ex.exception) assertEquals(event, ex.request) } class TestException : RuntimeException() }
6
Kotlin
21
21
ac681929de003e82da5910ffe41ed71ee4336899
1,201
events-protocol
Apache License 2.0
pushmanager/src/main/java/com/grumpyshoe/module/pushmanager/models/RemoteMessageData.kt
grumpyshoe
146,342,390
false
null
package com.grumpyshoe.module.pushmanager.models import android.net.Uri /** * <p>RemoteMessageData is a model for holding all notification information that's available from incomming message</p> * * @since 1.0.0 * @version 1.0.0 * @author grumpyshoe * */ data class RemoteMessageData( var tag: String? = null, var bodyLocalizationKey: String? = null, var bodyLocalizationArgs: Array<String>? = null, var title: String? = null, var body: String? = null, var clickAction: String? = null, var color: String? = null, var icon: String? = null, var link: Uri? = null, var sound: String? = null, var titleLocalizationKey: String? = null, var titleLocalizationArgs: Array<String>? = null, var data: MutableMap<String, String>? = null, var messageType: String? = null, var collapseKey: String? = null, var from: String? = null, var messageId: String? = null, var originalPriority: Int? = null, var priority: Int? = null, var sentTime: Long? = null, var to: String? = null, var ttl: String? = null)
2
null
6
47
bad2e049faa2b7f8d9628cc77068ce0ecb32df69
1,179
android-module-pushmanager
MIT License
app/src/main/kotlin/com/tinashe/hymnal/ui/hymns/hymnals/HymnalListBottomSheetFragment.kt
TinasheMzondiwa
272,096,849
false
null
package com.tinashe.hymnal.ui.hymns.hymnals import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.tinashe.hymnal.R import com.tinashe.hymnal.data.model.Hymnal import com.tinashe.hymnal.databinding.HymnalListBottomSheetFragmentBinding import com.tinashe.hymnal.extensions.arch.observeNonNull import com.tinashe.hymnal.ui.hymns.hymnals.adapter.HymnalsListAdapter import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HymnalListBottomSheetFragment : BottomSheetDialogFragment() { private val viewModel: HymnalListViewModel by activityViewModels() private var binding: HymnalListBottomSheetFragmentBinding? = null private var hymnalSelected: ((Hymnal) -> Unit)? = null private val listAdapter: HymnalsListAdapter = HymnalsListAdapter { hymnalSelected?.invoke(it) dismiss() } private val appBarElevation = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val raiseTitleBar = dy > 0 || recyclerView.computeVerticalScrollOffset() != 0 binding?.toolbar?.isActivated = raiseTitleBar } } override fun getTheme(): Int = R.style.ThemeOverlay_CIS_BottomSheetDialog override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return HymnalListBottomSheetFragmentBinding.inflate( inflater, container, false ).also { binding = it }.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.hymnalListLiveData.observeNonNull(viewLifecycleOwner) { binding?.progressBar?.isVisible = false listAdapter.submitList(ArrayList(it)) } binding?.apply { toolbar.setNavigationOnClickListener { dismiss() } hymnalsListView.apply { addOnScrollListener(appBarElevation) adapter = listAdapter } } viewModel.loadData() } companion object { fun newInstance(hymnalSelected: (Hymnal) -> Unit): HymnalListBottomSheetFragment = HymnalListBottomSheetFragment().apply { this.hymnalSelected = hymnalSelected } } }
5
null
14
40
84aeaa57933eb9c3a418cd495ff9c282d4e9b573
2,705
cis-android
Apache License 2.0
app/src/main/kotlin/com/tinashe/hymnal/ui/hymns/hymnals/HymnalListBottomSheetFragment.kt
TinasheMzondiwa
272,096,849
false
null
package com.tinashe.hymnal.ui.hymns.hymnals import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.tinashe.hymnal.R import com.tinashe.hymnal.data.model.Hymnal import com.tinashe.hymnal.databinding.HymnalListBottomSheetFragmentBinding import com.tinashe.hymnal.extensions.arch.observeNonNull import com.tinashe.hymnal.ui.hymns.hymnals.adapter.HymnalsListAdapter import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HymnalListBottomSheetFragment : BottomSheetDialogFragment() { private val viewModel: HymnalListViewModel by activityViewModels() private var binding: HymnalListBottomSheetFragmentBinding? = null private var hymnalSelected: ((Hymnal) -> Unit)? = null private val listAdapter: HymnalsListAdapter = HymnalsListAdapter { hymnalSelected?.invoke(it) dismiss() } private val appBarElevation = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val raiseTitleBar = dy > 0 || recyclerView.computeVerticalScrollOffset() != 0 binding?.toolbar?.isActivated = raiseTitleBar } } override fun getTheme(): Int = R.style.ThemeOverlay_CIS_BottomSheetDialog override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return HymnalListBottomSheetFragmentBinding.inflate( inflater, container, false ).also { binding = it }.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.hymnalListLiveData.observeNonNull(viewLifecycleOwner) { binding?.progressBar?.isVisible = false listAdapter.submitList(ArrayList(it)) } binding?.apply { toolbar.setNavigationOnClickListener { dismiss() } hymnalsListView.apply { addOnScrollListener(appBarElevation) adapter = listAdapter } } viewModel.loadData() } companion object { fun newInstance(hymnalSelected: (Hymnal) -> Unit): HymnalListBottomSheetFragment = HymnalListBottomSheetFragment().apply { this.hymnalSelected = hymnalSelected } } }
5
null
14
40
84aeaa57933eb9c3a418cd495ff9c282d4e9b573
2,705
cis-android
Apache License 2.0
components/views/src/main/java/io/horizontalsystems/views/SettingsViewDropdown.kt
fahimaltinordu
312,207,740
true
{"Kotlin": 1883211, "Java": 33448, "Ruby": 5803, "Shell": 2024}
package io.horizontalsystems.views import android.content.Context import android.util.AttributeSet import androidx.core.view.isVisible import kotlinx.android.synthetic.main.view_settings_dropdown.view.* import kotlinx.android.synthetic.main.view_settings_dropdown_text.view.* class SettingsViewDropdown @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : SettingsViewBase(context, attrs, defStyleAttr) { fun showDropdownValue(text: String?) { dropdownValue.text = text dropdownValue.isVisible = text != null } fun showDropdownIcon(show: Boolean) { dropdownIcon.isVisible = show } init { inflate(context, R.layout.view_settings_dropdown, this) val attributes = context.obtainStyledAttributes(attrs, R.styleable.SettingsViewDropdown) try { showTitle(attributes.getString(R.styleable.SettingsViewDropdown_title)) showSubtitle(attributes.getString(R.styleable.SettingsViewDropdown_subtitle)) showIcon(attributes.getDrawable(R.styleable.SettingsViewDropdown_icon)) showDropdownValue(attributes.getString(R.styleable.SettingsViewDropdown_value)) } finally { attributes.recycle() } } }
0
Kotlin
0
4
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
1,283
WILC-wallet-android
MIT License
src/main/kotlin/org/neo4j/graphql/CypherGenerator.kt
mneedham
88,902,386
false
null
package org.neo4j.graphql import graphql.language.* import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.kernel.internal.Version fun <T> Iterable<T>.joinNonEmpty(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String { return if (iterator().hasNext()) joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform).toString() else "" } abstract class CypherGenerator { companion object { val VERSION = Version.getNeo4jVersion() val DEFAULT_CYPHER_VERSION = "3.1" fun instance(): CypherGenerator { if (VERSION.startsWith("3.1")) return Cypher31Generator() return Cypher30Generator() } } abstract fun compiled() : String abstract fun generateQueryForField(field: Field): String; protected fun metaData(name: String) = GraphSchemaScanner.getMetaData(name)!! protected fun attr(variable: String, field: String) = "`$variable`.`$field`" protected fun isPlural(name: String) = name.endsWith("s") protected fun singular(name: String) = name.substring(0, name.length - 1) protected fun formatValue(value: Value?): String = when (value) { is VariableReference -> "{`${value.name}`}" // todo turn into parameters !! is IntValue -> value.value.toString() is FloatValue -> value.value.toString() is BooleanValue -> value.isValue().toString() is StringValue -> "\"${value.value}\"" is EnumValue -> "\"${value.name}\"" is ObjectValue -> "{" + value.objectFields.map { it.name + ":" + formatValue(it.value) }.joinToString(",") + "}" is ArrayValue -> "[" + value.values.map { formatValue(it) }.joinToString(",") + "]" else -> "" // todo raise exception ? } } class Cypher31Generator : CypherGenerator() { override fun compiled() = "compiledExperimentalFeatureNotSupportedForProductionUse" fun projectMap(field: Field, variable: String, md: MetaData, orderBys: MutableList<Pair<String,Boolean>>): String { val selectionSet = field.selectionSet ?: return "" return projectSelectionFields(md, variable, selectionSet, orderBys).map{ if (it.second == attr(variable, it.first)) ".`${it.first}`" else "`${it.first}` : ${it.second}" }.joinNonEmpty(", ","`$variable` {","}"); } fun where(field: Field, variable: String, md: MetaData, orderBys: MutableList<Pair<String,Boolean>>): String { val predicates = field.arguments.mapNotNull { val name = it.name if (name == "orderBy") { if (it.value is ArrayValue) { (it.value as ArrayValue).values.filterIsInstance<EnumValue>().forEach { val pairs = it.name.split("_") orderBys.add(Pair(pairs[0], pairs[1].toLowerCase() == "asc")) } } null } else if (isPlural(name) && it.value is ArrayValue && md.properties.containsKey(singular(name))) "`${variable}`.`${singular(name)}` IN ${formatValue(it.value)} " else "`${variable}`.`$name` = ${formatValue(it.value)} " // todo directives for more complex filtering }.joinToString(" AND \n") return if (predicates.isBlank()) "" else " WHERE " + predicates; } fun projectSelectionFields(md: MetaData, variable: String, selectionSet: SelectionSet, orderBys: MutableList<Pair<String,Boolean>>): List<Pair<String, String>> { return selectionSet.selections.filterIsInstance<Field>().mapNotNull { f -> // val alias = f.alias ?: f.name // alias is handled in graphql layer val field = f.name val info = md.relationshipFor(field) // todo correct medatadata of if (info == null) { Pair(field, attr(variable, field)) } else { if (f.selectionSet == null) null // todo else { val (patternComp, fieldVariable) = formatPatternComprehension(md,variable,f, orderBys) // metaData(info.label) Pair(field, if (info.multi) patternComp else "head(${patternComp})") } } } } fun nestedPatterns(metaData: MetaData, variable: String, selectionSet: SelectionSet, orderBys: MutableList<Pair<String,Boolean>>): String { return projectSelectionFields(metaData, variable, selectionSet, orderBys).map{ pair -> val (fieldName, projection) = pair "$projection AS `$fieldName`" }.joinToString(",\n","RETURN ") } fun formatPatternComprehension(md: MetaData, variable: String, field: Field, orderBysIgnore: MutableList<Pair<String,Boolean>>): Pair<String,String> { val fieldName = field.name val info = md.relationshipFor(fieldName) ?: return Pair("","") val fieldVariable = variable + "_" + fieldName; val arrowLeft = if (!info.out) "<" else "" val arrowRight = if (info.out) ">" else "" val fieldMetaData = GraphSchemaScanner.getMetaData(info.label)!! val pattern = "(`$variable`)$arrowLeft-[:`${info.type}`]-$arrowRight(`$fieldVariable`:`${info.label}`)" val orderBys2 = mutableListOf<Pair<String,Boolean>>() val where = where(field, fieldVariable, fieldMetaData, orderBys2) val projection = projectMap(field, fieldVariable, fieldMetaData, orderBysIgnore) var result = "[ $pattern $where | $projection]" if (orderBys2.isNotEmpty()) result = "graphql.sortColl($result,${orderBys2.map { "${if (it.second) "^" else ""}'${it.first}'" }.joinNonEmpty(",","[","]")})" return Pair(result,fieldVariable) } override fun generateQueryForField(field: Field): String { val name = field.name val variable = name val md = metaData(name) val orderBys = mutableListOf<Pair<String,Boolean>>() return "MATCH (`$variable`:`$name`) \n" + where(field, variable, md, orderBys) + nestedPatterns(md, variable, field.selectionSet, orderBys) + orderBys.map{ "${it.first} ${if (it.second) "asc" else "desc"}"}.joinNonEmpty(",", "\nORDER BY "); // "\nRETURN *" // + projection(field, variable, md) } } class Cypher30Generator : CypherGenerator() { override fun compiled() = "compiled" fun orderBy(orderBys:List<String>) = if (orderBys.isEmpty()) "" else orderBys.joinNonEmpty(",", "\nWITH * ORDER BY ") fun optionalMatches(metaData: MetaData, variable: String, selections: Iterable<Selection>, orderBys: MutableList<String>) = selections.map { when (it) { is Field -> formatNestedRelationshipMatch(metaData, variable, it, orderBys) else -> "" } }.joinToString("\n") fun formatNestedRelationshipMatch(md: MetaData, variable: String, field: Field, orderBys: MutableList<String>): String { val fieldName = field.name val info = md.relationshipFor(fieldName) ?: return "" val fieldVariable = variable + "_" + fieldName; val arrowLeft = if (!info.out) "<" else "" val arrowRight = if (info.out) ">" else "" val fieldMetaData = GraphSchemaScanner.getMetaData(info.label)!! val pattern = "(`$variable`)$arrowLeft-[:`${info.type}`]-$arrowRight(`$fieldVariable`:`${info.label}`)" val where = where(field, fieldVariable, fieldMetaData, orderBys) val result = "\nOPTIONAL MATCH $pattern $where\n" return result + if (field.selectionSet.selections.isNotEmpty()) optionalMatches(fieldMetaData, fieldVariable, field.selectionSet.selections, orderBys) else "" } fun where(field: Field, variable: String, md: MetaData, orderBys: MutableList<String>): String { val predicates = field.arguments.mapNotNull { val name = it.name if (name == "orderBy") { if (it.value is ArrayValue) { (it.value as ArrayValue).values.filterIsInstance<EnumValue>().forEach { val pairs = it.name.split("_") orderBys.add("`$variable`.`${pairs[0]}` ${pairs[1]}") } } null } else if (isPlural(name) && it.value is ArrayValue && md.properties.containsKey(singular(name))) "`${variable}`.`${singular(name)}` IN ${formatValue(it.value)} " else "`${variable}`.`$name` = ${formatValue(it.value)} " // todo directives for more complex filtering }.joinToString(" AND \n") return if (predicates.isBlank()) "" else " WHERE " + predicates; } fun projection(field: Field, variable: String, md: MetaData): String { val selectionSet = field.selectionSet ?: return "" return projectSelectionFields(md, variable, selectionSet).map{ "${it.second} AS `${it.first}`" }.joinToString(", "); } fun projectMap(field: Field, variable: String, md: MetaData): String { val selectionSet = field.selectionSet ?: return "" return "CASE `$variable` WHEN null THEN null ELSE {"+projectSelectionFields(md, variable, selectionSet).map{ "`${it.first}` : ${it.second}" }.joinToString(", ")+"} END"; } fun projectSelectionFields(md: MetaData, variable: String, selectionSet: SelectionSet): List<Pair<String, String>> { return selectionSet.selections.filterIsInstance<Field>().map { f -> // val alias = f.alias ?: f.name // alias is handled in graphql layer val alias = f.name val info = md.relationshipFor(f.name) // todo correct medatadata of if (info == null) { Pair(alias, "`$variable`.`${f.name}`") } else { if (f.selectionSet == null) null // todo else { val fieldVariable = variable + "_" + f.name val map = projectMap(f, fieldVariable, metaData(info.label)) Pair(alias, if (info.multi) "collect($map)" else map) } } }.filterNotNull() } override fun generateQueryForField(field: Field): String { val name = field.name val variable = name val md = metaData(name) val orderBys = mutableListOf<String>() return "MATCH (`$variable`:`$name`) \n" + where(field, variable, md, orderBys) + optionalMatches(md, variable, field.selectionSet.selections, orderBys) + // TODO order within each orderBy(orderBys) + "\nRETURN " + projection(field, variable, md) } }
0
Kotlin
0
1
6408650254af45deb3dbc78cd5b1bd9f249d05e2
11,141
neo4j-graphql
Apache License 2.0
kotlin/isogram/src/main/kotlin/Isogram.kt
vladflore
299,923,035
false
{"Text": 1, "Ignore List": 1, "Markdown": 51, "Gradle": 10, "Java": 21, "XML": 1, "Gradle Kotlin DSL": 5, "Shell": 9, "Batchfile": 5, "INI": 5, "Kotlin": 10, "Julia": 31, "Python": 20, "jq": 2, "JSON": 1}
object Isogram { fun isIsogram(input: String): Boolean { var specialCharsCount = 0 var letters = emptySet<Char>() for (ch in input.toLowerCase()) { if (ch.isLetter()) { letters = letters.plus(ch) } else { specialCharsCount++ } } return letters.size == input.length - specialCharsCount } }
1
null
1
1
6d6ec893c8389b8fd648cbe6ac9c34930a207ee8
318
exercism
MIT License
app/src/main/java/com/zsoltbertalan/flickslate/data/db/UpcomingMoviesDao.kt
herrbert74
779,374,786
false
{"Kotlin": 227177}
package com.zsoltbertalan.flickslate.data.db import com.zsoltbertalan.flickslate.common.async.IoDispatcher import com.zsoltbertalan.flickslate.common.util.runCatchingUnit import com.zsoltbertalan.flickslate.domain.model.Movie import com.zsoltbertalan.flickslate.domain.model.PageData import com.zsoltbertalan.flickslate.domain.model.PagingReply import io.realm.kotlin.Realm import io.realm.kotlin.UpdatePolicy import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import javax.inject.Inject import javax.inject.Singleton @Singleton class UpcomingMoviesDao @Inject constructor( private val realm: Realm, @IoDispatcher private val ioContext: CoroutineDispatcher, ) : UpcomingMoviesDataSource { override suspend fun purgeDatabase() { realm.write { val moviesToDelete = this.query(UpcomingMovieDbo::class).find() delete(moviesToDelete) } } override suspend fun insertUpcomingMovies(movies: List<Movie>, page: Int) { runCatchingUnit { realm.write { movies.map { copyToRealm(it.toUpcomingMoviesDbo(page), UpdatePolicy.ALL) } } } } override suspend fun insertUpcomingMoviesPageData(page: PageData) { runCatchingUnit { realm.write { copyToRealm(page.toUpcomingMoviesPageDbo(), UpdatePolicy.ALL) } } } override fun getUpcomingMovies(page: Int): Flow<PagingReply<Movie>?> { return realm.query(UpcomingMovieDbo::class, "page = $0", page).asFlow() .map { change -> val pageData = getPageData(page) val isLastPage = pageData?.totalPages == page val pagingList = change.list.map { it.toMovie() }.ifEmpty { null } pagingList?.let { PagingReply(pagingList, isLastPage) } }.flowOn(ioContext) } private fun getPageData(page: Int): PageData? { return realm.query(UpcomingMoviesPageDbo::class, "page = $0", page).find() .map { dbo -> dbo.toPageData() }.firstOrNull() } }
1
Kotlin
2
6
26ed9b8411ad4ff512ee53ac666ac894caba9293
1,948
FlickSlate
Apache License 2.0
commandbasedarchitecture_coroutine/src/main/java/io/scal/commandbasedarchitecture/commands/ExecutionStrategies.kt
scalio
249,327,477
false
{"Kotlin": 80418}
package io.scal.commandbasedarchitecture.commands /** * Strategy that will be used by CommandManager to control command execution flow. */ interface ExecutionStrategy { /** * Called before adding command to pending. * If returns false - command will be skipped and never be executed. * If true - command will be executed somewhere in the future. * @return if the command should be added to execution queue. */ fun shouldAddToPendingActions( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean /** * Called before pendingActionCommand execution to know if this command should wait some time. * Calls during the execution phase of the command with implementing strategy. * @return true if command should wait */ fun shouldBlockOtherTask(pendingActionCommand: Command<*, *>): Boolean /** * Called on the command that want to execute to know if it is a good time for this. * @return true if command should be executed */ fun shouldExecuteAction( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean } /** * Allows concurrent execution always. */ open class ConcurrentStrategy : ExecutionStrategy { override fun shouldAddToPendingActions( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean = true override fun shouldBlockOtherTask(pendingActionCommand: Command<*, *>): Boolean = false override fun shouldExecuteAction( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean = true } /** * Allows concurrent execution only if there are no running commands with same strategy and tag. * Also will remove any pending command with the same tag and replace with a new one. */ open class ConcurrentStrategyWithTag(private val tag: Any) : ConcurrentStrategy() { override fun shouldAddToPendingActions( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean { return !pendingActionCommands.any { command -> command.strategy.let { it is ConcurrentStrategyWithTag && it.tag == tag } } } override fun shouldExecuteAction( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean = !runningActionCommands.any { command -> command.strategy.let { it is ConcurrentStrategyWithTag && it.tag == tag } } } /** * Will be added to the queue only if there are no other tasks with this strategy in pending and running queues. * Will be executed only as a single task and block all other tasks from execution. */ open class SingleStrategy : ExecutionStrategy { override fun shouldAddToPendingActions( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean = !pendingActionCommands.any { it.strategy is SingleStrategy } && !runningActionCommands.any { it.strategy is SingleStrategy } override fun shouldBlockOtherTask(pendingActionCommand: Command<*, *>): Boolean = true override fun shouldExecuteAction( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean = runningActionCommands.isEmpty() } /** * Same as SingleStrategy but will be added to the pending queue only if there are no pending or * running task with a strategy of the same tag. */ open class SingleWithTagStrategy(private val tag: Any) : SingleStrategy() { override fun shouldAddToPendingActions( pendingActionCommands: List<Command<*, *>>, runningActionCommands: List<Command<*, *>> ): Boolean = !pendingActionCommands.any { command -> command.strategy.let { it is SingleWithTagStrategy && it.tag == tag } } && !runningActionCommands.any { command -> command.strategy.let { it is SingleWithTagStrategy && it.tag == tag } } }
0
Kotlin
1
6
ca30738ba772b77090b1c61edaa6f6a7a055974f
4,263
command-based-architecture
Apache License 2.0
domain/src/main/java/org/kafka/domain/observers/ObserveCreatorItems.kt
vipulyaara
612,950,214
false
{"Kotlin": 635130, "JavaScript": 440999, "HTML": 11959, "CSS": 7888, "Shell": 2974}
package org.kafka.domain.observers import com.kafka.data.dao.ItemDao import com.kafka.data.entities.Item import com.kafka.data.model.ArchiveQuery import com.kafka.data.model.booksByAuthor import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toPersistentList import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import org.kafka.base.CoroutineDispatchers import org.kafka.base.domain.SubjectInteractor import javax.inject.Inject class ObserveCreatorItems @Inject constructor( private val dispatchers: CoroutineDispatchers, private val observeQueryItems: ObserveQueryItems, private val itemDao: ItemDao ) : SubjectInteractor<ObserveCreatorItems.Params, ImmutableList<Item>>() { override fun createObservable(params: Params): Flow<ImmutableList<Item>> { return itemDao.observe(params.itemId) .flowOn(dispatchers.io) .flatMapLatest { it?.creator?.name?.let { creator -> val query = ArchiveQuery().booksByAuthor(creator) observeQueryItems.execute(ObserveQueryItems.Params(query)) } ?: flowOf(emptyList()) } .map { it.filterNot { it.itemId == params.itemId }.toPersistentList() } } data class Params(val itemId: String) }
5
Kotlin
5
86
fa64a43602eecac8b93ae9e8b713f6d29ba90727
1,447
Kafka
Apache License 2.0
datawedgeconfigurator/src/main/java/com/zebra/nilac/dwconfigurator/models/ResultType.kt
nilac8991
261,186,326
false
{"Kotlin": 134096, "Java": 744}
package com.zebra.nilac.dwconfigurator.models enum class ResultType { NONE, LAST_RESULT, COMPLETE_RESULT }
0
Kotlin
1
1
791ef7abaf61d864c6e206d290be11f5ae25a2c0
111
datawedge-configurator
MIT License
lint/src/com/android/tools/idea/lint/common/AndroidLintJcenterInspectionSuppressor.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * 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.tools.idea.lint.common import com.intellij.codeInspection.InspectionSuppressor import com.intellij.codeInspection.SuppressQuickFix import com.intellij.psi.PsiElement /** * This suppresses other tools' inspections for calls to jcenter() in Gradle build files written in * Groovy: a generic inspection from the Java-level deprecation of jcenter() in some Gradle * versions, and a more specific inspection from the Gradle IDEA plugin. * * Note that this mechanism does not function for KotlinScript Gradle build files, which */ class AndroidLintJcenterInspectionSuppressor : InspectionSuppressor { override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean = when { toolId == "JCenterRepository" -> true toolId == "GrDeprecatedAPIUsage" && element.text == "jcenter" -> true else -> false } override fun getSuppressActions(element: PsiElement?, toolId: String): Array<SuppressQuickFix> = SuppressQuickFix.EMPTY_ARRAY }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,614
android
Apache License 2.0
app/src/main/java/com/yenaly/han1meviewer/worker/HUpdateWorker.kt
YenalyLiew
524,046,895
false
{"Kotlin": 723868, "Java": 88900}
package com.yenaly.han1meviewer.worker import android.content.Context import android.content.pm.ServiceInfo import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.net.toFile import androidx.core.net.toUri import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingWorkPolicy import androidx.work.ForegroundInfo import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.workDataOf import com.yenaly.han1meviewer.EMPTY_STRING import com.yenaly.han1meviewer.Preferences import com.yenaly.han1meviewer.R import com.yenaly.han1meviewer.UPDATE_NOTIFICATION_CHANNEL import com.yenaly.han1meviewer.logic.model.github.Latest import com.yenaly.han1meviewer.logic.network.HUpdater import com.yenaly.han1meviewer.util.installApkPackage import com.yenaly.han1meviewer.util.runSuspendCatching import com.yenaly.han1meviewer.util.updateFile import com.yenaly.yenaly_libs.utils.showShortToast import kotlin.random.Random /** * @project Han1meViewer * @author <NAME> * @time 2024/03/22 022 21:27 */ class HUpdateWorker( private val context: Context, workerParams: WorkerParameters, ) : CoroutineWorker(context, workerParams), WorkerMixin { companion object { const val TAG = "HUpdateWorker" const val DOWNLOAD_LINK = "download_link" const val NODE_ID = "node_id" const val UPDATE_APK = "update_apk" /** * This function is used to enqueue a download task */ fun enqueue(context: Context, latest: Latest) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val data = workDataOf( DOWNLOAD_LINK to latest.downloadLink, NODE_ID to latest.nodeId, ) val req = OneTimeWorkRequestBuilder<HUpdateWorker>() .addTag(TAG) .setConstraints(constraints) .setInputData(data) .build() WorkManager.getInstance(context) .beginUniqueWork(TAG, ExistingWorkPolicy.REPLACE, req) .enqueue() } /** * This function is used to collect the output of the download task */ suspend fun collectOutput(context: Context) = WorkManager.getInstance(context) .getWorkInfosByTagFlow(TAG) .collect { workInfos -> // 只有一個! val workInfo = workInfos.firstOrNull() workInfo?.let { when (it.state) { WorkInfo.State.SUCCEEDED -> { val apkPath = it.outputData.getString(UPDATE_APK) val file = apkPath?.toUri()?.toFile() file?.let { context.installApkPackage(file) } } WorkInfo.State.FAILED -> { showShortToast(R.string.update_failed) } else -> Unit } } } } private val downloadLink by inputData(DOWNLOAD_LINK, EMPTY_STRING) private val nodeId by inputData(NODE_ID, EMPTY_STRING) private val downloadId = Random.nextInt() override suspend fun doWork(): Result { with(HUpdater) { val file = context.updateFile.apply { delete() } val inject = runSuspendCatching { setForeground(createForegroundInfo(progress = 0)) file.injectUpdate(downloadLink) { progress -> setForeground(createForegroundInfo(progress)) } } if (inject.isSuccess) { val outputData = workDataOf(UPDATE_APK to file.toUri().toString()) Preferences.updateNodeId = nodeId return Result.success(outputData) } else { inject.exceptionOrNull()?.printStackTrace() file.delete() return Result.failure() } } } private fun createForegroundInfo(progress: Int = 0): ForegroundInfo { return ForegroundInfo( downloadId, NotificationCompat.Builder(context, UPDATE_NOTIFICATION_CHANNEL) .setSmallIcon(R.mipmap.ic_launcher) .setOngoing(true) .setContentTitle(context.getString(R.string.downloading_update_percent, progress)) .setPriority(NotificationCompat.PRIORITY_HIGH) .setSilent(true) // #issue-98: 下载时不发出声音 .setProgress(100, progress, false) .build(), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC } else 0 ) } }
21
Kotlin
78
999
b0fa1a9e50b1567e4b5a504dcb6579d5f35427fa
5,020
Han1meViewer
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/appmesh/HttpGatewayRoutePathMatch.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 137826907}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.appmesh import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import io.cloudshiftdev.constructs.Construct import kotlin.String /** * Defines HTTP gateway route matching based on the URL path of the request. * * Example: * * ``` * VirtualGateway gateway; * VirtualService virtualService; * gateway.addGatewayRoute("gateway-route-http-2", GatewayRouteBaseProps.builder() * .routeSpec(GatewayRouteSpec.http(HttpGatewayRouteSpecOptions.builder() * .routeTarget(virtualService) * .match(HttpGatewayRouteMatch.builder() * // This rewrites the path from '/test' to '/rewrittenPath'. * .path(HttpGatewayRoutePathMatch.exactly("/test", "/rewrittenPath")) * .build()) * .build())) * .build()); * ``` */ public abstract class HttpGatewayRoutePathMatch( cdkObject: software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch, ) : CdkObject(cdkObject) { /** * Returns the gateway route path match configuration. * * @param scope */ public open fun bind(scope: Construct): HttpGatewayRoutePathMatchConfig = unwrap(this).bind(scope.let(Construct.Companion::unwrap)).let(HttpGatewayRoutePathMatchConfig::wrap) private class Wrapper( cdkObject: software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch, ) : HttpGatewayRoutePathMatch(cdkObject) public companion object { public fun exactly(path: String): HttpGatewayRoutePathMatch = software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch.exactly(path).let(HttpGatewayRoutePathMatch::wrap) public fun exactly(path: String, rewriteTo: String): HttpGatewayRoutePathMatch = software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch.exactly(path, rewriteTo).let(HttpGatewayRoutePathMatch::wrap) public fun regex(regex: String): HttpGatewayRoutePathMatch = software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch.regex(regex).let(HttpGatewayRoutePathMatch::wrap) public fun regex(regex: String, rewriteTo: String): HttpGatewayRoutePathMatch = software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch.regex(regex, rewriteTo).let(HttpGatewayRoutePathMatch::wrap) public fun startsWith(prefix: String): HttpGatewayRoutePathMatch = software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch.startsWith(prefix).let(HttpGatewayRoutePathMatch::wrap) public fun startsWith(prefix: String, rewriteTo: String): HttpGatewayRoutePathMatch = software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch.startsWith(prefix, rewriteTo).let(HttpGatewayRoutePathMatch::wrap) internal fun wrap(cdkObject: software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch): HttpGatewayRoutePathMatch = CdkObjectWrappers.wrap(cdkObject) as? HttpGatewayRoutePathMatch ?: Wrapper(cdkObject) internal fun unwrap(wrapped: HttpGatewayRoutePathMatch): software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.appmesh.HttpGatewayRoutePathMatch } }
4
Kotlin
0
4
e15f2e27e08adeb755ad44b2424c195521a6f5ba
3,361
kotlin-cdk-wrapper
Apache License 2.0
test/main/kotlin/org/wasabi/test/AutoLocationInterceptorSpecs.kt
server-side
66,091,082
true
{"Kotlin": 108901, "Shell": 582, "HTML": 477, "CSS": 36}
package org.wasabi.test import org.wasabi.protocol.http.StatusCodes import org.wasabi.interceptors.enableAutoLocation import kotlin.test.assertEquals import org.junit.Test as spec public class AutoLocationInterceptorSpecs : TestServerContext() { @spec fun with_auto_location_interceptor_enabled_when_setting_response_as_created_and_resourceId_it_should_return_location_on_post () { val headers = hashMapOf( "User-Agent" to "test-client", "Cache-Control" to "max-age=0", "Accept" to "text/html,application/xhtml+xml,application/xml", "Accept-Encoding" to "gzip,deflate,sdch", "Accept-Language" to "en-US,en;q=0.8", "Accept-Charset" to "ISO-8859-1,utf-8;q=0.7,*" ) TestServer.appServer.enableAutoLocation() TestServer.appServer.post("/person", { response.resourceId = "20" response.setStatus(StatusCodes.Created) }) val response = postForm("http://localhost:${TestServer.definedPort}/person", headers, arrayListOf()) assertEquals("http://localhost:${TestServer.definedPort}/person/20", response.headers.filter { it.getName() == "Location" }.firstOrNull()?.getValue()) } }
0
Kotlin
0
0
f48fba1b1b0b95957b2e13632fadfae7ed109863
1,257
wasabi
Apache License 2.0
idea/testData/refactoring/rename/renameKotlinPropertyWithJvmField/after/RenameKotlinPropertyWithJvmField.kt
JakeWharton
99,388,807
false
null
package testing.rename public open class C { @JvmStatic var second = 1 }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
77
kotlin
Apache License 2.0
app/src/main/java/com/luuu/seven/module/special/detail/ComicSpecialDetailContract.kt
oteher
288,484,684
false
{"Kotlin": 223873}
package com.luuu.seven.module.special.detail import com.luuu.seven.base.BasePresenter import com.luuu.seven.base.BaseView import com.luuu.seven.bean.ComicSpecialDetBean /** * Created by lls on 2017/8/4. * */ interface ComicSpecialDetailContract { interface Presenter : BasePresenter { fun getComicSpecialDetail(id: Int) } interface View : BaseView<Presenter> { fun updateComicList(data: ComicSpecialDetBean) } }
0
null
0
0
56d8fc35e2cd2281e9b96806f0d35d9e0c02f3e1
449
Seven
MIT License
NotificactionTest/app/src/main/java/com/example/notificactiontest/MainActivity.kt
zhoudahuai252
262,296,020
false
null
package com.example.notificactiontest import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.core.app.NotificationCompat import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel("normal", "Normal", NotificationManager.IMPORTANCE_DEFAULT) val channel2 = NotificationChannel("important", "Important", NotificationManager.IMPORTANCE_HIGH) manager.createNotificationChannel(channel2) } sendNotice.setOnClickListener { val intent = Intent(this, NotificationActivity::class.java) val pi = PendingIntent.getActivity(this, 0, intent, 0) val notification = NotificationCompat.Builder(this, "important") .setContentTitle("This is content title") .setContentText("This is content text ...................dfsddfsdfsdfsd") .setSmallIcon(R.drawable.small_icon) .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.large_icon)) .setContentIntent(pi) /* .setStyle( NotificationCompat.BigTextStyle().bigText( "learn how to build notifications ,send and sync data and use voice actions. Get " + "the official Android IDE and developer tools to build apps for Android" ) )*/ .setStyle( NotificationCompat.BigPictureStyle() .bigLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.big_image)) ) .setAutoCancel(true) .build() manager.notify(1, notification) } } }
0
Kotlin
0
0
949fbfc9a32fd755adf89beca3f97889d152afec
2,374
studyRepository
Apache License 2.0
okio/src/nonJvmMain/kotlin/okio/Buffer.kt
square
17,812,502
false
null
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import okio.internal.commonClear import okio.internal.commonCompleteSegmentByteCount import okio.internal.commonCopy import okio.internal.commonCopyTo import okio.internal.commonEquals import okio.internal.commonGet import okio.internal.commonHashCode import okio.internal.commonIndexOf import okio.internal.commonIndexOfElement import okio.internal.commonRangeEquals import okio.internal.commonRead import okio.internal.commonReadAll import okio.internal.commonReadByte import okio.internal.commonReadByteArray import okio.internal.commonReadByteString import okio.internal.commonReadDecimalLong import okio.internal.commonReadFully import okio.internal.commonReadHexadecimalUnsignedLong import okio.internal.commonSkip import okio.internal.commonReadInt import okio.internal.commonReadLong import okio.internal.commonReadShort import okio.internal.commonReadUtf8 import okio.internal.commonReadUtf8CodePoint import okio.internal.commonReadUtf8Line import okio.internal.commonReadUtf8LineStrict import okio.internal.commonSelect import okio.internal.commonSnapshot import okio.internal.commonWritableSegment import okio.internal.commonWrite import okio.internal.commonWriteAll import okio.internal.commonWriteByte import okio.internal.commonWriteDecimalLong import okio.internal.commonWriteHexadecimalUnsignedLong import okio.internal.commonWriteInt import okio.internal.commonWriteLong import okio.internal.commonWriteShort import okio.internal.commonWriteUtf8 import okio.internal.commonWriteUtf8CodePoint actual class Buffer : BufferedSource, BufferedSink { internal actual var head: Segment? = null actual var size: Long = 0L internal set actual override val buffer: Buffer get() = this actual override fun emitCompleteSegments(): Buffer = this // Nowhere to emit to! actual override fun emit(): Buffer = this // Nowhere to emit to! override fun exhausted(): Boolean = size == 0L override fun require(byteCount: Long) { if (size < byteCount) throw EOFException() } override fun request(byteCount: Long): Boolean = size >= byteCount override fun peek(): BufferedSource = PeekSource(this).buffer() actual fun copyTo( out: Buffer, offset: Long, byteCount: Long ): Buffer = commonCopyTo(out, offset, byteCount) actual fun copyTo( out: Buffer, offset: Long ): Buffer = copyTo(out, offset, size - offset) actual operator fun get(pos: Long): Byte = commonGet(pos) actual fun completeSegmentByteCount(): Long = commonCompleteSegmentByteCount() override fun readByte(): Byte = commonReadByte() override fun readShort(): Short = commonReadShort() override fun readInt(): Int = commonReadInt() override fun readLong(): Long = commonReadLong() override fun readShortLe(): Short = readShort().reverseBytes() override fun readIntLe(): Int = readInt().reverseBytes() override fun readLongLe(): Long = readLong().reverseBytes() override fun readDecimalLong(): Long = commonReadDecimalLong() override fun readHexadecimalUnsignedLong(): Long = commonReadHexadecimalUnsignedLong() override fun readByteString(): ByteString = commonReadByteString() override fun readByteString(byteCount: Long): ByteString = commonReadByteString(byteCount) override fun readFully(sink: Buffer, byteCount: Long): Unit = commonReadFully(sink, byteCount) override fun readAll(sink: Sink): Long = commonReadAll(sink) override fun readUtf8(): String = readUtf8(size) override fun readUtf8(byteCount: Long): String = commonReadUtf8(byteCount) override fun readUtf8Line(): String? = commonReadUtf8Line() override fun readUtf8LineStrict(): String = readUtf8LineStrict(Long.MAX_VALUE) override fun readUtf8LineStrict(limit: Long): String = commonReadUtf8LineStrict(limit) override fun readUtf8CodePoint(): Int = commonReadUtf8CodePoint() override fun select(options: Options): Int = commonSelect(options) override fun readByteArray(): ByteArray = commonReadByteArray() override fun readByteArray(byteCount: Long): ByteArray = commonReadByteArray(byteCount) override fun read(sink: ByteArray): Int = commonRead(sink) override fun readFully(sink: ByteArray): Unit = commonReadFully(sink) override fun read(sink: ByteArray, offset: Int, byteCount: Int): Int = commonRead(sink, offset, byteCount) actual fun clear(): Unit = commonClear() actual override fun skip(byteCount: Long): Unit = commonSkip(byteCount) actual override fun write(byteString: ByteString): Buffer = commonWrite(byteString) actual override fun write(byteString: ByteString, offset: Int, byteCount: Int) = commonWrite(byteString, offset, byteCount) internal actual fun writableSegment(minimumCapacity: Int): Segment = commonWritableSegment(minimumCapacity) actual override fun writeUtf8(string: String): Buffer = writeUtf8(string, 0, string.length) actual override fun writeUtf8(string: String, beginIndex: Int, endIndex: Int): Buffer = commonWriteUtf8(string, beginIndex, endIndex) actual override fun writeUtf8CodePoint(codePoint: Int): Buffer = commonWriteUtf8CodePoint(codePoint) actual override fun write(source: ByteArray): Buffer = commonWrite(source) actual override fun write(source: ByteArray, offset: Int, byteCount: Int): Buffer = commonWrite(source, offset, byteCount) override fun writeAll(source: Source): Long = commonWriteAll(source) actual override fun write(source: Source, byteCount: Long): Buffer = commonWrite(source, byteCount) actual override fun writeByte(b: Int): Buffer = commonWriteByte(b) actual override fun writeShort(s: Int): Buffer = commonWriteShort(s) actual override fun writeShortLe(s: Int): Buffer = writeShort(s.toShort().reverseBytes().toInt()) actual override fun writeInt(i: Int): Buffer = commonWriteInt(i) actual override fun writeIntLe(i: Int): Buffer = writeInt(i.reverseBytes()) actual override fun writeLong(v: Long): Buffer = commonWriteLong(v) actual override fun writeLongLe(v: Long): Buffer = writeLong(v.reverseBytes()) actual override fun writeDecimalLong(v: Long): Buffer = commonWriteDecimalLong(v) actual override fun writeHexadecimalUnsignedLong(v: Long): Buffer = commonWriteHexadecimalUnsignedLong(v) override fun write(source: Buffer, byteCount: Long): Unit = commonWrite(source, byteCount) override fun read(sink: Buffer, byteCount: Long): Long = commonRead(sink, byteCount) override fun indexOf(b: Byte): Long = indexOf(b, 0, Long.MAX_VALUE) override fun indexOf(b: Byte, fromIndex: Long): Long = indexOf(b, fromIndex, Long.MAX_VALUE) override fun indexOf(b: Byte, fromIndex: Long, toIndex: Long): Long = commonIndexOf(b, fromIndex, toIndex) override fun indexOf(bytes: ByteString): Long = indexOf(bytes, 0) override fun indexOf(bytes: ByteString, fromIndex: Long): Long = commonIndexOf(bytes, fromIndex) override fun indexOfElement(targetBytes: ByteString): Long = indexOfElement(targetBytes, 0L) override fun indexOfElement(targetBytes: ByteString, fromIndex: Long): Long = commonIndexOfElement(targetBytes, fromIndex) override fun rangeEquals(offset: Long, bytes: ByteString): Boolean = rangeEquals(offset, bytes, 0, bytes.size) override fun rangeEquals( offset: Long, bytes: ByteString, bytesOffset: Int, byteCount: Int ): Boolean = commonRangeEquals(offset, bytes, bytesOffset, byteCount) override fun flush() { } override fun close() { } override fun timeout(): Timeout = Timeout.NONE override fun equals(other: Any?): Boolean = commonEquals(other) override fun hashCode(): Int = commonHashCode() /** * Returns a human-readable string that describes the contents of this buffer. Typically this * is a string like `[text=Hello]` or `[hex=0000ffff]`. */ override fun toString() = snapshot().toString() actual fun copy(): Buffer = commonCopy() actual fun snapshot(): ByteString = commonSnapshot() actual fun snapshot(byteCount: Int): ByteString = commonSnapshot(byteCount) }
92
null
1210
8,795
0f6c9cf31101483e6ee9602e80a10f7697c8f75a
8,628
okio
Apache License 2.0
rpgJavaInterpreter-core/src/test/kotlin/com/smeup/rpgparser/parsing/ast/DataDefinitionTestCompiled.kt
smeup
170,714,014
false
{"RPGLE": 7104144, "Kotlin": 1772824, "ANTLR": 163198, "Java": 13658, "Ruby": 1899, "PowerShell": 861, "Dockerfile": 551, "Batchfile": 395}
package com.smeup.rpgparser.parsing.ast class DataDefinitionTestCompiled : DataDefinitionTest() { override fun useCompiledVersion() = true }
5
RPGLE
11
65
fb9f97fb57b9f9a87fdfbec3697d21f6bd251004
146
jariko
Apache License 2.0
app/src/main/java/live/mehiz/mpvkt/ui/preferences/SubtitlesPreferencesScreen.kt
abdallahmehiz
799,697,356
false
{"Kotlin": 142134}
package live.mehiz.mpvkt.ui.preferences import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import live.mehiz.mpvkt.R import live.mehiz.mpvkt.preferences.SubtitlesPreferences import me.zhanghai.compose.preference.ProvidePreferenceLocals import me.zhanghai.compose.preference.textFieldPreference import org.koin.compose.koinInject object SubtitlesPreferencesScreen : Screen { @OptIn(ExperimentalMaterial3Api::class) @Composable override fun Content() { val navigator = LocalNavigator.currentOrThrow val preferences = koinInject<SubtitlesPreferences>() Scaffold( topBar = { TopAppBar( title = { Text(stringResource(R.string.pref_preferred_languages)) }, navigationIcon = { IconButton(onClick = { navigator.pop() }) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, null) } }, ) }, ) { padding -> ProvidePreferenceLocals { LazyColumn( modifier = Modifier .fillMaxSize() .padding(padding), ) { textFieldPreference( preferences.preferredLanguages.key(), defaultValue = preferences.preferredLanguages.defaultValue(), textToValue = { it }, title = { Text(stringResource(R.string.pref_preferred_languages)) }, summary = { if (it.isNotBlank()) Text(it) }, textField = { value, onValueChange, _ -> Column { Text(stringResource(`is`.xyz.mpv.R.string.pref_default_subtitle_language_message)) TextField( value, onValueChange, modifier = Modifier.fillMaxWidth() ) } }, ) } } } } }
3
Kotlin
2
3
7aaf01ee879aafafb69319d3a0b69a0865b7a031
2,727
mpvKt
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/FullRefusjonTilNullRefusjonE2ETest.kt
navikt
193,907,367
false
null
package no.nav.helse.spleis.e2e import no.nav.helse.Toggle import no.nav.helse.Toggle.Companion.enable import no.nav.helse.februar import no.nav.helse.hendelser.Inntektsmelding import no.nav.helse.hendelser.Sykmeldingsperiode import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom import no.nav.helse.hendelser.til import no.nav.helse.inspectors.inspektør import no.nav.helse.januar import no.nav.helse.utbetalingslinjer.Oppdrag import no.nav.helse.utbetalingslinjer.Oppdragstatus.AKSEPTERT import no.nav.helse.økonomi.Inntekt.Companion.daglig import no.nav.helse.økonomi.Prosentdel.Companion.prosent import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class FullRefusjonTilNullRefusjonE2ETest : AbstractEndToEndTest() { @BeforeEach fun setup() { Toggle.LageBrukerutbetaling.enable() } @AfterEach fun teardown() { Toggle.LageBrukerutbetaling.pop() } @Test fun `starter med ingen refusjon`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar, refusjon = Inntektsmelding.Refusjon(0.daglig, null)) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode) håndterUtbetalingsgodkjenning(1.vedtaksperiode, true) håndterUtbetalt(1.vedtaksperiode, AKSEPTERT) håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent)) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent)) håndterYtelser(2.vedtaksperiode) håndterSimulering(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode, true) håndterUtbetalt(2.vedtaksperiode, AKSEPTERT) assertFalse(inspektør.utbetaling(0).inspektør.arbeidsgiverOppdrag.harUtbetalinger()) assertTrue(inspektør.utbetaling(0).inspektør.personOppdrag.harUtbetalinger()) assertEquals(17.januar til 31.januar, Oppdrag.periode(inspektør.utbetaling(0).inspektør.personOppdrag)) assertFalse(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag.harUtbetalinger()) assertTrue(inspektør.utbetaling(1).inspektør.personOppdrag.harUtbetalinger()) assertEquals(17.januar til 28.februar, Oppdrag.periode(inspektør.utbetaling(1).inspektør.personOppdrag)) } @Test fun `starter med refusjon, så ingen refusjon`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar, refusjon = Inntektsmelding.Refusjon(INNTEKT, 31.januar)) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode) håndterUtbetalingsgodkjenning(1.vedtaksperiode, true) håndterUtbetalt(1.vedtaksperiode, AKSEPTERT) håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent)) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent)) håndterYtelser(2.vedtaksperiode) håndterSimulering(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode, true) håndterUtbetalt(2.vedtaksperiode, AKSEPTERT) assertFalse(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag.harUtbetalinger()) assertEquals(17.januar til 31.januar, Oppdrag.periode(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag)) assertTrue(inspektør.utbetaling(1).inspektør.personOppdrag.harUtbetalinger()) assertEquals(1.februar til 28.februar, Oppdrag.periode(inspektør.utbetaling(1).inspektør.personOppdrag)) } @Test fun `starter med refusjon som opphører i neste periode`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar, refusjon = Inntektsmelding.Refusjon(INNTEKT, 3.februar)) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode) håndterUtbetalingsgodkjenning(1.vedtaksperiode, true) håndterUtbetalt(1.vedtaksperiode, AKSEPTERT) håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent)) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent)) håndterYtelser(2.vedtaksperiode) assertTrue(inspektør.periodeErForkastet(2.vedtaksperiode)) { "refusjonen opphører i den andre perioden, som betyr at vi skal betale ut penger i to oppdrag samtidig" } } @Test fun `starter med refusjon, så korrigeres refusjonen til ingenting`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode) håndterUtbetalingsgodkjenning(1.vedtaksperiode, true) håndterUtbetalt(1.vedtaksperiode, AKSEPTERT) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar, refusjon = Inntektsmelding.Refusjon(INNTEKT, 31.januar)) håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent)) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent)) håndterYtelser(2.vedtaksperiode) håndterSimulering(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode, true) håndterUtbetalt(2.vedtaksperiode, AKSEPTERT) assertFalse(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag.harUtbetalinger()) assertEquals(17.januar til 31.januar, Oppdrag.periode(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag)) assertTrue(inspektør.utbetaling(1).inspektør.personOppdrag.harUtbetalinger()) assertEquals(1.februar til 28.februar, Oppdrag.periode(inspektør.utbetaling(1).inspektør.personOppdrag)) } @Test fun `starter med ingen refusjon, så korrigeres refusjonen til full`() = listOf(Toggle.LageBrukerutbetaling, Toggle.DelvisRefusjon).enable { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar, refusjon = Inntektsmelding.Refusjon(0.daglig, null)) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode) håndterUtbetalingsgodkjenning(1.vedtaksperiode, true) håndterUtbetalt(1.vedtaksperiode, AKSEPTERT) håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 1.januar) håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent)) håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent)) håndterYtelser(2.vedtaksperiode) håndterSimulering(2.vedtaksperiode) håndterUtbetalingsgodkjenning(2.vedtaksperiode, true) håndterUtbetalt(2.vedtaksperiode, AKSEPTERT) assertFalse(inspektør.utbetaling(0).inspektør.arbeidsgiverOppdrag.harUtbetalinger()) assertTrue(inspektør.utbetaling(0).inspektør.personOppdrag.harUtbetalinger()) assertEquals(17.januar til 31.januar, Oppdrag.periode(inspektør.utbetaling(0).inspektør.personOppdrag)) assertTrue(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag.harUtbetalinger()) assertTrue(inspektør.utbetaling(1).inspektør.personOppdrag.harUtbetalinger()) assertTrue(inspektør.utbetaling(1).inspektør.personOppdrag[0].erOpphør()) assertEquals(17.januar til 28.februar, Oppdrag.periode(inspektør.utbetaling(1).inspektør.arbeidsgiverOppdrag)) assertNoWarnings(2.vedtaksperiode.filter()) } }
0
null
2
4
a3ba622f138449986fc9fd44e467104a61b95577
8,462
helse-spleis
MIT License
src/main/kotlin/com/mt/notion/api/block/request/update/UpdateParagraphBlockRequest.kt
motui
479,945,371
false
null
package com.mt.notion.api.block.request.update import com.mt.notion.api.block.BlockObjectType /** * * @author it.motui */ data class UpdateParagraphBlockRequest( override val archived: Boolean? = false, val type: BlockObjectType? = BlockObjectType.Paragraph, val paragraph: UpdateBlockRichText ) : UpdateBlockRequest
0
Kotlin
0
1
80b7b256d8d7c34b15cf79d1e5f539c8ef4736b4
333
notion-sdk-kotlin
MIT License
app/src/main/java/bry1337/github/io/newsthings/ui/MainActivity.kt
Bry1337
204,101,629
false
null
package bry1337.github.io.deliveryman import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.findNavController import androidx.navigation.ui.NavigationUI.* import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) setupNavigation() } private fun setupNavigation() { val navController = findNavController(R.id.nav_host_fragment) setupActionBarWithNavController(this, navController, null) setupWithNavController(toolbar, navController) } override fun onSupportNavigateUp(): Boolean { return navigateUp(findNavController(R.id.nav_host_fragment), null) } }
0
Kotlin
0
0
883aaaaa746aae68567660d058a6694107f226a8
842
redesigned-garbanzo
The Unlicense
chapter-final/app/src/main/java/com/example/learnwithme/presentation/components/CustomProgressIndicator.kt
fsalom
677,505,777
false
{"Kotlin": 275503}
package com.example.learnwithme.presentation.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay @Composable fun CustomProgressIndicator() { var show by remember { mutableStateOf(true) } val timeout: Long = 10000 LaunchedEffect(key1 = Unit){ delay(timeout) show = false } if (show) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { CircularProgressIndicator( modifier = Modifier.size(32.dp), color = Color.LightGray, strokeWidth = 5.dp ) } } }
0
Kotlin
0
0
d4b60cb1150c5a10397ed92ce8b04893e7310948
1,374
android-compose
MIT License