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
web/buildSrc/src/main/kotlin/SeleniumDriverPlugin.kt
JetBrains
293,498,508
false
null
package jetbrains.compose.web.gradle import org.gradle.api.* import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform import java.io.File import java.net.URL private val CHROME_DRIVER_VERSION = "114.0.5735.90" private val GECKO_DRIVER_VERSION = "0.31.0" private fun download(url: String, file: File) { println("downloading ${url} to ${file}") file.writeBytes(URL(url).readBytes()) } private fun Project.extractZip(archive: File, destDir: String) { println("unpacking ${archive.absolutePath} to ${destDir}") copy { copySpec -> copySpec .from(zipTree(archive)) .into(destDir) } } private fun Project.extractTar(archive: File, destDir: String) { println("unpacking ${archive.absolutePath} to ${destDir}") copy { copySpec -> copySpec .from(tarTree(resources.gzip(archive))) .into(destDir) } } private fun Project.extract(archive: File, destDir: String) { when { archive.absolutePath.endsWith(".zip") -> extractZip(archive, destDir) archive.absolutePath.endsWith(".gz") -> extractTar(archive, destDir) } } private fun resolvePath(id: String): String { val os = DefaultNativePlatform.getCurrentOperatingSystem() val arch = DefaultNativePlatform.getCurrentArchitecture() val geckoRepo = "https://github.com/mozilla/geckodriver/releases/download/v$GECKO_DRIVER_VERSION/" val chromeRepo = "https://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/" return when (id) { "chrome" -> chromeRepo + when { os.isWindows -> "chromedriver_win32.zip" os.isMacOsX -> if (arch.isArm) { "chromedriver_mac64_m1.zip" } else { "chromedriver_mac64.zip" } else -> "chromedriver_linux64.zip" } "gecko" -> geckoRepo + when { os.isWindows -> "geckodriver-v$GECKO_DRIVER_VERSION-win64.zip" os.isMacOsX -> if (arch.isArm) { "geckodriver-v$GECKO_DRIVER_VERSION-macos-aarch64.tar.gz" } else { "geckodriver-v$GECKO_DRIVER_VERSION-macos.tar.gz" } else -> "geckodriver-v$GECKO_DRIVER_VERSION-linux64.tar.gz" } else -> throw Exception("unknown id: ${id}") } } private fun Project.pathToDriverDir(id: String) = gradle.gradleUserHomeDir.resolve("selenium/$id").absolutePath private fun Project.pathToDriver(id: String): String { val os = DefaultNativePlatform.getCurrentOperatingSystem() val extension = if (os.isWindows) ".exe" else "" return File(pathToDriverDir(id)).resolve("${id}driver$extension").absolutePath } private fun Project.install(id: String) { val driverPath = resolvePath(id) File.createTempFile("selenium_", "." + driverPath.substringAfterLast(".")).let { download( driverPath, it ) project.extract(it, project.pathToDriverDir(id)) } } class SeleniumDriverPlugin: Plugin<Project> { override fun apply(project: Project) { if (System.getProperty("webdriver.chrome.driver") == null) { project.extensions.add("webdriver.chrome.driver", project.pathToDriver("chrome")) } if (System.getProperty("webdriver.gecko.driver") == null) { project.extensions.add("webdriver.gecko.driver", project.pathToDriver("gecko")) } project.tasks.register("installGeckoDriver") { project.install("gecko") } project.tasks.register("installChromeDriver") { project.install("chrome") } project.tasks.register("installWebDrivers") { it.dependsOn("installChromeDriver", "installGeckoDriver") } } }
934
Kotlin
933
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
3,776
compose-jb
Apache License 2.0
app/src/main/java/com/dmbaryshev/bd/model/dto/VkPhoto.kt
DmBard
57,616,046
false
null
package com.dmbaryshev.bd.model.dto import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class VkPhoto( @SerializedName("id") @Expose @PrimaryKey open var id: Int = 0, @SerializedName("album_id") @Expose open var albumId: Int = 0, @SerializedName("owner_id") @Expose open var ownerId: Int = 0, @SerializedName("photo_75") @Expose open var photo75: String = "", @SerializedName("photo_130") @Expose open var photo130: String = "", @SerializedName("photo_604") @Expose open var photo604: String = "", @SerializedName("photo_807") @Expose open var photo807: String = "", @SerializedName("photo_1280") @Expose open var photo1280: String = "", @SerializedName("width") @Expose open var width: Int = 0, @SerializedName("height") @Expose open var height: Int = 0, @SerializedName("text") @Expose open var text: String = "", @SerializedName("date") @Expose open var date: Int = 0, @SerializedName("access_key") @Expose open var accessKey: String = "" ):RealmObject(){}
0
Kotlin
0
7
7c554d784a45097001a2af7505e00bddc594fecb
1,412
bd
Apache License 2.0
domain/src/main/java/com/thelazybattley/domain/di/RepositoryModule.kt
dellosaneil
720,658,411
false
{"Kotlin": 180336}
package com.thelazybattley.domain.di import com.thelazybattley.domain.repository.WeatherRepository import com.thelazybattley.domain.repository.impl.WeatherRepositoryImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Binds abstract fun bindsWeatherRepository(impl: WeatherRepositoryImpl): WeatherRepository }
0
Kotlin
0
0
adb7ffc205a27b95b8c847ee3af6dcca373b80ca
474
weather-app
Apache License 2.0
filesystem/src/jvmMain/kotlin/nio/NioReadFd.kt
illarionov
848,247,126
false
{"Kotlin": 1163678, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
/* * Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package at.released.weh.filesystem.nio import arrow.core.Either import arrow.core.left import at.released.weh.filesystem.error.BadFileDescriptor import at.released.weh.filesystem.error.ReadError import at.released.weh.filesystem.internal.delegatefs.FileSystemOperationHandler import at.released.weh.filesystem.op.Messages.fileDescriptorNotOpenMessage import at.released.weh.filesystem.op.readwrite.ReadFd import kotlin.concurrent.withLock internal class NioReadFd( private val fsState: NioFileSystemState, ) : FileSystemOperationHandler<ReadFd, ReadError, ULong> { override fun invoke(input: ReadFd): Either<ReadError, ULong> = fsState.fsLock.withLock { val channel = fsState.get(input.fd) ?: return BadFileDescriptor(fileDescriptorNotOpenMessage(input.fd)).left() return channel.read(input.iovecs, input.strategy) } }
1
Kotlin
0
3
8960e9ee5feb1ef319446725f4ca60e55d5b1c83
1,131
wasi-emscripten-host
Apache License 2.0
modules/graph/sources-jvm/assembly/RaptorGraphsComponent.kt
fluidsonic
246,018,343
false
null
package io.fluidsonic.raptor.graph import io.fluidsonic.raptor.* public class RaptorGraphsComponent internal constructor() : RaptorComponent.Base<RaptorGraphsComponent>(RaptorGraphPlugin), RaptorComponentSet<RaptorGraphComponent> { @RaptorDsl override val all: RaptorAssemblyQuery<RaptorGraphComponent> get() = componentRegistry.all(Keys.graphComponent).all internal fun complete(): Collection<RaptorGraph> = componentRegistry.many(Keys.graphComponent).map { it.complete() } @RaptorDsl public fun new(): RaptorGraphComponent = componentRegistry.register(Keys.graphComponent, RaptorGraphComponent()) @RaptorDsl public fun new(configure: RaptorGraphComponent.() -> Unit) { new().configure() } } @RaptorDsl public val RaptorPluginScope<in RaptorGraphPlugin>.graphs: RaptorGraphsComponent get() = componentRegistry.oneOrNull(Keys.graphsComponent) ?: throw RaptorPluginNotInstalledException(RaptorGraphPlugin)
0
Kotlin
1
6
aa106d096b700d6eadbcf9ef5df8ec102f7a3fac
936
raptor
Apache License 2.0
frogosdk/src/main/java/com/frogobox/sdk/ext/FrogoRxJavaExt.kt
frogobox
463,917,159
false
null
package com.frogobox.sdk.ext import androidx.lifecycle.MutableLiveData import com.frogobox.coresdk.observer.FrogoApiObserver import com.frogobox.coresdk.observer.FrogoLocalObserver import com.frogobox.coresdk.response.FrogoDataResponse import com.frogobox.coresdk.response.FrogoStateResponse import com.frogobox.coresdk.source.FrogoResult import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.schedulers.Schedulers /** * Created by faisalamir on 08/04/22 * FrogoSDK * ----------------------------------------- * Name : Muhammad Faisal Amir * E-mail : faisalamircs@gmail.com * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2022 Frogobox Media Inc. * All rights reserved * */ fun <T : Any> Observable<T>.doApiRequest( callback: FrogoDataResponse<T>, addCallbackSubscribe: (d: Disposable) -> Unit ) { subscribeOn(Schedulers.io()) .doOnSubscribe { callback.onShowProgress() } .doAfterTerminate { callback.onHideProgress() callback.onFinish() } .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : FrogoApiObserver<T>() { override fun onApiSuccess(data: T) { callback.onSuccess(data) } override fun onApiFailure(code: Int, errorMessage: String) { callback.onFailed(code, errorMessage) } override fun onApiFinish() { callback.onFinish() } override fun onApiStartObserver(disposable: Disposable) { addCallbackSubscribe(disposable) } }) } fun <T : Any> Observable<T>.doApiRequest( result: MutableLiveData<FrogoResult<T>>, addCallbackSubscribe: (d: Disposable) -> Unit ) { doApiRequest(object : FrogoDataResponse<T> { override fun onShowProgress() { result.postValue(FrogoResult.ShowLoading()) } override fun onHideProgress() { result.postValue(FrogoResult.HideLoading()) } override fun onSuccess(data: T) { result.postValue(FrogoResult.Success(data)) } override fun onFailed(code: Int, errorMessage: String) { result.postValue(FrogoResult.Error(code, errorMessage)) } override fun onFinish() { result.postValue(FrogoResult.Finish()) } }) { addCallbackSubscribe(it) } } // ------------------------------------------------------------------------------------------------- fun <T : Any> Single<T>.fetchRoomDB( callback: FrogoDataResponse<T>, addCallbackSubscribe: (d: Disposable) -> Unit ) { subscribeOn(Schedulers.io()) .doOnSubscribe { callback.onShowProgress() } .doAfterTerminate { callback.onHideProgress() } .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : FrogoLocalObserver<T>() { override fun onLocalFinish() { callback.onFinish() } override fun onLocalFailure(code: Int, errorMessage: String) { callback.onFailed(code, errorMessage) } override fun onLocalSuccess(data: T) { callback.onSuccess(data) } override fun onLocalStartObserver(disposable: Disposable) { addCallbackSubscribe(disposable) } }) } fun <T : Any> Observable<T>.fetchPreference(callback: FrogoDataResponse<T>) { subscribeOn(Schedulers.io()) .doOnSubscribe { callback.onShowProgress() } .doAfterTerminate { callback.onHideProgress() } .observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.onSuccess(it) callback.onFinish() }, { it.message?.let { it1 -> callback.onFailed(200, it1) } callback.onFinish() }) } // ------------------------------------------------------------------------------------------------- fun Completable.executeRoomDB(callback: FrogoStateResponse) { callback.onShowProgress() subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.onSuccess() callback.onHideProgress() callback.onFinish() }) { it.message?.let { it1 -> callback.onFailed(200, it1) } callback.onHideProgress() callback.onFinish() } } fun Completable.executePreference(callback: FrogoStateResponse) { callback.onShowProgress() subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.onSuccess() callback.onHideProgress() callback.onFinish() }) { it.message?.let { it1 -> callback.onFailed(200, it1) } callback.onHideProgress() callback.onFinish() } } fun Completable.executeAction(callback: FrogoStateResponse) { callback.onShowProgress() subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ callback.onSuccess() callback.onHideProgress() callback.onFinish() }) { it.message?.let { it1 -> callback.onFailed(200, it1) } callback.onHideProgress() callback.onFinish() } } // -------------------------------------------------------------------------------------------------
0
Kotlin
4
12
7c7f694d6a74cbbdd902a0fdc9548d41371217a2
5,837
frogo-sdk
Apache License 2.0
shared/src/main/kotlin/bz/stewart/bracken/shared/data/VisibleType.kt
abigpotostew
92,021,572
false
null
package bz.stewart.bracken.shared.data /** * For enum classes with an ordinal per instance. To help with selecting the item with both an integer and a nice visible name * Created by stew on 1/25/17. */ interface VisibleType { fun lowercaseName(): String fun capitalizedName(): String fun niceFormat(): String fun shortLabel(): String fun shortCode():String }
0
Kotlin
0
0
edd326981cc23168d7bf23852e638767dbac3547
383
easypolitics
Apache License 2.0
save-cloud-common/src/commonMain/kotlin/com/saveourtool/save/entities/vulnerability/VulnerabilityStatus.kt
saveourtool
300,279,336
false
{"Kotlin": 3416213, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
package com.saveourtool.common.entities.vulnerability import kotlin.js.JsExport import kotlinx.serialization.Serializable /** * A value for vulnerability statuses. * * @property value */ @Serializable @JsExport @Suppress("IDENTIFIER_LENGTH") enum class VulnerabilityStatus(val value: String) { /** * Approve status */ APPROVED("Approved"), /** * Automatically approved by batch-upload */ AUTO_APPROVED("Approved"), /** * Created status */ CREATED("Created"), /** * Review status */ PENDING_REVIEW("Edited"), /** * Reject status */ REJECTED("Rejected"), ; }
201
Kotlin
3
38
8f62e13ee6618a36ad2df7ff15ecfb8019ec19d5
661
save-cloud
MIT License
kmdc/kmdc-radio/src/jsMain/kotlin/MDCRadio.kt
mpetuska
430,798,310
false
null
package dev.petuska.kmdc.radio import androidx.compose.runtime.Composable import dev.petuska.kmdc.core.Builder import dev.petuska.kmdc.core.MDCDsl import dev.petuska.kmdc.core.initialiseMDC import dev.petuska.kmdc.core.mdc import dev.petuska.kmdc.core.rememberUniqueDomElementId import dev.petuska.kmdc.form.field.MDCFormFieldScope import org.jetbrains.compose.web.attributes.InputType import org.jetbrains.compose.web.attributes.builders.InputAttrsScope import org.jetbrains.compose.web.attributes.disabled import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.Input import org.jetbrains.compose.web.dom.Label import org.jetbrains.compose.web.dom.Text @JsModule("@material/radio/dist/mdc.radio.css") public external val MDCRadioStyle: dynamic public data class MDCRadioOpts( public var disabled: Boolean = false, public var label: String? = null, ) /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-radio) */ @MDCDsl @Composable public fun MDCRadio( checked: Boolean, opts: Builder<MDCRadioOpts>? = null, attrs: Builder<InputAttrsScope<Boolean>>? = null, ) { MDCRadioBody(checked, opts, attrs) } /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-radio) */ @MDCDsl @Composable public fun MDCFormFieldScope.MDCRadio( checked: Boolean, opts: Builder<MDCRadioOpts>? = null, attrs: Builder<InputAttrsScope<Boolean>>? = null, ) { MDCRadioBody(checked, opts, attrs = { ref { it.mdc<MDCRadioModule.MDCRadio> { setInput(it, this) } onDispose { } } attrs?.invoke(this) }) } @MDCDsl @Composable private fun MDCRadioBody( checked: Boolean, opts: Builder<MDCRadioOpts>? = null, attrs: Builder<InputAttrsScope<Boolean>>? = null, ) { MDCRadioStyle val options = MDCRadioOpts().apply { opts?.invoke(this) } val radioId = rememberUniqueDomElementId() Div(attrs = { classes("mdc-radio") if (options.disabled) classes("mdc-radio--disabled") initialiseMDC(MDCRadioModule.MDCRadio::attachTo) }) { Input(type = InputType.Radio, attrs = { classes("mdc-radio__native-control") // This must precede `checked()` checked(checked) // This must follow `classes(...)` id(radioId) if (options.disabled) disabled() attrs?.invoke(this) }) Div(attrs = { classes("mdc-radio__background") }) { Div(attrs = { classes("mdc-radio__outer-circle") }) Div(attrs = { classes("mdc-radio__inner-circle") }) } Div(attrs = { classes("mdc-radio__ripple") }) } options.label?.let { Label(forId = radioId, attrs = { id("$radioId-label") }) { Text(it) } } }
22
Kotlin
8
29
67b31502b5f76b64f7571821fdd0b78a3df0a68c
2,707
kmdc
Apache License 2.0
app/src/main/java/com/ilaps/androidtest/common/auth/BaseAuthPresenter.kt
ricardoAntolin
96,248,010
false
null
package com.ilaps.androidtest.common.auth import com.google.firebase.auth.FirebaseAuth /** * Created by ricar on 5/7/17. */ abstract class BaseAuthPresenter<T : BaseAuthView > : FirebaseAuth.AuthStateListener { var view: T? = null var auth = FirebaseAuth.getInstance()!! fun onStart(view: T) { this.view = view auth.addAuthStateListener(this) } fun onStop() { auth.removeAuthStateListener(this) } override fun onAuthStateChanged(p0: FirebaseAuth) { val user = p0.currentUser if (user != null) view?.userLogged(user) } }
0
Kotlin
0
0
cdcc78769ad8948b039791bf6e6da31aa7a53642
599
AndroidBluetoothDeviceListExample
Apache License 2.0
utbot-java-fuzzing/src/main/kotlin/org/utbot/fuzzing/spring/valid/ValidEntity.kt
UnitTestBot
480,810,501
false
null
package org.utbot.fuzzing.spring.valid import org.utbot.common.toDynamicProperties import org.utbot.common.withValue import org.utbot.framework.plugin.api.ClassId import org.utbot.framework.plugin.api.FieldId import org.utbot.framework.plugin.api.MethodId import org.utbot.framework.plugin.api.UtAssembleModel import org.utbot.framework.plugin.api.UtDirectSetFieldModel import org.utbot.framework.plugin.api.UtExecutableCallModel import org.utbot.framework.plugin.api.UtSpringEntityManagerModel import org.utbot.framework.plugin.api.util.SpringModelUtils.entityClassIds import org.utbot.framework.plugin.api.util.SpringModelUtils.generatedValueClassIds import org.utbot.framework.plugin.api.util.SpringModelUtils.detachMethodIdOrNull import org.utbot.framework.plugin.api.util.SpringModelUtils.emailClassIds import org.utbot.framework.plugin.api.util.SpringModelUtils.persistMethodIdOrNull import org.utbot.framework.plugin.api.util.SpringModelUtils.idClassIds import org.utbot.framework.plugin.api.util.SpringModelUtils.notBlankClassIds import org.utbot.framework.plugin.api.util.SpringModelUtils.notEmptyClassIds import org.utbot.framework.plugin.api.util.allDeclaredFieldIds import org.utbot.framework.plugin.api.util.executableId import org.utbot.framework.plugin.api.util.id import org.utbot.framework.plugin.api.util.jClass import org.utbot.framework.plugin.api.util.jField import org.utbot.fuzzer.FuzzedType import org.utbot.fuzzer.FuzzedValue import org.utbot.fuzzer.IdGenerator import org.utbot.fuzzer.fuzzed import org.utbot.fuzzing.FuzzedDescription import org.utbot.fuzzing.JavaValueProvider import org.utbot.fuzzing.Routine import org.utbot.fuzzing.Seed import org.utbot.fuzzing.providers.findAccessibleModifiableFields import org.utbot.fuzzing.providers.nullRoutine import org.utbot.fuzzing.spring.decorators.PreservableFuzzedTypeProperty import org.utbot.fuzzing.spring.addProperties import org.utbot.fuzzing.spring.properties import org.utbot.fuzzing.utils.hex enum class EntityLifecycleState( val fieldAnnotationsToAvoidInitializing: List<ClassId> = emptyList(), val entityManagerMethodsGetter: () -> List<MethodId> = { emptyList() }, ) { NEW_WITHOUT_GENERATED_VALUES(generatedValueClassIds), NEW_WITHOUT_ID(idClassIds), NEW, MANAGED(generatedValueClassIds + idClassIds, { listOfNotNull(persistMethodIdOrNull) }), DETACHED(generatedValueClassIds + idClassIds, { listOfNotNull(persistMethodIdOrNull, detachMethodIdOrNull) }), } object EntityLifecycleStateProperty : PreservableFuzzedTypeProperty<EntityLifecycleState> class ValidEntityValueProvider( val idGenerator: IdGenerator<Int>, val onlyAcceptWhenValidIsRequired: Boolean ) : JavaValueProvider { override fun accept(type: FuzzedType): Boolean { return (!onlyAcceptWhenValidIsRequired || EntityLifecycleStateProperty in type.properties) && entityClassIds.any { @Suppress("UNCHECKED_CAST") type.classId.jClass.getAnnotation(it.jClass as Class<out Annotation>) != null } } override fun generate(description: FuzzedDescription, type: FuzzedType): Sequence<Seed<FuzzedType, FuzzedValue>> = sequence { val lifecycleStates = type.properties[EntityLifecycleStateProperty]?.let { listOf(it) } ?: EntityLifecycleState.values().toList() lifecycleStates.forEach { lifecycleState -> generateForLifecycleState(description, type.classId, lifecycleState)?.let { yield(it) } } } private fun generateForLifecycleState( description: FuzzedDescription, classId: ClassId, lifecycleState: EntityLifecycleState ): Seed.Recursive<FuzzedType, FuzzedValue>? { val noArgConstructorId = try { classId.jClass.getDeclaredConstructor().executableId } catch (e: NoSuchMethodException) { return null } return Seed.Recursive( construct = Routine.Create(types = emptyList()) { _ -> val id = idGenerator.createId() UtAssembleModel( id = id, classId = classId, modelName = "${noArgConstructorId.classId.name}${noArgConstructorId.parameters}#" + id.hex(), instantiationCall = UtExecutableCallModel(null, noArgConstructorId, params = emptyList()), modificationsChainProvider = { lifecycleState.entityManagerMethodsGetter().map { methodId -> UtExecutableCallModel( instance = UtSpringEntityManagerModel(), executable = methodId, params = listOf(this), ) } } ).fuzzed { summary = "%var% = ${classId.simpleName}()" } }, modify = sequence { // TODO maybe all fields findAccessibleModifiableFields( description, classId, description.description.packageName ).forEach { fd -> val field = classId.allDeclaredFieldIds.first { it.name == fd.name }.jField if (lifecycleState.fieldAnnotationsToAvoidInitializing.any { @Suppress("UNCHECKED_CAST") field.getAnnotation(it.jClass as Class<out Annotation>) != null }) return@forEach val validationProperties = field.annotatedType.annotations.mapNotNull { annotation -> when (annotation.annotationClass.id) { in notEmptyClassIds -> NotEmptyTypeFlag.withValue(Unit) in notBlankClassIds -> NotBlankTypeFlag.withValue(Unit) in emailClassIds -> EmailTypeFlag.withValue(Unit) // TODO support more validators else -> null } }.toDynamicProperties() val typeWithProperties = fd.type.addProperties(validationProperties) when { fd.canBeSetDirectly -> { yield(Routine.Call(listOf(typeWithProperties)) { self, values -> val model = self.model as UtAssembleModel (model.modificationsChain as MutableList).add( index = 0, // prepending extra modifications to keep `persist()` modification last UtDirectSetFieldModel( model, FieldId(classId, fd.name), values.first().model ) ) }) } fd.setter != null -> { yield(Routine.Call(listOf(typeWithProperties)) { self, values -> val model = self.model as UtAssembleModel (model.modificationsChain as MutableList).add( index = 0, // prepending extra modifications to keep `persist()` modification last UtExecutableCallModel( model, fd.setter.executableId, values.map { it.model } ) ) }) } } } }, empty = nullRoutine(classId) ) } }
415
null
38
91
abb62682c70d7d2ecc4ad610851d304f7ad716e4
7,996
UTBotJava
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/leetcode/LargestIslandTest.kt
ashtanko
203,993,092
false
{"Kotlin": 7135393, "Shell": 1168, "Makefile": 1135}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.stream.Stream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class LargestIslandTest<out T : LargestIsland>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of( arrayOf( intArrayOf(1, 0), intArrayOf(0, 1), ), 3, ), Arguments.of( arrayOf( intArrayOf(1, 1), intArrayOf(1, 0), ), 4, ), Arguments.of( arrayOf( intArrayOf(1, 1), intArrayOf(1, 1), ), 4, ), ) } @DisplayName("largest island test") @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun isLargestIslandCorrect(grid: Array<IntArray>, expected: Int) { val actual = strategy.perform(grid) assertThat(actual).isEqualTo(expected) } } class LargestIslandDFSTest : LargestIslandTest<LargestIsland>(LargestIslandDFS()) class LargestIslandComponentSizesTest : LargestIslandTest<LargestIsland>(LargestIslandComponentSizes()) class LargestIslandUnionFindTest : LargestIslandTest<LargestIsland>(LargestIslandUnionFind())
4
Kotlin
0
19
354dd5fb65ab0ec96c42b7772c2cb1d292a96db0
2,399
kotlab
Apache License 2.0
plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickAutoCommitTest.kt
androidports
115,100,208
false
null
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.cherrypick import git4idea.test.* class GitCherryPickAutoCommitTest : GitCherryPickTest() { override fun setUp() { super.setUp() myGitSettings.isAutoCommitOnCherryPick = true } fun `test simple cherry-pick`() { branch("feature") val commit = file("c.txt").create().addCommit("fix #1").hash() checkout("feature") cherryPick(commit) assertSuccessfulNotification("Cherry-pick successful", "${shortHash(commit)} fix #1") assertLastMessage("fix #1\n\n(cherry picked from commit ${commit})") changeListManager.assertOnlyDefaultChangelist() } fun `test dirty tree conflicting with commit`() { `check dirty tree conflicting with commit`() } fun `test untracked file conflicting with commit`() { `check untracked file conflicting with commit`() } fun `test conflict with cherry-picked commit should show merge dialog`() { `check conflict with cherry-picked commit should show merge dialog`() } fun `test unresolved conflict with cherry-picked commit should produce a changelist`() { val commit = prepareConflict() `do nothing on merge`() cherryPick(commit) `assert merge dialog was shown`() changeListManager.assertChangeListExists("on_master\n\n(cherry picked from commit ${shortHash(commit)})") assertWarningNotification("Cherry-picked with conflicts", """ ${shortHash(commit)} on_master Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/> """) } fun `test resolve conflicts and commit`() { `check resolve conflicts and commit`() } fun `test resolve conflicts but cancel commit`() { val commit = prepareConflict() `mark as resolved on merge`() vcsHelper.onCommit { false } cherryPick(commit) `assert merge dialog was shown`() changeListManager.assertChangeListExists("on_master\n\n(cherry picked from commit ${shortHash(commit)})") assertNoNotification() } fun `test cherry-pick 2 commits`() { branch("feature") val commit1 = file("one.txt").create().addCommit("fix #1").hash() val commit2 = file("two.txt").create().addCommit("fix #2").hash() checkout("feature") cherryPick(commit1, commit2) assertLogMessages(""" fix #2 (cherry picked from commit $commit2)""", """ fix #1 (cherry picked from commit $commit1)""") assertSuccessfulNotification("Cherry-pick successful",""" ${shortHash(commit1)} fix #1 ${shortHash(commit2)} fix #2 """) } fun `test cherry-picked 3 commits where 2nd conflicts with local changes`() { val common = file("common.txt") common.create("initial content\n").addCommit("common") branch("feature") val commit1 = file("one.txt").create().addCommit("fix #1").hash() val commit2 = common.append("on master\n").addCommit("appended common").hash() val commit3 = file("two.txt").create().addCommit("fix #2").hash() checkout("feature") common.append("on feature\n") cherryPick(commit1, commit2, commit3) assertErrorNotification("Cherry-pick Failed", """ ${shortHash(commit2)} appended common Your local changes would be overwritten by cherry-pick. Commit your changes or stash them to proceed. However cherry-pick succeeded for the following commit: ${shortHash(commit1)} fix #1""") } fun `test cherry-pick 3 commits, where second conflicts with master`() { val common = file("common.txt") common.create("initial content\n").addCommit("common") branch("feature") val commit1 = file("one.txt").create().addCommit("fix #1").hash() val commit2 = common.append("on master\n").addCommit("appended common").hash() val commit3 = file("two.txt").create().addCommit("fix #2").hash() checkout("feature") common.append("on feature\n").addCommit("appended on feature").hash() `do nothing on merge`() cherryPick(commit1, commit2, commit3) `assert merge dialog was shown`() assertLastMessage("fix #1\n\n(cherry picked from commit $commit1)") } // IDEA-73548 fun `test nothing to commit`() { val commit = file("c.txt").create().addCommit("fix #1").hash() checkoutNew("feature") cherryPick(commit) assertWarningNotification("Nothing to cherry-pick", "All changes from ${shortHash(commit)} have already been applied") } // IDEA-73548 fun `test several commits one of which have already been applied`() { file("common.txt").create("common content\n").addCommit("common file") checkoutNew("feature") val commit1 = file("a.txt").create("initial\n").addCommit("fix #1").hash() val emptyCommit = file("common.txt").append("more to common\n").addCommit("to common").hash() val commit3 = file("a.txt").append("more\n").addCommit("fix #2").hash() checkout("master") file("common.txt").append("more to common\n").addCommit("to common from master") cherryPick(commit1, emptyCommit, commit3) assertLogMessages( """ fix #2 (cherry picked from commit $commit3)""", """ fix #1 (cherry picked from commit $commit1)""") assertSuccessfulNotification("Cherry-picked 2 commits from 3",""" ${shortHash(commit1)} fix #1 ${shortHash(commit3)} fix #2 ${shortHash(emptyCommit)} was skipped, because all changes have already been applied.""") } }
6
null
1
4
6e4f7135c5843ed93c15a9782f29e4400df8b068
6,000
intellij-community
Apache License 2.0
app/src/main/java/com/simplepeople/watcha/ui/auth/signin/SignInScreen.kt
hbjosemaria
786,895,118
false
{"Kotlin": 425852}
package com.simplepeople.watcha.ui.auth.signin import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Key import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import com.simplepeople.watcha.R import com.simplepeople.watcha.ui.common.composables.DefaultTextIconButton import com.simplepeople.watcha.ui.common.composables.ImageWithMessage @Composable fun SignInScreen( signInViewModel: SignInViewModel = hiltViewModel(), navigateToHome: () -> Unit, navigateToSignUp: () -> Unit, navigateToAuth: () -> Unit, ) { val snackBarHostState = remember { SnackbarHostState() } val loginState by signInViewModel.loginState.collectAsState() val context = LocalContext.current LaunchedEffect(loginState.loginResult, loginState.userHasSessionId) { if (loginState.loginResult == LoginResult.Success(true) && loginState.userHasSessionId) { navigateToHome() } else if (loginState.loginResult == LoginResult.Success(true) && !loginState.userHasSessionId) { navigateToAuth() } } LaunchedEffect(loginState.snackbarItem) { if (loginState.snackbarItem.show) { snackBarHostState.currentSnackbarData?.dismiss() snackBarHostState.showSnackbar( message = context.getString(loginState.snackbarItem.message), duration = SnackbarDuration.Short ) signInViewModel.resetSnackbar() } } Scaffold( snackbarHost = { SnackbarHost(snackBarHostState) } ) { paddingValues -> Box( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { Column( modifier = Modifier .align(Alignment.Center), ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Image( modifier = Modifier .width(140.dp) .align(Alignment.CenterHorizontally) .padding( bottom = 12.dp ), painter = painterResource(id = R.drawable.logo_main_screen), contentDescription = stringResource(id = R.string.app_logo), contentScale = ContentScale.Fit ) ImageWithMessage( modifier = Modifier, image = R.drawable.login, message = R.string.sign_in_header ) Spacer( modifier = Modifier .fillMaxWidth() .height(6.dp) ) Text( modifier = Modifier .align(Alignment.CenterHorizontally), text = stringResource(id = R.string.sign_in_subheader), fontSize = 12.sp, textAlign = TextAlign.Center ) } } Column( modifier = Modifier .align(Alignment.BottomCenter) .padding( bottom = 40.dp ) ) { DefaultTextIconButton( modifier = Modifier .align(Alignment.CenterHorizontally), action = { signInViewModel.signIn() }, iconImage = Icons.Filled.Key, contentDescription = Icons.Filled.Key.name, text = R.string.sign_in ) DefaultTextIconButton( modifier = Modifier .align(Alignment.CenterHorizontally), action = navigateToSignUp, text = R.string.sign_up ) } } } }
0
Kotlin
0
3
05cd1a2abc9fd5b19c5d4273d99dc4b7bd2c97e3
5,388
Watcha
Apache License 2.0
src/main/kotlin/com/sharparam/klox/LoxClass.kt
Sharparam
101,596,196
false
null
/* * Copyright (c) 2017 by <NAME>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.sharparam.klox class LoxClass(val name: String, val superclass: LoxClass?, private val methods: Map<String, LoxFunction>): LoxCallable { override val arity: Int = methods["init"]?.arity ?: 0 override fun invoke(interpreter: Interpreter, arguments: Iterable<Any?>): Any? { val instance = LoxInstance(this) if (hasMethod("init")) getMethod("init", instance)?.invoke(interpreter, arguments) return instance } fun hasMethod(key: String): Boolean = methods.containsKey(key) || (superclass?.hasMethod(key) ?: false) fun getMethod(key: String, instance: LoxInstance): LoxFunction? = methods[key]?.bind(instance) ?: superclass?.getMethod(key, instance) override fun toString() = "<class $name>" }
0
Kotlin
0
2
88d17293d65ac03f5cd78ecd47605b8abda8edf5
1,894
klox
MIT License
app/src/main/java/com/herry/test/app/nestedfragments/overlay/main1/NestedNavFragmentsOverlayMain1Sub1Fragment.kt
HerryPark
273,154,769
false
null
package com.herry.test.app.nestedfragments.overlay.main1 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.herry.libs.app.nav.NavBundleUtil import com.herry.libs.widget.extension.popToNavHost import com.herry.test.app.base.nav.BaseNavFragment import com.herry.test.databinding.NestedNavFragmentsOverlayMain1Sub1FragmentBinding class NestedNavFragmentsOverlayMain1Sub1Fragment : BaseNavFragment() { private var _binding: NestedNavFragmentsOverlayMain1Sub1FragmentBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { if (_binding == null) { _binding = NestedNavFragmentsOverlayMain1Sub1FragmentBinding.inflate(inflater, container, false) binding.nestedNavFragmentsOverlayMain1Sub1FragmentClose.setOnClickListener { view -> popToNavHost(NavBundleUtil.createNavigationBundle(false)) } } return binding.root } }
0
Kotlin
1
3
d30435c01387614ec24a79ffd5afcdb89edf5298
1,190
HerryApiDemo
Apache License 2.0
src/commonTest/kotlin/org/treeWare/metaModel/validation/PackageValidationTests.kt
tree-ware
214,941,384
false
{"Kotlin": 953717}
package org.treeWare.metaModel.validation import org.treeWare.metaModel.assertJsonStringValidationErrors import org.treeWare.metaModel.newTestMetaModelJson import org.treeWare.metaModel.testMetaModelCommonPackageJson import org.treeWare.metaModel.testMetaModelCommonRootJson import kotlin.test.Test class PackageValidationTests { @Test fun `Packages list must be specified`() { val metaModelJson = """ | { | "name": "test_meta_model", | "package": "org.tree_ware.test.main", | "version": { | "semantic": "1.0.0", | "name": "pacific-ocean" | }, | "root": { | "entity": "entity1", | "package": "org.tree_ware.test.common" | } | } """.trimMargin() val expectedErrors = listOf("Packages are missing") assertJsonStringValidationErrors(metaModelJson, expectedErrors) } @Test fun `Packages list must not be empty`() { val metaModelJson = """ | { | "name": "test_meta_model", | "package": "org.tree_ware.test.main", | "version": { | "semantic": "1.0.0", | "name": "pacific-ocean" | }, | "root": { | "entity": "entity1", | "package": "org.tree_ware.test.common" | }, | "packages": [] | } """.trimMargin() val expectedErrors = listOf("Entity /org.tree_ware.test.common/entity1 cannot be resolved") assertJsonStringValidationErrors(metaModelJson, expectedErrors) } @Test fun `Package must have a name`() { val metaModelJson = """ | { | "name": "test_meta_model", | "version": { | "semantic": "1.0.0", | "name": "pacific-ocean" | }, | "root": { | "entity": "entity1", | "package": "org.tree_ware.test.common" | }, | "packages": [ | {}, | {"name": "package1"}, | {} | ] | } """.trimMargin() val expectedDecodeErrors = listOf( "Missing key fields [name] in instance of /org.tree_ware.meta_model.main/package", "Missing key fields [name] in instance of /org.tree_ware.meta_model.main/package" ) val expectedErrors = listOf("Entity /org.tree_ware.test.common/entity1 cannot be resolved") assertJsonStringValidationErrors(metaModelJson, expectedErrors, expectedDecodeErrors) } @Test fun `Package entities may be empty`() { val testPackageJson = """ | { | "name": "package1", | "entities": [] | } """.trimMargin() val metaModelJson = newTestMetaModelJson(testMetaModelCommonRootJson, testMetaModelCommonPackageJson, testPackageJson) val expectedErrors = listOf<String>() assertJsonStringValidationErrors(metaModelJson, expectedErrors) } @Test fun `Package enumerations may be empty`() { val testPackage = """ | { | "name": "package1", | "enumerations": [] | } """.trimMargin() val metaModelJson = newTestMetaModelJson(testMetaModelCommonRootJson, testMetaModelCommonPackageJson, testPackage) val expectedErrors = listOf<String>() assertJsonStringValidationErrors(metaModelJson, expectedErrors) } }
35
Kotlin
0
1
3f5b7ee679c838515d07ba1e1abedfc09da21dde
3,682
tree-ware-kotlin-core
Apache License 2.0
app/src/main/java/rafamatias/com/boilerplate/AppApplication.kt
rafamatias
74,966,219
false
null
package rafamatias.com.boilerplate class AppApplication { }
0
Kotlin
4
19
8d3f4d97f81b8e2035d783c361b2ea9f3daf0227
60
android-boilerplate
The Unlicense
pupilidlib/src/commonMain/kotlin/at/asitplus/wallet/pupilid/HttpClientBuilder.kt
a-sit-plus
738,128,206
false
{"Kotlin": 149407, "Batchfile": 2673}
package at.asitplus.wallet.pupilid import io.github.aakira.napier.Napier import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.defaultRequest import io.ktor.client.plugins.logging.LogLevel import io.ktor.client.plugins.logging.Logger import io.ktor.client.plugins.logging.Logging import io.ktor.client.request.header import io.ktor.http.HttpHeaders import io.ktor.serialization.kotlinx.json.json import kotlin.time.Duration.Companion.seconds class HttpClientBuilder( /** * Max time to establish a connections. * Connection establishment will fail if exceeded. * Default: 20 */ connectionTimeoutSeconds: Int = 10, /** * Max time (in seconds) between transmission of data packet. * Connection will be reset, if exceeded * Default: 20 */ socketTimeoutSeconds: Int = 10, /** * User Agent header to set on every request, should contain * the app name and the version, e.g. "com.example.wallet iOS 1.0.4" */ userAgent: String? = null, /** * Whether to enable logging calls with Napier */ enableLogging: Boolean = false, /** * Can be passed to enable mocks in unit tests, to use the default engine, pass `null` */ engine: HttpClientEngine? = null, /** * Can be passed to extend the setup of the HttpClient */ extendSetup: (HttpClientConfig<*>.() -> Unit)? = null ) { val client: HttpClient init { val setup: HttpClientConfig<*>.() -> Unit = { -> install(ContentNegotiation) { json() } install(HttpTimeout) { connectTimeoutMillis = connectionTimeoutSeconds.seconds.inWholeMilliseconds socketTimeoutMillis = socketTimeoutSeconds.seconds.inWholeMilliseconds } defaultRequest { userAgent.let { header(HttpHeaders.UserAgent, it) } } if (enableLogging) { install(Logging) { logger = object : Logger { override fun log(message: String) { Napier.v(message = message, tag = "ktor") } } level = LogLevel.INFO } } extendSetup?.let { it() } } client = engine?.let { HttpClient(it) { setup() } } ?: HttpClient { setup() } } }
0
Kotlin
0
1
a49a0c2ee159c30bbf52d1b214c4ae825c9723d3
2,625
pupilidlib
Apache License 2.0
features/business/src/main/java/com/mecheka/feature/business/BusinessScreenState.kt
Mecheka
628,698,363
false
null
@file:OptIn(ExperimentalContracts::class) package com.mecheka.feature.business import com.mecheka.data.model.ArticleResponse import kotlin.contracts.ExperimentalContracts sealed interface BusinessScreenState object Loading : BusinessScreenState object Error : BusinessScreenState data class Success(val data: List<ArticleResponse>) : BusinessScreenState
0
Kotlin
0
0
90d23c97e7970b4cbd7c0f4b9653ef1684b1d700
357
Compose-news
Apache License 2.0
AndroidLint-7.4.2/lint-plugin/app/src/main/java/com/easelint/gradle/KotlinPrint.kt
Western-parotia
642,632,046
false
null
package com.easelint.gradle class KotlinPrint { fun log() { //报告中,println 没检测出来 println("this is foo log") } }
0
Kotlin
2
14
a9e3988f1b0d3399a8343bb72fecc14fd71db4fe
135
EaseLint
MIT License
app/src/main/java/com/aditprayogo/samana_user/presentation/change_profile/ChangePasswordViewModel.kt
SAMANA-JABAR
365,926,412
false
null
package com.aditprayogo.samana_user.presentation.change_profile import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.aditprayogo.core.domain.model.PasswordData import com.aditprayogo.core.domain.usecase.auth.AuthUseCase import com.aditprayogo.core.state.LoaderState import com.aditprayogo.core.state.ResultState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import javax.inject.Inject /** * Created by <NAME>. */ interface ChangePasswordViewModelContract { fun changePassword(nik: String, currentPass: String, newPass: String) } @HiltViewModel class ChangePasswordViewModel @Inject constructor( private val authUseCase: AuthUseCase ) : ViewModel(), ChangePasswordViewModelContract { private val _state = MutableLiveData<LoaderState>() val state get() = _state private val _error = MutableLiveData<String?>() val error get() = _error private val _networkError = MutableLiveData<Boolean>() val networkError get() = _networkError private val _passwordData = MutableLiveData<PasswordData>() val passwordData get() = _passwordData override fun changePassword( nik: String, currentPass: String, newPass: String ) { _state.value = LoaderState.ShowLoading viewModelScope.launch { authUseCase.changePassword(nik, currentPass, newPass).collect { data -> when(data) { is ResultState.Success -> { _passwordData.postValue(data.data!!) _state.value = LoaderState.HideLoading } is ResultState.Error -> { _error.postValue(data.error) _state.value = LoaderState.HideLoading } is ResultState.NetworkError -> { _networkError.postValue(true) } } } } } }
0
Kotlin
0
3
37cf6340acf60165721770802c51e552be44d673
2,094
SAMANA-USER
Apache License 2.0
src/main/kotlin/com/appstats/appstatisticsinfo/model/AppStatisticsModel.kt
siavashtf
291,537,112
false
null
package com.appstats.appstatisticsinfo.model class AppStatisticsModel (val weekNum: Int, val year: Int, val requests: Int = 0, val clicks: Int = 0, val installs: Int = 0)
0
Kotlin
0
0
3d3cc4c54c2c4172c4197c614ac1f806b0d4ed8f
275
app-statics-info
Apache License 2.0
app/src/main/java/com/bnsantos/view/skeleton/di/modules/AppModule.kt
bnsantos
93,883,250
false
null
package com.bnsantos.view.skeleton.di.modules import android.app.Application import android.arch.persistence.room.Room import com.bnsantos.view.skeleton.api.ApiResponse import com.bnsantos.view.skeleton.api.ApiResponseDeserializer import com.bnsantos.view.skeleton.api.PeopleService import com.bnsantos.view.skeleton.db.DB import com.bnsantos.view.skeleton.db.PersonDao import com.bnsantos.view.skeleton.model.Person import com.bnsantos.view.skeleton.model.PersonDeserializer import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class AppModule(val mApp: Application) { @Singleton @Provides fun gson(): Gson = GsonBuilder() .registerTypeAdapter(ApiResponse::class.java, ApiResponseDeserializer) .registerTypeAdapter(Person::class.java, PersonDeserializer) .create() @Singleton @Provides fun peopleService(gson: Gson): PeopleService = Retrofit.Builder() .baseUrl("https://randomuser.me/") .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(PeopleService::class.java) @Singleton @Provides fun provideDB() : DB = Room.databaseBuilder(mApp, DB::class.java, "skeleton.db").build() @Singleton @Provides fun personDao(db: DB) : PersonDao = db.personDao() }
0
Kotlin
0
0
48bcadd1f936247cb9e5fc51b1d2b09e48a4a5c6
1,578
android-skeleton-view
Apache License 2.0
app/src/main/kotlin/de/ljz/questify/ui/components/DismissBackground.kt
LJZApps
806,522,161
false
{"Kotlin": 229922}
package de.ljz.questify.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Done import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.SwipeToDismissBoxState import androidx.compose.material3.SwipeToDismissBoxValue import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun DismissBackground(dismissState: SwipeToDismissBoxState) { val color = when (dismissState.dismissDirection) { SwipeToDismissBoxValue.StartToEnd -> Color(0xFFFF1744) SwipeToDismissBoxValue.EndToStart -> Color.Green SwipeToDismissBoxValue.Settled -> Color.Transparent } Row( modifier = Modifier .fillMaxSize() .background(color) .padding(12.dp, 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Icon( Icons.Default.Delete, contentDescription = "delete" ) Text( "Löschen" ) Spacer(modifier = Modifier) Text( "Erledigt" ) Icon( // make sure add baseline_archive_24 resource to drawable folder Icons.Default.Done, contentDescription = "Fertig" ) } }
0
Kotlin
0
0
dc04f195c507b4385b8df3cb034a410c253d6603
1,950
Questify-Android
MIT License
feature/hidden-notes-dialog/data/src/main/kotlin/ru/maksonic/beresta/feature/hidden_notes_dialog/data/PinFailManagerCore.kt
maksonic
580,058,579
false
{"Kotlin": 1587340, "Assembly": 374}
package ru.maksonic.beresta.feature.hidden_notes_dialog.data import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import ru.maksonic.beresta.common.data.Datastore import ru.maksonic.beresta.feature.hidden_notes_dialog.domain.PinFailInfo import ru.maksonic.beresta.feature.hidden_notes_dialog.domain.PinFailManager /** * @Author maksonic on 05.08.2023 */ class PinFailManagerCore(private val datastore: Datastore) : PinFailManager { private companion object { private const val BASE_KEY = "prefs_hidden_notes_pin_fail" private const val INITIAL_FAIL_COUNT = 0 private const val INITIAL_IS_COOL_DOWN = false private const val INITIAL_END_TIME = 0L } private val failCountKey = intPreferencesKey(BASE_KEY + "count_key") private val coolDownKey = booleanPreferencesKey(BASE_KEY + "cool_down_key") private val endTimeKey = longPreferencesKey(BASE_KEY + "ent_time_key") override val state: Flow<PinFailInfo> = datastore.datastore.data.map { prefs -> PinFailInfo( failCount = prefs[failCountKey] ?: INITIAL_FAIL_COUNT, isCoolDown = prefs[coolDownKey] ?: INITIAL_IS_COOL_DOWN, endDate = prefs[endTimeKey] ?: INITIAL_END_TIME ) } override suspend fun updateFailCounter(value: Int) { datastore.datastore.edit { prefs -> prefs[failCountKey] = value } } override suspend fun updateCoolDown(isCoolDown: Boolean, endTime: Long) { datastore.datastore.edit { prefs -> prefs[coolDownKey] = isCoolDown prefs[endTimeKey] = endTime } } }
0
Kotlin
0
0
863585ab17882e444060e5535401c728f9fc335d
1,856
Beresta
MIT License
layout-inspector/testSrc/com/android/tools/idea/layoutinspector/metrics/AppInspectionInspectorMetricsTest.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.layoutinspector.metrics import com.android.testutils.MockitoKt.any import com.android.testutils.MockitoKt.mock import com.android.tools.idea.appinspection.test.DEFAULT_TEST_INSPECTION_STREAM import com.android.tools.idea.concurrency.waitForCondition import com.android.tools.idea.layoutinspector.LayoutInspectorRule import com.android.tools.idea.layoutinspector.MODERN_DEVICE import com.android.tools.idea.layoutinspector.createProcess import com.android.tools.idea.layoutinspector.pipeline.appinspection.AppInspectionInspectorRule import com.android.tools.idea.layoutinspector.pipeline.appinspection.AppInspectionTreeLoader import com.android.tools.idea.layoutinspector.pipeline.appinspection.dsl.ViewBounds import com.android.tools.idea.layoutinspector.pipeline.appinspection.dsl.ViewNode import com.android.tools.idea.layoutinspector.pipeline.appinspection.dsl.ViewRect import com.android.tools.idea.layoutinspector.pipeline.appinspection.dsl.ViewString import com.android.tools.idea.layoutinspector.pipeline.appinspection.view.ViewLayoutInspectorClient import com.android.tools.idea.layoutinspector.resource.ResourceLookup import com.android.tools.idea.layoutinspector.skia.SkiaParser import com.android.tools.idea.layoutinspector.window import com.android.tools.idea.protobuf.ByteString import com.android.tools.idea.stats.AnonymizerUtil import com.android.tools.layoutinspector.SkiaViewNode import com.google.common.truth.Truth.assertThat import com.google.wireless.android.sdk.stats.AndroidStudioEvent import com.google.wireless.android.sdk.stats.DeviceInfo import com.google.wireless.android.sdk.stats.DynamicLayoutInspectorEvent.DynamicLayoutInspectorEventType import com.intellij.testFramework.DisposableRule import layoutinspector.view.inspection.LayoutInspectorViewProtocol import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.mockito.Mockito.anyDouble import org.mockito.Mockito.`when` import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit private val MODERN_PROCESS = MODERN_DEVICE.createProcess(streamId = DEFAULT_TEST_INSPECTION_STREAM.streamId) class AppInspectionInspectorMetricsTest { val disposableRule = DisposableRule() private val inspectionRule = AppInspectionInspectorRule(disposableRule.disposable) private val inspectorRule = LayoutInspectorRule(listOf(inspectionRule.createInspectorClientProvider())) { it.name == MODERN_PROCESS.name } @get:Rule val ruleChain = RuleChain.outerRule(inspectionRule).around(inspectorRule).around(disposableRule)!! @get:Rule val usageTrackerRule = MetricsTrackerRule() @Before fun before() { inspectorRule.attachDevice(MODERN_DEVICE) } @Test fun attachMetricsLoggedAfterProcessSuccessfullyAttached() { inspectorRule.processNotifier.fireConnected(MODERN_PROCESS) val usages = usageTrackerRule.testTracker.usages .filter { it.studioEvent.kind == AndroidStudioEvent.EventKind.DYNAMIC_LAYOUT_INSPECTOR_EVENT } assertThat(usages).hasSize(2) usages[0].studioEvent.let { studioEvent -> val deviceInfo = studioEvent.deviceInfo assertThat(deviceInfo.anonymizedSerialNumber).isEqualTo(AnonymizerUtil.anonymizeUtf8(MODERN_DEVICE.serial)) assertThat(deviceInfo.model).isEqualTo(MODERN_DEVICE.model) assertThat(deviceInfo.manufacturer).isEqualTo(MODERN_DEVICE.manufacturer) assertThat(deviceInfo.deviceType).isEqualTo(DeviceInfo.DeviceType.LOCAL_PHYSICAL) val inspectorEvent = studioEvent.dynamicLayoutInspectorEvent assertThat(inspectorEvent.type).isEqualTo(DynamicLayoutInspectorEventType.ATTACH_REQUEST) assertThat(studioEvent.projectId).isEqualTo(AnonymizerUtil.anonymizeUtf8(inspectorRule.project.basePath!!)) } usages[1].studioEvent.let { studioEvent -> val inspectorEvent = studioEvent.dynamicLayoutInspectorEvent assertThat(inspectorEvent.type).isEqualTo(DynamicLayoutInspectorEventType.ATTACH_SUCCESS) assertThat(studioEvent.projectId).isEqualTo(AnonymizerUtil.anonymizeUtf8(inspectorRule.project.basePath!!)) } assertThat(usages[0].studioEvent.deviceInfo).isEqualTo(usages[1].studioEvent.deviceInfo) assertThat(usages[0].studioEvent.projectId).isEqualTo(usages[1].studioEvent.projectId) } @Test fun attachMetricsLoggedAfterProcessFailedToAttach() { inspectionRule.viewInspector.interceptWhen({it.hasStartFetchCommand()}) { LayoutInspectorViewProtocol.Response.newBuilder().apply { startFetchResponseBuilder.apply { error = "failed to start" } }.build() } inspectorRule.processNotifier.fireConnected(MODERN_PROCESS) val usages = usageTrackerRule.testTracker.usages .filter { it.studioEvent.kind == AndroidStudioEvent.EventKind.DYNAMIC_LAYOUT_INSPECTOR_EVENT } waitForCondition(1, TimeUnit.SECONDS) { usages.size == 3 } assertThat(usages).hasSize(3) usages[0].studioEvent.let { studioEvent -> val deviceInfo = studioEvent.deviceInfo assertThat(deviceInfo.anonymizedSerialNumber).isEqualTo(AnonymizerUtil.anonymizeUtf8(MODERN_DEVICE.serial)) assertThat(deviceInfo.model).isEqualTo(MODERN_DEVICE.model) assertThat(deviceInfo.manufacturer).isEqualTo(MODERN_DEVICE.manufacturer) assertThat(deviceInfo.deviceType).isEqualTo(DeviceInfo.DeviceType.LOCAL_PHYSICAL) val inspectorEvent = studioEvent.dynamicLayoutInspectorEvent assertThat(inspectorEvent.type).isEqualTo(DynamicLayoutInspectorEventType.ATTACH_REQUEST) assertThat(studioEvent.projectId).isEqualTo(AnonymizerUtil.anonymizeUtf8(inspectorRule.project.basePath!!)) } usages[1].studioEvent.let { studioEvent -> val deviceInfo = studioEvent.deviceInfo assertThat(deviceInfo.anonymizedSerialNumber).isEqualTo(AnonymizerUtil.anonymizeUtf8(MODERN_DEVICE.serial)) assertThat(deviceInfo.model).isEqualTo(MODERN_DEVICE.model) assertThat(deviceInfo.manufacturer).isEqualTo(MODERN_DEVICE.manufacturer) assertThat(deviceInfo.deviceType).isEqualTo(DeviceInfo.DeviceType.LOCAL_PHYSICAL) val inspectorEvent = studioEvent.dynamicLayoutInspectorEvent assertThat(inspectorEvent.type).isEqualTo(DynamicLayoutInspectorEventType.ATTACH_SUCCESS) } usages[2].studioEvent.let { studioEvent -> val inspectorEvent = studioEvent.dynamicLayoutInspectorEvent assertThat(inspectorEvent.type).isEqualTo(DynamicLayoutInspectorEventType.SESSION_DATA) } } @Test fun testInitialRenderLogging() { inspectorRule.launchSynchronously = false inspectionRule.viewInspector.listenWhen({ true }) { inspectorRule.inspectorModel.update(window("w1", 1L), listOf("w1"), 1) } val getUsages = { usageTrackerRule.testTracker.usages .filter { it.studioEvent.dynamicLayoutInspectorEvent.type == DynamicLayoutInspectorEventType.INITIAL_RENDER } } inspectorRule.asyncLaunchLatch = CountDownLatch(1) inspectorRule.processNotifier.fireConnected(MODERN_PROCESS) inspectorRule.asyncLaunchLatch.await() waitForCondition(1, TimeUnit.SECONDS) { inspectorRule.inspectorClient.isConnected } var rootId = 1L val skiaParser = mock<SkiaParser>().also { `when`(it.getViewTree(any(), any(), anyDouble(), any())).thenAnswer { SkiaViewNode(rootId, listOf()) } } (inspectorRule.inspectorClient.treeLoader as AppInspectionTreeLoader).skiaParser = skiaParser // Load the tree with root id 1. The subsequent refreshImages() should generate an initial load event. val (window, _, _) = inspectorRule.inspectorClient.treeLoader.loadComponentTree(createFakeData(rootId), ResourceLookup(inspectorRule.project), inspectorRule.inspectorClient.process)!! window!!.refreshImages(1.0) assertThat(getUsages()).hasSize(1) // A further refreshImages() shouldn't generate another event. window.refreshImages(1.0) assertThat(getUsages()).hasSize(1) // Load a new window with root id 2. This still shouldn't generate another event. rootId = 2 val (window2, _, _) = inspectorRule.inspectorClient.treeLoader.loadComponentTree(createFakeData(rootId), ResourceLookup(inspectorRule.project), inspectorRule.inspectorClient.process)!! window2!!.refreshImages(1.0) assertThat(getUsages()).hasSize(1) // disconnecting causes two separate events inspectorRule.asyncLaunchLatch = CountDownLatch(2) // Now disconnect and reconnect. This should generate another event. inspectorRule.processNotifier.fireDisconnected(MODERN_PROCESS) inspectorRule.asyncLaunchLatch.await() waitForCondition(1, TimeUnit.SECONDS) { !inspectorRule.inspectorClient.isConnected } inspectorRule.asyncLaunchLatch = CountDownLatch(1) inspectorRule.processNotifier.fireConnected(MODERN_PROCESS) inspectorRule.asyncLaunchLatch.await() inspectorRule.asyncLaunchLatch = CountDownLatch(1) waitForCondition(1, TimeUnit.SECONDS) { inspectorRule.inspectorClient.isConnected } (inspectorRule.inspectorClient.treeLoader as AppInspectionTreeLoader).skiaParser = skiaParser val (window3, _, _) = inspectorRule.inspectorClient.treeLoader.loadComponentTree(createFakeData(rootId), ResourceLookup(inspectorRule.project), inspectorRule.inspectorClient.process)!! window3!!.refreshImages(1.0) assertThat(getUsages()).hasSize(2) } private fun createFakeData( rootId: Long, screenshotType: LayoutInspectorViewProtocol.Screenshot.Type = LayoutInspectorViewProtocol.Screenshot.Type.SKP) : ViewLayoutInspectorClient.Data { val viewLayoutEvent = LayoutInspectorViewProtocol.LayoutEvent.newBuilder().apply { ViewString(1, "en-us") ViewString(2, "com.example") ViewString(3, "MyViewClass1") appContextBuilder.apply { configurationBuilder.apply { countryCode = 1 } } rootView = ViewNode { id = rootId packageName = 2 className = 3 bounds = ViewBounds(ViewRect(100, 200)) } screenshotBuilder.apply { type = screenshotType bytes = ByteString.copyFrom(byteArrayOf(1, 2, 3)) } }.build() return ViewLayoutInspectorClient.Data( 11, listOf(123, 456), viewLayoutEvent, null ) } }
5
Kotlin
230
948
10110983c7e784122d94c7467e9d243aba943bf4
11,399
android
Apache License 2.0
shared/src/commonMain/kotlin/com/presta/customer/ui/components/processLoanDisbursement/ProcessLoanDisbursementComponent.kt
morgan4080
678,697,424
false
null
package com.presta.customer.ui.components.processLoanDisbursement import com.presta.customer.ui.components.auth.store.AuthStore import com.presta.customer.ui.components.processLoanDisbursement.store.ProcessingLoanDisbursementStore import kotlinx.coroutines.flow.StateFlow interface ProcessLoanDisbursementComponent { val authState: StateFlow<AuthStore.State> val authStore: AuthStore val amount: Double val fees: Double val requestId: String val processingLoanDisbursementStore: ProcessingLoanDisbursementStore val processingTransactionState: StateFlow<ProcessingLoanDisbursementStore.State> fun onAuthEvent(event: AuthStore.Intent) fun onProcessingLoanDisbursementEvent(event: ProcessingLoanDisbursementStore.Intent) fun navigate() }
0
Kotlin
0
0
d26cc0013c5bedf29d2f349b86e90052a0aca64e
776
kotlin-multiplatform
Apache License 2.0
app/src/main/java/com/boolder/boolder/view/detail/LineVectorView.kt
boolder-org
566,723,758
false
null
package com.boolder.boolder.view.detail import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.View import androidx.annotation.ColorRes class LineVectorView @JvmOverloads constructor( context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val points = mutableListOf<PointF>() private val controlPoint1 = mutableListOf<PointF>() private val controlPoint2 = mutableListOf<PointF>() private val path = Path() private val lineTrickiness by lazy { TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 4f, resources.displayMetrics ) } private val paint = Paint() private var viewCanvas: Canvas? = null private var bitmap: Bitmap? = null private val bitmapPaint = Paint(Paint.DITHER_FLAG) override fun onSizeChanged( w: Int, h: Int, oldw: Int, oldh: Int ) { super.onSizeChanged(w, h, oldw, oldh) bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) viewCanvas = Canvas(bitmap!!) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) drawBezierCurve(canvas) bitmap?.let { canvas?.drawBitmap(it, 0f, 0f, bitmapPaint) } } private fun drawBezierCurve(canvas: Canvas?) { try { if (points.isEmpty() && controlPoint1.isEmpty() && controlPoint2.isEmpty()) return path.reset() path.moveTo(points.first().x * width, points.first().y * height) for (i in 1 until points.size) { path.cubicTo( controlPoint1[i.dec()].x * width, controlPoint1[i.dec()].y * height, controlPoint2[i.dec()].x * width, controlPoint2[i.dec()].y * height, points[i].x * width, points[i].y * height ) } canvas?.drawPath(path, paint) } catch (e: Exception) { Log.e("TAG", e.message ?: "") } } fun addDataPoints(data: List<PointD>, point1: List<PointD>, point2: List<PointD>, @ColorRes drawColor: Int) { paint.apply { isAntiAlias = true strokeWidth = lineTrickiness style = Paint.Style.STROKE strokeJoin = Paint.Join.ROUND strokeCap = Paint.Cap.ROUND color = drawColor } post { Thread { points.clear() controlPoint1.clear() controlPoint2.clear() points.addAll(data.toF()) controlPoint1.addAll(point1.toF()) controlPoint2.addAll(point2.toF()) postInvalidate() }.start() } } fun clearPath() { points.clear() controlPoint1.clear() controlPoint2.clear() postInvalidate() } }
14
Kotlin
5
9
0a322e4bbde8e05cef50d092c1ac2e94d919f310
3,094
boolder-android
MIT License
app/src/main/java/com/androidstudy/mpesa/common/DarajaLiveData.kt
kiptechie
196,429,964
true
{"Java Properties": 2, "Gradle": 5, "Shell": 1, "Markdown": 4, "Batchfile": 1, "Text": 1, "Ignore List": 3, "Proguard": 2, "Java": 38, "XML": 17, "YAML": 1, "Kotlin": 7}
package com.androidstudy.mpesa.common import android.arch.lifecycle.LiveData import com.androidstudy.daraja.callback.DarajaException import com.androidstudy.daraja.callback.DarajaListener class DarajaLiveData<T> : LiveData<Resource<T>>(), DarajaListener<T> { init { value = Resource(Status.LOADING) } override fun onResult(data: T) { value = Resource(data) } override fun onError(exception: DarajaException) { value = Resource(DarajaException(exception.localizedMessage)) } }
1
Java
0
1
130017d0e11c8ec9f72d02aa4c7853121ef96e80
529
AndroidMPesaAPI
MIT License
src/main/kotlin/net/dontdrinkandroot/fixtures/Fixture.kt
dontdrinkandroot
87,098,098
false
null
package net.dontdrinkandroot.fixtures import net.dontdrinkandroot.fixtures.referencerepository.ReferenceRepository import javax.persistence.EntityManager import kotlin.reflect.KClass /** * A [Fixture] is responsible for storing one or many objects in the database. */ interface Fixture { /** * Specifies fixture classes that need to be loaded before this fixture. * * @return The collection of fixture classes to load before this fixture. */ val dependencies: Collection<KClass<out Fixture>> get() = emptyList() /** * Loads this fixture into the database via the [EntityManager]. Can use the [ReferenceRepository] to * retrieve objects needed and to store the objects created. * * @param entityManager The EntityManager to interact with the database. * @param referenceRepository The Repository to store or retrieve other fixture objects. */ fun load(entityManager: EntityManager, referenceRepository: ReferenceRepository) }
1
Kotlin
0
2
c9cb40f2e11654d719066d399e99356693a7d7e8
1,010
fixtures.java
Apache License 2.0
src/main/kotlin/dk/cachet/carp/webservices/deployment/serdes/StudyDeploymentStatusSerializer.kt
cph-cachet
674,650,033
false
{"Kotlin": 671905, "TypeScript": 111037, "HTML": 14219, "Shell": 4202, "CSS": 1656, "Dockerfile": 1264, "JavaScript": 706}
package dk.cachet.carp.webservices.deployment.serdes import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import dk.cachet.carp.deployments.application.StudyDeploymentStatus import dk.cachet.carp.webservices.common.configuration.internationalisation.service.MessageBase import dk.cachet.carp.webservices.common.exception.serialization.SerializationException import dk.cachet.carp.webservices.common.input.WS_JSON import kotlinx.serialization.encodeToString import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger /** * The Class [StudyDeploymentStatusSerializer]. * [StudyDeploymentStatusSerializer] implements the serialization logic for [StudyDeploymentStatus]. */ @Suppress("TooGenericExceptionCaught", "SwallowedException") class StudyDeploymentStatusSerializer( private val validationMessages: MessageBase, ) : JsonSerializer<StudyDeploymentStatus>() { companion object { private val LOGGER: Logger = LogManager.getLogger() } /** * The [serialize] function is used to serialize the parsed object. * * @param studyDeploymentStatus The [studyDeploymentStatus] object containing the json object parsed. * @param jsonGenerator The [jsonGenerator] to write JSON content generated from the study deployment status. * @param serializers The [serializers] to serialize the parsed object from the study deployment status. * @throws SerializationException If the [StudyDeploymentStatus] is blank or empty. * Also, if the [StudyDeploymentStatus] contains invalid format. * @return The serialization of deployment service request object. */ override fun serialize( studyDeploymentStatus: StudyDeploymentStatus?, jsonGenerator: JsonGenerator?, serializers: SerializerProvider?, ) { if (studyDeploymentStatus == null) { LOGGER.error("The core StudyDeploymentStatus is null.") throw SerializationException(validationMessages.get("deployment.status.serialization.empty")) } val serialized: String try { serialized = WS_JSON.encodeToString(studyDeploymentStatus) } catch (ex: Exception) { LOGGER.error("The core StudyDeploymentStatus is not valid. Exception: ${ex.message}") throw SerializationException( validationMessages.get("deployment.status.serialization.error", ex.message.toString()), ) } jsonGenerator!!.writeRawValue(serialized) } }
27
Kotlin
1
3
6f16c3c5f1b5b8bdd7abc30fd312c0cad973473c
2,619
carp-webservices-spring
MIT License
device-explorer-monitor/src/com/android/tools/idea/device/explorer/monitor/ui/DeviceMonitorViewImpl.kt
JetBrains
60,701,247
false
{"Kotlin": 43855938, "Java": 36698280, "HTML": 1216565, "Starlark": 735324, "C++": 216476, "Python": 101594, "C": 71515, "Lex": 66026, "NSIS": 58516, "AIDL": 32502, "Shell": 28591, "CMake": 21034, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2022 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.device.explorer.monitor.ui import com.android.tools.idea.device.explorer.monitor.DeviceMonitorModel import com.android.tools.idea.device.explorer.monitor.DeviceMonitorViewListener import com.android.tools.idea.device.explorer.monitor.ui.menu.item.DebugMenuItem import com.android.tools.idea.device.explorer.monitor.ui.menu.item.ForceStopMenuItem import com.android.tools.idea.device.explorer.monitor.ui.menu.item.KillMenuItem import com.android.tools.idea.device.explorer.monitor.ui.menu.item.MenuContext import com.android.tools.idea.device.explorer.monitor.ui.menu.item.RefreshMenuItem import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.ui.table.JBTable import java.awt.BorderLayout import java.util.function.Consumer import javax.swing.JComponent class DeviceMonitorViewImpl( model: DeviceMonitorModel, private val table: JBTable = ProcessListTableBuilder().build(model.tableModel) ): DeviceMonitorView, DeviceMonitorActionsListener { private val panel = DeviceMonitorPanel() private val listeners = mutableListOf<DeviceMonitorViewListener>() override val panelComponent: JComponent get() = panel.component override fun setup() { setUpTable() createTreePopupMenu() createToolbar() } override fun addListener(listener: DeviceMonitorViewListener) { listeners.add(listener) } override fun removeListener(listener: DeviceMonitorViewListener) { listeners.remove(listener) } override val numOfSelectedNodes: Int get() { return table.selectedRowCount } override fun refreshNodes() { listeners.forEach(Consumer { it.refreshInvoked() }) } override fun killNodes() { listeners.forEach(Consumer { it.killNodesInvoked(getModelRows(table.selectedRows)) }) } override fun forceStopNodes() { listeners.forEach(Consumer { it.forceStopNodesInvoked(getModelRows(table.selectedRows)) }) } override fun debugNodes() { listeners.forEach(Consumer { it.debugNodes(getModelRows(table.selectedRows)) }) } private fun setUpTable() { panel.processTablePane.viewport.add(table) } private fun createTreePopupMenu() { ComponentPopupMenu(table).apply { addItem(KillMenuItem(this@DeviceMonitorViewImpl, MenuContext.Popup)) addItem(ForceStopMenuItem(this@DeviceMonitorViewImpl, MenuContext.Popup)) addItem(DebugMenuItem(this@DeviceMonitorViewImpl, MenuContext.Popup)) install() } } private fun createToolbar() { createToolbarSubSection(DefaultActionGroup().apply { add(KillMenuItem(this@DeviceMonitorViewImpl, MenuContext.Toolbar).action) add(ForceStopMenuItem(this@DeviceMonitorViewImpl, MenuContext.Toolbar).action) add(DebugMenuItem(this@DeviceMonitorViewImpl, MenuContext.Toolbar).action) add(RefreshMenuItem(this@DeviceMonitorViewImpl).action) } ) } private fun createToolbarSubSection(group: DefaultActionGroup) { val actionManager = ActionManager.getInstance() val actionToolbar = actionManager.createActionToolbar("Device Monitor Toolbar", group, true).apply { targetComponent = panel.processTablePane } panel.toolbar.add(actionToolbar.component, BorderLayout.WEST) } private fun getModelRows(viewRows: IntArray): IntArray = IntArray(viewRows.size) { index -> table.convertRowIndexToModel(viewRows[index]) } }
2
Kotlin
230
876
9c0a89784cca3c01ab99cf251b71a26cdb87cc47
4,054
android
Apache License 2.0
Flashcards/task/src/flashcards/MainNoOOP.kt
redstrike
281,227,598
false
null
package flashcards import java.io.File import kotlin.random.Random fun main(args: Array<String>) { Flashcards().start(args) } class Flashcards { private val cards = mutableMapOf<String, String>() private val stats = mutableMapOf<String, Int>() private val logs = mutableListOf<String>() fun start(args: Array<String>) { // Get command line arguments var importPath = "" var exportPath = "" if (args.isNotEmpty()) { if (args.size % 2 != 0) return println("Error: Missing one or more arguments!") for (i in args.indices step 2) { when (args[i]) { "-import" -> importPath = args[i + 1] "-export" -> exportPath = args[i + 1] } } } // Import cards on init if (importPath.isNotEmpty()) importCards(importPath) // Start flashcards while (true) { printLine("\nInput the action (add, remove, import, export, ask, exit, log, hardest card, reset stats):") when (readInput().toLowerCase()) { "add" -> addCard() "remove" -> removeCard() "export" -> exportCards(getFilename()) "import" -> importCards(getFilename()) "ask" -> ask() "log" -> exportLogs() "hardest card" -> getHardestCards() "reset stats" -> resetStats() "exit" -> { printLine("Bye bye!") // Export cards on exit if (exportPath.isNotEmpty()) exportCards(exportPath) return } } } } private fun printLine(message: String) { println(message) logs.add(message) } private fun readInput(): String { val input = readLine()!!.trim() logs.add(input) return input } private fun getTerm(): String { printLine("The card:") return readInput() } private fun addCard() { val term = getTerm() if (cards.containsKey(term)) { printLine("The card \"$term\" already exists.") return } printLine("The definition of the card:") val definition = readInput() if (cards.containsValue(definition)) { printLine("The definition \"$definition\" already exists.") return } cards[term] = definition stats[term] = 0 // error count printLine("The pair (\"$term\":\"$definition\") has been added.") } private fun removeCard() { val term = getTerm() if (!cards.containsKey(term)) { printLine("Can't remove \"$term\": there is no such card.") return } cards.remove(term) stats.remove(term) printLine("The card has been removed.") } private fun getFilename(): String { printLine("File name:") return readInput() } private fun exportCards(pathname: String) { val data = StringBuilder() cards.forEach { val (term, definition) = it val errorCount = stats[term] data.append("$term=$definition=$errorCount\n") } File(pathname).writeText(data.toString()) printLine("${cards.size} cards have been saved.") } private fun importCards(pathname: String) { val file = File(pathname) if (!file.exists()) { printLine("File not found.") return } val cardList = file.readLines() cardList.forEach { val (term, definition, errorCount) = it.split('=') cards[term] = definition stats[term] = errorCount.toInt() } printLine("${cardList.size} cards have been loaded.") } private fun ask() { printLine("How many times to ask?") val times = readInput().toInt() repeat(times) { val index = Random.nextInt(0, until = cards.size) val (term, definition) = cards.entries.elementAt(index) printLine("Print the definition of \"$term\":") val answer = readInput() val errorCount = if (stats[term] != null) stats[term]!! else 0 printLine(when { answer == definition -> "Correct answer." cards.containsValue(answer) -> { stats[term] = errorCount + 1 val anotherTerm = cards.filter { it.value == answer }.keys.first() getWrongMessage(definition, anotherTerm) } else -> { stats[term] = errorCount + 1 getWrongMessage(definition) } }) } } private fun getWrongMessage(definition: String, anotherTerm: String? = null): String { val message = "Wrong answer. The correct one is \"$definition\"" if (anotherTerm.isNullOrEmpty()) { return "$message." } return "$message, you've just written the definition of \"$anotherTerm\"." } private fun exportLogs() { val file = File(getFilename()) printLine("The log has been saved.") file.writeText(logs.joinToString("\n")) } private fun getHardestCards() { if (stats.isEmpty() || stats.filter { it.value > 0 }.isEmpty()) { printLine("There are no cards with errors.") return } val largestWrongCount = stats.maxBy { it.value }!!.value val hardestCards = stats.filterValues { it == largestWrongCount } if (hardestCards.size == 1) { val (term) = hardestCards.entries.elementAt(0) printLine("The hardest card is \"$term\". You have $largestWrongCount errors answering it.") return } val hardestTerms = hardestCards.keys.joinToString { "\"$it\"" } printLine("The hardest cards are $hardestTerms. You have $largestWrongCount errors answering them.") } private fun resetStats() { stats.clear() printLine("Card statistics have been reset.") } }
0
HTML
0
0
b02ef280def789f03fbf0941f745b64356a93b85
6,225
flashcards
MIT License
Instagram-Gallery-Animation/Android/app/src/main/java/app/nikhil/instagramgalleryanimation/utils/ImagesData.kt
nikhilbansal97
270,763,824
false
{"Kotlin": 25919}
package app.nikhil.instagramgalleryanimation.utils val TEST_IMAGES_SQUARE = listOf( "https://images.unsplash.com/photo-1582885745933-e43bee4517ae?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1491438590914-bc09fcaaf77a?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1501386761578-eac5c94b800a?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1512626120412-faf41adb4874?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1502635385003-ee1e6a1a742d?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1529835299686-53bd13fb3ee1?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1507608869274-d3177c8bb4c7?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1503721827581-14e4c8676769?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80", "https://images.unsplash.com/photo-1530023367847-a683933f4172?ixlib=rb-1.2.1&fit=crop&w=1000&h=1000&q=80" ) val TEST_IMAGES_ORIGINAL = listOf( "https://images.unsplash.com/photo-1582885745933-e43bee4517ae?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1491438590914-bc09fcaaf77a?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1501386761578-eac5c94b800a?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1512626120412-faf41adb4874?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1502635385003-ee1e6a1a742d?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1529835299686-53bd13fb3ee1?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1507608869274-d3177c8bb4c7?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1503721827581-14e4c8676769?ixlib=rb-1.2.1", "https://images.unsplash.com/photo-1530023367847-a683933f4172?ixlib=rb-1.2.1" ) val TEST_IMAGES = arrayListOf<Image>().apply { for (i in TEST_IMAGES_SQUARE.indices) { add(Image(shortUrl = TEST_IMAGES_SQUARE[i], originalUrl = TEST_IMAGES_ORIGINAL[i])) add(Image(shortUrl = TEST_IMAGES_SQUARE[i], originalUrl = TEST_IMAGES_ORIGINAL[i])) } } .shuffled()
0
Kotlin
0
3
01a469640001a50fba4a4640d4e16bf0b662b8d3
2,118
Mobile-UI-Samples
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/personrecord/service/MatchService.kt
ministryofjustice
608,040,205
false
{"Kotlin": 278212, "PLpgSQL": 8836, "Shell": 2601, "Dockerfile": 1145}
package uk.gov.justice.digital.hmpps.personrecord.service import kotlinx.coroutines.runBlocking import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.personrecord.client.MatchRequest import uk.gov.justice.digital.hmpps.personrecord.client.MatchRequestData import uk.gov.justice.digital.hmpps.personrecord.client.MatchResponse import uk.gov.justice.digital.hmpps.personrecord.client.MatchScoreClient import uk.gov.justice.digital.hmpps.personrecord.jpa.entity.PersonEntity import uk.gov.justice.digital.hmpps.personrecord.model.person.Person import uk.gov.justice.digital.hmpps.personrecord.service.type.TelemetryEventType.MATCH_CALL_FAILED const val MAX_RETRY_ATTEMPTS: Int = 3 @Service class MatchService(val matchScoreClient: MatchScoreClient, val telemetryService: TelemetryService) { @Value("\${retry.delay}") private val retryDelay: Long = 0 fun score(candidateRecord: PersonEntity, newRecord: Person): MatchResult { val candidateRecordIdentifier = candidateRecord.defendantId ?: "defendant1" val newRecordIdentifier = newRecord.defendantId ?: "defendant2" val matchRequest = MatchRequest( uniqueId = MatchRequestData(candidateRecordIdentifier, newRecordIdentifier), firstName = MatchRequestData(candidateRecord.firstName, newRecord.firstName), surname = MatchRequestData(candidateRecord.lastName, newRecord.lastName), dateOfBirth = MatchRequestData(candidateRecord.dateOfBirth.toString(), newRecord.dateOfBirth.toString()), pncNumber = MatchRequestData(candidateRecord.pnc?.pncId, newRecord.otherIdentifiers?.pncIdentifier?.pncId), ) val matchScore = getScore(matchRequest) return MatchResult( matchScore?.matchProbability?.value!!, // candidateRecordUUID = candidateRecord.person?.personId.toString(), candidateRecordIdentifierType = "defendantId", candidateRecordIdentifier = candidateRecordIdentifier, newRecordIdentifierType = "defendantId", newRecordIdentifier = newRecordIdentifier, ) } private fun getScore(matchRequest: MatchRequest): MatchResponse? = runBlocking { try { return@runBlocking RetryExecutor.runWithRetry( MAX_RETRY_ATTEMPTS, retryDelay, ) { matchScoreClient.getMatchScore(matchRequest) } } catch (exception: Exception) { telemetryService.trackEvent( MATCH_CALL_FAILED, emptyMap(), ) throw exception } } } class MatchResult( val probability: String, // val candidateRecordUUID: String, val candidateRecordIdentifierType: String, val candidateRecordIdentifier: String, val newRecordIdentifierType: String, val newRecordIdentifier: String, )
8
Kotlin
2
1
b25adf2f2b28fd4f7e17158e33528688205aee3e
2,755
hmpps-person-record
MIT License
src/main/kotlin/me/senseiwells/arucas/interpreter/Interpreter.kt
senseiwells
410,678,534
false
null
package me.senseiwells.arucas.interpreter import me.senseiwells.arucas.api.ArucasAPI import me.senseiwells.arucas.api.ArucasErrorHandler import me.senseiwells.arucas.api.docs.visitor.ArucasDocParser import me.senseiwells.arucas.builtin.* import me.senseiwells.arucas.classes.* import me.senseiwells.arucas.classes.instance.ClassInstance import me.senseiwells.arucas.compiler.* import me.senseiwells.arucas.compiler.lexer.Lexer import me.senseiwells.arucas.exceptions.* import me.senseiwells.arucas.functions.builtin.BuiltInFunction import me.senseiwells.arucas.functions.user.DelegatedConstructor import me.senseiwells.arucas.functions.user.UserConstructorFunction import me.senseiwells.arucas.functions.user.UserDefinedClassFunction import me.senseiwells.arucas.functions.user.UserDefinedFunction import me.senseiwells.arucas.interpreter.Interpreter.Companion.dummy import me.senseiwells.arucas.interpreter.Interpreter.Companion.of import me.senseiwells.arucas.nodes.* import me.senseiwells.arucas.nodes.expressions.* import me.senseiwells.arucas.nodes.statements.* import me.senseiwells.arucas.typed.LazyDefinitions import me.senseiwells.arucas.utils.* import me.senseiwells.arucas.utils.collections.FunctionMap import me.senseiwells.arucas.utils.collections.ModuleMap import me.senseiwells.arucas.utils.collections.PrimitiveDefinitionMap import me.senseiwells.arucas.utils.impl.ArucasList import me.senseiwells.arucas.utils.impl.ArucasOrderedMap import me.senseiwells.arucas.utils.impl.ArucasThread import me.senseiwells.arucas.utils.misc.ErrorSafe import java.util.* import java.util.concurrent.Future import kotlin.reflect.KClass /** * The interpreter class. This is responsible for running * the Arucas code. * * This class visits all statement and expressions that have been parsed * interpreting it. It holds much of the state while executing and is * **NOT** thread safe. You must [branch] the interpreter for use * either at a later time or on a different thread. * * The interpreter can be created with [of], this will be the root * interpreter. You are able to configure the [ArucasAPI] that the * interpreter uses. * * Here is an example: * ```kotlin * val code = "print('Hello from Arucas!');" * val name = "MyInterpreter" * val builder = ArucasAPI.Builder() * .addDefault() * val api = builder.build() * val interpreter = Interpreter.of(code, name, api) * // Blocks the current thread * interpreter.executeBlocking() * // Alternatively you can do * interpreter.executeAsync() * ``` * * You are also able to create [dummy] interpreters. These are intended * for data generation, e.g. generating documentation based on the * documentation annotations. * * @see ArucasAPI * @see ArucasDocParser */ @Suppress("UNUSED") sealed class Interpreter: StatementVisitor<Unit>, ExpressionVisitor<ClassInstance>, ErrorSafe { companion object { /** * Creates a new root interpreter. * * @param content the content to interpret. * @param name the name of the interpreter. * @param api the api used by the interpreter. * @return the new interpreter. */ @JvmStatic fun of(content: String, name: String, api: ArucasAPI = ArucasAPI.Builder().addDefault().build()): Interpreter { return Mother(content, name, api) } /** * Creates a dummy interpreter for data generation. * * @param api the api used by the interpreter. * @return the dummy interpreter. * * @see ArucasDocParser */ @JvmStatic fun dummy(api: ArucasAPI = ArucasAPI.Builder().addDefault().build()): Interpreter { return of("", "dummy", api).also { it.loadApi() } } } /** * Whether the current interpreter is the root. */ open val isMain = false /** * The content that the interpreter is executing. */ abstract val content: String /** * The name of the interpreter. */ abstract val name: String /** * The API that is being used by the interpreter. * * @see ArucasAPI */ abstract val api: ArucasAPI /** * The interpreter's properties. * * @see Properties */ abstract val properties: Properties /** * The table containing the variables, functions, and classes in the global scope. * * @see StackTable */ abstract val globalTable: StackTable /** * A collection of all the primitive definitions. * * @see PrimitiveDefinitionMap */ abstract val primitives: PrimitiveDefinitionMap /** * A collection of all the available modules. * * @see ModuleMap */ abstract val modules: ModuleMap /** * The interpreter's thread handler. * * @see ThreadHandler */ protected abstract val threadHandler: ThreadHandler /** * All the built-in functions. * * @see FunctionMap */ protected abstract val functions: FunctionMap /** * The local cache containing locations for different [Visitable]s. * * @see LocalCache */ protected abstract val localCache: LocalCache /** * The current stack table (the current scope). * * @see StackTable */ protected abstract var currentTable: StackTable /** * The stacktrace of the interpreter. * * @see call */ protected val stackTrace = Stack<Trace>() /** * The [Propagator.Return] instance, we only have one instance since * we are single-threaded we can deal with mutations and save on objects. * * @see Propagator.Return */ private val returnThrowable by lazy { Propagator.Return(this.getNull()) } /** * This executes the interpreter asynchronously. This * provides a [Future] for any [ClassInstance] that it returns. * * Any exceptions thrown by will be handled by this method. * * @return the class instance that the script returns wrapped in a future. * @see Interpreter */ fun executeAsync(): Future<ClassInstance?> { return this.threadHandler.async(this, this.api.getMainExecutor(), this::execute) } /** * This executes the interpreter on the current thread * blocking its execution till the interpreter has finished. * * Any exceptions will also not be handled by this method. * * @return the class instance that the script returns. * @see Interpreter */ fun executeBlocking(): ClassInstance { return this.threadHandler.blocking(this, this.api.getMainExecutor(), this::execute) } /** * This compiles the [content] into an abstract syntax tree of [Statement] and [Expression]. * These can then be visited by [StatementVisitor] and [ExpressionVisitor], usually an [Interpreter]. * * @return the list of [Statement]s that form the AST. */ internal fun compile(): List<Statement> { this.loadApi() val compileStart = System.nanoTime() return Parser(Lexer(this.content, this.name).createTokens()).parse().also { val resolver = Resolver(it, this.primitives, this.functions.map { f -> f.getPrimitive(FunctionDef::class)!! }) this.localCache.mergeWith(resolver.run()) val compileTime = TimeUtils.nanosToString(System.nanoTime() - compileStart) this.logDebug("Compile time for '${this.name}' was $compileTime") } } /** * This compiles the [content] then visits it with this [Interpreter]. * * @see compile */ internal fun interpret() { val statements = this.compile() val executionStart = System.nanoTime() try { statements.forEach(this::execute) } finally { val executionTime = TimeUtils.nanosToString(System.nanoTime() - executionStart) this.logDebug("Execution time for '${this.name}' was $executionTime") } } /** * This checks whether the interpreter should be running. * * @return whether the interpreter should be running. */ fun isRunning(): Boolean { return this.threadHandler.running } /** * This adds a callback for when the root interpreter stops executing. * * This can happen as a result of a propagated error or closing naturally * or [forcibly stopped](stop). * * @param runnable the callback. */ fun addStopEvent(runnable: Runnable) { this.threadHandler.addShutdownEvent(runnable) } /** * This stops the interpreter from executing further. */ fun stop() { this.threadHandler.stop() } /** * This runs a function asynchronously to the main interpreter thread. * * @param function the code to run async. * @return a [Future] of a possible [ClassInstance], null if an error is thrown within the [function]. */ fun runAsync(function: () -> ClassInstance): Future<ClassInstance?> { return this.threadHandler.async(this, function) } /** * This runs a callable [ClassInstance] on a new [ArucasThread]. * * @param callable the callable [ClassInstance]. * @param name the name of the thread. * @return the [ArucasThread] that the [callable] is running on. */ fun runFunctionOnThread(callable: ClassInstance, name: String = "Arucas Async Thread"): ArucasThread { return this.threadHandler.runFunctionOnThread(callable, this, name) } /** * Converts [Any] into a [ClassInstance]. * * @param any the value to convert. * @return the [ClassInstance]. * @see ValueConverter */ fun convertValue(any: Any?): ClassInstance { return this.api.getConverter().convertFrom(any, this) } /** * Gets the primitive definition from its [Class]. * * This will throw an exception if the definition is not found. * * @param T the exact type of [PrimitiveDefinition]. * @param clazz the class of the [PrimitiveDefinition]. * @return the [PrimitiveDefinition]. */ fun <T: PrimitiveDefinition<*>> getPrimitive(clazz: Class<out T>): T { return this.primitives.get(clazz) ?: throw IllegalArgumentException("No such definition for '${clazz.simpleName}'") } /** * Gets the primitive definition from its [KClass]. * * This will throw an exception if the definition is not found. * * @param T the exact type of [PrimitiveDefinition]. * @param klass the class of the [PrimitiveDefinition]. * @return the [PrimitiveDefinition]. * @see getPrimitive */ fun <T: PrimitiveDefinition<*>> getPrimitive(klass: KClass<out T>): T { return this.getPrimitive(klass.java) } /** * This creates a [ClassInstance] of a [CreatableDefinition] with a given primitive [value]. * * @param T the type of [CreatableDefinition]. * @param V the primitive type of [T]. * @param clazz the class of the [CreatableDefinition]. * @param value the primitive value. * @return the created [ClassInstance] */ fun <T: CreatableDefinition<V>, V> create(clazz: Class<out T>, value: V): ClassInstance { return this.getPrimitive(clazz).create(value) } /** * This creates a [ClassInstance] of a [CreatableDefinition] with a given primitive [value]. * * @param T the type of [CreatableDefinition]. * @param V the primitive type of [T]. * @param klass the class of the [CreatableDefinition]. * @param value the primitive value. * @return the created [ClassInstance] * @see create */ fun <T: CreatableDefinition<V>, V> create(klass: KClass<out T>, value: V): ClassInstance { return this.create(klass.java, value) } /** * This 'creates' a boolean [ClassInstance]. * * In reality this just gets one of the existing constant * [ClassInstance] so they will have the same identity. * * @param boolean the boolean value. * @return the boolean [ClassInstance]. */ fun createBool(boolean: Boolean): ClassInstance { return this.getPrimitive(BooleanDef::class).from(boolean) } /** * Gets the null [ClassInstance]. * * @return the null [ClassInstance]. */ fun getNull(): ClassInstance { return this.getPrimitive(NullDef::class).NULL } /** * Checks whether the interpreter */ fun isWithinStack(stack: StackTable): Boolean { return this.currentTable.hasAncestor(stack) } /** * Creates a [Branch]. This is needed for when going off thread * or when saving the interpreter's state for later use. * * Creating a branch saves the current stack table, other than * that branches inherit all other properties from their parent. * * Here is an example of how to use [branch]: * ```kotlin * val interpreter = /* Get interpreter */ * // We must branch here to save the current stack state. * val branch = interpreter.branch() * Thread { * for (i in 0..100) { * // This runAsync call can be on any interpreter * interpreter.runAsync { * // We must create a branch of the branch to ensure thread safety * val inner = branch.branch() * // Do stuff with new inner branch * } * } * }.start() * ``` */ fun branch(): Interpreter { return Branch(this) } /** * Creates a [Child]. This is needed for running sub-scripts within * a script. This is needed because creating another root interpreter will * result in different instances of class definitions. * * A child inherits all the parent's definitions, functions, etc. however * gains its own global table to run its own script. To execute a child * interpreter it is the same a root interpreter: [executeBlocking] or [executeAsync]. * * Children are used for importing, they are able to define classes and * add them to the [modules] field. * * @param content the content of the child script. * @param name the name of the child. * @return the child interpreter. */ fun child(content: String, name: String): Interpreter { return Child(content, name, false, this) } /** * Tries to log a message to the debug output. It will * only log the message if the [Properties.isDebug] field * is set to true. * * @param message the message to log. */ fun logDebug(message: String) { if (this.properties.isDebug) { this.api.getOutput().logln(message) } } /** * Checks if the interpreter is in experimental mode. If * it is not then an error will be thrown. * * @param message a lazy message. */ fun throwIfNotExperimental(message: () -> String = { "Interpreter is not in experimental mode" }) { if (!this.properties.isExperimental) { runtimeError(message()) } } /** * Runs a function, and catches any [Exception]s. * * This mirrors the functionality of [ErrorSafe] however * provides `inline` functionality for performance. * * @see ErrorSafe.runSafe */ inline fun <T> runSafe(block: () -> T): T? { return try { block() } catch (e: Exception) { this.handleError(e) null } } /** * Runs a function, and catches any [Exception]s. * * This mirrors the functionality of [ErrorSafe] however * provides `inline` functionality for performance. * * @see ErrorSafe.runSafe */ inline fun <T> runSafe(default: T, block: () -> T): T { return try { block() } catch (e: Exception) { this.handleError(e) default } } /** * Runs a function, and catches any [InterruptedException]s. * * This mirrors the functionality of [ErrorSafe] however * provides `inline` functionality for performance. * * @see ErrorSafe.canInterrupt */ inline fun <T> canInterrupt(block: () -> T): T { return try { block() } catch (e: InterruptedException) { throw Propagator.Stop.INSTANCE } } /** * This handles any uncaught exceptions by passing them to the * [ThreadHandler]. This will deal with the error appropriately * calling the [ArucasErrorHandler] methods and stopping the script. * * @param throwable the uncaught [Throwable]. */ override fun handleError(throwable: Throwable) { this.threadHandler.handleError(throwable, this) } /** * This executes the interpreter. This is used by [executeBlocking] and [executeAsync] * * @return the class instance that the script returns. */ protected abstract fun execute(): ClassInstance /** * This loads any API elements, such as the built-in classes and extensions. * * @see [ArucasAPI] */ protected abstract fun loadApi() /** * Called when a class is defined. * * @param table the stack that the class is being defined on/ */ protected open fun defineClass(table: StackTable, definition: ClassDefinition) { table.defineClass(definition) } /** * Executes a statement on a given [StackTable]. * * @param table the table to jump to. * @param statement the statement to execute. */ internal fun execute(table: StackTable, statement: Statement) { this.jumpTable(table) { this.execute(statement) } } /** * Evaluates an expression on a given [StackTable]. * * @param table the table to jump to. * @param expression the expression to evaluate. * @return the result of the [expression]. */ /* internal */ fun evaluate(table: StackTable, expression: Expression): ClassInstance { return this.jumpTable(table) { this.evaluate(expression) } } /** * This method calls a [ClassInstance] and pushes it to the [stackTrace] for errors. * * @param instance the [ClassInstance] to call. * @param args the arguments to provide for the call. * @param trace the [Trace] to push to the [stackTrace]. * @return the [ClassInstance] returned by the instance call. */ /* internal */ fun call(instance: ClassInstance, args: List<ClassInstance>, trace: CallTrace = Trace.INTERNAL): ClassInstance { this.poll() try { this.stackTrace.push(trace) @Suppress("DEPRECATION") return instance.call(this, args) } catch (runtime: RuntimeError) { runtime.fillStackTrace(this.stackTrace) throw runtime } catch (fatal: FatalError) { throw fatal } catch (propagator: Propagator) { throw propagator } catch (stackOverflow: StackOverflowError) { throw RuntimeError("Ran out of space on the stack", stackOverflow, trace).also { it.fillStackTrace(this.stackTrace) } } catch (throwable: Throwable) { throw FatalError("An unexpected error was thrown", throwable, this.stackTrace) } finally { this.stackTrace.pop() } } /** * Jumps to the next stack, the child of the current stack table. * It then executes [block], then pops the stack back to the original. * * @param T the return type of [block]. * @param block the block to execute within the next stack. * @return the return value of [block]. * @see StackTable * @see jumpTable */ private inline fun <T> jumpNextTable(block: () -> T): T { return this.jumpTable(StackTable(this.modules, this.currentTable), block) } /** * Jumps to an arbitrary given stack then executes the [block], * then pops the stack back to the original. * * @param T the return type of [block]. * @param table the [StackTable] to jump to. * @param block the block to execute within the stack. * @return the return value of [block]. * @see StackTable * @see jumpNextTable */ private inline fun <T> jumpTable(table: StackTable, block: () -> T): T { val previous = this.currentTable try { this.currentTable = table return block() } finally { this.currentTable = previous } } /** * Checks whether the interpreter is still able to run. * * @return whether the interpreter can still run. */ private fun poll(): Boolean { this.api.getPoller().poll(this) if (!this.isRunning()) { throw Propagator.Stop.INSTANCE } val thread = Thread.currentThread() if (thread is ArucasThread && thread.isFrozen) { thread.freeze() } return true } private fun execute(statement: Statement) { statement.visit(this) } private fun executeNext(vararg statements: Statement) { this.jumpNextTable { statements.forEach { this.execute(it) } } } private fun evaluate(expression: Expression): ClassInstance { return expression.visit(this) } private fun isInstanceType(instance: ClassInstance, typeNames: Array<String>?, trace: Trace): Boolean { typeNames ?: return true for (name in typeNames) { val definition = this.currentTable.getClass(name) definition ?: runtimeError("No such class with name '$name'", trace) if (instance.isOf(definition)) { return true } } return false } private fun tryImport(importPath: String, local: Boolean) { if (!this.modules.tried(importPath)) { this.modules.addLazy(importPath) { val content = this.api.getLibraryManager().getImport(importPath.split("."), local, this) content ?: return@addLazy val child: Interpreter = Child(content, importPath, true, this) child.execute() this.localCache.mergeWith(child.localCache) } } } @Suppress("SameParameterValue") private fun getVariable(name: String, trace: Trace, visitable: Visitable? = null): ClassInstance { return this.getVariableNullable(name, trace, visitable) ?: runtimeError("No such variable '$name' exists", trace) } private fun getVariableNullable(name: String, trace: Trace, visitable: Visitable? = null): ClassInstance? { visitable ?: return this.currentTable.getVar(name) val distance = this.localCache.getVar(visitable) distance?.let { this.currentTable.getVar(name, distance)?.let { variable -> return variable } // So theoretically, it's possible that a variable defined in a function // was cached in that location but was since defined in the previous scopes // where it currently resides. This means that we need to check the scopes above. // But this should be avoided as it can lead to unwanted behaviours. this.currentTable.getVar(name)?.let { variable -> this.logDebug("Local variable '$name' was defined previously in a scope but was accessed in scopes above") return variable } if (name == "this") { runtimeError("Tried to access 'this' or 'super' in a static context", trace) } throw IllegalArgumentException("Failed to fetch variable '${name}' at cached location (${it})") } return this.globalTable.getVar(name) } private fun getFunction(name: String, parameters: Int, trace: Trace, visitable: Visitable? = null): ClassInstance { if (visitable != null) { this.localCache.getFunction(visitable)?.let { distance -> this.currentTable.getFunction(name, parameters, distance)?.let { return it } throw IllegalArgumentException("Failed to fetch function '${name}::${parameters}' at cached location (${distance})") } this.localCache.getVar(visitable)?.let { distance -> this.currentTable.getVar(name, distance)?.let { return it } throw IllegalArgumentException("Failed to fetch function '${name}::${parameters}' at cached location (${distance})") } this.globalTable.getFunction(name, parameters)?.let { return it } this.globalTable.getVar(name)?.let { return it } } else { this.currentTable.getFunction(name, parameters)?.let { return it } this.currentTable.getVar(name)?.let { return it } } return this.functions.get(name, parameters) ?: this.noFunctionError(name, parameters, trace) } private fun getClass(name: String, trace: Trace, visitable: Visitable? = null): ClassDefinition { if (visitable != null) { this.localCache.getClass(visitable)?.let { distance -> this.currentTable.getClass(name, distance)?.let { return it } throw IllegalArgumentException("Failed to fetch class '${name}' at cached location (${distance})") } this.globalTable.getClass(name)?.let { return it } } this.currentTable.getClass(name)?.let { return it } runtimeError("No such class '$name' exists", trace) } private fun noFunctionError(name: String, parameters: Int, trace: Trace): Nothing { val error = if (parameters == 0) "" else " with $parameters parameter${if (parameters == 1) "" else "s"}" runtimeError("No such function '$name'$error exists", trace) } private fun visitClassBody(definition: ArucasClassDefinition, body: ClassBodyStatement, needsSuper: Boolean, type: String) { definition.fields.value.addAll(body.fields) if (needsSuper && body.constructors.isEmpty()) { runtimeError("Derived class constructor must initialise super constructor", body.start) } body.constructors.forEach { c -> if (needsSuper && c.delegate.type == DelegatedConstructor.Type.NONE) { runtimeError("Derived class constructor must initialise super constructor", c.start) } val parameters = c.parameters.map { it.create(this.currentTable, c.start) } UserConstructorFunction.of(c.arbitrary, definition, c.delegate, parameters, c.body, this.currentTable, c.start, c.private).let { definition.constructors.value.add(this.create(FunctionDef::class, it)) } } body.methods.forEach { m -> if (m.private) { if (definition.canOverride(m.name, m.parameters.size)) { runtimeError("Cannot override the public method '${m.name}' with private implementation in class '${definition.name}'", m.start) } } val parameters = m.parameters.map { it.create(this.currentTable, m.start) } val returns = LazyDefinitions.of(m.returnTypes, this.currentTable, m.start) UserDefinedClassFunction.of(m.arbitrary, m.name, parameters, m.body, this.currentTable, m.start, returns, m.private).let { definition.methods.value.add(this.create(FunctionDef::class, it)) } } body.operators.forEach { (m, t) -> val parameters = m.parameters.map { it.create(this.currentTable, m.start) } val returns = LazyDefinitions.of(m.returnTypes, this.currentTable, m.start) UserDefinedClassFunction.of(m.arbitrary, m.name, parameters, m.body, this.currentTable, m.start, returns, m.private).let { definition.operators.value.add(t, this.create(FunctionDef::class, it)) } } body.staticMethods.forEach { m -> val parameters = m.parameters.map { it.create(this.currentTable, m.start) } val returns = LazyDefinitions.of(m.returnTypes, this.currentTable, m.start) UserDefinedFunction.of(m.arbitrary, m.name, parameters, m.body, this.currentTable, m.start, returns, m.private).let { definition.staticMethods.value.add(this.create(FunctionDef::class, it)) } } body.staticFields.forEach { v -> definition.staticFields.value[v.name] = v.create(this, this.currentTable, body.start) } body.staticInitializers.forEach { this.execute(it) } if (definition.staticFields.isInitialized()) { definition.staticFields.value.values.forEach { it.finalise(body.start) } } for (interfaceDefinition in definition.interfaces()) { if (!interfaceDefinition.hasRequiredMethods(definition)) { runtimeError("$type '${definition.name}' has not properly implemented '${interfaceDefinition.name}'", body.start) } } } private fun visitSuper(superExpression: SuperExpression, trace: Trace): Pair<ClassInstance, ClassDefinition> { val instance = this.getVariable("this", trace, superExpression) val name = this.localCache.getSuper(superExpression) ?: throw IllegalStateException("Could not get super context name") return instance to instance.definition.superclassOf(name) } // Visiting Implementations: override fun visitVoid(void: VoidStatement) { } override fun visitStatements(statements: Statements) { statements.statements.forEach { this.execute(it) } } override fun visitScope(scope: ScopeStatement) { this.executeNext(scope.statements) } override fun visitLocalVar(local: LocalVarStatement) { this.currentTable.defineVar(local.name, this.evaluate(local.assignee)) } override fun visitExpression(expression: ExpressionStatement) { this.evaluate(expression.expression) } override fun visitIf(ifStatement: IfStatement) { val condition = this.evaluate(ifStatement.condition).getPrimitive(BooleanDef::class) condition ?: runtimeError("Condition must result in a Boolean", ifStatement.start) if (condition) { this.execute(ifStatement.body) } else { this.execute(ifStatement.otherwise) } } override fun visitSwitch(switch: SwitchStatement) { val condition = this.evaluate(switch.condition) try { switch.casesList.forEachIndexed { i, cases -> for (case in cases) { if (condition.equals(this, this.evaluate(case), switch.start)) { this.execute(switch.caseStatements[i]) return } } } switch.defaultStatement?.let { this.execute(it) } } catch (_: Propagator.Break) { } } override fun visitFunction(function: FunctionStatement) { val parameters = function.parameters.map { it.create(this.currentTable, function.start) } val returns = LazyDefinitions.of(function.returnTypes, this.currentTable, function.start) UserDefinedFunction.of(function.arbitrary, function.name, parameters, function.body, this.currentTable, function.start, returns).let { if (!function.isClass) { this.currentTable.defineFunction(this.create(FunctionDef::class, it)) } } } override fun visitReturn(returnStatement: ReturnStatement) { val returnValue = this.evaluate(returnStatement.expression) throw this.returnThrowable.also { it.returnValue = returnValue } } override fun visitWhile(whileStatement: WhileStatement) { while (this.poll()) { val condition = this.evaluate(whileStatement.condition).getPrimitive(BooleanDef::class) condition ?: runtimeError("Condition must result in Boolean", whileStatement.Start) if (!condition) { break } try { this.execute(whileStatement.body) } catch (ignored: Propagator.Continue) { continue } catch (breakPropagator: Propagator.Break) { break } } } override fun visitFor(forStatement: ForStatement) { this.jumpNextTable { this.execute(forStatement.initial) while (this.poll()) { val condition = this.evaluate(forStatement.condition).getPrimitive(BooleanDef::class) condition ?: runtimeError("Condition must result in Boolean", forStatement.start) if (!condition) { break } try { this.execute(forStatement.body) } catch (breakPropagator: Propagator.Break) { break } catch (_: Propagator.Continue) { } this.evaluate(forStatement.expression) } } } override fun visitForeach(foreach: ForeachStatement) { val result = this.evaluate(foreach.iterable) val iterator = if (result.isOf(IterableDef::class)) { result.callMember(this, "iterator", listOf(), IteratorDef::class, foreach.start) } else { result.expect(IteratorDef::class, "'foreach' loop must iterate over an Iterable or Iterator", foreach.start) result } val wrapped = CollectionUtils.wrapIterator(this, iterator, foreach.start) for (value in wrapped) { this.poll() val shouldBreak = this.jumpNextTable { this.currentTable.defineVar(foreach.name, value) try { this.execute(foreach.body) } catch (breakPropagator: Propagator.Break) { return@jumpNextTable true } catch (_: Propagator.Continue) { } false } if (shouldBreak) { break } } } override fun visitContinue(continueStatement: ContinueStatement) { throw Propagator.Continue.INSTANCE } override fun visitBreak(breakStatement: BreakStatement) { throw Propagator.Break.INSTANCE } override fun visitTry(tryStatement: TryStatement) { try { this.execute(tryStatement.body) } catch (error: RuntimeError) { tryStatement.catchParameter ?: throw error this.jumpNextTable { val instance = error.getInstance(this) if (!this.isInstanceType(instance, tryStatement.catchParameter.hints, tryStatement.start)) { throw instance.getPrimitive(ErrorDef::class)!! } this.logDebug("Error '$error' was caught") this.currentTable.defineVar(tryStatement.catchParameter.name, instance) this.execute(tryStatement.catchBody) } } finally { // Executed even if the error is not a RuntimeError this.execute(tryStatement.finally) } } override fun visitThrow(throwStatement: ThrowStatement) { val error = this.evaluate(throwStatement.throwable).getPrimitive(ErrorDef::class) error ?: runtimeError("Tried to throw a non Error value", throwStatement.trace) error.pushToTop(throwStatement.trace) throw error } override fun visitConstructor(constructor: ConstructorStatement) { throw IllegalStateException("Interpreter visited constructor") } override fun visitClassBody(classBody: ClassBodyStatement) { throw IllegalStateException("Interpreter visited class body") } override fun visitClass(classStatement: ClassStatement) { val interfaces = HashSet<InterfaceDefinition>() var superclass: ClassDefinition? = null var needsSuper = false for (parent in classStatement.parents) { val parentClass = this.getClass(parent, classStatement.start, classStatement) if (parentClass is InterfaceDefinition) { interfaces.add(parentClass) continue } if (superclass == null) { if (!parentClass.canExtend() || !parentClass.constructors.isInitialized()) { runtimeError("Cannot extend class '${parentClass.name}'", classStatement.start) } needsSuper = true superclass = parentClass continue } runtimeError("Classes can only extend one non-interface super class", classStatement.start) } this.jumpNextTable { val definition = ArucasClassDefinition(classStatement.name, this, this.currentTable, superclass, interfaces) this.defineClass(this.currentTable.parent!!, definition) this.visitClassBody(definition, classStatement.body, needsSuper, "class") } } override fun visitEnum(enumStatement: EnumStatement) { val interfaces = HashSet<InterfaceDefinition>() for (parent in enumStatement.parents) { val parentClass = this.getClass(parent, enumStatement.start, enumStatement) if (parentClass !is InterfaceDefinition) { runtimeError("Enums can only implement interfaces, cannot extend class '${parentClass.name}'", enumStatement.start) } interfaces.add(parentClass) } this.jumpNextTable { val definition = EnumDefinition(enumStatement.name, this, this.currentTable, interfaces) this.defineClass(this.currentTable.parent!!, definition) if (enumStatement.body is ClassBodyStatement) { this.visitClassBody(definition, enumStatement.body, false, "enum") } enumStatement.enums.forEach { name, (args, trace) -> val elements = ArrayList<ClassInstance>() for (expression in args) { elements.add(this.evaluate(expression)) } definition.addEnum(this, name, elements, trace) } } } override fun visitInterface(interfaceStatement: InterfaceStatement) { val definition = InterfaceDefinition(interfaceStatement.name, this, interfaceStatement.requiredMethods) this.defineClass(this.currentTable, definition) } override fun visitImport(importStatement: ImportStatement) { val importPath = importStatement.path val local = importStatement.local if (!this.modules.has(importPath)) { this.tryImport(importPath, local) } if (importStatement.names.isNotEmpty()) { for (name in importStatement.names) { this.currentTable.addModule(name, importPath) } } else { this.currentTable.addAllModules(importPath) } } override fun visitExact(exact: ExactExpression): ClassInstance { return exact.instance } override fun <L: PrimitiveDefinition<*>> visitLiteral(literal: LiteralExpression<L>): ClassInstance { return literal.cache ?: literal.supplier(this.getPrimitive(literal.klass)).also { literal.cache = it } } override fun visitBracket(bracket: BracketExpression): ClassInstance { return this.evaluate(bracket.expression) } override fun visitList(list: ListExpression): ClassInstance { val elements = ArucasList() for (expression in list.expressions) { elements.add(this.evaluate(expression)) } return this.create(ListDef::class, elements) } override fun visitMap(map: MapExpression): ClassInstance { val elements = ArucasOrderedMap() map.expressions.forEach { (k, v) -> elements.put(this, this.evaluate(k), this.evaluate(v)) } return this.create(MapDef::class, elements) } override fun visitFunction(function: FunctionExpression): ClassInstance { val parameters = function.parameters.map { it.create(this.currentTable, function.start) } val returns = LazyDefinitions.of(function.returnTypes, this.currentTable, function.start) UserDefinedFunction.of(function.arbitrary, function.name, parameters, function.body, this.currentTable, function.start, returns).let { return this.create(FunctionDef::class, it) } } override fun visitUnary(unary: UnaryExpression): ClassInstance { if (unary.expression is SuperExpression) { this.visitSuper(unary.expression, unary.expression.trace).let { (i, d) -> return d.unary(i, this, unary.type, unary.trace) } } return this.evaluate(unary.expression).unary(this, unary.type, unary.trace) } override fun visitBinary(binary: BinaryExpression): ClassInstance { if (binary.left is SuperExpression) { this.visitSuper(binary.left, binary.left.trace).let { (i, d) -> return d.binary(i, this, binary.type, { this.evaluate(binary.right) }, binary.trace) } } return this.evaluate(binary.left).binary(this, binary.type, { this.evaluate(binary.right) }, binary.trace) } override fun visitUnpackAssign(assign: UnpackAssignExpression): ClassInstance { val list = this.evaluate(assign.assignee) if (!list.isOf(ListDef::class)) { runtimeError("Expression in unpacking assignment must result in an List value", assign.trace) } val size = list.callMemberPrimitive(this, "size", ArrayList(), NumberDef::class, assign.trace).toInt() if (size != assign.assignables.size) { runtimeError("Unpacking assign size does not match list size", assign.trace) } val callTrace = CallTrace(assign.trace, "Unpacking") assign.assignables.forEachIndexed { i, assignable -> val value = list.bracketAccess(this.create(NumberDef::class, i.toDouble()), this, callTrace) this.evaluate(assignable.copyWith(value)) } return list } override fun visitAccess(access: AccessExpression): ClassInstance { val variable = this.getVariableNullable(access.name, access.trace, access) variable?.let { return it } if (this.functions.has(access.name) || this.currentTable.hasFunction(access.name)) { val child = this.branch() val delegate = BuiltInFunction.arb("\$delegate.${access.name}", { val callTrace = CallTrace(access.trace, "${access.name}::${it.size()}") // We need to create a branch of the branch, this is because // this delegate may be used again in the future, or maybe // even by another thread, we cannot guarantee thread safety val inner = child.branch() inner.call(inner.getFunction(access.name, it.size(), access.trace), it.arguments, callTrace) }) return this.create(FunctionDef::class, delegate) } runtimeError("No such variable '${access.name}' exists", access.trace) } override fun visitFunctionAccess(access: FunctionAccessExpression): ClassInstance { return this.getFunction(access.name, access.parameters, access.trace, access) } override fun visitAssign(assign: AssignExpression): ClassInstance { val instance = this.evaluate(assign.assignee) this.localCache.getVar(assign)?.let { this.currentTable.defineVar(assign.name, instance, it) return instance } // Normally you could assume that we always // define the variable here, but there's an edge // case, that is if the variable is in a function // the variable may not have been defined yet if (!this.currentTable.assignVar(assign.name, instance)) { this.currentTable.defineVar(assign.name, instance) } return instance } override fun visitCall(call: CallExpression): ClassInstance { val arguments = ArrayList<ClassInstance>() for (expression in call.arguments) { arguments.add(this.evaluate(expression)) } val function = this.evaluate(call.expression) return this.call(function, arguments, CallTrace(call.trace, function.toString(this, call.trace))) } override fun visitThis(thisExpression: ThisExpression): ClassInstance { return this.getVariable("this", thisExpression.trace, thisExpression) } override fun visitSuper(superExpression: SuperExpression): ClassInstance { runtimeError("Cannot directly access 'super'", superExpression.trace) } override fun visitMemberAccess(access: MemberAccessExpression): ClassInstance { val instance = when (val expression = access.expression) { is AccessExpression -> { val instance = this.getVariableNullable(expression.name, access.trace, expression) instance ?: this.getClass(expression.name, expression.trace, expression).let { return it.staticMemberAccess(this, access.name, access.trace) } } is SuperExpression -> { this.visitSuper(expression, expression.trace).let { (i, d) -> return d.memberAccess(i, this, access.name, access.trace) } } else -> this.evaluate(access.expression) } return instance.memberAccess(this, access.name, access.trace) } override fun visitMemberAssign(assign: MemberAssignExpression): ClassInstance { val assignee = this.evaluate(assign.assignee) val instance = if (assign.expression is AccessExpression) { val instance = this.getVariableNullable(assign.expression.name, assign.trace, assign.expression) instance ?: this.getClass(assign.expression.name, assign.expression.trace, assign).let { it.staticMemberAssign(this, assign.name, assignee, assign.trace) return assignee } } else { this.evaluate(assign.expression) } return instance.memberAssign(this, assign.name, assignee, assign.trace) } override fun visitMemberCall(call: MemberCallExpression): ClassInstance { val arguments = ArrayList<ClassInstance>() for (expression in call.arguments) { arguments.add(this.evaluate(expression)) } val instance = when (val expression = call.expression) { is AccessExpression -> { val instance = this.getVariableNullable(expression.name, call.trace, expression) instance ?: this.getClass(expression.name, expression.trace, expression).let { return it.staticFunctionCall(this, call.name, arguments, call.trace) } } is SuperExpression -> { this.visitSuper(expression, expression.trace).let { (i, d) -> val function = d.memberFunctionAccess(i, this, call.name , arguments, call.trace, d) val callTrace = CallTrace(call.trace, "<${d.name}>.super.${call.name}::${arguments.size - 1}") return this.call(function, arguments, callTrace) } } else -> this.evaluate(call.expression) } return instance.callMember(this, call.name, arguments, call.trace) } override fun visitNewAccess(access: NewAccessExpression): ClassInstance { val classDefinition = this.getClass(access.name, access.trace, access) return classDefinition.accessConstructor(this, access.trace) } override fun visitNewCall(call: NewCallExpression): ClassInstance { this.poll() val classDefinition = this.getClass(call.name, call.trace, call) val arguments = ArrayList<ClassInstance>() for (expression in call.arguments) { arguments.add(this.evaluate(expression)) } return classDefinition.callConstructor(this, arguments, call.trace) } override fun visitBracketAccess(access: BracketAccessExpression): ClassInstance { val index = this.evaluate(access.index) if (access.expression is SuperExpression) { this.visitSuper(access.expression, access.trace).let { (i, d) -> return d.bracketAccess(i, this, index, access.trace) } } return this.evaluate(access.expression).bracketAccess(index, this, access.trace) } override fun visitBracketAssign(assign: BracketAssignExpression): ClassInstance { val index = this.evaluate(assign.index) val assignee = this.evaluate(assign.assignee) if (assign.expression is SuperExpression) { this.visitSuper(assign.expression, assign.trace).let { (i, d) -> return d.bracketAssign(i, this, index, assignee, assign.trace) } } return this.evaluate(assign.expression).bracketAssign(index, this, assignee, assign.trace) } private class Mother( override val content: String, override val name: String, override val api: ArucasAPI, ): Interpreter() { override val isMain = true override val threadHandler = ThreadHandler(this) override val properties = this.api.getProperties().invoke() override val modules = ModuleMap() override val functions = FunctionMap() override val primitives = PrimitiveDefinitionMap() override val globalTable = StackTable(this.modules) override val localCache = LocalCache() override var currentTable = this.globalTable override fun execute(): ClassInstance { return this.threadHandler.execute() } override fun loadApi() { this.api.getBuiltInDefinitions().forEach { p -> val primitive = p(this) this.primitives.add(primitive) this.modules.addBuiltIn(primitive) } this.primitives.forEach { it.merge() } this.api.getBuiltInExtensions().forEach { e -> e.getBuiltInFunctions().forEach { this.functions.add(this.create(FunctionDef::class, it)) } } this.api.getClassDefinitions().forEach { (importPath, definitions) -> for (factory in definitions) { val primitive = factory(this) this.primitives.add(primitive) this.modules.add(importPath, primitive) primitive.merge() } } } } private class Child( override val content: String, override val name: String, val isImporting: Boolean, parent: Interpreter ): Interpreter() { override val api = parent.api override val properties = parent.properties override val globalTable = StackTable(parent.modules) override var currentTable = this.globalTable override val threadHandler = parent.threadHandler override val modules = parent.modules override val functions = parent.functions override val primitives = parent.primitives override val localCache = parent.localCache override fun execute(): ClassInstance { return try { this.interpret() this.getNull() } catch (returnPropagator: Propagator.Return) { returnPropagator.returnValue } catch (compileError: CompileError) { // Compile errors are propagated as runtime errors // so parent script can handle accordingly runtimeError("Compiling failed", compileError) } } override fun loadApi() { // API is already loaded } override fun defineClass(table: StackTable, definition: ClassDefinition) { super.defineClass(table, definition) if (table == this.globalTable && this.isImporting) { this.modules.add(this.name, definition) } } } private class Branch(interpreter: Interpreter): Interpreter() { override val content = interpreter.content override val name = interpreter.name override val api = interpreter.api override val properties = interpreter.properties override val modules = interpreter.modules override val threadHandler = interpreter.threadHandler override val functions = interpreter.functions override val primitives = interpreter.primitives override val globalTable = interpreter.globalTable override var currentTable = interpreter.currentTable override var localCache = interpreter.localCache init { for (trace in interpreter.stackTrace) { this.stackTrace.push(trace) } } override fun execute(): ClassInstance { throw IllegalStateException("Branch cannot be executed") } override fun loadApi() { throw IllegalStateException("Branch cannot reload API") } } }
0
null
4
17
239610d1ce529ab087125dab4c592f28cc963ca7
53,759
Arucas
MIT License
app/src/main/java/io/github/drumber/kitsune/data/mapper/MediaUnitMapper.kt
Drumber
406,471,554
false
{"Kotlin": 993796, "Ruby": 2109}
package io.github.drumber.kitsune.data.mapper import io.github.drumber.kitsune.data.presentation.model.media.unit.Chapter import io.github.drumber.kitsune.data.presentation.model.media.unit.Episode import io.github.drumber.kitsune.data.source.network.media.model.unit.NetworkChapter import io.github.drumber.kitsune.data.source.network.media.model.unit.NetworkEpisode import io.github.drumber.kitsune.data.source.network.media.model.unit.NetworkMediaUnit object MediaUnitMapper { fun NetworkMediaUnit.toMediaUnit() = when (this) { is NetworkEpisode -> toEpisode() is NetworkChapter -> toChapter() } fun NetworkEpisode.toEpisode() = Episode( id = id.require(), description = description, titles = titles, canonicalTitle = canonicalTitle, number = number, seasonNumber = seasonNumber, relativeNumber = relativeNumber, length = length, airdate = airdate, thumbnail = thumbnail ) fun NetworkChapter.toChapter() = Chapter( id = id.require(), description = description, titles = titles, canonicalTitle = canonicalTitle, number = number, volumeNumber = volumeNumber, length = length, thumbnail = thumbnail, published = published, ) }
6
Kotlin
4
92
ba6f2a69cb71a9fd71d4825921ff6d9b6300471e
1,322
Kitsune
Apache License 2.0
plugins/graphql-kotlin-plugin-core/src/test/kotlin/com/expediagroup/graphql/plugin/generator/types/GenerateGraphQLUnionTypeSpecIT.kt
wpK
271,208,040
true
{"Kotlin": 1086808, "HTML": 6411, "JavaScript": 5387, "CSS": 297}
/* * Copyright 2020 Expedia, 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 * * 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.expediagroup.graphql.plugin.generator.types import com.expediagroup.graphql.plugin.generator.verifyGeneratedFileSpecContents import graphql.language.SelectionSet import io.mockk.mockk import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import kotlin.test.assertEquals class GenerateGraphQLUnionTypeSpecIT { @Test fun `verify we can generate union type using inline fragments`() { val expected = """ package com.expediagroup.graphql.plugin.generator.integration import com.expediagroup.graphql.client.GraphQLClient import com.expediagroup.graphql.types.GraphQLResponse import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY import com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME import kotlin.Int import kotlin.String const val UNION_QUERY_WITH_INLINE_FRAGMENTS: String = "query UnionQueryWithInlineFragments {\n unionQuery {\n __typename\n ... on BasicObject {\n id\n name\n }\n ... on ComplexObject {\n id\n name\n optional\n }\n }\n}" class UnionQueryWithInlineFragments( private val graphQLClient: GraphQLClient<*> ) { suspend fun execute(): GraphQLResponse<UnionQueryWithInlineFragments.Result> = graphQLClient.execute(UNION_QUERY_WITH_INLINE_FRAGMENTS, "UnionQueryWithInlineFragments", null) /** * Some basic description */ data class BasicObject( val id: Int, /** * Object name */ val name: String ) : UnionQueryWithInlineFragments.BasicUnion /** * Multi line description of a complex type. * This is a second line of the paragraph. * This is final line of the description. */ data class ComplexObject( /** * Some unique identifier */ val id: Int, /** * Some object name */ val name: String, /** * Optional value * Second line of the description */ val optional: String? ) : UnionQueryWithInlineFragments.BasicUnion /** * Very basic union of BasicObject and ComplexObject */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename" ) @JsonSubTypes(value = [com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = UnionQueryWithInlineFragments.BasicObject::class, name="BasicObject"),com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = UnionQueryWithInlineFragments.ComplexObject::class, name="ComplexObject")]) interface BasicUnion data class Result( /** * Query returning union */ val unionQuery: UnionQueryWithInlineFragments.BasicUnion ) } """.trimIndent() val queryWithInlineFragments = """ query UnionQueryWithInlineFragments { unionQuery { __typename ... on BasicObject { id name } ... on ComplexObject { id name optional } } } """.trimIndent() verifyGeneratedFileSpecContents(queryWithInlineFragments, expected) } @Test fun `verify we can generate union type using named fragments`() { val expected = """ package com.expediagroup.graphql.plugin.generator.integration import com.expediagroup.graphql.client.GraphQLClient import com.expediagroup.graphql.types.GraphQLResponse import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY import com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME import kotlin.Int import kotlin.String const val UNION_QUERY_WITH_NAMED_FRAGMENTS: String = "query UnionQueryWithNamedFragments {\n unionQuery {\n ... basicObjectFields\n ... complexObjectFields\n }\n}\n\nfragment basicObjectFields on BasicObject {\n __typename\n id\n name\n}\nfragment complexObjectFields on ComplexObject {\n __typename\n id\n name\n optional\n}" class UnionQueryWithNamedFragments( private val graphQLClient: GraphQLClient<*> ) { suspend fun execute(): GraphQLResponse<UnionQueryWithNamedFragments.Result> = graphQLClient.execute(UNION_QUERY_WITH_NAMED_FRAGMENTS, "UnionQueryWithNamedFragments", null) /** * Some basic description */ data class BasicObject( val id: Int, /** * Object name */ val name: String ) : UnionQueryWithNamedFragments.BasicUnion /** * Multi line description of a complex type. * This is a second line of the paragraph. * This is final line of the description. */ data class ComplexObject( /** * Some unique identifier */ val id: Int, /** * Some object name */ val name: String, /** * Optional value * Second line of the description */ val optional: String? ) : UnionQueryWithNamedFragments.BasicUnion /** * Very basic union of BasicObject and ComplexObject */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename" ) @JsonSubTypes(value = [com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = UnionQueryWithNamedFragments.BasicObject::class, name="BasicObject"),com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = UnionQueryWithNamedFragments.ComplexObject::class, name="ComplexObject")]) interface BasicUnion data class Result( /** * Query returning union */ val unionQuery: UnionQueryWithNamedFragments.BasicUnion ) } """.trimIndent() val queryWithNamedFragments = """ query UnionQueryWithNamedFragments { unionQuery { ... basicObjectFields ... complexObjectFields } } fragment basicObjectFields on BasicObject { __typename id name } fragment complexObjectFields on ComplexObject { __typename id name optional } """.trimIndent() verifyGeneratedFileSpecContents(queryWithNamedFragments, expected) } @Test fun `verify union type generation will throw exception if not all implementations are selected`() { val invalidQuery = """ query InvalidQueryMissingTypeSelection { unionQuery { ... on BasicObject { __typename id name } } } """.trimIndent() assertThrows<RuntimeException> { verifyGeneratedFileSpecContents(invalidQuery, "should throw exception") } } @Test fun `verify union type generation will throw exception if __typename is not selected`() { val invalidQuery = """ query InvalidQueryMissingTypename { unionQuery { ... on BasicObject { id name } ... on ComplexObject { id name optional } } } """.trimIndent() assertThrows<RuntimeException> { verifyGeneratedFileSpecContents(invalidQuery, "should throw exception") } } @Test fun `verify union type generation will throw exception if we pass empty selection set`() { assertThrows<RuntimeException> { generateGraphQLUnionTypeSpec(mockk(), mockk(), SelectionSet.newSelectionSet().build()) } } @Test fun `verify graphql client generation will throw exception if we select same type with different selection sets`() { val invalidQuery = """ query InvalidQuerySelectingSameObjectWithDifferentFields { unionQuery { __typename ... on BasicObject { id name } ... on ComplexObject { id name optional } } complexObjectQuery { id name details { value } } } """.trimIndent() assertThrows<RuntimeException> { verifyGeneratedFileSpecContents(invalidQuery, "will throw exception") } } @Test fun `verify graphql client generation will throw exception if we select union type and same concrete type without __typename`() { val invalidQuery = """ query InvalidQuerySelectingSameObjectWithDifferentFields { complexObjectQuery { id name optional } unionQuery { __typename ... on BasicObject { id name } ... on ComplexObject { id name optional } } } """.trimIndent() val exception = assertThrows<RuntimeException> { verifyGeneratedFileSpecContents(invalidQuery, "will throw exception") } assertEquals("multiple selections of ComplexObject GraphQL type with different selection sets - missing __typename", exception.message) } }
1
null
0
0
67a1158416fa5baab05f8832af39d807a4120476
11,870
graphql-kotlin
Apache License 2.0
ktor-http/test/io/ktor/tests/http/CodecTest.kt
hallefy
112,228,070
true
{"Kotlin": 1507570, "Java": 62081, "HTML": 30993, "FreeMarker": 6484, "CSS": 5444, "JavaScript": 3408}
package io.ktor.tests.http import io.ktor.http.* import org.junit.Test import java.net.* import java.util.* import kotlin.test.* class CodecTest { private val swissAndGerman = "\u0047\u0072\u00fc\u0065\u007a\u0069\u005f\u007a\u00e4\u006d\u00e4" private val russian = "\u0412\u0441\u0435\u043c\u005f\u043f\u0440\u0438\u0432\u0435\u0442" @Test fun testUTFEncodeDecode() { assertEquals("%D0%92%D1%81%D0%B5%D0%BC_%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82", encodeURLQueryComponent(russian)) assertEquals("%D0%92%D1%81%D0%B5%D0%BC_%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82", encodeURLPart(russian)) assertEquals("Gr%C3%BCezi_z%C3%A4m%C3%A4", encodeURLQueryComponent(swissAndGerman)) assertEquals("Gr%C3%BCezi_z%C3%A4m%C3%A4", encodeURLPart(swissAndGerman)) for (msg in listOf(russian, swissAndGerman)) { encodeAndDecodeTest(msg) encodeAndDecodeTestURLPart(msg) } } @Test fun testBasicEncodeDecode() { val s = "Test me!" val encoded = encodeURLQueryComponent(s) assertEquals("Test+me%21", encoded) encodeAndDecodeTest(s) } @Test fun testSimpleBasicEncodeDecode() { val s = "simple" val encoded = encodeURLQueryComponent(s) assertEquals("simple", encoded) encodeAndDecodeTest(s) } @Test fun testBasicEncodeDecodeURLPart() { val s = "Test me!" val encoded = encodeURLPart(s) assertEquals("Test%20me%21", encoded) encodeAndDecodeTestURLPart(s) } @Test fun testAllReserved() { val s = "*~!@#$%^&()+{}\"\\;:`,/[]" val encoded = encodeURLQueryComponent(s) assertEquals("*%7E%21%40%23%24%25%5E%26%28%29%2B%7B%7D%22%5C%3B%3A%60%2C%2F%5B%5D", encoded) encodeAndDecodeTest(s) } @Test fun testAllReservedURLPart() { val s = "*~!@#$%^&()+{}\"\\;:`,/[]" val encoded = encodeURLPart(s) assertEquals("%2A~%21%40%23%24%25%5E%26%28%29+%7B%7D%22%5C%3B%3A%60%2C%2F%5B%5D", encoded) encodeAndDecodeTestURLPart(s) } @Test fun testAllReservedURLPartLowerCase() { val s = " *~!@#$%^&()+{}\"\\;:`,/[]" val encoded = encodeURLQueryComponent(s).toLowerCase() assertEquals("+*%7e%21%40%23%24%25%5e%26%28%29%2b%7b%7d%22%5c%3b%3a%60%2c%2f%5b%5d", encoded) assertEquals(s, decodeURLQueryComponent(encoded)) } @Test fun testBrokenOrIncompleteHEX() { assertFails { decodeURLQueryComponent("foo+%+bar") } assertEquals("0", decodeURLQueryComponent("%30")) assertFails { decodeURLQueryComponent("%") } assertFails { decodeURLQueryComponent("%0") } } @Test(timeout = 1000L) fun testDecodeRandom() { val rnd = Random() val chars = "+%0123abc" for (step in 0..1000) { val size = rnd.nextInt(15) + 1 val sb = CharArray(size) for (i in 0..size - 1) { sb[i] = chars[rnd.nextInt(chars.length)] } try { decodeURLQueryComponent(String(sb)) } catch (ignore: URISyntaxException) { } catch (t: Throwable) { fail("Failed at ${String(sb)}") } } } private fun encodeAndDecodeTest(s: String) { assertEquals(s, decodeURLQueryComponent(encodeURLQueryComponent(s))) } private fun encodeAndDecodeTestURLPart(s: String) { assertEquals(s, decodeURLPart(encodeURLPart(s))) } }
0
Kotlin
0
1
b5dcbe5b740c2d25c7704104e01e0a01bf53d675
3,609
ktor
Apache License 2.0
payjp-android-core/src/main/kotlin/jp/pay/android/model/Card.kt
payjp
111,647,224
false
{"Kotlin": 648511, "Java": 12719, "Ruby": 6109, "Shell": 1151}
/* * * Copyright (c) 2021 PAY, Inc. * * 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 jp.pay.android.model import android.os.Bundle import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlinx.parcelize.Parcelize import java.util.Date /** * PAY.JP card object. * For security reasons, the card number is masked and you can get only last4 character. * The full documentations are following. * cf. [https://pay.jp/docs/api/#cardオブジェクト](https://pay.jp/docs/api/#cardオブジェクト) */ @JsonClass(generateAdapter = true) @Parcelize data class Card( val id: String, val name: String?, val last4: String, val brand: CardBrand, @Json(name = "exp_month") val expirationMonth: Int, @Json(name = "exp_year") val expirationYear: Int, val fingerprint: String, val livemode: Boolean, val created: Date, @Json(name = "address_state") val addressState: String?, @Json(name = "address_city") val addressCity: String?, @Json(name = "address_line1") val addressLine1: String?, @Json(name = "address_line2") val addressLine2: String?, val country: String?, @Json(name = "address_zip") val addressZip: String?, @Json(name = "address_zip_check") val addressZipCheck: String, val email: String?, val phone: String?, val customer: String?, @Json(name = "cvc_check") val cvcCheck: String, val metadata: Bundle, @Json(name = "three_d_secure_status") val threeDSecureStatus: ThreeDSecureStatus?, val `object`: String ) : Parcelable { override fun hashCode(): Int = id.hashCode() override fun equals(other: Any?): Boolean { return other === this || (other is Card && other.id == id) } }
1
Kotlin
2
6
6f3cb6184c3def6cae1244fdbdeb8351fb086cf1
2,762
payjp-android
MIT License
src/nativeMain/kotlin/me/zzp/linsp/interpreter/Bindings.kt
redraiment
12,399,146
false
{"Kotlin": 41992, "NewLisp": 2789}
package me.zzp.linsp.interpreter import me.zzp.linsp.interpreter.Expression.Atom.Companion.nil import me.zzp.linsp.interpreter.Expression.Atom.Companion.t /** * Represents a scope of variable bindings within the environment. */ data class Bindings( /** * The enclosing (parent) scope from which this scope inherits bindings. */ private val parent: Bindings? = null, ) { /** * The local context or scope that holds the variable bindings specific to this environment level. */ private val context = mutableMapOf<String, Expression>() /** * A convenient constructor for creating a Bindings instance with an initial set of variable bindings. */ constructor(vararg pairs: Pair<String, Expression>, parent: Bindings? = null) : this(parent) { context.putAll(pairs) } /** * Retrieves the value of a variable by [name] from the current scope. * * - If the variable is not found, it attempts to retrieve from the parent scope. * - If the variable is not found in any scope, it throws a [NoSuchElementException]. */ operator fun get(name: String): Expression = context[name] ?: parent?.get(name) ?: throw NoSuchElementException(name) /** * Sets the [expression] value of a [name] variable in the current scope. */ operator fun set(name: String, expression: Expression) { context[name] = expression } companion object { /** * The global environment of the Lisp interpreter, containing predefined * bindings that are available throughout the execution of the interpreter. * The global environment serves as the outermost scope from which all other local scopes inherit. */ val GLOBAL = Bindings( "t" to t, "nil" to nil, ) } }
0
Kotlin
1
7
24c106209289bf5d9c965a75eed2fb7c7173addd
1,853
linsp
MIT License
reaktive/src/commonTest/kotlin/com/badoo/reaktive/single/TimerTest.kt
badoo
174,194,386
false
null
package com.badoo.reaktive.single import com.badoo.reaktive.scheduler.Scheduler import com.badoo.reaktive.test.base.assertDisposed import com.badoo.reaktive.test.base.assertNotError import com.badoo.reaktive.test.base.assertSubscribed import com.badoo.reaktive.test.scheduler.TestScheduler import com.badoo.reaktive.test.scheduler.assertAllExecutorsDisposed import com.badoo.reaktive.test.single.assertNotSuccess import com.badoo.reaktive.test.single.assertSuccess import com.badoo.reaktive.test.single.test import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class TimerTest { private val scheduler = TestScheduler() private val timer = scheduler.timer private val upstream = singleTimer(1000L, scheduler) private val observer = upstream.test() @Test fun calls_onSubscribe_only_once_WHEN_subscribed() { observer.assertSubscribed() } @Test fun does_not_call_onError_ON_subscribe() { observer.assertNotError() } @Test fun acquires_executor_WHEN_subscribed() { assertFalse(scheduler.executors.all(Scheduler.Executor::isDisposed)) } @Test fun does_not_succeed_IF_timeout_not_reached() { timer.advanceBy(999L) observer.assertNotSuccess() } @Test fun does_not_call_onError_IF_timeout_not_reached() { timer.advanceBy(999L) observer.assertNotError() } @Test fun succeed_WHEN_timeout_reached() { timer.advanceBy(1000L) observer.assertSuccess(1000L) } @Test fun does_not_call_onError_WHEN_timeout_reached() { timer.advanceBy(1000L) observer.assertNotError() } @Test fun disposes_WHEN_timeout_reached() { timer.advanceBy(1000L) observer.assertDisposed() } @Test fun disposes_executor_WHEN_timeout_reached() { timer.advanceBy(1000L) scheduler.assertAllExecutorsDisposed() } @Test fun onSuccess_ignored_AFTER_dispose() { observer.dispose() timer.advanceBy(1000L) observer.assertNotSuccess() } @Test fun disposes_AFTER_dispose() { observer.dispose() observer.assertDisposed() } @Test fun disposes_executor_AFTER_dispose() { observer.dispose() scheduler.assertAllExecutorsDisposed() } @Test fun does_not_call_onError_ON_dispose() { observer.dispose() observer.assertNotError() } }
8
Kotlin
57
956
c712c70be2493956e7057f0f30199994571b3670
2,481
Reaktive
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ssmcontacts/_ssmcontacts.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION") package cloudshift.awscdk.dsl.services.ssmcontacts import software.amazon.awscdk.services.ssmcontacts.CfnContact import software.amazon.awscdk.services.ssmcontacts.CfnContactChannel import software.amazon.awscdk.services.ssmcontacts.CfnContactChannelProps import software.amazon.awscdk.services.ssmcontacts.CfnContactProps import software.amazon.awscdk.services.ssmcontacts.CfnPlan import software.amazon.awscdk.services.ssmcontacts.CfnPlanProps import software.amazon.awscdk.services.ssmcontacts.CfnRotation import software.amazon.awscdk.services.ssmcontacts.CfnRotationProps import software.constructs.Construct import kotlin.String import kotlin.Unit public object ssmcontacts { /** * The `AWS::SSMContacts::Contact` resource specifies a contact or escalation plan. * * Incident Manager contacts are a subset of actions and data types that you can use for managing * responder engagement and interaction. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnContact cfnContact = CfnContact.Builder.create(this, "MyCfnContact") * .alias("alias") * .displayName("displayName") * .type("type") * // the properties below are optional * .plan(List.of(StageProperty.builder() * .durationInMinutes(123) * .rotationIds(List.of("rotationIds")) * .targets(List.of(TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build())) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-contact.html) */ public inline fun cfnContact( scope: Construct, id: String, block: CfnContactDsl.() -> Unit = {} ): CfnContact { val builder = CfnContactDsl(scope, id) builder.apply(block) return builder.build() } /** * The `AWS::SSMContacts::ContactChannel` resource specifies a contact channel as the method that * Incident Manager uses to engage your contact. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnContactChannel cfnContactChannel = CfnContactChannel.Builder.create(this, * "MyCfnContactChannel") * .channelAddress("channelAddress") * .channelName("channelName") * .channelType("channelType") * .contactId("contactId") * // the properties below are optional * .deferActivation(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-contactchannel.html) */ public inline fun cfnContactChannel( scope: Construct, id: String, block: CfnContactChannelDsl.() -> Unit = {} ): CfnContactChannel { val builder = CfnContactChannelDsl(scope, id) builder.apply(block) return builder.build() } /** * Properties for defining a `CfnContactChannel`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnContactChannelProps cfnContactChannelProps = CfnContactChannelProps.builder() * .channelAddress("channelAddress") * .channelName("channelName") * .channelType("channelType") * .contactId("contactId") * // the properties below are optional * .deferActivation(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-contactchannel.html) */ public inline fun cfnContactChannelProps(block: CfnContactChannelPropsDsl.() -> Unit = {}): CfnContactChannelProps { val builder = CfnContactChannelPropsDsl() builder.apply(block) return builder.build() } /** * Information about the contact channel that Incident Manager uses to engage the contact. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * ChannelTargetInfoProperty channelTargetInfoProperty = ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-contact-channeltargetinfo.html) */ public inline fun cfnContactChannelTargetInfoProperty( block: CfnContactChannelTargetInfoPropertyDsl.() -> Unit = {} ): CfnContact.ChannelTargetInfoProperty { val builder = CfnContactChannelTargetInfoPropertyDsl() builder.apply(block) return builder.build() } /** * The contact that Incident Manager is engaging during an incident. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * ContactTargetInfoProperty contactTargetInfoProperty = ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-contact-contacttargetinfo.html) */ public inline fun cfnContactContactTargetInfoProperty( block: CfnContactContactTargetInfoPropertyDsl.() -> Unit = {} ): CfnContact.ContactTargetInfoProperty { val builder = CfnContactContactTargetInfoPropertyDsl() builder.apply(block) return builder.build() } /** * Properties for defining a `CfnContact`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnContactProps cfnContactProps = CfnContactProps.builder() * .alias("alias") * .displayName("displayName") * .type("type") * // the properties below are optional * .plan(List.of(StageProperty.builder() * .durationInMinutes(123) * .rotationIds(List.of("rotationIds")) * .targets(List.of(TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build())) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-contact.html) */ public inline fun cfnContactProps(block: CfnContactPropsDsl.() -> Unit = {}): CfnContactProps { val builder = CfnContactPropsDsl() builder.apply(block) return builder.build() } /** * The `Stage` property type specifies a set amount of time that an escalation plan or engagement * plan engages the specified contacts or contact methods. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * StageProperty stageProperty = StageProperty.builder() * .durationInMinutes(123) * .rotationIds(List.of("rotationIds")) * .targets(List.of(TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-contact-stage.html) */ public inline fun cfnContactStageProperty(block: CfnContactStagePropertyDsl.() -> Unit = {}): CfnContact.StageProperty { val builder = CfnContactStagePropertyDsl() builder.apply(block) return builder.build() } /** * The contact or contact channel that's being engaged. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * TargetsProperty targetsProperty = TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-contact-targets.html) */ public inline fun cfnContactTargetsProperty(block: CfnContactTargetsPropertyDsl.() -> Unit = {}): CfnContact.TargetsProperty { val builder = CfnContactTargetsPropertyDsl() builder.apply(block) return builder.build() } /** * Information about the stages and on-call rotation teams associated with an escalation plan or * engagement plan. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnPlan cfnPlan = CfnPlan.Builder.create(this, "MyCfnPlan") * .contactId("contactId") * // the properties below are optional * .rotationIds(List.of("rotationIds")) * .stages(List.of(StageProperty.builder() * .durationInMinutes(123) * // the properties below are optional * .targets(List.of(TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build())) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-plan.html) */ public inline fun cfnPlan( scope: Construct, id: String, block: CfnPlanDsl.() -> Unit = {} ): CfnPlan { val builder = CfnPlanDsl(scope, id) builder.apply(block) return builder.build() } /** * Information about the contact channel that Incident Manager uses to engage the contact. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * ChannelTargetInfoProperty channelTargetInfoProperty = ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-plan-channeltargetinfo.html) */ public inline fun cfnPlanChannelTargetInfoProperty( block: CfnPlanChannelTargetInfoPropertyDsl.() -> Unit = {} ): CfnPlan.ChannelTargetInfoProperty { val builder = CfnPlanChannelTargetInfoPropertyDsl() builder.apply(block) return builder.build() } /** * The contact that Incident Manager is engaging during an incident. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * ContactTargetInfoProperty contactTargetInfoProperty = ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-plan-contacttargetinfo.html) */ public inline fun cfnPlanContactTargetInfoProperty( block: CfnPlanContactTargetInfoPropertyDsl.() -> Unit = {} ): CfnPlan.ContactTargetInfoProperty { val builder = CfnPlanContactTargetInfoPropertyDsl() builder.apply(block) return builder.build() } /** * Properties for defining a `CfnPlan`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnPlanProps cfnPlanProps = CfnPlanProps.builder() * .contactId("contactId") * // the properties below are optional * .rotationIds(List.of("rotationIds")) * .stages(List.of(StageProperty.builder() * .durationInMinutes(123) * // the properties below are optional * .targets(List.of(TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build())) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-plan.html) */ public inline fun cfnPlanProps(block: CfnPlanPropsDsl.() -> Unit = {}): CfnPlanProps { val builder = CfnPlanPropsDsl() builder.apply(block) return builder.build() } /** * A set amount of time that an escalation plan or engagement plan engages the specified contacts * or contact methods. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * StageProperty stageProperty = StageProperty.builder() * .durationInMinutes(123) * // the properties below are optional * .targets(List.of(TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-plan-stage.html) */ public inline fun cfnPlanStageProperty(block: CfnPlanStagePropertyDsl.() -> Unit = {}): CfnPlan.StageProperty { val builder = CfnPlanStagePropertyDsl() builder.apply(block) return builder.build() } /** * The contact or contact channel that's being engaged. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * TargetsProperty targetsProperty = TargetsProperty.builder() * .channelTargetInfo(ChannelTargetInfoProperty.builder() * .channelId("channelId") * .retryIntervalInMinutes(123) * .build()) * .contactTargetInfo(ContactTargetInfoProperty.builder() * .contactId("contactId") * .isEssential(false) * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-plan-targets.html) */ public inline fun cfnPlanTargetsProperty(block: CfnPlanTargetsPropertyDsl.() -> Unit = {}): CfnPlan.TargetsProperty { val builder = CfnPlanTargetsPropertyDsl() builder.apply(block) return builder.build() } /** * Specifies a rotation in an on-call schedule. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnRotation cfnRotation = CfnRotation.Builder.create(this, "MyCfnRotation") * .contactIds(List.of("contactIds")) * .name("name") * .recurrence(RecurrenceSettingsProperty.builder() * .numberOfOnCalls(123) * .recurrenceMultiplier(123) * // the properties below are optional * .dailySettings(List.of("dailySettings")) * .monthlySettings(List.of(MonthlySettingProperty.builder() * .dayOfMonth(123) * .handOffTime("handOffTime") * .build())) * .shiftCoverages(List.of(ShiftCoverageProperty.builder() * .coverageTimes(List.of(CoverageTimeProperty.builder() * .endTime("endTime") * .startTime("startTime") * .build())) * .dayOfWeek("dayOfWeek") * .build())) * .weeklySettings(List.of(WeeklySettingProperty.builder() * .dayOfWeek("dayOfWeek") * .handOffTime("handOffTime") * .build())) * .build()) * .startTime("startTime") * .timeZoneId("timeZoneId") * // the properties below are optional * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-rotation.html) */ public inline fun cfnRotation( scope: Construct, id: String, block: CfnRotationDsl.() -> Unit = {} ): CfnRotation { val builder = CfnRotationDsl(scope, id) builder.apply(block) return builder.build() } /** * Information about when an on-call shift begins and ends. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CoverageTimeProperty coverageTimeProperty = CoverageTimeProperty.builder() * .endTime("endTime") * .startTime("startTime") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-rotation-coveragetime.html) */ public inline fun cfnRotationCoverageTimeProperty( block: CfnRotationCoverageTimePropertyDsl.() -> Unit = {} ): CfnRotation.CoverageTimeProperty { val builder = CfnRotationCoverageTimePropertyDsl() builder.apply(block) return builder.build() } /** * Information about on-call rotations that recur monthly. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * MonthlySettingProperty monthlySettingProperty = MonthlySettingProperty.builder() * .dayOfMonth(123) * .handOffTime("handOffTime") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-rotation-monthlysetting.html) */ public inline fun cfnRotationMonthlySettingProperty( block: CfnRotationMonthlySettingPropertyDsl.() -> Unit = {} ): CfnRotation.MonthlySettingProperty { val builder = CfnRotationMonthlySettingPropertyDsl() builder.apply(block) return builder.build() } /** * Properties for defining a `CfnRotation`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * CfnRotationProps cfnRotationProps = CfnRotationProps.builder() * .contactIds(List.of("contactIds")) * .name("name") * .recurrence(RecurrenceSettingsProperty.builder() * .numberOfOnCalls(123) * .recurrenceMultiplier(123) * // the properties below are optional * .dailySettings(List.of("dailySettings")) * .monthlySettings(List.of(MonthlySettingProperty.builder() * .dayOfMonth(123) * .handOffTime("handOffTime") * .build())) * .shiftCoverages(List.of(ShiftCoverageProperty.builder() * .coverageTimes(List.of(CoverageTimeProperty.builder() * .endTime("endTime") * .startTime("startTime") * .build())) * .dayOfWeek("dayOfWeek") * .build())) * .weeklySettings(List.of(WeeklySettingProperty.builder() * .dayOfWeek("dayOfWeek") * .handOffTime("handOffTime") * .build())) * .build()) * .startTime("startTime") * .timeZoneId("timeZoneId") * // the properties below are optional * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssmcontacts-rotation.html) */ public inline fun cfnRotationProps(block: CfnRotationPropsDsl.() -> Unit = {}): CfnRotationProps { val builder = CfnRotationPropsDsl() builder.apply(block) return builder.build() } /** * Information about when an on-call rotation is in effect and how long the rotation period lasts. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * RecurrenceSettingsProperty recurrenceSettingsProperty = RecurrenceSettingsProperty.builder() * .numberOfOnCalls(123) * .recurrenceMultiplier(123) * // the properties below are optional * .dailySettings(List.of("dailySettings")) * .monthlySettings(List.of(MonthlySettingProperty.builder() * .dayOfMonth(123) * .handOffTime("handOffTime") * .build())) * .shiftCoverages(List.of(ShiftCoverageProperty.builder() * .coverageTimes(List.of(CoverageTimeProperty.builder() * .endTime("endTime") * .startTime("startTime") * .build())) * .dayOfWeek("dayOfWeek") * .build())) * .weeklySettings(List.of(WeeklySettingProperty.builder() * .dayOfWeek("dayOfWeek") * .handOffTime("handOffTime") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-rotation-recurrencesettings.html) */ public inline fun cfnRotationRecurrenceSettingsProperty( block: CfnRotationRecurrenceSettingsPropertyDsl.() -> Unit = {} ): CfnRotation.RecurrenceSettingsProperty { val builder = CfnRotationRecurrenceSettingsPropertyDsl() builder.apply(block) return builder.build() } /** * Information about the days of the week that the on-call rotation coverage includes. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * ShiftCoverageProperty shiftCoverageProperty = ShiftCoverageProperty.builder() * .coverageTimes(List.of(CoverageTimeProperty.builder() * .endTime("endTime") * .startTime("startTime") * .build())) * .dayOfWeek("dayOfWeek") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-rotation-shiftcoverage.html) */ public inline fun cfnRotationShiftCoverageProperty( block: CfnRotationShiftCoveragePropertyDsl.() -> Unit = {} ): CfnRotation.ShiftCoverageProperty { val builder = CfnRotationShiftCoveragePropertyDsl() builder.apply(block) return builder.build() } /** * Information about rotations that recur weekly. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ssmcontacts.*; * WeeklySettingProperty weeklySettingProperty = WeeklySettingProperty.builder() * .dayOfWeek("dayOfWeek") * .handOffTime("handOffTime") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssmcontacts-rotation-weeklysetting.html) */ public inline fun cfnRotationWeeklySettingProperty( block: CfnRotationWeeklySettingPropertyDsl.() -> Unit = {} ): CfnRotation.WeeklySettingProperty { val builder = CfnRotationWeeklySettingPropertyDsl() builder.apply(block) return builder.build() } }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
26,593
awscdk-dsl-kotlin
Apache License 2.0
Examples/src/main/kotlin/examples/ComponentSignalSystem.kt
nflsilva
521,306,727
false
{"Kotlin": 72548, "GLSL": 3784}
package examples import core.BaseEntity import core.CoreEngine import core.CoreEngineDelegate import core.component.BaseComponent import core.component.ComponentSignal import core.component.ComponentSignalDataField import core.component.render.ShapeComponent import core.dto.UpdateContext import org.joml.Random import org.joml.Vector2f import render.dto.Color import render.dto.Shape import render.dto.Transform import ui.dto.InputStateData import java.util.* fun main(args: Array<String>) { val engine = CoreEngine() val gameLogic = ComponentSignalSystem(engine) engine.delegate = gameLogic engine.start() println("Done!") } class ComponentSignalSystem(private val engine: CoreEngine) : CoreEngineDelegate { private val shapes = mutableListOf<Ball>() private val gravity: Vector2f = Vector2f(0f, -1000f) class Ball(positionX: Float, positionY: Float, radius: Float): BaseEntity(Transform(Vector2f(positionX, positionY), 0.0f, Vector2f(radius))) { private val acceleration: Vector2f = Vector2f().zero() private var oldPosition = Vector2f(positionX, positionY) init { val rr = Random().nextFloat() val rg = Random().nextFloat() val rb = Random().nextFloat() addComponent(ShapeComponent(uid, Shape.Type.DONUT, Color(rr, rg, rb, 1.0f))) addComponent(FloorDetectionComponent(uid)) addComponent(InvertForceComponent(uid)) } fun step(dt: Double){ var currentPosition = Vector2f(transform.position.x, transform.position.y) val velocity = Vector2f(currentPosition.x, currentPosition.y).sub(oldPosition) oldPosition = Vector2f(currentPosition.x, currentPosition.y) acceleration.mul(dt.toFloat() * dt.toFloat()) currentPosition = currentPosition.add(velocity).add(acceleration) transform.position.x = currentPosition.x transform.position.y = currentPosition.y acceleration.zero() } fun accelerate(value: Vector2f){ acceleration.add(value) } fun stop(){ oldPosition = transform.position acceleration.zero() } } class FloorDetectionComponent(entityId: UUID): BaseComponent(entityId){ companion object { const val FORCE_DATA_TYPE = "force" const val FLOOR_DELECTION_SIGNAL_TYPE = "floor" } init { setUpdateObserver { entity, context -> onUpdate(entity, context) } } private fun onUpdate(entity: BaseEntity, context: UpdateContext) { if(entity.transform.position.y <= 10f){ context.core.sendSignal( ComponentSignal(entity.uid, FLOOR_DELECTION_SIGNAL_TYPE, entity.uid) .apply { data[FORCE_DATA_TYPE] = ComponentSignalDataField(float = 5000f) }) } } } class InvertForceComponent(entityId: UUID): BaseComponent(entityId){ var newAcceleration: Float? = null init { setUpdateObserver { entity, context -> onUpdate(entity, context) } setSignalObserver { entity, signal -> onSignal(entity, signal) } } private fun onUpdate(entity: BaseEntity, context: UpdateContext) { val ball = entity as? Ball ?: return newAcceleration?.let { ball.accelerate(Vector2f(0.0f, it)) newAcceleration = null } } private fun onSignal(entity: BaseEntity, signal: ComponentSignal) { val isSignalType = signal.type == FloorDetectionComponent.FLOOR_DELECTION_SIGNAL_TYPE val isForThisEntity = signal.receiverEntityId == entity.uid if(!isSignalType || !isForThisEntity) return newAcceleration = signal.data[FloorDetectionComponent.FORCE_DATA_TYPE]?.float } } override fun onStart() { for(i in 0 until 50) { val b0 = Ball( Random().nextFloat() * 1280, Random().nextFloat() * 720, Random().nextFloat() * 25f + 10f) engine.addEntity(b0) shapes.add(b0) } } override fun onUpdate(elapsedTime: Double, input: InputStateData) { shapes.forEach { shape -> shape.accelerate(gravity) shape.step(elapsedTime) } } override fun onFrame() {} override fun onCleanUp() {} }
0
Kotlin
0
0
5047a234767efda80c0afec990bf27aec5b8effd
4,570
2DGT
MIT License
wgpu4k/src/commonMain/kotlin/io.ygdrasil.wgpu/ShaderModule.kt
wgpu4k
773,068,055
false
{"Kotlin": 1933246, "TypeScript": 1001930, "HTML": 93097, "WGSL": 70068, "JavaScript": 8101, "CSS": 5773, "Shell": 253}
package io.ygdrasil.wgpu expect class ShaderModule : AutoCloseable { } data class ShaderModuleDescriptor( var code: String, var label: String? = null, var sourceMap: Any? = null, var compilationHints: Array<CompilationHint>? = null ) { data class CompilationHint( var entryPoint: String, // TODO //var layout: dynamic /* GPUPipelineLayout? | "auto" */ ) }
0
Kotlin
1
0
f4cd0a7e3512b9cdc122ffac5bfe6ccc611398da
371
wgpu4k
MIT License
app/src/main/java/com/aleahim/listee/TodoListViewHolder.kt
mihaelamj
331,379,409
false
null
package com.aleahim.listee import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class TodoListViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { var listPositionTextView = itemView.findViewById<TextView>(R.id.itemNumber) var listTitleTextView = itemView.findViewById<TextView>(R.id.itemString) }
0
Kotlin
0
0
b5b4f840b42a53ca82829d0ade2dc8d6ed0f3f30
406
AndroidToDo
MIT License
uxmobile/src/main/java/sk/uxtweak/uxmobile/ui/DebugActivity.kt
macro39
389,744,953
false
null
package sk.uxtweak.uxmobile.ui import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.Window import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.commit import androidx.fragment.app.transaction import androidx.lifecycle.Observer import kotlinx.android.synthetic.main.debug_layout.* import sk.uxtweak.uxmobile.R class DebugActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.debug_layout) supportFragmentManager.commit { replace(R.id.fragmentContainer, DebugFragment.newInstance(), DebugFragment.TAG) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.debug_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.menuClose -> finish() } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
9dc1d26c95c42f739c7aa9610da815a01ea7f5d2
1,212
UxMobile
Apache License 2.0
Labs/app/src/main/java/top/chilfish/labs/sms/SMSActivity.kt
Chilfish
610,771,353
false
null
package top.chilfish.labs.sms import android.Manifest import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import top.chilfish.labs.base.BaseActivity import top.chilfish.labs.databinding.ActivitySmsBinding class SMSActivity : BaseActivity() { private val smsPermissionCode = 101 private val smsContentUri = Uri.parse("content://sms/") private val COUNT = 10 private lateinit var binding: ActivitySmsBinding private lateinit var rv: RecyclerView private val smsAdapter = SMSAdapter() private fun init() { binding = ActivitySmsBinding.inflate(layoutInflater) rv = binding.listSms rv.layoutManager = LinearLayoutManager(this) rv.adapter = smsAdapter } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) init() setContentView(binding.root) binding.fab.setOnClickListener { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.READ_SMS), smsPermissionCode ) } else { readSms() } } } private fun readSms() { val cursor = contentResolver.query( smsContentUri, null, null, null, null ) var i = 0 cursor?.let { if (it.moveToFirst()) { val bodyIndex = it.getColumnIndex("body") val addressIndex = it.getColumnIndex("address") do { val body = it.getString(bodyIndex) val address = it.getString(addressIndex) smsAdapter.addItem(SMSEntity(address, body)) } while (it.moveToNext() && i++ < COUNT) } it.close() } } }
0
Kotlin
0
0
e5b88162f8d3d305a3b8c144653e0bf062e70ae1
2,205
Android-demo
MIT License
src/commonMain/kotlin/org.angproj.aux/utf/blk/TamilSupplement.kt
angelos-project
677,039,667
false
{"Kotlin": 986392, "Python": 196308}
/** * Copyright (c) 2024 by Kristoffer Paulsson <kristoffer.paulsson@talenten.se>. * * This software is available under the terms of the MIT license. Parts are licensed * under different terms if stated. The legal terms are attached to the LICENSE file * and are made available on: * * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT * * Contributors: * Kristoffer Paulsson - initial implementation */ package org.angproj.aux.utf.blk import org.angproj.aux.utf.UtfBlock public object TamilSupplement : UtfBlock { override val name: String = "Tamil Supplement" override val meta: String = "0x11fc0..0x11fff (51/13)" override val range: IntRange = 0x11fc0..0x11fff override val noCtrl: Boolean = false override val noUse: List<Int> by lazy { listOf( 0x11ff2, 0x11ff3, 0x11ff4, 0x11ff5, 0x11ff6, 0x11ff7, 0x11ff8, 0x11ff9, 0x11ffa, 0x11ffb, 0x11ffc, 0x11ffd, 0x11ffe ) } }
0
Kotlin
0
0
f9142bec995ef434cc7cdc02f01a7ed9ac3cd00b
1,112
angelos-project-aux
MIT License
idea/src/org/jetbrains/kotlin/idea/intentions/AddAccessorIntentions.kt
cr8tpro
189,964,139
true
null
/* * Copyright 2010-2017 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.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.startOffset abstract class AbstractAddAccessorsIntention( private val addGetter: Boolean, private val addSetter: Boolean ) : SelfTargetingRangeIntention<KtProperty>(KtProperty::class.java, createFamilyName(addGetter, addSetter)) { override fun applicabilityRange(element: KtProperty): TextRange? { if (element.isLocal || element.isAbstract() || element.hasDelegate() || element.hasModifier(KtTokens.LATEINIT_KEYWORD) || element.hasModifier(KtTokens.CONST_KEYWORD) || element.hasJvmFieldAnnotation() ) { return null } val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return null if (descriptor.isExpect) return null val hasInitializer = element.hasInitializer() if (element.typeReference == null && !hasInitializer) return null if (addSetter && (!element.isVar || element.setter != null)) return null if (addGetter && element.getter != null) return null return if (hasInitializer) element.nameIdentifier?.textRange else element.textRange } override fun applyTo(element: KtProperty, editor: Editor?) { val hasInitializer = element.hasInitializer() val psiFactory = KtPsiFactory(element) if (addGetter) { val expression = if (hasInitializer) psiFactory.createExpression("field") else psiFactory.createBlock("TODO()") val getter = psiFactory.createPropertyGetter(expression) val added = if (element.setter != null) { element.addBefore(getter, element.setter) } else { element.add(getter) } if (!hasInitializer) { (added as? KtPropertyAccessor)?.bodyBlockExpression?.statements?.firstOrNull()?.let { editor?.caretModel?.moveToOffset(it.startOffset) } } } if (addSetter) { val expression = if (hasInitializer) psiFactory.createBlock("field = value") else psiFactory.createEmptyBody() val setter = psiFactory.createPropertySetter(expression) val added = element.add(setter) if (!hasInitializer && !addGetter) { (added as? KtPropertyAccessor)?.bodyBlockExpression?.lBrace?.let { editor?.caretModel?.moveToOffset(it.startOffset + 1) } } } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val property = diagnostic.psiElement as? KtProperty ?: return null return if (property.isVar) { val getter = property.getter val setter = property.setter when { getter == null && setter == null -> AddPropertyAccessorsIntention() getter == null -> AddPropertyGetterIntention() else -> AddPropertySetterIntention() } } else { AddPropertyGetterIntention() } } } } private fun createFamilyName(addGetter: Boolean, addSetter: Boolean): String = when { addGetter && addSetter -> KotlinBundle.message("text.add.getter.and.setter") addGetter -> KotlinBundle.message("text.add.getter") addSetter -> KotlinBundle.message("text.add.setter") else -> throw AssertionError("At least one from (addGetter, addSetter) should be true") } class AddPropertyAccessorsIntention : AbstractAddAccessorsIntention(true, true), LowPriorityAction class AddPropertyGetterIntention : AbstractAddAccessorsIntention(true, false) class AddPropertySetterIntention : AbstractAddAccessorsIntention(false, true)
0
Kotlin
1
2
dca23f871cc22acee9258c3d58b40d71e3693858
5,288
kotlin
Apache License 2.0
src/main/kotlin/win/rushmi0/jungmha/database/service/DogWalkerReviewService.kt
rushmi0
729,413,199
false
{"Kotlin": 215402, "PLpgSQL": 11138, "HTML": 3377, "Dockerfile": 102}
package org.jungmha.database.service import io.micronaut.context.annotation.Bean import io.micronaut.runtime.http.scope.RequestScope import io.micronaut.scheduling.TaskExecutors import io.micronaut.scheduling.annotation.ExecuteOn import org.jungmha.database.field.DogWalkerReviewField import org.jungmha.database.form.DogWalkerReviewForm /** * **Interface DogWalkerReviewService** * * Interface นี้ให้บริการเกี่ยวกับการจัดการข้อมูลรีวิวของผู้เดินสุนัข (Dog Walker Reviews) ในระบบ * โดยมีเมธอดต่าง ๆ ที่จะทำหน้าที่ค้นหา แสดงข้อมูลทั้งหมด และดำเนินการเพิ่ม แก้ไข และลบข้อมูลรีวิว */ @Bean @RequestScope @ExecuteOn(TaskExecutors.IO) interface DogWalkerReviewService { /** * **เมธอด dogWalkerReviewAll** * * ใช้สำหรับค้นหาข้อมูลรีวิวของผู้เดินสุนัขทั้งหมดในระบบ * * @return รายการข้อมูล DogWalkerReviewField ทั้งหมด */ suspend fun dogWalkerReviewAll(): List<DogWalkerReviewField> /** * **เมธอด insert** * * ใช้สำหรับเพิ่มข้อมูลรีวิวของผู้เดินสุนัขใหม่ * * @param payload ข้อมูลรีวิว DogWalkerReviewForm * @return true หากการเพิ่มสำเร็จ, false หากไม่สำเร็จ */ suspend fun insert(payload: DogWalkerReviewForm): Boolean /** * **เมธอด updateSingleField** * * ใช้สำหรับแก้ไขข้อมูลเดี่ยวของรีวิว * * @param id ID ของรีวิว * @param fieldName ชื่อฟิลด์ที่ต้องการแก้ไข * @param newValue ค่าใหม่ที่ใช้ในการแก้ไข * @return true หากการแก้ไขสำเร็จ, false หากไม่สำเร็จ */ suspend fun updateSingleField(id: Int, fieldName: String, newValue: String): Boolean /** * **เมธอด delete** * * ใช้สำหรับลบข้อมูลรีวิว * * @param id ID ของรีวิว * @return true หากการลบสำเร็จ, false หากไม่สำเร็จ */ suspend fun delete(id: Int): Boolean }
0
Kotlin
0
1
d0a3f53ea7c04e4b9f0ba18f737974bee712b6c8
1,797
Jungmha
MIT License
src/jvmMain/kotlin/com/sdercolin/vlabeler/ui/dialog/CustomFileDialog.kt
sdercolin
503,365,242
false
null
package com.sdercolin.vlabeler.ui.dialog import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Description import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.Folder import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.input.pointer.PointerIcon import androidx.compose.ui.input.pointer.pointerHoverIcon import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.window.DialogWindow import androidx.compose.ui.window.rememberDialogState import cafe.adriel.bonsai.core.Bonsai import cafe.adriel.bonsai.core.BonsaiStyle import cafe.adriel.bonsai.core.node.Branch import cafe.adriel.bonsai.core.node.Leaf import cafe.adriel.bonsai.core.tree.Tree import cafe.adriel.bonsai.core.tree.TreeScope import com.sdercolin.vlabeler.ui.common.CancelButton import com.sdercolin.vlabeler.ui.common.ConfirmButton import com.sdercolin.vlabeler.ui.common.FreeSizedIconButton import com.sdercolin.vlabeler.ui.string.Strings import com.sdercolin.vlabeler.ui.string.string import com.sdercolin.vlabeler.ui.theme.AppTheme import com.sdercolin.vlabeler.util.HomeDir import com.sdercolin.vlabeler.util.Resources import com.sdercolin.vlabeler.util.runIf import com.sdercolin.vlabeler.util.toFile import org.jetbrains.compose.splitpane.ExperimentalSplitPaneApi import org.jetbrains.compose.splitpane.HorizontalSplitPane import org.jetbrains.compose.splitpane.SplitPaneState import java.awt.Cursor import java.io.File @Composable fun CustomFileDialog( mode: Int, title: String, initialDirectory: String?, initialFileName: String?, extensions: List<String>?, directoryMode: Boolean, onCloseRequest: (parent: String?, name: String?) -> Unit, ) { val root = HomeDir val fileFree = DirectoryTree(root) DialogWindow( title = title, icon = painterResource(Resources.iconIco), onCloseRequest = { onCloseRequest(null, null) }, state = rememberDialogState(width = 800.dp, height = 600.dp), resizable = true, ) { AppTheme { Content( mode = mode, root = root, fileTree = fileFree, initialDirectory = initialDirectory, initialFileName = initialFileName, extensions = extensions, directoryMode = directoryMode, onCloseRequest = onCloseRequest, ) } } } @OptIn(ExperimentalSplitPaneApi::class) @Composable private fun Content( mode: Int, root: File, fileTree: Tree<File>, initialDirectory: String?, initialFileName: String?, extensions: List<String>?, directoryMode: Boolean, onCloseRequest: (parent: String?, name: String?) -> Unit, ) { val saveMode = remember(mode) { mode == java.awt.FileDialog.SAVE } val splitPaneState = remember { SplitPaneState( initialPositionPercentage = 0.3f, moveEnabled = true, ) } var currentDirectory by remember { mutableStateOf(initialDirectory?.toFile() ?: root) } var currentFileName by remember { mutableStateOf(initialFileName ?: "") } var currentExtension by remember { mutableStateOf( extensions?.firstOrNull { currentFileName.isNotEmpty() && currentFileName.endsWith(it) } ?: extensions?.firstOrNull() ?: "*", ) } fun updateCurrentDirectory(directory: File) { currentDirectory = directory if (!saveMode) { currentFileName = "" } } Surface(modifier = Modifier.fillMaxSize()) { HorizontalSplitPane(splitPaneState = splitPaneState) { first { Bonsai( modifier = Modifier.fillMaxSize().padding(10.dp), tree = fileTree, style = BonsaiStyle( nodeNameTextStyle = MaterialTheme.typography.body2.copy(color = MaterialTheme.colors.onSurface), toggleIconColorFilter = ColorFilter.tint(MaterialTheme.colors.onSurface), ), onClick = { updateCurrentDirectory(it.content) }, ) } second { Column(modifier = Modifier.fillMaxSize().padding(20.dp)) { Row( modifier = Modifier.fillMaxWidth().padding(horizontal = 5.dp), verticalAlignment = Alignment.CenterVertically, ) { val canGoBack = currentDirectory != root FreeSizedIconButton( onClick = { updateCurrentDirectory(currentDirectory.parentFile ?: root) }, modifier = Modifier.padding(5.dp), enabled = canGoBack, ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colors.onSurface.copy(alpha = if (canGoBack) 0.8f else 0.3f), ) } Spacer(modifier = Modifier.width(20.dp)) BasicTextField( modifier = Modifier.weight(1f) .background(MaterialTheme.colors.onSurface.copy(alpha = 0.3f)) .padding(10.dp), value = currentDirectory.absolutePath, onValueChange = {}, readOnly = true, singleLine = true, textStyle = MaterialTheme.typography.body2.copy(color = MaterialTheme.colors.onSurface), ) } Box( modifier = Modifier.fillMaxWidth() .weight(1f) .padding(horizontal = 5.dp, vertical = 15.dp), ) { val files = currentDirectory.listFiles().orEmpty().sortedWith { o1, o2 -> when { o1.isDirectory && !o2.isDirectory -> -1 !o1.isDirectory && o2.isDirectory -> 1 else -> o1.name.compareTo(o2.name) } } val lazyState = rememberLazyListState() LazyColumn( state = lazyState, modifier = Modifier.fillMaxSize(), ) { items(files, key = { it.absolutePath }) { file -> val isSelectable = if (directoryMode) { file.isDirectory } else { file.isDirectory || currentExtension == "*" || file.name.endsWith(".$currentExtension") } val isSelected = file.name == currentFileName Row( modifier = Modifier.fillMaxWidth() .clickable(enabled = isSelectable) { if (file.isDirectory) { updateCurrentDirectory(file) } else { currentFileName = file.name } } .runIf(isSelected) { background(MaterialTheme.colors.onSurface.copy(alpha = 0.3f)) } .padding(10.dp), verticalAlignment = Alignment.CenterVertically, ) { val icon = when { file.isDirectory -> Icons.Default.Folder else -> Icons.Default.Description } Icon( imageVector = icon, contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colors.onSurface.copy( alpha = if (isSelectable) 0.8f else 0.3f, ), ) Spacer(modifier = Modifier.width(15.dp)) Text( text = file.name, style = MaterialTheme.typography.body2.copy( color = MaterialTheme.colors.onSurface.copy( alpha = if (isSelectable) 1f else 0.3f, ), ), ) } } } VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter(lazyState), ) } if (!directoryMode) { Row( modifier = Modifier.fillMaxWidth().padding(horizontal = 5.dp), ) { BasicTextField( modifier = Modifier.weight(1f) .background(MaterialTheme.colors.onSurface.copy(alpha = 0.3f)) .padding(10.dp), value = currentFileName, onValueChange = { currentFileName = it }, singleLine = true, textStyle = MaterialTheme.typography.body2.copy(color = MaterialTheme.colors.onSurface), cursorBrush = SolidColor(MaterialTheme.colors.onSurface.copy(alpha = 0.8f)), ) Spacer(modifier = Modifier.width(20.dp)) var expanded by remember { mutableStateOf(false) } Box { Row( modifier = Modifier.background(MaterialTheme.colors.onSurface.copy(alpha = 0.3f)) .padding(10.dp), verticalAlignment = Alignment.CenterVertically, ) { Spacer(modifier = Modifier.width(5.dp)) val selectable = extensions.orEmpty().size > 1 FreeSizedIconButton( onClick = { expanded = !expanded }, enabled = selectable, ) { Icon( imageVector = Icons.Default.ExpandLess, contentDescription = null, modifier = Modifier.size(16.dp), tint = MaterialTheme.colors.onSurface.copy( alpha = if (selectable) 0.8f else 0.3f, ), ) } Spacer(modifier = Modifier.width(20.dp)) BasicTextField( modifier = Modifier.width(60.dp), value = "*.$currentExtension", onValueChange = { }, readOnly = true, singleLine = true, textStyle = MaterialTheme.typography.body2.copy( color = MaterialTheme.colors.onSurface, ), ) } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, ) { extensions?.forEach { extension -> DropdownMenuItem( onClick = { currentExtension = extension expanded = false }, ) { Text("*.$extension") } } } } } } Spacer(modifier = Modifier.height(25.dp)) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { CancelButton( onClick = { onCloseRequest(null, null) }, ) Spacer(Modifier.width(25.dp)) val canSubmit = when { !directoryMode && !saveMode -> { currentFileName.isNotEmpty() && currentDirectory.resolve(currentFileName).isFile && (currentExtension == "*" || currentFileName.endsWith(".$currentExtension")) } else -> true } val confirmText = when { directoryMode -> Strings.CommonSelect saveMode -> Strings.CommonSave else -> Strings.CommonOpen } ConfirmButton( text = string(confirmText), enabled = canSubmit, onClick = { val parent = if (directoryMode) { currentDirectory.parentFile?.absolutePath ?: "" } else { currentDirectory.absolutePath } val name = when { directoryMode -> { currentDirectory.name } saveMode -> { if (currentFileName.endsWith(".$currentExtension")) { currentFileName } else { "$currentFileName.$currentExtension" } } else -> { currentFileName } } onCloseRequest(parent, name) }, ) } } } splitter { visiblePart { Box( Modifier .width(1.dp) .fillMaxHeight() .background(MaterialTheme.colors.onBackground), ) } handle { Box( Modifier .markAsHandle() .pointerHoverIcon(PointerIcon(Cursor(Cursor.E_RESIZE_CURSOR))) .width(5.dp) .fillMaxHeight(), ) } } } } } @Composable private fun DirectoryTree(root: File): Tree<File> = Tree { DirectoryTree(root) } @Composable private fun TreeScope.DirectoryTree( root: File, ) { root.listFiles() ?.filter { it.isDirectory } ?.sortedBy { it.name } ?.forEach { DirectoryNode(it) } } @Composable private fun TreeScope.DirectoryNode(file: File) { if (file.listFiles()?.any { it.isDirectory } == true) { Branch( content = file, name = file.name, ) { DirectoryTree(file) } } else { Leaf( content = file, name = file.name, ) } }
8
null
22
147
f4e47b6c386e1446f9e311549156a6d29aa8d3da
19,718
vlabeler
Apache License 2.0
plugin-bazel-event-service/src/main/kotlin/bazel/bazel/events/TestSummary.kt
JetBrains
143,697,750
false
{"Kotlin": 450284, "Java": 15926, "Starlark": 4160, "Gherkin": 3553, "ANTLR": 1773, "Batchfile": 968, "CSS": 636}
/* * Copyright 2000-2023 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 bazel.bazel.events // Payload of the event summarizing a test. data class TestSummary( override val id: Id, override val children: List<Id>, val label: String, // Wrapper around BlazeTestStatus to support importing that enum to proto3. // Overall status of test, accumulated over all runs, shards, and attempts. val overallStatus: TestStatus, // Total number of runs val totalRunCount: Int, // Path to logs of passed runs. val passed: List<File>, // Path to logs of failed runs; val failed: List<File>, // Total number of cached test actions val totalNumCached: Int) : BazelContent
7
Kotlin
10
13
47f69a5fd7f6f7e851f3373890067d31183330c6
1,305
teamcity-bazel-plugin
Apache License 2.0
samples/demoapp/src/main/java/com/joaquimverges/demoapp/ListFragment.kt
joaquim-verges
126,538,789
false
null
package com.joaquimverges.demoapp import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.joaquimverges.demoapp.logic.MyListLogic import com.joaquimverges.demoapp.ui.MyListItem import com.joaquimverges.helium.core.assemble import com.joaquimverges.helium.core.plus import com.joaquimverges.helium.core.retained.getRetainedLogicBlock import com.joaquimverges.helium.ui.list.ListUi class ListFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val logic = getRetainedLogicBlock<MyListLogic>() val listUi = ListUi(inflater, { layoutInflater, parentContainer -> MyListItem(layoutInflater, parentContainer) }) assemble(logic + listUi) return listUi.view } }
3
Kotlin
18
345
f2e2166fcd802696982da00ea785cbb1c473cdeb
908
Helium
Apache License 2.0
app/src/main/java/org/unifiedpush/example/utils/WebPush.kt
UnifiedPush
324,809,670
false
{"Kotlin": 26453}
@file:Suppress("ktlint:standard:no-wildcard-imports") package org.unifiedpush.example.utils import android.util.Base64 import com.google.crypto.tink.subtle.EllipticCurves import java.security.* import java.security.interfaces.ECPublicKey import java.security.spec.ECGenParameterSpec import java.security.spec.PKCS8EncodedKeySpec import java.security.spec.X509EncodedKeySpec data class SerializedKeyPair( val private: String, val public: String, ) /** * https://www.rfc-editor.org/rfc/rfc8291 */ object WebPush { fun generateKeyPair(): KeyPair { return KeyPairGenerator.getInstance("EC").apply { initialize( ECGenParameterSpec("secp256r1"), ) }.generateKeyPair() } fun generateAuthSecret(): ByteArray { return ByteArray(16).apply { SecureRandom().nextBytes(this) } } fun encodeKeyPair(keyPair: KeyPair): SerializedKeyPair { return SerializedKeyPair( private = b64encode(keyPair.private.encoded), public = b64encode(keyPair.public.encoded), ) } fun decodePubKey(raw: String): ECPublicKey { val kf = KeyFactory.getInstance("EC") val publicBytes = b64decode(raw) val publicSpec = X509EncodedKeySpec(publicBytes) return kf.generatePublic(publicSpec) as ECPublicKey } fun decodeKeyPair(serializedKeyPair: SerializedKeyPair): KeyPair { val kf = KeyFactory.getInstance("EC") val privateBytes = b64decode(serializedKeyPair.private) val privateSpec = PKCS8EncodedKeySpec(privateBytes) val privateKey = kf.generatePrivate(privateSpec) val publicKey = decodePubKey(serializedKeyPair.public) return KeyPair(publicKey, privateKey) } fun serializePublicKey(publicKey: ECPublicKey): String { return b64encode( EllipticCurves.pointEncode(EllipticCurves.CurveType.NIST_P256, EllipticCurves.PointFormatType.UNCOMPRESSED, publicKey.w), ) } fun b64encode(byteArray: ByteArray): String { return Base64.encodeToString( byteArray, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING, ) } fun b64decode(string: String): ByteArray { return Base64.decode( string, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING, ) } }
1
Kotlin
9
17
d0142b4dc32782f5709a80f22d1a7f8d1de9cb81
2,401
android-example
Apache License 2.0
eth/wallet/src/commonMain/kotlin/kosh/eth/wallet/Secp256k1.kt
niallkh
855,100,709
false
{"Kotlin": 1813876, "Swift": 594}
package kosh.eth.wallet import okio.ByteString import okio.ByteString.Companion.toByteString import fr.acinq.secp256k1.Secp256k1 as LibSecp256k1 internal object Secp256k1 { fun sign( messageHash: ByteString, privateKey: ByteString, ): ByteString = LibSecp256k1.sign( message = messageHash.toByteArray(), privkey = privateKey.toByteArray() ).toByteString() fun recover( signature: ByteString, messageHash: ByteString, recId: Int, ): ByteString = LibSecp256k1.ecdsaRecover( sig = signature.toByteArray(), message = messageHash.toByteArray(), recid = recId ).toByteString() fun verify( signature: ByteString, messageHash: ByteString, publicKey: ByteString, ): Boolean = LibSecp256k1.verify( signature = signature.toByteArray(), message = messageHash.toByteArray(), pubkey = publicKey.toByteArray() ) fun publicKey( privateKey: ByteString, ): ByteString = LibSecp256k1.pubkeyCreate( privkey = privateKey.toByteArray() ).toByteString() }
0
Kotlin
0
3
f48555a563dfee5b07184771a6c94c065765d570
1,130
kosh
MIT License
app/src/main/java/com/example/ctut_student/fragments/loginRegister/LoginFragment.kt
seven1106
701,369,145
false
{"Kotlin": 19932}
package com.example.ctut_student.fragments.loginRegister //import com.example.ctut_student.activities.ShoppingActivity //import com.example.ctut_student.databinding.ResetPassowrdDialogBinding //import com.example.ctut_student.dialog.setupBottomSheetDialog import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.example.ctut_student.R import com.example.ctut_student.activities.DashboardActivity import com.example.ctut_student.databinding.FragmentLoginBinding import com.example.ctut_student.dialog.setupBottomSheetDialog import com.example.ctut_student.util.Resource import com.example.ctut_student.viewmodel.LoginViewModel import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class LoginFragment : Fragment(R.layout.fragment_login) { private lateinit var binding: FragmentLoginBinding private val viewModel by viewModels<LoginViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentLoginBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.tvDontHaveAccount.setOnClickListener { findNavController().navigate(R.id.action_loginFragment_to_registerFragment) } binding.apply { buttonLoginLogin.setOnClickListener { val email = edEmailLogin.text.toString().trim() val password = edPasswordLogin.text.toString() viewModel.login(email, password) } } binding.tvForgotPasswordLogin.setOnClickListener { setupBottomSheetDialog { email -> viewModel.resetPassword(email) } } lifecycleScope.launchWhenStarted { viewModel.resetPassword.collect { when (it) { is Resource.Loading -> { } is Resource.Success -> { Snackbar.make( requireView(), "Reset link was sent to your email", Snackbar.LENGTH_LONG ).show() } is Resource.Error -> { Snackbar.make(requireView(), "Error: ${it.message}", Snackbar.LENGTH_LONG) .show() } else -> Unit } } } lifecycleScope.launchWhenStarted { viewModel.login.collect { when (it) { is Resource.Loading -> { binding.buttonLoginLogin.startAnimation() } is Resource.Success -> { binding.buttonLoginLogin.revertAnimation() Intent(requireActivity(), DashboardActivity::class.java).also { intent -> intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } } is Resource.Error -> { Toast.makeText(requireContext(), it.message, Toast.LENGTH_LONG).show() binding.buttonLoginLogin.revertAnimation() } else -> Unit } } } } }
0
Kotlin
0
0
8041bfcc08ee73bf8f470d179c5fe44e674b1df9
3,923
CTUT-Student
MIT License
src/main/kotlin/com/cycode/plugin/components/toolWindow/components/treeView/utils.kt
cycodehq
661,784,325
false
{"Kotlin": 119058}
package com.cycode.plugin.components.toolWindow.components.treeView import com.cycode.plugin.components.toolWindow.components.treeView.nodes.ScaDetectionNode import com.cycode.plugin.components.toolWindow.components.treeView.nodes.SecretDetectionNode import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import java.io.File private fun openFileInEditor(project: Project, filePath: String, lineNumber: Int) { val file = File(filePath) val virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file) ?: return val editorManager = FileEditorManager.getInstance(project) editorManager.openTextEditor( OpenFileDescriptor(project, virtualFile, lineNumber, 0), true ) } fun openSecretDetectionInFile(project: Project, node: SecretDetectionNode) { val filePath = node.detection.detectionDetails.getFilepath() val line = node.detection.detectionDetails.line openFileInEditor(project, filePath, line) } fun openScaDetectionInFile(project: Project, node: ScaDetectionNode) { val filePath = node.detection.detectionDetails.getFilepath() val line = node.detection.detectionDetails.lineInFile - DIFFERENCE_BETWEEN_SCA_LINE_NUMBERS openFileInEditor(project, filePath, line) }
0
Kotlin
0
1
2653ec6d8a3b541c8d6f08a295b8527c552d2b7d
1,380
intellij-platform-plugin
MIT License
sample/src/testSpec/java/com/freeletics/rxredux/PopularRepositoriesSpec.kt
freeletics
138,705,451
false
null
package com.freeletics.coredux import com.freeletics.coredux.businesslogic.pagination.PaginationStateMachine import io.reactivex.Observable import okhttp3.mockwebserver.MockWebServer import org.junit.Assert import timber.log.Timber import java.util.concurrent.TimeUnit /** * Abstraction layer that shows what a user can do on the screen */ interface Screen { /** * Scroll the list to the item at position */ fun scrollToEndOfList() /** * Action on the screen: Clicks on the retry button to retry loading the first page */ fun retryLoadingFirstPage() /** * Launches the screen. * After having this called, the screen is visible */ fun loadFirstPage() } /** * Can record states over time. */ interface StateRecorder { /** * Observable of recorded States */ fun renderedStates(): Observable<PaginationStateMachine.State> } /** * Keep the whole history of all states over time */ class StateHistory(private val stateRecorder: StateRecorder) { /** * All states that has been captured and asserted in an `on`cl */ private var stateHistory: List<PaginationStateMachine.State> = emptyList() /** * Waits until the next state is rendered and then retruns a [StateHistorySnapshot] * or if a timeout happens then a TimeOutException will be thrown */ internal fun waitUntilNextRenderedState(): StateHistorySnapshot { val recordedStates = stateRecorder.renderedStates() .take(stateHistory.size + 1L) .toList() .timeout(1, TimeUnit.MINUTES) .doOnError { it.printStackTrace() } .blockingGet() val history = stateHistory stateHistory = recordedStates return StateHistorySnapshot( actualRecordedStates = recordedStates, verifiedHistory = history ) } /** * A Snapshot in time */ internal data class StateHistorySnapshot( /** * The actual full recorded history of states */ val actualRecordedStates: List<PaginationStateMachine.State>, /** * full history of all states that we have already verified / validated and * are sure that this list of states is correct */ val verifiedHistory: List<PaginationStateMachine.State> ) } private data class Given( private val screen: Screen, private val stateHistory: StateHistory, private val composedMessage: String ) { inner class On(private val composedMessage: String) { inner class It(private val composedMessage: String) { internal fun assertStateRendered(expectedState: PaginationStateMachine.State) { val (recordedStates, verifiedHistory) = stateHistory.waitUntilNextRenderedState() val expectedStates = verifiedHistory + expectedState Assert.assertEquals( composedMessage, expectedStates, recordedStates ) Timber.d("✅ $composedMessage") } } infix fun String.byRendering(expectedState: PaginationStateMachine.State) { val message = this val it = It("$composedMessage *IT* $message") it.assertStateRendered(expectedState) } } fun on(message: String, block: On.() -> Unit) { val on = On("*GIVEN* $composedMessage *ON* $message") on.block() } } /** * A simple holder object for all required configuration */ data class ScreenConfig( val mockWebServer: MockWebServer ) class PopularRepositoriesSpec( private val screen: Screen, private val stateHistory: StateHistory, private val config: ScreenConfig ) { private fun given(message: String, block: Given.() -> Unit) { val given = Given(screen, stateHistory, message) given.block() } fun runTests(connectionErrorMessage: String) { val server = config.mockWebServer given("the device is offline") { server.shutdown() on("loading first page") { screen.loadFirstPage() "shows loading first page" byRendering PaginationStateMachine.State.LoadingFirstPageState "shows error loading first page" byRendering PaginationStateMachine.State.ErrorLoadingFirstPageState( connectionErrorMessage ) } } given("device is online (was offline before)") { server.enqueue200(FIRST_PAGE) server.start(MOCK_WEB_SERVER_PORT) Thread.sleep(5000) on("user clicks retry loading first page") { screen.retryLoadingFirstPage() "shows loading" byRendering PaginationStateMachine.State.LoadingFirstPageState "shows first page" byRendering PaginationStateMachine.State.ShowContentState( items = FIRST_PAGE, page = 1 ) } server.enqueue200(SECOND_PAGE) on("scrolling to the end of the first page") { screen.scrollToEndOfList() "shows loading next page" byRendering PaginationStateMachine.State.ShowContentAndLoadNextPageState( items = FIRST_PAGE, page = 1 ) "shows next page content" byRendering PaginationStateMachine.State.ShowContentState( items = FIRST_PAGE + SECOND_PAGE, page = 2 ) } } given("device is offline again (was online before)") { server.shutdown() on("scrolling to end of second page") { screen.scrollToEndOfList() "shows loading next page" byRendering PaginationStateMachine.State.ShowContentAndLoadNextPageState( items = FIRST_PAGE + SECOND_PAGE, page = 2 ) "shows error info for few seconds on top of the list of items" byRendering PaginationStateMachine.State.ShowContentAndLoadNextPageErrorState( items = FIRST_PAGE + SECOND_PAGE, page = 2, errorMessage = connectionErrorMessage ) "hides error information and shows items only" byRendering PaginationStateMachine.State.ShowContentState( items = FIRST_PAGE + SECOND_PAGE, page = 2 ) } } } }
24
null
6
572
1560f7ae9bd29b7be11f7a2f2d14e308af07c578
6,938
RxRedux
Apache License 2.0
app/src/main/java/com/example/flixsterpart1/CurrentMovieRecyclerViewAdapter.kt
MattPanda4
541,942,620
false
{"Kotlin": 6446}
package com.example.flixsterpart1 import android.content.Context import android.content.Intent import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide private const val TAG = "MovieAdapter" const val MOVIE = "MOVIE" class CurrentMovieRecyclerViewAdapter(private val context: Context, private val movies: MutableList<CurrentMovie>) : RecyclerView.Adapter<CurrentMovieRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { Log.i(TAG, "onCreateViewHolder") val view = LayoutInflater.from(context).inflate(R.layout.fragment_current_movies, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { Log.i(TAG, "onBindViewHolder position $position") val currentMovies = movies[position] holder.bind(currentMovies) } override fun getItemCount() = movies.size inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView), View.OnClickListener{ private val mPoster = itemView.findViewById<ImageView>(R.id.movie_image) private val mTitle = itemView.findViewById<TextView>(R.id.movie_title) private val mOverview = itemView.findViewById<TextView>(R.id.movie_description) init { itemView.setOnClickListener(this) } fun bind(movie: CurrentMovie){ mTitle.text = movie.title mOverview.text = movie.overview Glide.with(context) .load(movie.posterImageURL) .centerCrop() .into(mPoster) } override fun onClick(p0: View?) { //1. get notified of particular movie which was clicked on val movie = movies[adapterPosition] Toast.makeText(context, movie.title, Toast.LENGTH_SHORT).show() val intent = Intent(context, MovieDetailActivity::class.java) intent.putExtra(MOVIE,movie) context.startActivity(intent) } } }
2
Kotlin
0
0
52ae5f5b53093fe5fe30ac49c18c51b14eedf892
2,277
Flixster_Part_1
Apache License 2.0
app/src/main/kotlin/com/numero/itube/repository/VideoRepository.kt
NUmeroAndDev
130,776,366
false
null
package com.numero.itube.repository import androidx.lifecycle.LiveData import com.numero.itube.api.request.ChannelVideoRequest import com.numero.itube.api.request.SearchVideoRequest import com.numero.itube.api.response.Result import com.numero.itube.model.* interface VideoRepository { fun fetchVideoDetail(videoId: VideoId, channelId: ChannelId): LiveData<Result<VideoDetail>> fun fetchVideoList(request: SearchVideoRequest): LiveData<State<SearchVideoList>> fun fetchChannelVideoList(request: ChannelVideoRequest): LiveData<Result<ChannelVideoList>> }
2
Kotlin
0
3
f1ed07fd0efb98239563c8940f69d498ba6f2602
571
iTube-android
MIT License
domain/src/main/java/ru/rznnike/eyehealthmanager/domain/gateway/UserGateway.kt
RznNike
207,148,781
false
{"Kotlin": 903281}
package ru.rznnike.eyehealthmanager.domain.gateway import ru.rznnike.eyehealthmanager.domain.model.AcuityTestingSettings import ru.rznnike.eyehealthmanager.domain.model.TestingSettings import ru.rznnike.eyehealthmanager.domain.model.enums.AppTheme interface UserGateway { suspend fun getWelcomeDialogShowed(): Boolean suspend fun setWelcomeDialogShowed(newValue: Boolean) suspend fun getDisplayedChangelogVersion(): Int suspend fun setDisplayedChangelogVersion(newValue: Int) suspend fun getTestingSettings(): TestingSettings suspend fun setTestingSettings(newValue: TestingSettings) suspend fun getAcuityTestingSettings(): AcuityTestingSettings suspend fun setAcuityTestingSettings(newValue: AcuityTestingSettings) suspend fun getApplyDynamicCorrections(): Boolean suspend fun setApplyDynamicCorrections(newValue: Boolean) suspend fun getAppTheme(): AppTheme suspend fun setAppTheme(appTheme: AppTheme) }
0
Kotlin
1
5
ea21e191ea3d6797be32f7f5e66e8e0ebae30ab6
967
EyeHealthManager
MIT License
RadioButtonMenuItemIcon/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* import java.io.Serializable import javax.swing.* import javax.swing.plaf.UIResource fun makeUI() = JPanel(BorderLayout()).also { EventQueue.invokeLater { it.rootPane.jMenuBar = createMenuBar() } it.add(JScrollPane(JTextArea())) it.preferredSize = Dimension(320, 240) } private fun createMenuBar(): JMenuBar { val menu = JMenu("RadioButtonMenuItem-Test") menu.add(JRadioButtonMenuItem("default", true)) UIManager.put("RadioButtonMenuItem.checkIcon", RadioButtonMenuItemIcon1()) menu.add(JRadioButtonMenuItem("ANTIALIASING", true)) UIManager.put("RadioButtonMenuItem.checkIcon", RadioButtonMenuItemIcon2()) menu.add(JRadioButtonMenuItem("fillOval", true)) val menuBar = JMenuBar() menuBar.add(menu) return menuBar } private class RadioButtonMenuItemIcon1 : Icon, UIResource, Serializable { override fun paintIcon( c: Component, g: Graphics, x: Int, y: Int, ) { if (c is AbstractButton) { val model = c.model if (model.isSelected) { val g2 = g.create() as? Graphics2D ?: return g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON, ) g2.translate(x, y) g2.fillRoundRect(3, 3, iconWidth - 6, iconHeight - 6, 4, 4) g2.dispose() } } } override fun getIconWidth() = 12 override fun getIconHeight() = 12 companion object { private const val serialVersionUID = 1L } } private class RadioButtonMenuItemIcon2 : Icon, UIResource, Serializable { override fun paintIcon( c: Component, g: Graphics, x: Int, y: Int, ) { if (c is AbstractButton) { val model = c.model if (model.isSelected) { val g2 = g.create() as? Graphics2D ?: return g2.translate(x, y) g2.fillOval(2, 2, iconWidth - 5, iconHeight - 5) g2.dispose() } } } override fun getIconWidth() = 12 override fun getIconHeight() = 12 companion object { private const val serialVersionUID = 1L } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
Kotlin
6
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
2,481
kotlin-swing-tips
MIT License
graphite/src/main/kotlin/io/qalipsis/plugins/graphite/GraphiteSpecificationNamespace.kt
qalipsis
453,136,595
false
{"Kotlin": 237352}
/* * Copyright 2022 AERIS IT Solutions GmbH * * 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.qalipsis.plugins.graphite import io.qalipsis.api.scenario.ScenarioSpecification import io.qalipsis.api.steps.AbstractPluginStepWrapper import io.qalipsis.api.steps.AbstractScenarioSpecificationWrapper import io.qalipsis.api.steps.StepSpecification /** * Step wrapper to append to all steps before using a step from the Graphite plugin. * * @author Palina Bril */ interface GraphiteStepSpecification<INPUT, OUTPUT, SELF : StepSpecification<INPUT, OUTPUT, SELF>> : StepSpecification<INPUT, OUTPUT, SELF> /** * Step wrapper to append to all steps before using a step from the Graphite plugin. * * @author Palina Bril */ internal class GraphiteSpecificationImpl<INPUT, OUTPUT>(wrappedStepSpec: StepSpecification<INPUT, OUTPUT, *>) : AbstractPluginStepWrapper<INPUT, OUTPUT>(wrappedStepSpec), GraphiteStepSpecification<INPUT, OUTPUT, AbstractPluginStepWrapper<INPUT, OUTPUT>> fun <INPUT, OUTPUT> StepSpecification<INPUT, OUTPUT, *>.graphite(): GraphiteStepSpecification<INPUT, OUTPUT, *> = GraphiteSpecificationImpl(this) /** * Scenario wrapper to append to a scenario before using a step from the Graphite plugin. * * @author Palina Bril */ class GraphiteScenarioSpecification(scenario: ScenarioSpecification) : AbstractScenarioSpecificationWrapper(scenario) fun ScenarioSpecification.graphite() = GraphiteScenarioSpecification(this)
0
Kotlin
0
0
a832bb4761c139f9e8f7474f39d7a7345f2cda74
1,984
qalipsis-plugin-graphite
Apache License 2.0
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/meta/SuspendTests.kt
slatekit
55,942,000
false
{"Text": 42, "Ignore List": 42, "YAML": 3, "Markdown": 22, "Gradle": 79, "Shell": 46, "Batchfile": 40, "Java Properties": 25, "Kotlin": 884, "JSON": 12, "INI": 9, "EditorConfig": 26, "Java": 13, "SQL": 1, "XML": 4, "Swift": 3}
package test.meta import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import kiit.apis.executor.Executor import kiit.meta.Reflector class SuspendTests { @Test fun callSuspend(){ val sample = ReflectSample() runBlocking { val member = Reflector.getMethod(ReflectSample::class, "add") val result = Executor.invoke(sample, member!!, arrayOf(1, 2)) Assert.assertEquals(3, result) } } @Test fun callNormal(){ val sample = ReflectSample() runBlocking { val member = Reflector.getMethod(ReflectSample::class, "inc") val result = Executor.invoke(sample, member!!, arrayOf(1, 2)) Assert.assertEquals(3, result) } } } class ReflectSample { suspend fun add(a: Int, b:Int):Int { val result = a + b return result } fun inc(a: Int, b:Int):Int { val result = a + b return result } }
3
Kotlin
13
112
d17b592aeb28c5eb837d894e98492c69c4697862
1,001
slatekit
Apache License 2.0
pumpkin-protocol-modern/src/main/kotlin/pumpkin/protocol/modern/ModernProtocolState.kt
ItsDoot
224,063,495
false
null
package pumpkin.protocol.modern import pumpkin.protocol.core.Direction import pumpkin.protocol.core.ProtocolRegistry import pumpkin.protocol.core.ProtocolState import pumpkin.protocol.modern.ModernProtocolVersion.Minecraft_1_14_4 import pumpkin.protocol.modern.packet.handshake.SBHandshakePacket import pumpkin.protocol.modern.packet.login.CBDisconnectLoginPacket import pumpkin.protocol.modern.packet.login.CBPluginRequestLoginPacket import pumpkin.protocol.modern.packet.login.CBSuccessLoginPacket import pumpkin.protocol.modern.packet.login.SBPluginResponseLoginPacket import pumpkin.protocol.modern.packet.login.SBStartLoginPacket import pumpkin.protocol.modern.packet.play.* import pumpkin.protocol.modern.packet.status.CBResponseStatusPacket import pumpkin.protocol.modern.packet.status.SBRequestStatusPacket import pumpkin.protocol.modern.packet.status.TWPingPongStatusPacket enum class ModernProtocolState : ProtocolState<ModernPacket> { HANDSHAKE { init { serverbound[0x00 to Minecraft_1_14_4] = SBHandshakePacket } }, PLAY { init { serverbound[0x00 to Minecraft_1_14_4] = SBTeleportConfirmPlayPacket // serverbound[0x01 to Minecraft_1_14_4] = SBQueryBlockNBTPlayPacket serverbound[0x02 to Minecraft_1_14_4] = SBSetDifficultyPlayPacket serverbound[0x03 to Minecraft_1_14_4] = SBChatMessagePlayPacket serverbound[0x04 to Minecraft_1_14_4] = SBClientStatusPlayPacket serverbound[0x05 to Minecraft_1_14_4] = SBClientSettingsPlayPacket // serverbound[0x06 to Minecraft_1_14_4] = SBTabCompletePlayPacket // serverbound[0x07 to Minecraft_1_14_4] = SBConfirmTransactionPlayPacket // serverbound[0x08 to Minecraft_1_14_4] = SBClickWindowButtonPlayPacket serverbound[0x09 to Minecraft_1_14_4] = SBClickWindowPlayPacket serverbound[0x0A to Minecraft_1_14_4] = SBCloseWindowPlayPacket serverbound[0x0B to Minecraft_1_14_4] = SBPluginMessagePlayPacket // serverbound[0x0C to Minecraft_1_14_4] = SBEditBookPlayPacket // serverbound[0x0D to Minecraft_1_14_4] = SBQueryEntityNBTPlayPacket // serverbound[0x0E to Minecraft_1_14_4] = SBUseEntityPlayPacket serverbound[0x0F to Minecraft_1_14_4] = TWKeepAlivePlayPacket // serverbound[0x10 to Minecraft_1_14_4] = SBLockDifficultyPlayPacket // serverbound[0x11 to Minecraft_1_14_4] = SBPlayerPositionPlayPacket serverbound[0x12 to Minecraft_1_14_4] = SBPlayerPositionAndLookPlayPacket // serverbound[0x13 to Minecraft_1_14_4] = SBPlayerLookPlayPacket // serverbound[0x14 to Minecraft_1_14_4] = SBPlayerPlayPacket // serverbound[0x15 to Minecraft_1_14_4] = SBVehicleMovePlayPacket // serverbound[0x16 to Minecraft_1_14_4] = SBSteerBoatPlayPacket // serverbound[0x17 to Minecraft_1_14_4] = SBPickItemPlayPacket // serverbound[0x18 to Minecraft_1_14_4] = SBCraftRecipeRequestPlayPacket serverbound[0x19 to Minecraft_1_14_4] = SBPlayerAbilitiesPlayPacket serverbound[0x1A to Minecraft_1_14_4] = SBPlayerDiggingPlayPacket // serverbound[0x1B to Minecraft_1_14_4] = SBEntityActionPlayPacket // serverbound[0x1C to Minecraft_1_14_4] = SBSteerVehiclePlayPacket // serverbound[0x1D to Minecraft_1_14_4] = SBRecipeBookDataPlayPacket // serverbound[0x1E to Minecraft_1_14_4] = SBNameItemPlayPacket // serverbound[0x1F to Minecraft_1_14_4] = SBResourcePackStatusPlayPacket serverbound[0x20 to Minecraft_1_14_4] = SBAdvancementTabPlayPacket // serverbound[0x21 to Minecraft_1_14_4] = SBSelectTradePlayPacket serverbound[0x22 to Minecraft_1_14_4] = SBSetBeaconEffectPlayPacket serverbound[0x23 to Minecraft_1_14_4] = SBHeldItemChangePlayPacket // serverbound[0x24 to Minecraft_1_14_4] = SBUpdateCommandBlockPlayPacket // serverbound[0x25 to Minecraft_1_14_4] = SBUpdateCommandBlockMinecartPlayPacket // serverbound[0x26 to Minecraft_1_14_4] = SBCreativeInventoryActionPlayPacket // serverbound[0x27 to Minecraft_1_14_4] = SBUpdateJigsawBlockPlayPacket // serverbound[0x28 to Minecraft_1_14_4] = SBUpdateStructureBlockPlayPacket // serverbound[0x29 to Minecraft_1_14_4] = SBUpdateSignPlayPacket serverbound[0x2A to Minecraft_1_14_4] = SBAnimationPlayPacket // serverbound[0x2B to Minecraft_1_14_4] = SBSpectatePlayPacket // serverbound[0x2C to Minecraft_1_14_4] = SBPlayerBlockPlacementPlayPacket // serverbound[0x2D to Minecraft_1_14_4] = SBUseItemPlayPacket // clientbound[0x00 to Minecraft_1_14_4] = CBSpawnObjectPlayPacket clientbound[0x01 to Minecraft_1_14_4] = CBSpawnExpOrbPlayPacket // clientbound[0x02 to Minecraft_1_14_4] = CBSpawnGlobalEntityPlayPacket // clientbound[0x03 to Minecraft_1_14_4] = CBSpawnMobPlayPacket // clientbound[0x04 to Minecraft_1_14_4] = CBSpawnPaintingPlayPacket // clientbound[0x05 to Minecraft_1_14_4] = CBSpawnPlayerPlayPacket clientbound[0x06 to Minecraft_1_14_4] = CBAnimationPlayPacket // clientbound[0x07 to Minecraft_1_14_4] = CBStatisticsPlayPacket clientbound[0x08 to Minecraft_1_14_4] = CBBlockBreakAnimationPlayPacket // clientbound[0x09 to Minecraft_1_14_4] = CBUpdateBlockEntityPlayPacket clientbound[0x0A to Minecraft_1_14_4] = CBBlockActionPlayPacket // clientbound[0x0B to Minecraft_1_14_4] = CBBlockChangePlayPacket // clientbound[0x0C to Minecraft_1_14_4] = CBBossBarPlayPacket clientbound[0x0D to Minecraft_1_14_4] = CBServerDifficultyPlayPacket clientbound[0x0E to Minecraft_1_14_4] = CBChatMessagePlayPacket // clientbound[0x0F to Minecraft_1_14_4] = CBMultiBlockChangePlayPacket // clientbound[0x10 to Minecraft_1_14_4] = CBTabCompletePlayPacket // clientbound[0x11 to Minecraft_1_14_4] = CBDeclareCommandsPlayPacket // clientbound[0x12 to Minecraft_1_14_4] = CBConfirmTransactionPlayPacket // clientbound[0x13 to Minecraft_1_14_4] = CBCloseWindowPlayPacket // clientbound[0x14 to Minecraft_1_14_4] = CBWindowItemsPlayPacket // clientbound[0x15 to Minecraft_1_14_4] = CBWindowPropertyPlayPacket // clientbound[0x16 to Minecraft_1_14_4] = CBSetSlotPlayPacket // clientbound[0x17 to Minecraft_1_14_4] = CBSetCooldownPlayPacket clientbound[0x18 to Minecraft_1_14_4] = CBPluginMessagePlayPacket // clientbound[0x19 to Minecraft_1_14_4] = CBNamedSoundEffectPlayPacket clientbound[0x1A to Minecraft_1_14_4] = CBDisconnectPlayPacket // clientbound[0x1B to Minecraft_1_14_4] = CBEntityStatusPlayPacket // clientbound[0x1C to Minecraft_1_14_4] = CBExplosionPlayPacket // clientbound[0x1D to Minecraft_1_14_4] = CBUnloadChunkPlayPacket // clientbound[0x1E to Minecraft_1_14_4] = CBChangeGameStatePlayPacket // clientbound[0x1F to Minecraft_1_14_4] = CBOpenHorseWindowPlayPacket clientbound[0x20 to Minecraft_1_14_4] = TWKeepAlivePlayPacket // clientbound[0x21 to Minecraft_1_14_4] = CBChunkDataPlayPacket // clientbound[0x22 to Minecraft_1_14_4] = CBEffectPlayPacket // clientbound[0x23 to Minecraft_1_14_4] = CBParticlePlayPacket // clientbound[0x24 to Minecraft_1_14_4] = CBUpdateLightPlayPacket clientbound[0x25 to Minecraft_1_14_4] = CBJoinGamePlayPacket // clientbound[0x26 to Minecraft_1_14_4] = CBMapDataPlayPacket // clientbound[0x27 to Minecraft_1_14_4] = CBTradeListPlayPacket // clientbound[0x28 to Minecraft_1_14_4] = CBEntityRelativeMovePlayPacket // clientbound[0x29 to Minecraft_1_14_4] = CBEntityLookAndRelativeMovePlayPacket // clientbound[0x2A to Minecraft_1_14_4] = CBEntityLookPlayPacket // clientbound[0x2B to Minecraft_1_14_4] = CBEntityPlayPacket // clientbound[0x2C to Minecraft_1_14_4] = CBVehicleMovePlayPacket // clientbound[0x2D to Minecraft_1_14_4] = CBOpenBookPlayPacket // clientbound[0x2E to Minecraft_1_14_4] = CBOpenWindowPlayPacket // clientbound[0x2F to Minecraft_1_14_4] = CBOpenSignEditorPlayPacket // clientbound[0x30 to Minecraft_1_14_4] = CBCraftRecipeResponsePlayPacket clientbound[0x31 to Minecraft_1_14_4] = CBPlayerAbilitiesPlayPacket // clientbound[0x32 to Minecraft_1_14_4] = CBCombatEventPlayPacket clientbound[0x33 to Minecraft_1_14_4] = CBPlayerInfoPlayPacket // clientbound[0x34 to Minecraft_1_14_4] = CBFacePlayerPlayPacket clientbound[0x35 to Minecraft_1_14_4] = CBPlayerPositionAndLookPlayPacket // clientbound[0x36 to Minecraft_1_14_4] = CBUnlockRecipesPlayPacket // clientbound[0x37 to Minecraft_1_14_4] = CBDestroyEntitiesPlayPacket // clientbound[0x38 to Minecraft_1_14_4] = CBRemoveEntityEffectPlayPacket // clientbound[0x39 to Minecraft_1_14_4] = CBResourcePackSendPlayPacket // clientbound[0x3A to Minecraft_1_14_4] = CBRespawnPlayPacket // clientbound[0x3B to Minecraft_1_14_4] = CBEntityHeadLookPlayPacket // clientbound[0x3C to Minecraft_1_14_4] = CBSelectAdvancementTabPlayPacket // clientbound[0x3D to Minecraft_1_14_4] = CBWorldBorderPlayPacket // clientbound[0x3E to Minecraft_1_14_4] = CBCameraPlayPacket clientbound[0x3F to Minecraft_1_14_4] = CBHeldItemChangePlayPacket clientbound[0x40 to Minecraft_1_14_4] = CBUpdateViewPositionPlayPacket // clientbound[0x41 to Minecraft_1_14_4] = CBUpdateViewDistancePlayPacket // clientbound[0x42 to Minecraft_1_14_4] = CBDisplayScoreboardPlayPacket // clientbound[0x43 to Minecraft_1_14_4] = CBEntityMetadataPlayPacket // clientbound[0x44 to Minecraft_1_14_4] = CBAttachEntityPlayPacket // clientbound[0x45 to Minecraft_1_14_4] = CBEntityVelocityPlayPacket // clientbound[0x46 to Minecraft_1_14_4] = CBEntityEquipmentPlayPacket // clientbound[0x47 to Minecraft_1_14_4] = CBSetExperiencePlayPacket // clientbound[0x48 to Minecraft_1_14_4] = CBUpdateHealthPlayPacket // clientbound[0x49 to Minecraft_1_14_4] = CBScoreboardObjectivePlayPacket // clientbound[0x4A to Minecraft_1_14_4] = CBSetPassengersPlayPacket // clientbound[0x4B to Minecraft_1_14_4] = CBTeamsPlayPacket // clientbound[0x4C to Minecraft_1_14_4] = CBUpdateScorePlayPacket clientbound[0x4D to Minecraft_1_14_4] = CBSpawnPositionPlayPacket // clientbound[0x4E to Minecraft_1_14_4] = CBTimeUpdatePlayPacket // clientbound[0x4F to Minecraft_1_14_4] = CBTitlePlayPacket // clientbound[0x50 to Minecraft_1_14_4] = CBEntitySoundEffectPlayPacket // clientbound[0x51 to Minecraft_1_14_4] = CBSoundEffectPlayPacket // clientbound[0x52 to Minecraft_1_14_4] = CBStopSoundPlayPacket // clientbound[0x53 to Minecraft_1_14_4] = CBPlayerListHeaderAndFooterPlayPacket // clientbound[0x54 to Minecraft_1_14_4] = CBNBTQueryResponsePlayPacket // clientbound[0x55 to Minecraft_1_14_4] = CBCollectItemPlayPacket // clientbound[0x56 to Minecraft_1_14_4] = CBEntityTeleportPlayPacket // clientbound[0x57 to Minecraft_1_14_4] = CBAdvancementsPlayPacket // clientbound[0x58 to Minecraft_1_14_4] = CBEntityPropertiesPlayPacket // clientbound[0x59 to Minecraft_1_14_4] = CBEntityEffectPlayPacket // clientbound[0x5A to Minecraft_1_14_4] = CBDeclareRecipesPlayPacket clientbound[0x5B to Minecraft_1_14_4] = CBTagsPlayPacket // clientbound[0x5C to Minecraft_1_14_4] = CBAcknowledgePlayerDiggingPlayPacket } }, STATUS { init { serverbound[0x00 to Minecraft_1_14_4] = SBRequestStatusPacket serverbound[0x01 to Minecraft_1_14_4] = TWPingPongStatusPacket clientbound[0x00 to Minecraft_1_14_4] = CBResponseStatusPacket clientbound[0x01 to Minecraft_1_14_4] = TWPingPongStatusPacket } }, LOGIN { init { serverbound[0x00 to Minecraft_1_14_4] = SBStartLoginPacket serverbound[0x02 to Minecraft_1_14_4] = SBPluginResponseLoginPacket clientbound[0x00 to Minecraft_1_14_4] = CBDisconnectLoginPacket clientbound[0x02 to Minecraft_1_14_4] = CBSuccessLoginPacket clientbound[0x04 to Minecraft_1_14_4] = CBPluginRequestLoginPacket } }; override val clientbound: ProtocolRegistry<ModernPacket> = ProtocolRegistry(Direction.CLIENT_BOUND, ModernProtocolVersion.SUPPORTED) override val serverbound: ProtocolRegistry<ModernPacket> = ProtocolRegistry(Direction.SERVER_BOUND, ModernProtocolVersion.SUPPORTED) companion object { fun fromHandshake(id: Int): ModernProtocolState = when (id) { 1 -> STATUS 2 -> LOGIN else -> throw IllegalStateException("Invalid next state: $id") } } }
0
Kotlin
1
1
afa6c39fc722f616ee8410b325a402b92994082f
13,534
pumpkin
MIT License
mqtt/src/main/kotlin/com/oneliang/ktx/frame/mqtt/MqttSender.kt
tongxiaoyi
379,480,354
false
null
package com.oneliang.ktx.frame.mqtt import com.oneliang.ktx.frame.handler.SendHandler import com.oneliang.ktx.util.logging.LoggerManager import org.fusesource.mqtt.client.BlockingConnection import org.fusesource.mqtt.client.QoS class MqttSender(host: String, username: String, password: String, threadCount: Int = 2) { companion object { private val logger = LoggerManager.getLogger(MqttSender::class) } private val sendHandler: SendHandler<BlockingConnection> = SendHandler(threadCount, initialize = { MqttClient.connect(host, username, password) }) init { logger.info("send handler starting") this.sendHandler.start() } fun send(topic: String, data: ByteArray, retain: Boolean) { this.sendHandler.execute { it.publish(topic, data, QoS.EXACTLY_ONCE, retain) } } }
1
null
2
1
1a4cbe107b7adc8941691911f75c3fc2aa383ca1
861
frame-kotlin
Apache License 2.0
android/app/src/main/kotlin/com/example/movies_streaming/MainActivity.kt
asnan23
372,857,935
false
{"Dart": 25267, "HTML": 1521, "Swift": 404, "Kotlin": 133, "Objective-C": 38}
package com.example.movies_streaming import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
7c7f9f080d8dee124538fa7814dea0a7ebc7eca4
133
flutter_submission1
MIT License
AvataryugKotlinSDK/app/src/main/java/Avataryug/Client/Api/AvatarManagementApi.kt
avataryug
676,819,707
false
{"Kotlin": 702219}
/** * * 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 com.Avataryug.client.Apis import Avataryug.Client.AvatarProjectSettings import com.Avataryug.client.Infrastructure.ApiClient import java.io.IOException import okhttp3.OkHttpClient import okhttp3.HttpUrl import com.Avataryug.client.Models.GenerateAvatarMeshRequest import com.Avataryug.client.Models.GenerateAvatarMeshResult import com.Avataryug.client.Models.GetAllBucketVerticesResult import com.Avataryug.client.Models.GetAvatarPresetByIDRequest import com.Avataryug.client.Models.GetAvatarPresetsResult import com.Avataryug.client.Models.GetClipsByIDResult import com.Avataryug.client.Models.GetClipsResult import com.Avataryug.client.Models.GetExpressionByIDResult import com.Avataryug.client.Models.GetExpressionsResult import com.Avataryug.client.Models.GrantAvatarPresetItemsToUserRequest import com.Avataryug.client.Models.GrantAvatarPresetItemsToUserResult import com.Avataryug.client.Models.GrantAvatarPresetToUserRequest import com.Avataryug.client.Models.GrantAvatarPresetToUserResult import com.Avataryug.client.Models.RenderAvatarImageRequest import com.Avataryug.client.Models.RenderAvatarImageResult import com.Avataryug.client.Models.SyncAvatarsRequest import com.Avataryug.client.Models.SyncAvatarsResult import com.Avataryug.client.Infrastructure.ApiResponse import com.Avataryug.client.Infrastructure.ClientException import com.Avataryug.client.Infrastructure.ClientError import com.Avataryug.client.Infrastructure.ServerException import com.Avataryug.client.Infrastructure.ServerError import com.Avataryug.client.Infrastructure.MultiValueMap import com.Avataryug.client.Infrastructure.RequestConfig import com.Avataryug.client.Infrastructure.RequestMethod import com.Avataryug.client.Infrastructure.ResponseType import com.Avataryug.client.Infrastructure.Success /** * Represents a collection of functions to interact with the API endpoints */ class AvatarManagementApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { companion object { @JvmStatic val defaultBasePath: String by lazy { val id = AvatarProjectSettings.Project_Id System.getProperties().getProperty(ApiClient.baseUrlKey, "https://$id.avataryugapi.com/client") } } /** * Generate Avatar Mesh * Generates the 3D mesh as per the configuration in the Config panel * @param generateAvatarMeshRequest (optional) * @return GenerateAvatarMeshResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun generateAvatarMesh(generateAvatarMeshRequest: GenerateAvatarMeshRequest? = null) : GenerateAvatarMeshResult { val localVarResponse = generateAvatarMeshWithHttpInfo(generateAvatarMeshRequest = generateAvatarMeshRequest) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GenerateAvatarMeshResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Generate Avatar Mesh * Generates the 3D mesh as per the configuration in the Config panel * @param generateAvatarMeshRequest (optional) * @return ApiResponse<GenerateAvatarMeshResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun generateAvatarMeshWithHttpInfo(generateAvatarMeshRequest: GenerateAvatarMeshRequest?) : ApiResponse<GenerateAvatarMeshResult?> { val localVariableConfig = generateAvatarMeshRequestConfig(generateAvatarMeshRequest = generateAvatarMeshRequest) return request<GenerateAvatarMeshRequest, GenerateAvatarMeshResult>( localVariableConfig ) } /** * To obtain the request config of the operation generateAvatarMesh * * @param generateAvatarMeshRequest (optional) * @return RequestConfig */ fun generateAvatarMeshRequestConfig(generateAvatarMeshRequest: GenerateAvatarMeshRequest?) : RequestConfig<GenerateAvatarMeshRequest> { val localVariableBody = generateAvatarMeshRequest val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.POST, path = "/GenerateAvatarMesh", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get Avatar Presets * Get all avatar presets * @return GetAvatarPresetsResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getAvatarPresets(status: kotlin.Int, Gender: kotlin.Int) : GetAvatarPresetsResult { val localVarResponse = getAvatarPresetsWithHttpInfo(status,Gender) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetAvatarPresetsResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get Avatar Presets * Get all avatar presets * @return ApiResponse<GetAvatarPresetsResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getAvatarPresetsWithHttpInfo(status: kotlin.Int, Gender: kotlin.Int) : ApiResponse<GetAvatarPresetsResult?> { val localVariableConfig = getAvatarPresetsRequestConfig(status, Gender) return request<Unit, GetAvatarPresetsResult>( localVariableConfig ) } /** * To obtain the request config of the operation getAvatarPresets * * @return RequestConfig */ fun getAvatarPresetsRequestConfig(status: kotlin.Int, Gender: kotlin.Int) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("Status", listOf(status.toString())) put("Gender", listOf(Gender.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetAvatarPresets", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get Avatar Presets By ID * Retrive Avatar preset by ID * @param avatarPresetID Unique Identifier for the Avatar Preset which is being requested * @return GetAvatarPresetByIDRequest * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getAvatarPresetsByID(avatarPresetID: kotlin.String) : GetAvatarPresetByIDRequest { val localVarResponse = getAvatarPresetsByIDWithHttpInfo(avatarPresetID = avatarPresetID) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetAvatarPresetByIDRequest ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get Avatar Presets By ID * Retrive Avatar preset by ID * @param avatarPresetID Unique Identifier for the Avatar Preset which is being requested * @return ApiResponse<GetAvatarPresetByIDRequest?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getAvatarPresetsByIDWithHttpInfo(avatarPresetID: kotlin.String) : ApiResponse<GetAvatarPresetByIDRequest?> { val localVariableConfig = getAvatarPresetsByIDRequestConfig(avatarPresetID = avatarPresetID) return request<Unit, GetAvatarPresetByIDRequest>( localVariableConfig ) } /** * To obtain the request config of the operation getAvatarPresetsByID * * @param avatarPresetID Unique Identifier for the Avatar Preset which is being requested * @return RequestConfig */ fun getAvatarPresetsByIDRequestConfig(avatarPresetID: kotlin.String) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("AvatarPresetID", listOf(avatarPresetID.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetAvatarPresetsByID", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get Clips * Get all the clips by Active status * @param status Status of the clips * @return GetClipsResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getClips(status: kotlin.Int) : GetClipsResult { val localVarResponse = getClipsWithHttpInfo(status = status) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetClipsResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get Clips * Get all the clips by Active status * @param status Status of the clips * @return ApiResponse<GetClipsResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getClipsWithHttpInfo(status: kotlin.Int) : ApiResponse<GetClipsResult?> { val localVariableConfig = getClipsRequestConfig(status = status) return request<Unit, GetClipsResult>( localVariableConfig ) } /** * To obtain the request config of the operation getClips * * @param status Status of the clips * @return RequestConfig */ fun getClipsRequestConfig(status: kotlin.Int) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("Status", listOf(status.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetClips", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get Clips By ID * Get the specified clip&#39;s details by providing ClipID * @param clipID Unique Identifier for the clip * @return GetClipsByIDResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getClipsByID(clipID: kotlin.String) : GetClipsByIDResult { val localVarResponse = getClipsByIDWithHttpInfo(clipID = clipID) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetClipsByIDResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get Clips By ID * Get the specified clip&#39;s details by providing ClipID * @param clipID Unique Identifier for the clip * @return ApiResponse<GetClipsByIDResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getClipsByIDWithHttpInfo(clipID: kotlin.String) : ApiResponse<GetClipsByIDResult?> { val localVariableConfig = getClipsByIDRequestConfig(clipID = clipID) return request<Unit, GetClipsByIDResult>( localVariableConfig ) } /** * To obtain the request config of the operation getClipsByID * * @param clipID Unique Identifier for the clip * @return RequestConfig */ fun getClipsByIDRequestConfig(clipID: kotlin.String) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("ClipID", listOf(clipID.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetClipsByID", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get Expression By ID * Get the specified expression details by providing ExpressionID * @param expressionID Unique Identifier for the expression * @return GetExpressionByIDResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getExpressionByID(expressionID: kotlin.String) : GetExpressionByIDResult { val localVarResponse = getExpressionByIDWithHttpInfo(expressionID = expressionID) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetExpressionByIDResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get Expression By ID * Get the specified expression details by providing ExpressionID * @param expressionID Unique Identifier for the expression * @return ApiResponse<GetExpressionByIDResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getExpressionByIDWithHttpInfo(expressionID: kotlin.String) : ApiResponse<GetExpressionByIDResult?> { val localVariableConfig = getExpressionByIDRequestConfig(expressionID = expressionID) return request<Unit, GetExpressionByIDResult>( localVariableConfig ) } /** * To obtain the request config of the operation getExpressionByID * * @param expressionID Unique Identifier for the expression * @return RequestConfig */ fun getExpressionByIDRequestConfig(expressionID: kotlin.String) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("ExpressionID", listOf(expressionID.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetExpressionByID", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get Expressions * Get all the active expressions * @param status Status of Expressions * @return GetExpressionsResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getExpressions(status: kotlin.Int) : GetExpressionsResult { val localVarResponse = getExpressionsWithHttpInfo(status = status) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetExpressionsResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get Expressions * Get all the active expressions * @param status Status of Expressions * @return ApiResponse<GetExpressionsResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getExpressionsWithHttpInfo(status: kotlin.Int) : ApiResponse<GetExpressionsResult?> { val localVariableConfig = getExpressionsRequestConfig(status = status) return request<Unit, GetExpressionsResult>( localVariableConfig ) } /** * To obtain the request config of the operation getExpressions * * @param status Status of Expressions * @return RequestConfig */ fun getExpressionsRequestConfig(status: kotlin.Int) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("Status", listOf(status.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetExpressions", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Get All Bucket Vertices * Get vertices for all buckets * @param platform Name of the platform. I.e. Unreal, Unity * @return GetAllBucketVerticesResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun getGetallbucketvertices(platform: kotlin.String) : GetAllBucketVerticesResult { val localVarResponse = getGetallbucketverticesWithHttpInfo(platform = platform) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GetAllBucketVerticesResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Get All Bucket Vertices * Get vertices for all buckets * @param platform Name of the platform. I.e. Unreal, Unity * @return ApiResponse<GetAllBucketVerticesResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun getGetallbucketverticesWithHttpInfo(platform: kotlin.String) : ApiResponse<GetAllBucketVerticesResult?> { val localVariableConfig = getGetallbucketverticesRequestConfig(platform = platform) return request<Unit, GetAllBucketVerticesResult>( localVariableConfig ) } /** * To obtain the request config of the operation getGetallbucketvertices * * @param platform Name of the platform. I.e. Unreal, Unity * @return RequestConfig */ fun getGetallbucketverticesRequestConfig(platform: kotlin.String) : RequestConfig<Unit> { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>() .apply { put("Platform", listOf(platform.toString())) } val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, path = "/GetAllBucketVertices", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Grant Avatar Preset Items To User * * @param grantAvatarPresetItemsToUserRequest Request payload (optional) * @return GrantAvatarPresetItemsToUserResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun grantAvatarPresetItemsToUser(grantAvatarPresetItemsToUserRequest: GrantAvatarPresetItemsToUserRequest? = null) : GrantAvatarPresetItemsToUserResult { val localVarResponse = grantAvatarPresetItemsToUserWithHttpInfo(grantAvatarPresetItemsToUserRequest = grantAvatarPresetItemsToUserRequest) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GrantAvatarPresetItemsToUserResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Grant Avatar Preset Items To User * * @param grantAvatarPresetItemsToUserRequest Request payload (optional) * @return ApiResponse<GrantAvatarPresetItemsToUserResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun grantAvatarPresetItemsToUserWithHttpInfo(grantAvatarPresetItemsToUserRequest: GrantAvatarPresetItemsToUserRequest?) : ApiResponse<GrantAvatarPresetItemsToUserResult?> { val localVariableConfig = grantAvatarPresetItemsToUserRequestConfig(grantAvatarPresetItemsToUserRequest = grantAvatarPresetItemsToUserRequest) return request<GrantAvatarPresetItemsToUserRequest, GrantAvatarPresetItemsToUserResult>( localVariableConfig ) } /** * To obtain the request config of the operation grantAvatarPresetItemsToUser * * @param grantAvatarPresetItemsToUserRequest Request payload (optional) * @return RequestConfig */ fun grantAvatarPresetItemsToUserRequestConfig(grantAvatarPresetItemsToUserRequest: GrantAvatarPresetItemsToUserRequest?) : RequestConfig<GrantAvatarPresetItemsToUserRequest> { val localVariableBody = grantAvatarPresetItemsToUserRequest val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.POST, path = "/GrantAvatarPresetItemsToUser", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Grant Avatar Preset To User * * @param grantAvatarPresetToUserRequest (optional) * @return GrantAvatarPresetToUserResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun grantAvatarPresetToUser(grantAvatarPresetToUserRequest: GrantAvatarPresetToUserRequest? = null) : GrantAvatarPresetToUserResult { val localVarResponse = grantAvatarPresetToUserWithHttpInfo(grantAvatarPresetToUserRequest = grantAvatarPresetToUserRequest) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as GrantAvatarPresetToUserResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Grant Avatar Preset To User * * @param grantAvatarPresetToUserRequest (optional) * @return ApiResponse<GrantAvatarPresetToUserResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun grantAvatarPresetToUserWithHttpInfo(grantAvatarPresetToUserRequest: GrantAvatarPresetToUserRequest?) : ApiResponse<GrantAvatarPresetToUserResult?> { val localVariableConfig = grantAvatarPresetToUserRequestConfig(grantAvatarPresetToUserRequest = grantAvatarPresetToUserRequest) return request<GrantAvatarPresetToUserRequest, GrantAvatarPresetToUserResult>( localVariableConfig ) } /** * To obtain the request config of the operation grantAvatarPresetToUser * * @param grantAvatarPresetToUserRequest (optional) * @return RequestConfig */ fun grantAvatarPresetToUserRequestConfig(grantAvatarPresetToUserRequest: GrantAvatarPresetToUserRequest?) : RequestConfig<GrantAvatarPresetToUserRequest> { val localVariableBody = grantAvatarPresetToUserRequest val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.POST, path = "/GrantAvatarPresetToUser", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Render Avatar Image * * @param renderAvatarImageRequest (optional) * @return RenderAvatarImageResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun renderAvatarImage(renderAvatarImageRequest: RenderAvatarImageRequest? = null) : RenderAvatarImageResult { val localVarResponse = renderAvatarImageWithHttpInfo(renderAvatarImageRequest = renderAvatarImageRequest) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as RenderAvatarImageResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Render Avatar Image * * @param renderAvatarImageRequest (optional) * @return ApiResponse<RenderAvatarImageResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun renderAvatarImageWithHttpInfo(renderAvatarImageRequest: RenderAvatarImageRequest?) : ApiResponse<RenderAvatarImageResult?> { val localVariableConfig = renderAvatarImageRequestConfig(renderAvatarImageRequest = renderAvatarImageRequest) return request<RenderAvatarImageRequest, RenderAvatarImageResult>( localVariableConfig ) } /** * To obtain the request config of the operation renderAvatarImage * * @param renderAvatarImageRequest (optional) * @return RequestConfig */ fun renderAvatarImageRequestConfig(renderAvatarImageRequest: RenderAvatarImageRequest?) : RequestConfig<RenderAvatarImageRequest> { val localVariableBody = renderAvatarImageRequest val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.POST, path = "/RenderAvatarImage", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } /** * Sync Avatars * Creates missing avatars into the mentioned platform for the user * @param syncAvatarsRequest (optional) * @return SyncAvatarsResult * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception * @throws UnsupportedOperationException If the API returns an informational or redirection response * @throws ClientException If the API returns a client error response * @throws ServerException If the API returns a server error response */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun syncAvatars(syncAvatarsRequest: SyncAvatarsRequest? = null) : SyncAvatarsResult { val localVarResponse = syncAvatarsWithHttpInfo(syncAvatarsRequest = syncAvatarsRequest) return when (localVarResponse.responseType) { ResponseType.Success -> (localVarResponse as Success<*>).data as SyncAvatarsResult ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") ResponseType.ClientError -> { val localVarError = localVarResponse as ClientError<*> throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } ResponseType.ServerError -> { val localVarError = localVarResponse as ServerError<*> throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) } } } /** * Sync Avatars * Creates missing avatars into the mentioned platform for the user * @param syncAvatarsRequest (optional) * @return ApiResponse<SyncAvatarsResult?> * @throws IllegalStateException If the request is not correctly configured * @throws IOException Rethrows the OkHttp execute method exception */ @Suppress("UNCHECKED_CAST") @Throws(IllegalStateException::class, IOException::class) fun syncAvatarsWithHttpInfo(syncAvatarsRequest: SyncAvatarsRequest?) : ApiResponse<SyncAvatarsResult?> { val localVariableConfig = syncAvatarsRequestConfig(syncAvatarsRequest = syncAvatarsRequest) return request<SyncAvatarsRequest, SyncAvatarsResult>( localVariableConfig ) } /** * To obtain the request config of the operation syncAvatars * * @param syncAvatarsRequest (optional) * @return RequestConfig */ fun syncAvatarsRequestConfig(syncAvatarsRequest: SyncAvatarsRequest?) : RequestConfig<SyncAvatarsRequest> { val localVariableBody = syncAvatarsRequest val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap<String, String> = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.POST, path = "/SyncAvatars", query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, body = localVariableBody ) } private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] }
0
Kotlin
0
1
e340350f2c70e1020d2f3330229ac74d9b59fda2
47,017
avataryug-sdk-for-kotlin
Apache License 2.0
desktop/ConstraintLayoutInspector/app/src/androidx/constraintLayout/desktop/link/LayoutView.kt
zhaopengpeng025
385,005,083
true
{"Java": 4619891, "Kotlin": 368933, "Shell": 1512}
/* * Copyright 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 androidx.constraintLayout.desktop.link import androidx.constraintLayout.desktop.scan.KeyFrameNodes import androidx.constraintLayout.desktop.scan.WidgetFrameUtils import androidx.constraintLayout.desktop.ui.timeline.TimeLinePanel import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector.TimeLineCmd import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector.TimeLineListener import androidx.constraintLayout.desktop.utils.Desk import androidx.constraintlayout.core.motion.utils.Utils import androidx.constraintlayout.core.parser.CLKey import androidx.constraintlayout.core.parser.CLObject import androidx.constraintlayout.core.parser.CLParser import androidx.constraintlayout.core.state.WidgetFrame import java.awt.* import java.awt.geom.Path2D import javax.swing.JFrame import javax.swing.JPanel class LayoutView(link: MotionLink) : JPanel(BorderLayout()) { var widgets = ArrayList<Widget>() var zoom = 0.9f val motionLink = link var mTimeLinePanel: TimeLinePanel? = null var mSceneString: String? = null data class Widget(val id: String, val key: CLKey) { var interpolated = WidgetFrame() var start = WidgetFrame() var end = WidgetFrame() var name = "unknown"; var path = Path2D.Float() val drawFont = Font("Helvetica", Font.ITALIC, 32) val keyFrames = KeyFrameNodes() init { name = key.content() val sections = key.value as CLObject val count = sections.size() for (i in 0 until count) { val sec = sections[i] as CLKey when (sec.content()) { "start" -> WidgetFrameUtils.deserialize(sec, end) "end" -> WidgetFrameUtils.deserialize(sec, start) "interpolated" -> WidgetFrameUtils.deserialize(sec, interpolated) "path" -> WidgetFrameUtils.getPath(sec, path) "keyPos" -> keyFrames.setKeyFramesPos(sec) "keyTypes" -> keyFrames.setKeyFramesTypes(sec) "keyFrames" -> keyFrames.setKeyFramesProgress(sec) } } } fun width(): Int { return interpolated.width() } fun height(): Int { return interpolated.height() } fun draw(g: Graphics2D, drawRoot: Boolean) { val END_LOOK = WidgetFrameUtils.OUTLINE or WidgetFrameUtils.DASH_OUTLINE; g.color = WidgetFrameUtils.theme.startColor() WidgetFrameUtils.render(start, g, END_LOOK); keyFrames.render(g) g.color = WidgetFrameUtils.theme.endColor() WidgetFrameUtils.render(end, g, END_LOOK); g.color = WidgetFrameUtils.theme.pathColor() WidgetFrameUtils.renderPath(path, g); g.color = WidgetFrameUtils.theme.interpolatedColor() var style = WidgetFrameUtils.FILL if (drawRoot) { g.color = WidgetFrameUtils.theme.rootBackgroundColor() } g.font = drawFont style += WidgetFrameUtils.TEXT interpolated.name = name WidgetFrameUtils.render(interpolated, g, style); } } override fun paint(g: Graphics?) { super.paint(g) if (widgets.size == 0) { return } val root = widgets[0] var rootWidth = root.width().toFloat() var rootHeight = root.height().toFloat() var scaleX = width / rootWidth var scaleY = height / rootHeight var offX = 0.0f var offY = 0.0f if (scaleX < scaleY) { scaleY = scaleX } else { scaleX = scaleY } scaleX *= zoom scaleY *= zoom offX = (width - root.width().toFloat() * scaleX) / 2 offY = (height - root.height().toFloat() * scaleY) / 2 g!!.color = WidgetFrameUtils.theme.backgroundColor() g!!.fillRect(0, 0, width, height) val g2 = g as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.translate(offX.toDouble(), offY.toDouble()) g2.scale(scaleX.toDouble(), scaleY.toDouble()) for (widget in widgets) { widget.draw(g2, widget == root) } } fun showTimeLine() { if (mTimeLinePanel == null && mSceneString != null) { mTimeLinePanel = TimeLinePanel.showTimeline(mSceneString) mTimeLinePanel?.addTimeLineListener { cmd: TimeLineCmd?, pos: Float -> motionLink.sendProgress(pos) } } else { mTimeLinePanel?.popUp() } } fun hideTimeLine() { mTimeLinePanel?.popDown() } fun setSceneString(str : String) { mSceneString = str } fun setLayoutInformation(information: String) { if (information.trim().isEmpty()) { return } try { val list = CLParser.parse(information) widgets.clear() for (i in 0 until list.size()) { val widget = list[i] if (widget is CLKey) { val widgetId = widget.content() widgets.add(Widget(widgetId, widget)) } } repaint() } catch (e : Exception) { e.printStackTrace() } } companion object { fun showLayoutView(link: MotionLink): LayoutView? { val frame = JFrame("Layout Inspector") val inspector = LayoutInspector(link) frame.contentPane = inspector Desk.rememberPosition(frame, null) frame.isVisible = true return inspector.layoutView } } }
0
null
0
0
582b571b14b2fb549a891f28edfe8a93d39ce82a
6,412
constraintlayout
Apache License 2.0
app/src/main/java/com/kylecorry/trail_sense/tools/weather/ui/fields/PressureWeatherField.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.tools.weather.ui.fields import android.content.Context import com.kylecorry.andromeda.core.system.Resources import com.kylecorry.andromeda.views.list.ListItem import com.kylecorry.andromeda.views.list.ResourceListIcon import com.kylecorry.sol.units.Pressure import com.kylecorry.trail_sense.R import com.kylecorry.trail_sense.shared.FormatService import com.kylecorry.trail_sense.shared.Units import com.kylecorry.trail_sense.shared.UserPreferences class PressureWeatherField(private val pressure: Pressure?) : WeatherField { override fun getListItem(context: Context): ListItem? { pressure ?: return null val formatter = FormatService.getInstance(context) val units = UserPreferences(context).pressureUnits val color = Resources.androidTextColorSecondary(context) val value = formatter.formatPressure( pressure.convertTo(units), Units.getDecimalPlaces(units) ) return ListItem( 1, context.getString(R.string.pressure), icon = ResourceListIcon(R.drawable.ic_barometer, color), trailingText = value ) } }
456
null
66
989
41176d17b498b2dcecbbe808fbe2ac638e90d104
1,184
Trail-Sense
MIT License
src/main/kotlin/io/newm/kogmios/protocols/messages/MsgSubmitTxResponse.kt
projectNEWM
469,781,993
false
{"Kotlin": 341920, "Shell": 26}
package io.newm.kogmios.protocols.messages import io.newm.kogmios.protocols.model.result.SubmitTxResult import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Response that comes back from Ogmios after a submitTx message is sent. */ @Serializable @SerialName(MsgSubmitTx.METHOD_SUBMIT_TX) data class MsgSubmitTxResponse( @SerialName("result") override val result: SubmitTxResult, @SerialName("id") override val id: String, ) : JsonRpcSuccessResponse()
0
Kotlin
1
4
74366f8b75ba73db5341df34389eb90b5d2d6ba9
505
kogmios
Apache License 2.0
orbit-core/src/commonMain/kotlin/org/orbitmvi/orbit/ContainerDecorator.kt
orbit-mvi
323,600,732
false
null
/* * Copyright 2021 <NAME> & Appmattus Limited * Copyright 2020 Babylon Partners Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * File modified by <NAME> & Appmattus Limited * See: https://github.com/orbit-mvi/orbit-mvi/compare/c5b8b3f2b83b5972ba2ad98f73f75086a89653d3...main */ package org.orbitmvi.orbit import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import org.orbitmvi.orbit.annotation.OrbitExperimental import org.orbitmvi.orbit.syntax.ContainerContext /** * A decorator applying additional logic to a [Container]. * * @param STATE The container's state type. * @param SIDE_EFFECT The type of side effects posted by this container. Can be [Nothing] if this * container never posts side effects. */ public interface ContainerDecorator<STATE : Any, SIDE_EFFECT : Any> : Container<STATE, SIDE_EFFECT> { /** * The wrapped container. */ public val actual: Container<STATE, SIDE_EFFECT> override val settings: RealSettings get() = actual.settings override val stateFlow: StateFlow<STATE> get() = actual.stateFlow override val sideEffectFlow: Flow<SIDE_EFFECT> get() = actual.sideEffectFlow override suspend fun orbit(orbitIntent: suspend ContainerContext<STATE, SIDE_EFFECT>.() -> Unit) { actual.orbit(orbitIntent) } @OptIn(OrbitExperimental::class) override suspend fun inlineOrbit(orbitIntent: suspend ContainerContext<STATE, SIDE_EFFECT>.() -> Unit) { actual.inlineOrbit(orbitIntent) } }
31
null
55
865
0d7a4aedb1044d9c422a25e76ad8e6a84ae3fa50
2,045
orbit-mvi
Apache License 2.0
src/main/kotlin/com/tiquionophist/ui/ApplicationPreferences.kt
tiquionophist
405,590,882
false
{"Kotlin": 283918}
package com.tiquionophist.ui import androidx.compose.runtime.mutableStateOf import java.io.File import java.util.prefs.Preferences import kotlin.reflect.KProperty /** * Stores application-wide preferences which should be persisted between runs of the application. */ object ApplicationPreferences { private val prefs = Preferences.userNodeForPackage(ApplicationPreferences::class.java) /** * Whether the application should be in light mode. * * TODO use isSystemInDarkTheme() as the default (non-trivial since it's @Composable) */ var lightMode: Boolean by BooleanPropertyDelegate(prefs = prefs, propertyName = "light_mode", defaultValue = true) /** * The default directory to open when choosing a file, or null if it has not been set. */ var fileChooserDirectory: File? by FilePropertyDelegate(prefs = prefs, propertyName = "file_chooser_directory") /** * Delegates a boolean preference from [prefs], also storing it in a [MutableState] so that changes trigger a * recomposition. */ private class BooleanPropertyDelegate(val prefs: Preferences, val propertyName: String, defaultValue: Boolean) { private val state = mutableStateOf(prefs.getBoolean(propertyName, defaultValue)) operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean { return state.value } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) { prefs.putBoolean(propertyName, value) state.value = value } } /** * Delegates a [File] preference from [prefs]. */ private class FilePropertyDelegate(val prefs: Preferences, val propertyName: String) { operator fun getValue(thisRef: Any?, property: KProperty<*>): File? { return prefs.get(propertyName, "") .takeIf { it.isNotEmpty() } ?.let { File(it) } ?.takeIf { it.exists() } } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: File?) { if (value == null) { prefs.remove(propertyName) } else { prefs.put(propertyName, value.normalize().absolutePath) } } } }
1
Kotlin
0
5
18fa40446c0828d3251f89777292a2f8c4f8f3b9
2,275
hhs-scheduler
MIT License
solar/src/main/java/com/chiksmedina/solar/boldduotone/security/Incognito.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.boldduotone.security import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.boldduotone.SecurityGroup val SecurityGroup.Incognito: ImageVector get() { if (_incognito != null) { return _incognito!! } _incognito = Builder( name = "Incognito", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(21.0f, 16.5f) curveTo(21.0f, 18.433f, 19.433f, 20.0f, 17.5f, 20.0f) curveTo(15.567f, 20.0f, 14.0f, 18.433f, 14.0f, 16.5f) curveTo(14.0f, 14.567f, 15.567f, 13.0f, 17.5f, 13.0f) curveTo(19.433f, 13.0f, 21.0f, 14.567f, 21.0f, 16.5f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(1.25f, 10.0f) curveTo(1.25f, 9.5858f, 1.5858f, 9.25f, 2.0f, 9.25f) horizontalLineTo(22.0f) curveTo(22.4142f, 9.25f, 22.75f, 9.5858f, 22.75f, 10.0f) curveTo(22.75f, 10.4142f, 22.4142f, 10.75f, 22.0f, 10.75f) horizontalLineTo(2.0f) curveTo(1.5858f, 10.75f, 1.25f, 10.4142f, 1.25f, 10.0f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(4.1875f, 9.25f) lineTo(4.6138f, 7.5448f) curveTo(5.1595f, 5.3621f, 5.4323f, 4.2708f, 6.2461f, 3.6354f) curveTo(7.0599f, 3.0f, 8.1848f, 3.0f, 10.4347f, 3.0f) horizontalLineTo(13.5653f) curveTo(15.8152f, 3.0f, 16.9401f, 3.0f, 17.7539f, 3.6354f) curveTo(18.5677f, 4.2708f, 18.8405f, 5.3621f, 19.3862f, 7.5448f) lineTo(19.8125f, 9.25f) horizontalLineTo(4.1875f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(10.0f, 16.5f) curveTo(10.0f, 18.433f, 8.433f, 20.0f, 6.5f, 20.0f) curveTo(4.567f, 20.0f, 3.0f, 18.433f, 3.0f, 16.5f) curveTo(3.0f, 14.567f, 4.567f, 13.0f, 6.5f, 13.0f) curveTo(8.433f, 13.0f, 10.0f, 14.567f, 10.0f, 16.5f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(9.884f, 17.3966f) curveTo(9.9596f, 17.1104f, 9.9999f, 16.8099f, 9.9999f, 16.5f) curveTo(9.9999f, 16.2272f, 9.9687f, 15.9616f, 9.9096f, 15.7067f) lineTo(10.3232f, 15.4999f) curveTo(11.379f, 14.972f, 12.6216f, 14.972f, 13.6773f, 15.4999f) lineTo(14.0903f, 15.7064f) curveTo(14.0312f, 15.9614f, 13.9999f, 16.227f, 13.9999f, 16.5f) curveTo(13.9999f, 16.8098f, 14.0402f, 17.1101f, 14.1157f, 17.3961f) lineTo(13.0065f, 16.8415f) curveTo(12.3731f, 16.5248f, 11.6275f, 16.5248f, 10.9941f, 16.8415f) lineTo(9.884f, 17.3966f) close() } } .build() return _incognito!! } private var _incognito: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
4,846
SolarIconSetAndroid
MIT License
src/main/kotlin/com/github/hooll/commands/subCommands/CommandSell.kt
hooll
504,188,789
false
{"Kotlin": 28676}
package com.github.hooll.commands.subCommands import com.github.hooll.api.ZheFishApi import com.github.hooll.info import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack import taboolib.common.platform.command.subCommand import taboolib.platform.compat.VaultService import taboolib.platform.util.isAir object CommandSell { private fun ItemStack.isE(itemStack: ItemStack):Boolean{ if (this.isAir || itemStack.isAir){ return false } val a = this.clone() a.amount = 1 val b = itemStack.clone() b.amount = 1 return a == b } val command = subCommand { execute<Player> { sender, _, _ -> var money = 0.0 ZheFishApi.fishes.toList().forEach { data-> var num = 0 if (data.canSell){ sender.inventory.contents.forEach { if (it!=null&& it.isE(data.itemStack)){ num += it.amount it.amount = 0 } } money += num * data.price } } VaultService.economy?.depositPlayer(sender,money) sender.info("Info-SellSuccess",money) } } }
0
Kotlin
0
1
343ccdb14e340a85ad162270c6135b22a86d19d9
1,297
ZheFish
Creative Commons Zero v1.0 Universal
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/database/table/MoneyHiddenTable.kt
Nyrheim
269,929,653
true
{"Gradle": 71, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "YAML": 103, "Kotlin": 1043, "Java": 291, "HTML": 23, "CSS": 2, "JavaScript": 1}
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.economy.bukkit.database.table import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.economy.bukkit.RPKEconomyBukkit import com.rpkit.economy.bukkit.character.MoneyHidden import com.rpkit.economy.bukkit.database.jooq.rpkit.Tables.MONEY_HIDDEN import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents the money hidden table. */ class MoneyHiddenTable(database: Database, private val plugin: RPKEconomyBukkit): Table<MoneyHidden>(database, MoneyHidden::class) { private val cache = if (plugin.config.getBoolean("caching.money_hidden.id.enabled")) { database.cacheManager.createCache("rpk-economy-bukkit.money_hidden.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, MoneyHidden::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.money_hidden.id.size"))).build()) } else { null } private val characterCache = if (plugin.config.getBoolean("caching.money_hidden.character_id.enabled")) { database.cacheManager.createCache("rpk-economy-bukkit.money_hidden.character_id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, Int::class.javaObjectType, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.money_hidden.character_id.size"))).build()) } else { null } override fun create() { database.create .createTableIfNotExists(MONEY_HIDDEN) .column(MONEY_HIDDEN.ID, SQLDataType.INTEGER.identity(true)) .column(MONEY_HIDDEN.CHARACTER_ID, SQLDataType.INTEGER) .constraints( constraint("pk_money_hidden").primaryKey(MONEY_HIDDEN.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.4.0") } } override fun insert(entity: MoneyHidden): Int { database.create .insertInto( MONEY_HIDDEN, MONEY_HIDDEN.CHARACTER_ID ) .values( entity.character.id ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) characterCache?.put(entity.character.id, id) return id } override fun update(entity: MoneyHidden) { database.create .update(MONEY_HIDDEN) .set(MONEY_HIDDEN.CHARACTER_ID, entity.character.id) .where(MONEY_HIDDEN.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) characterCache?.put(entity.character.id, entity.id) } override fun get(id: Int): MoneyHidden? { if (cache?.containsKey(id) == true) { return cache.get(id) } else { val result = database.create .select(MONEY_HIDDEN.CHARACTER_ID) .from(MONEY_HIDDEN) .where(MONEY_HIDDEN.ID.eq(id)) .fetchOne() ?: return null val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val characterId = result.get(MONEY_HIDDEN.CHARACTER_ID) val character = characterProvider.getCharacter(characterId) if (character != null) { val moneyHidden = MoneyHidden( id, character ) cache?.put(id, moneyHidden) characterCache?.put(moneyHidden.character.id, id) return moneyHidden } else { characterCache?.remove(characterId) database.create .deleteFrom(MONEY_HIDDEN) .where(MONEY_HIDDEN.ID.eq(id)) .execute() return null } } } /** * Gets the money hidden instance for a character. * If there is no money hidden row for the character, null is returned. * * @param character The character * @return The money hidden instance, or null if there is no money hidden instance for the character */ fun get(character: RPKCharacter): MoneyHidden? { if (characterCache?.containsKey(character.id) == true) { return get(characterCache.get(character.id)) } else { val result = database.create .select(MONEY_HIDDEN.ID) .from(MONEY_HIDDEN) .where(MONEY_HIDDEN.CHARACTER_ID.eq(character.id)) .fetchOne() ?: return null return get(result.get(MONEY_HIDDEN.ID)) } } override fun delete(entity: MoneyHidden) { database.create .deleteFrom(MONEY_HIDDEN) .where(MONEY_HIDDEN.ID.eq(entity.id)) .execute() cache?.remove(entity.id) characterCache?.remove(entity.character.id) } }
0
null
0
0
f2196a76e0822b2c60e4a551de317ed717bbdc7e
6,088
RPKit
Apache License 2.0
src/main/kotlin/br/com/jiratorio/aspect/BenchMarkAspect.kt
andrelugomes
230,294,644
true
{"Kotlin": 541514, "PLSQL": 366, "Dockerfile": 315, "TSQL": 269}
package br.com.jiratorio.aspect import br.com.jiratorio.extension.log import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.aspectj.lang.annotation.Aspect import org.springframework.stereotype.Component import org.springframework.util.StopWatch @Aspect @Component class BenchMarkAspect { @Around("@annotation(br.com.jiratorio.aspect.annotation.ExecutionTime)") fun around(proceedingJoinPoint: ProceedingJoinPoint): Any? { val stopWatch = StopWatch(proceedingJoinPoint.signature.declaringType.simpleName) try { stopWatch.start(proceedingJoinPoint.signature.name) return proceedingJoinPoint.proceed() } finally { stopWatch.stop() log.info( "Aspect=BenchMarkAspect, operation={}#{}, executionTime={}", stopWatch.id, stopWatch.lastTaskName, stopWatch.lastTaskTimeMillis ) } } }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
959
jirareport
MIT License
src/main/kotlin/br/com/jiratorio/aspect/BenchMarkAspect.kt
andrelugomes
230,294,644
true
{"Kotlin": 541514, "PLSQL": 366, "Dockerfile": 315, "TSQL": 269}
package br.com.jiratorio.aspect import br.com.jiratorio.extension.log import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation.Around import org.aspectj.lang.annotation.Aspect import org.springframework.stereotype.Component import org.springframework.util.StopWatch @Aspect @Component class BenchMarkAspect { @Around("@annotation(br.com.jiratorio.aspect.annotation.ExecutionTime)") fun around(proceedingJoinPoint: ProceedingJoinPoint): Any? { val stopWatch = StopWatch(proceedingJoinPoint.signature.declaringType.simpleName) try { stopWatch.start(proceedingJoinPoint.signature.name) return proceedingJoinPoint.proceed() } finally { stopWatch.stop() log.info( "Aspect=BenchMarkAspect, operation={}#{}, executionTime={}", stopWatch.id, stopWatch.lastTaskName, stopWatch.lastTaskTimeMillis ) } } }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
959
jirareport
MIT License
core/filters/src/main/java/ru/tech/imageresizershrinker/core/filters/domain/model/WaterParams.kt
T8RIN
478,710,402
false
{"Kotlin": 6498864}
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.core.filters.domain.model data class WaterParams( val fractionSize: Float = 0.2f, val frequencyX: Float = 2f, val frequencyY: Float = 2f, val amplitudeX: Float = 0.5f, val amplitudeY: Float = 0.5f, )
10
Kotlin
176
3,817
486410d4a9ea3c832fc5aa63eb5bdc7b1fab871d
972
ImageToolbox
Apache License 2.0
data/sqldelight/src/nonAndroidMain/kotlin/com/taetae98/codelab/data/sqldelight/MemoLocalDataSourceImpl.kt
taetae98coding
708,459,882
false
{"Kotlin": 140653, "Swift": 1267, "HTML": 233, "Ruby": 109}
package com.taetae98.codelab.data.sqldelight import app.cash.paging.PagingSource import app.cash.sqldelight.paging3.QueryPagingSource import com.taetae98.codelab.data.dto.MemoDto import com.taetae98.codelab.data.local.MemoLocalDataSource import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.koin.core.annotation.Factory import org.koin.core.annotation.Named @Factory internal class MemoLocalDataSourceImpl( private val memoDatabase: MemoDatabase, @Named(SqldelightLocalDataSourceModule.DATABASE_DISPATCHER) private val databaseDispatcher: CoroutineDispatcher ) : MemoLocalDataSource { override suspend fun upsert(memo: MemoDto) { withContext(databaseDispatcher) { if (memo.id == 0L) { memoDatabase.memoEntityQueries.insert(null, memo.title) } else { memoDatabase.memoEntityQueries.upsert(memo.toEntity()) } } } override suspend fun delete(id: Long) { withContext(databaseDispatcher) { memoDatabase.memoEntityQueries.delete(id) } } override fun page(): PagingSource<Int, MemoDto> { val queries = memoDatabase.memoEntityQueries return QueryPagingSource( countQuery = queries.count(), transacter = queries, context = databaseDispatcher, queryProvider = { limit, offset -> queries.paging(limit, offset, ::MemoDto) } ) } }
0
Kotlin
0
0
ff8c88d02ca19066fe0373aa15e27167674dc3ab
1,513
CodeLab
Apache License 2.0
app/src/main/java/com/mollie/checkout/feature/payments/create/CreatePaymentViewModel.kt
mollie
431,494,734
false
{"Kotlin": 74081}
package com.mollie.checkout.feature.payments.create import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.mollie.checkout.R import com.mollie.checkout.data.PaymentsRepository import com.mollie.checkout.data.model.Payment import com.mollie.checkout.feature.base.BaseViewModel class CreatePaymentViewModel : BaseViewModel() { companion object { private val TEST_PRODUCTS = listOf( Pair("Walkman", 19.99), Pair("Goldfish", 2.99), Pair("Back to the future DVD", 6.00), Pair("Running shoes", 49.00), Pair("Haircut for men - appointment", 29.95), Pair("Electric Vehicle", 49_999.00), Pair("Comic book", 7.50), Pair("Game console", 495.00), Pair("Drone", 900.00), Pair("Encyclopedia", 28.99), Pair("Robot arm", 1_450.00), Pair("Virtual reality headset", 599.00), Pair("Smartwatch", 379.95), Pair("Spencer ", 28.75), ) // For testing in production // private val TEST_PRODUCTS = listOf( // Pair("TEST Webuildapps - Mollie example", 0.01), // ) } private val initialProduct = MutableLiveData<Pair<String, Double>?>() fun getInitialProduct(): LiveData<Pair<String, Double>?> = initialProduct fun createPayment(amount: Double?, description: String?): Payment? { if (isLoading().value == true) { Log.d("${this.javaClass}", "Already saving, ignoring") return null } if (amount == null || amount == 0.0) { setError(R.string.create_payment_error_missing_amount) return null } if (description.isNullOrBlank()) { setError(R.string.create_payment_error_missing_description) return null } return Payment( amount = amount, description = description ) } fun load(payment: Payment?) { if (payment == null) { initialProduct.value = TEST_PRODUCTS.random() } else { initialProduct.value = Pair(payment.description, payment.amount) } } suspend fun submit(payment: Payment): Payment? { setLoading(true) val response = PaymentsRepository.createPayment( payment.amount, payment.description, ) if (response.isSuccess()) { // Nothing to do } else { setError(response.getError()) } setLoading(false) return response.getData()?.data } }
1
Kotlin
2
2
fa2ea1801b6ffc11246fa55fc779bc44427b2bba
2,650
demo-checkout-android
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/appmesh/CfnRouteHttpPathMatchPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.appmesh import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.appmesh.CfnRoute /** * An object representing the path to match in the request. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.appmesh.*; * HttpPathMatchProperty httpPathMatchProperty = HttpPathMatchProperty.builder() * .exact("exact") * .regex("regex") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appmesh-route-httppathmatch.html) */ @CdkDslMarker public class CfnRouteHttpPathMatchPropertyDsl { private val cdkBuilder: CfnRoute.HttpPathMatchProperty.Builder = CfnRoute.HttpPathMatchProperty.builder() /** * @param exact The exact path to match on. */ public fun exact(exact: String) { cdkBuilder.exact(exact) } /** * @param regex The regex used to match the path. */ public fun regex(regex: String) { cdkBuilder.regex(regex) } public fun build(): CfnRoute.HttpPathMatchProperty = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
1,403
awscdk-dsl-kotlin
Apache License 2.0
src/commonMain/kotlin/character/classes/priest/specs/Shadow.kt
marisa-ashkandi
332,658,265
false
null
package character.classes.priest.specs import character.Spec import character.SpecEpDelta class Shadow : Spec() { override val name: String = "Shadow" override val epBaseStat: SpecEpDelta = spellPowerBase override val epStatDeltas: List<SpecEpDelta> = defaultCasterDeltas // All sockets are a flat 12 spell damage override fun redSocketEp(deltas: Map<String, Double>): Double { return 12.0 } override fun yellowSocketEp(deltas: Map<String, Double>): Double { return 12.0 } override fun blueSocketEp(deltas: Map<String, Double>): Double { return 12.0 } }
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
623
tbcsim
MIT License
shared/src/commonMain/kotlin/ui/matches/model/MatchesScreenParams.kt
Markable97
658,889,189
false
null
package ui.matches.model sealed class MatchesScreenParams( val title: String, ) { class TeamMatches( val teamName: String, val teamId: Int ) : MatchesScreenParams(teamName) class TournamentMatches( val tournamentName: String, val tournamentId: Int ) : MatchesScreenParams(tournamentName) data class PlayerMatches( val playerName: String, val matches: List<PlayerActionsInMatchUI> ) : MatchesScreenParams(playerName) } /*data class MatchesScreenParams( val title: String, val teamId: Int? = null, val tournamentId: Int? = null )*/
0
Kotlin
0
1
01b18bf170eb206ffdf27bf71e7bcf6f62ab1e78
622
SportCommunityKMM
Apache License 2.0
bindings/core/gio/src/nativeMain/kotlin/org/gtkkn/bindings/gio/StaticResource.kt
gtk-kn
609,191,895
false
{"Kotlin": 10448515, "Shell": 2740}
// This is a generated file. Do not modify. package org.gtkkn.bindings.gio import kotlinx.cinterop.CPointed import kotlinx.cinterop.CPointer import kotlinx.cinterop.reinterpret import org.gtkkn.extensions.glib.Record import org.gtkkn.extensions.glib.RecordCompanion import org.gtkkn.native.gio.GStaticResource import org.gtkkn.native.gio.g_static_resource_fini import org.gtkkn.native.gio.g_static_resource_get_resource import org.gtkkn.native.gio.g_static_resource_init import kotlin.Unit /** * #GStaticResource is an opaque data structure and can only be accessed * using the following functions. * * ## Skipped during bindings generation * * - field `data`: Record field data is private * - field `data_len`: Record field data_len is private * - field `resource`: Record field resource is private * - field `next`: Record field next is private * - field `padding`: Record field padding is private */ public class StaticResource( pointer: CPointer<GStaticResource>, ) : Record { public val gioStaticResourcePointer: CPointer<GStaticResource> = pointer /** * Finalized a GResource initialized by g_static_resource_init(). * * This is normally used by code generated by * [glib-compile-resources][glib-compile-resources] * and is not typically used by other code. * * @since 2.32 */ public fun fini(): Unit = g_static_resource_fini(gioStaticResourcePointer.reinterpret()) /** * Gets the GResource that was registered by a call to g_static_resource_init(). * * This is normally used by code generated by * [glib-compile-resources][glib-compile-resources] * and is not typically used by other code. * * @return a #GResource * @since 2.32 */ public fun getResource(): Resource = g_static_resource_get_resource(gioStaticResourcePointer.reinterpret())!!.run { Resource(reinterpret()) } /** * Initializes a GResource from static data using a * GStaticResource. * * This is normally used by code generated by * [glib-compile-resources][glib-compile-resources] * and is not typically used by other code. * * @since 2.32 */ public fun `init`(): Unit = g_static_resource_init(gioStaticResourcePointer.reinterpret()) public companion object : RecordCompanion<StaticResource, GStaticResource> { override fun wrapRecordPointer(pointer: CPointer<out CPointed>): StaticResource = StaticResource(pointer.reinterpret()) } }
0
Kotlin
0
13
c033c245f1501134c5b9b46212cd153c61f7efea
2,542
gtk-kn
Creative Commons Attribution 4.0 International
library/src/main/java/fr/baiget/simplenumberpicker/decimal/DecimalPickerDialog.kt
StephaneBg
84,314,738
false
null
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sbgapps.simplenumberpicker.decimal import android.annotation.SuppressLint import android.app.Dialog import android.content.DialogInterface import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.View import android.widget.ImageButton import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.sbgapps.simplenumberpicker.R import com.sbgapps.simplenumberpicker.utils.color import com.sbgapps.simplenumberpicker.utils.getThemeAccentColor import com.sbgapps.simplenumberpicker.utils.makeSelector import java.text.DecimalFormatSymbols class DecimalPickerDialog : DialogFragment() { private lateinit var dialog: AlertDialog private lateinit var numberTextView: TextView private lateinit var backspaceButton: ImageButton private lateinit var decimalSeparator: String private var reference = DEFAULT_REFERENCE private var relative = true private var natural = false private var style = R.style.SimpleNumberPickerTheme override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.let { assignArguments(savedInstanceState) } ?: run { arguments?.let { assignArguments(it) } } setStyle(DialogFragment.STYLE_NO_TITLE, style) isCancelable = false } @SuppressLint("SetTextI18n", "InflateParams") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val attributes = requireContext().obtainStyledAttributes(style, R.styleable.SimpleNumberPicker) val view = requireActivity().layoutInflater .inflate(R.layout.snp_dialog_decimal_picker, null) // Init number var color = attributes.getColor( R.styleable.SimpleNumberPicker_snpKeyColor, requireContext().color(android.R.color.secondary_text_light) ) numberTextView = view.findViewById(R.id.tv_number) numberTextView.setTextColor(color) if (savedInstanceState?.containsKey(ARG_SAVED_VALUE) == true) numberTextView.text = savedInstanceState.getString(ARG_SAVED_VALUE) // Init backspace color = attributes.getColor( R.styleable.SimpleNumberPicker_snpBackspaceColor, requireContext().color(android.R.color.secondary_text_light) ) backspaceButton = view.findViewById(R.id.key_backspace) backspaceButton.setImageDrawable( makeSelector(requireContext(), R.drawable.snp_ic_backspace_black_24dp, color) ) backspaceButton.setOnClickListener { var number = numberTextView.text.subSequence(0, numberTextView.text.length - 1) if (1 == number.length && '-' == number[0]) number = "" numberTextView.text = number onNumberChanged() } backspaceButton.setOnLongClickListener { numberTextView.text = "" onNumberChanged() true } // Create dialog dialog = AlertDialog.Builder(requireContext(), theme) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> var result = numberTextView.text.toString() if (result.isEmpty()) result = "0" result = result.replace(',', '.') if (result == ".") result = "0" val number = result.toFloat() val activity = activity val fragment = parentFragment when { activity is DecimalPickerHandler -> { activity.onDecimalNumberPicked(reference, number) } fragment is DecimalPickerHandler -> { fragment.onDecimalNumberPicked(reference, number) } } dismiss() } .setNegativeButton(android.R.string.cancel) { _, _ -> dismiss() } .create() // Init dialog color = attributes.getColor( R.styleable.SimpleNumberPicker_snpDialogBackground, requireContext().color(android.R.color.white) ) dialog.window?.setBackgroundDrawable(ColorDrawable(color)) // Init keys val listener = { v: View -> val key = v.tag as Int val id = numberTextView.text.toString() + Integer.toString(key) numberTextView.text = id onNumberChanged() } color = attributes.getColor( R.styleable.SimpleNumberPicker_snpKeyColor, getThemeAccentColor(requireContext()) ) val ids = resources.obtainTypedArray(R.array.snp_key_ids) for (i in 0 until NB_KEYS) { val key = view.findViewById<TextView>(ids.getResourceId(i, -1)) key.tag = i key.setOnClickListener(listener) key.setTextColor(color) } // Init sign val sign = view.findViewById<TextView>(R.id.key_sign) if (relative) { sign.setTextColor(color) sign.setOnClickListener { val number = numberTextView.text.toString() if (number.startsWith("-")) numberTextView.text = number.substring(1) else numberTextView.text = "-$number" onNumberChanged() } } else { sign.visibility = View.INVISIBLE } // Init decimal separator initDecimalSeparator() val separator = view.findViewById<TextView>(R.id.key_point) if (natural) { separator.visibility = View.INVISIBLE } else { separator.text = decimalSeparator separator.setTextColor(color) separator.setOnClickListener { if (numberTextView.text.toString().contains(decimalSeparator)) return@setOnClickListener val number = numberTextView.text.toString() numberTextView.text = number + decimalSeparator onNumberChanged() } } ids.recycle() attributes.recycle() return dialog } override fun onStart() { super.onStart() onNumberChanged() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) with(outState) { putInt(ARG_REFERENCE, reference) putBoolean(ARG_RELATIVE, relative) putBoolean(ARG_NATURAL, natural) putInt(ARG_STYLE, theme) putString(ARG_SAVED_VALUE, numberTextView.text.toString()) } } private fun onNumberChanged() { backspaceButton.isEnabled = 0 != numberTextView.length() if (numberTextView.text.isEmpty()) { dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = false } else { dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = !(1 == numberTextView.text.length && '-' == numberTextView.text[0]) } } private fun initDecimalSeparator() { val formatSymbols = DecimalFormatSymbols() decimalSeparator = "" + formatSymbols.decimalSeparator } private fun assignArguments(args: Bundle) { if (args.containsKey(ARG_REFERENCE)) reference = args.getInt(ARG_REFERENCE) if (args.containsKey(ARG_RELATIVE)) relative = args.getBoolean(ARG_RELATIVE) if (args.containsKey(ARG_NATURAL)) natural = args.getBoolean(ARG_NATURAL) if (args.containsKey(ARG_STYLE)) style = args.getInt(ARG_STYLE) } class Builder { private var reference = DEFAULT_REFERENCE private var relative = true private var natural = false private var theme = R.style.SimpleNumberPickerTheme fun setReference(reference: Int): Builder { this.reference = reference return this } fun setRelative(relative: Boolean): Builder { this.relative = relative return this } fun setNatural(natural: Boolean): Builder { this.natural = natural return this } fun setTheme(theme: Int): Builder { this.theme = theme return this } fun create(): DecimalPickerDialog { return newInstance(reference, relative, natural, theme) } } companion object { private const val ARG_REFERENCE = "ARG_REFERENCE" private const val ARG_RELATIVE = "ARG_RELATIVE" private const val ARG_NATURAL = "ARG_NATURAL" private const val ARG_STYLE = "ARG_STYLE" private const val ARG_SAVED_VALUE = "ARG_SAVED_VALUE" private const val NB_KEYS = 10 private const val DEFAULT_REFERENCE = 0 private fun newInstance( reference: Int, relative: Boolean, natural: Boolean, theme: Int ): DecimalPickerDialog { return DecimalPickerDialog().apply { arguments = Bundle().apply { putInt(ARG_REFERENCE, reference) putBoolean(ARG_RELATIVE, relative) putBoolean(ARG_NATURAL, natural) putInt(ARG_STYLE, theme) } } } } }
1
null
25
182
28a5f88c85521bee2f4b57f49e067f2974963332
10,023
SimpleNumberPicker
Apache License 2.0
shared/core/kotlin/com/github/salomonbrys/kodein/internal/CMap.kt
suclike
123,946,819
true
{"Kotlin": 367343, "Java": 15376, "Shell": 723, "HTML": 718}
package com.github.salomonbrys.kodein.internal import com.github.salomonbrys.kodein.bindings.Binding import com.github.salomonbrys.kodein.Kodein /** * Behaves like a `Map<Kodein.Key, Binding<*, Any>>`, but with some extra caching. * * Each time a new entry is added, the entry is put as-is in the [_map]. * If the keys's [Kodein.Key.argType] is a `ParameterizedType` that is entirely wildcard, then the [_raws] map is given an entry with it's raw type. * For example, when adding a factory with a key's argType being `List<*>`, the same factory will be added to the [_raws] map associated with a slightly different key: argType being the class `List`. * However, when adding a factory with a key's argType being `List<String>`, nothing will be added to the [_raws] map. */ internal class CMap { /** * The regular map associating keys to factories */ private val _map = HashMap<Kodein.Key<*, *>, Binding<*, *>>() // Inverse order ! private val _overrides = HashMap<Kodein.Key<*, *>, ArrayList<Binding<*, *>>>() /** * A map that contains "raws" version of keys in [_map] whose [Kodein.Key.argType] are `ParameterizedType`. */ private val _raws = HashMap<Kodein.Key<*, *>, Binding<*, *>>() /** * Get the factory associated with the given key, either from the regular map, or from the raw pre-cache. * * @param key The key of the factory to retrieve. * @return The factory, or null if none was found. */ operator fun get(key: Kodein.Key<*, *>) : Binding<*, *>? { _map[key]?.let { return it } _raws[key]?.let { return it } return null } fun getOverride(key: Kodein.Key<*, *>, overrideLevel: Int) : Binding<*, *>? { _overrides[key]?.let { val level = it.size - overrideLevel - 1 if (level < 0) return null return it.getOrNull(level) } return null } /** * Returns whether a key can be found in the [_map]. * * Because [_raws] is implicitly created, it is not looked into. * * @param key The key to look for. * @return Whether or not the key is in the [_map]. */ infix operator fun contains(key: Kodein.Key<*, *>) = _map.contains(key) /** * Adds a binding to the map. * * Adds the [key] and [binding] as-is into the [_map]. * If the [key]'s [Kodein.Key.argType] is a `ParameterizedType` that is entirely wildcard, then the [_raws] map is given an entry with it's raw type. * * @param key The key to add. * @param key The associated binding to add. */ operator fun set(key: Kodein.Key<*, *>, binding: Binding<*, *>) { val overridden = _map.put(key, binding) if (overridden != null) _overrides.getOrPut(key, { ArrayList() }).add(overridden) val rawArgType = key.argType.getRawIfWildcard() if (rawArgType != null) _raws[Kodein.Key(key.bind, rawArgType)] = binding } /** * Copies all of the mappings from the specified map to this map. * * @param bindings mappings to be stored in this map. */ fun putAll(bindings: Map<Kodein.Key<*, *>, Binding<*, *>>) { for ((key, factory) in bindings) set(key, factory) } /** * Wrapper that makes a map truly immutable, even in Java (Kotlin will throw an exception when trying to mutate). */ private class ImmutableMapView<K : Any, out V : Any>(private val _base: Map<K, V>) : Map<K, V> by _base /** * An immutable view of the [_map]. */ val bindings: Map<Kodein.Key<*, *>, Binding<*, *>> = ImmutableMapView(_map) val overrides: Map<Kodein.Key<*, *>, List<Binding<*, *>>> = ImmutableMapView(_overrides) }
0
Kotlin
0
0
b82605d7b3750f9a98c3a4aad91a9fd6f0de7818
3,782
Kodein
MIT License
subprojects/gradle/build-metrics/src/main/kotlin/com/avito/android/plugin/build_metrics/CollectTeamcityMetricsAction.kt
matzuk
257,593,222
true
{"Kotlin": 2509850, "Shell": 16022, "Python": 14063, "Dockerfile": 7151, "Makefile": 2131}
package com.avito.android.plugin.build_metrics import com.avito.android.graphite.GraphiteMetric import com.avito.android.graphite.GraphiteSender import com.avito.android.stats.graphiteSeries import com.avito.android.stats.graphiteSeriesElement import com.avito.teamcity.TeamcityApi import org.jetbrains.teamcity.rest.Build import java.time.Duration @Suppress("UnstableApiUsage") class CollectTeamcityMetricsAction( val buildId: String, private val teamcityApi: TeamcityApi, private val graphite: GraphiteSender ) { fun execute() { val build = teamcityApi.getBuild(buildId) sendMetric(build) } private fun sendMetric(build: Build) { val buildId = graphiteSeriesElement(build.id.stringId) val buildTypeId = graphiteSeries(build.buildConfigurationId.stringId) val buildStatus = graphiteSeriesElement(build.status?.name ?: "unknown") val duration = Duration.between(build.startDateTime, build.finishDateTime) // We use a redundant structure only for compatibility reasons val path = "ci.builds.teamcity.duration" + ".build_type_id.${buildTypeId}" + ".id.${buildId}" + ".agent._" + ".state._" + ".status.${buildStatus}" + "._._._._" graphite.send(GraphiteMetric(path, duration.seconds.toString(), build.startDateTime!!.toEpochSecond())) } }
0
null
1
0
796288a25a3a418ff09fe18239b60941e76e4d19
1,413
avito-android
Apache License 2.0
src/main/kotlin/apollointhehouse/betterwithweed/BetterWithWeed.kt
Apollointhehouse
704,758,442
false
{"Kotlin": 9398}
package apollointhehouse.betterwithweed import apollointhehouse.betterwithweed.block.ModBlocks import apollointhehouse.betterwithweed.item.ModItems import net.fabricmc.api.ModInitializer import org.slf4j.Logger import org.slf4j.LoggerFactory object BetterWithWeed: ModInitializer { const val MOD_ID: String = "betterwithweed" val LOGGER: Logger = LoggerFactory.getLogger(MOD_ID) override fun onInitialize() { LOGGER.info("BetterWithWeed Initialised!") ModBlocks.register() ModItems.register() } }
0
Kotlin
0
0
f9c57e389fdc5032c28e403f2b2cadc58e45600b
523
BetterWithWeed
Creative Commons Zero v1.0 Universal
android/app/src/main/java/com/kaelesty/audionautica/presentation/composables/access/AccessScreen.kt
Kaelesty
698,507,418
false
{"Kotlin": 62935, "Python": 14431}
package com.kaelesty.audionautica.presentation.composables.access import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import com.kaelesty.audionautica.R import com.kaelesty.audionautica.presentation.ui.theme.AudionauticaTheme import com.kaelesty.audionautica.presentation.viewmodels.AccessViewModel @Composable fun AccessScreen( viewModel: AccessViewModel ) { val accessScreenMode = rememberSaveable { mutableStateOf(AccessScreenMode.REGISTER) } Box( modifier = Modifier .fillMaxSize(), contentAlignment = Alignment.Center ) { Image( painter = painterResource(id = R.drawable.space_background), contentDescription = "Background", contentScale = ContentScale.FillBounds, modifier = Modifier .fillMaxSize() ) when(accessScreenMode.value) { AccessScreenMode.REGISTER -> Register(accessScreenMode, viewModel) AccessScreenMode.LOGIN -> Login(accessScreenMode, viewModel) } } } @Composable fun Register( controllerState: MutableState<AccessScreenMode>, viewModel: AccessViewModel ) { var error = viewModel.registerError.observeAsState("") MultiparameterInputCard( title = "Register", mainAction = CollectNamedAction( name = "Register", onCollect = { params, files -> viewModel.register(params) } ), leftAction = SimpleNamedAction( name = "Sing in", onAction = { controllerState.value = AccessScreenMode.LOGIN } ), rightAction = SimpleNamedAction( name = "Continue offline", onAction = { viewModel.continueOffline() }, ), parameters = listOf("Email", "Name", "Password"), errorMessage = error.value ) } @Composable fun Login( controllerState: MutableState<AccessScreenMode>, viewModel: AccessViewModel ) { val error = viewModel.loginError.observeAsState("") MultiparameterInputCard( title = "Sing in", mainAction = CollectNamedAction( name = "Sign in", onCollect = { params, files -> viewModel.signin(params) } ), leftAction = SimpleNamedAction( name = "No Account?", onAction = { controllerState.value = AccessScreenMode.REGISTER } ), rightAction = SimpleNamedAction( name = "Continue offline", onAction = { viewModel.continueOffline() }, ), parameters = listOf("Email", "Password"), errorMessage = error.value ) } //@Preview //@Composable //fun PreviewLight() { // AudionauticaTheme(darkTheme = false) { // AccessScreen(AccessViewModel()) // } //} // //@Preview //@Composable //fun PreviewDark() { // AudionauticaTheme(darkTheme = true) { // AccessScreen(AccessViewModel()) // } //}
0
Kotlin
1
1
aeceff48eab5e90608cd30aaa22213e7b0684657
3,115
project-fullstack-audionautica
The Unlicense
api/cache/src/main/kotlin/org/rsmod/api/cache/Js5Archives.kt
rsmod
293,875,986
false
{"Kotlin": 1817705}
package org.alter.api.cache public object Js5Archives { public const val TOTAL_ARCHIVES: Int = 22 public const val ANIMS: Int = 0 public const val BASES: Int = 1 public const val CONFIG: Int = 2 public const val INTERFACES: Int = 3 public const val SYNTHS: Int = 4 public const val MAPS: Int = 5 public const val MUSIC: Int = 6 public const val MODELS: Int = 7 public const val SPRITES: Int = 8 public const val TEXTURES: Int = 9 public const val BINARY: Int = 10 public const val JINGLES: Int = 11 public const val CLIENT_SCRIPTS: Int = 12 public const val FONT_METRICS: Int = 13 public const val VORBIS: Int = 14 public const val INSTRUMENTS: Int = 15 public const val WORLD_MAP_GEO_LEGACY: Int = 16 public const val DEFAULTS: Int = 17 public const val WORLD_MAP_GEO: Int = 18 public const val WORLD_MAP_DATA: Int = 19 public const val WORLD_MAP_GROUND: Int = 20 public const val DB_TABLE_INDEX: Int = 21 }
8
Kotlin
64
95
3ba446ed70bcde0870ef431e1a8527efc6837d6c
1,003
rsmod
ISC License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Pyramid.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.Pyramid: ImageVector get() { if (_pyramid != null) { return _pyramid!! } _pyramid = Builder(name = "Pyramid", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.51f, 24.0f) horizontalLineTo(4.488f) arcTo(4.445f, 4.445f, 0.0f, false, true, 0.656f, 21.831f) arcToRelative(4.5f, 4.5f, 0.0f, false, true, -0.145f, -4.42f) lineTo(8.022f, 2.428f) arcTo(4.463f, 4.463f, 0.0f, false, true, 12.0f, 0.0f) horizontalLineToRelative(0.0f) arcToRelative(4.465f, 4.465f, 0.0f, false, true, 3.977f, 2.428f) lineToRelative(7.52f, 15.0f) arcTo(4.508f, 4.508f, 0.0f, false, true, 19.51f, 24.0f) close() moveTo(10.677f, 3.808f) lineTo(3.171f, 18.781f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.04f, 1.49f) arcToRelative(1.471f, 1.471f, 0.0f, false, false, 1.277f, 0.723f) horizontalLineTo(19.51f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 1.326f, -2.2f) lineToRelative(-7.519f, -15.0f) arcTo(1.462f, 1.462f, 0.0f, false, false, 12.0f, 3.006f) horizontalLineToRelative(0.0f) arcTo(1.468f, 1.468f, 0.0f, false, false, 10.677f, 3.808f) close() } } .build() return _pyramid!! } private var _pyramid: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,429
icons
MIT License
untitled/src/main/kotlin/ativ_pratica/L1/q06.kt
leticiasaraivafontenele
765,887,801
false
{"Kotlin": 38029, "Java": 9595}
fun reais(){ println("os reais contem os racionais...") racionais() } fun racionais(){ println("os racionais contem os inteiros...") inteiros() } fun inteiros(){ println("os inteiros contem os naturais...") naturais() } fun naturais(){ println("e os naturais contem o 0.") } fun main() { reais() }
0
Kotlin
0
0
e10945a21ac5a61ff3a0d570715bb118e32fa277
330
CursoIntroducao-Dev-Android
MIT License
platform/src/test/kotlin/uk/gov/gdx/datashare/integration/repository/AcquirerSubscriptionEnrichmentFieldRepositoryTest.kt
alphagov
549,031,617
false
null
package uk.gov.gdx.datashare.integration.repository import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import uk.gov.gdx.datashare.helpers.builders.AcquirerBuilder import uk.gov.gdx.datashare.helpers.builders.AcquirerSubscriptionBuilder import uk.gov.gdx.datashare.helpers.builders.AcquirerSubscriptionEnrichmentFieldBuilder import uk.gov.gdx.datashare.integration.MockIntegrationTestBase import uk.gov.gdx.datashare.repositories.* class AcquirerSubscriptionEnrichmentFieldRepositoryTest( @Autowired private val acquirerRepository: AcquirerRepository, @Autowired private val acquirerSubscriptionRepository: AcquirerSubscriptionRepository, @Autowired private val acquirerSubscriptionEnrichmentFieldRepository: AcquirerSubscriptionEnrichmentFieldRepository, ) : MockIntegrationTestBase() { @Test fun `findAllByAcquirerSubscriptionId returns the correct values`() { val acquirer = acquirerRepository.save(AcquirerBuilder().build()) val checkedSubscription = acquirerSubscriptionRepository.save( AcquirerSubscriptionBuilder(acquirerId = acquirer.id).build(), ) val notCheckedSubscription = acquirerSubscriptionRepository.save( AcquirerSubscriptionBuilder(acquirerId = acquirer.id).build(), ) val returnedEnrichmentField = acquirerSubscriptionEnrichmentFieldRepository.save( AcquirerSubscriptionEnrichmentFieldBuilder(acquirerSubscriptionId = checkedSubscription.id).build(), ) val notReturnedEnrichmentField = acquirerSubscriptionEnrichmentFieldRepository.save( AcquirerSubscriptionEnrichmentFieldBuilder(acquirerSubscriptionId = notCheckedSubscription.id).build(), ) val enrichmentFields = acquirerSubscriptionEnrichmentFieldRepository.findAllByAcquirerSubscriptionId(checkedSubscription.id) assertThat( enrichmentFields.filter { e -> e.acquirerSubscriptionEnrichmentFieldId == returnedEnrichmentField.id }, ) .hasSize(1) assertThat( enrichmentFields.filter { e -> e.acquirerSubscriptionEnrichmentFieldId == notReturnedEnrichmentField.id }, ) .isEmpty() } @Test fun `deleteAllByAcquirerSubscriptionId deletes the correct values`() { val acquirer = acquirerRepository.save(AcquirerBuilder().build()) val checkedSubscription = acquirerSubscriptionRepository.save( AcquirerSubscriptionBuilder(acquirerId = acquirer.id).build(), ) val notCheckedSubscription = acquirerSubscriptionRepository.save( AcquirerSubscriptionBuilder(acquirerId = acquirer.id).build(), ) val enrichmentFieldToDelete = acquirerSubscriptionEnrichmentFieldRepository.save( AcquirerSubscriptionEnrichmentFieldBuilder(acquirerSubscriptionId = checkedSubscription.id).build(), ) val enrichmentFieldToNotDelete = acquirerSubscriptionEnrichmentFieldRepository.save( AcquirerSubscriptionEnrichmentFieldBuilder(acquirerSubscriptionId = notCheckedSubscription.id).build(), ) acquirerSubscriptionEnrichmentFieldRepository.deleteAllByAcquirerSubscriptionId(checkedSubscription.id) val deletedEnrichmentFields = acquirerSubscriptionEnrichmentFieldRepository.findAllByAcquirerSubscriptionId(checkedSubscription.id) val notDeletedEnrichmentFields = acquirerSubscriptionEnrichmentFieldRepository.findAllByAcquirerSubscriptionId(notCheckedSubscription.id) assertThat( deletedEnrichmentFields.filter { e -> e.acquirerSubscriptionEnrichmentFieldId == enrichmentFieldToDelete.id }, ) .isEmpty() assertThat( notDeletedEnrichmentFields.filter { e -> e.acquirerSubscriptionEnrichmentFieldId == enrichmentFieldToNotDelete.id }, ) .hasSize(1) } }
16
Kotlin
4
14
1cb74b085dfe446438bf9a24df5655d589b8432e
3,750
di-data-life-events-platform
MIT License
Algorithm/src/main/kotlin/baekjoon/silver/2178.kt
getupminaaa
740,836,169
false
{"Kotlin": 41552}
package baekjoon.silver import java.io.BufferedReader import java.io.InputStreamReader import java.util.* private var n = 0 private var m = 0 private lateinit var mazeInfo: MutableList<MutableList<Int>> private lateinit var visitInfo: MutableList<MutableList<Int>> private val dx = intArrayOf(-1, 0, 1, 0) private val dy = intArrayOf(0, 1, 0, -1) fun main() = with(BufferedReader(InputStreamReader(System.`in`))) { val input = readLine().split(" ").map { it.toInt() } n = input[0] m = input[1] mazeInfo = MutableList(n + 1) { MutableList(m + 1) { 0 } } visitInfo = MutableList(n + 1) { MutableList(m + 1) { -1 } } repeat(n) { n -> val temp = readLine().chunked(1).map { it.toInt() } temp.forEachIndexed { idx, it -> mazeInfo[n + 1][idx + 1] = it } } bfs() println(visitInfo[n][m]) } private fun bfs() { val queue: Queue<Pair<Int, Int>> = LinkedList() queue.add(Pair(1, 1)) visitInfo[1][1] = 1 while (queue.isNotEmpty()) { val (x, y) = queue.poll() for (i in 0..3) { val tx = x + dx[i] val ty = y + dy[i] if (tx in 0..n && ty in 0..m && mazeInfo[tx][ty] == 1 && visitInfo[tx][ty] == -1) { queue.add(Pair(tx, ty)) visitInfo[tx][ty] = visitInfo[x][y] + 1 } } } }
0
Kotlin
0
0
7f75e681085eb31303cd67f2c888979bf8142788
1,364
Algorithm
MIT License
data/src/main/java/com/anangkur/budgetku/data/model/budget/ProjectEntity.kt
anangkur
270,303,728
false
{"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "INI": 6, "Proguard": 6, "XML": 72, "Kotlin": 188, "JSON": 1, "Java": 8, "Gradle Kotlin DSL": 1, "JAR Manifest": 1, "SQL": 1}
package com.anangkur.budgetku.data.model.budget data class ProjectEntity( val id: String, val title: String, val startDate: String, val endDate: String, val listCategory: List<CategoryProjectEntity> )
10
Kotlin
0
3
82dc439d0df25cc894de5fc8d2604f1670c6cf31
221
Budget-Ku
MIT License
app/src/main/java/com/zaurh/bober/data/tenor/TenorResponse.kt
zaurh
853,441,625
false
{"Kotlin": 483608}
package com.zaurh.bober.data.tenor data class TenorResponse( val results: List<GifResult>? ) data class GifResult( val media: List<MediaFormat>? ) data class MediaFormat( val gif: GifFormat? ) data class GifFormat( val url: String? )
0
Kotlin
0
1
94b466d2af0556f50990d8effb3ac65c8e62f278
253
Bober
MIT License
ui-lib/src/androidTest/java/co/electriccoin/zcash/ui/fixture/MockSynchronizer.kt
Electric-Coin-Company
390,808,594
false
null
package co.electriccoin.zcash.ui.fixture import android.content.Context import cash.z.ecc.android.sdk.CloseableSynchronizer import cash.z.ecc.android.sdk.Synchronizer import cash.z.ecc.android.sdk.block.processor.CompactBlockProcessor import cash.z.ecc.android.sdk.model.Account import cash.z.ecc.android.sdk.model.BlockHeight import cash.z.ecc.android.sdk.model.PercentDecimal import cash.z.ecc.android.sdk.model.TransactionOverview import cash.z.ecc.android.sdk.model.TransactionRecipient import cash.z.ecc.android.sdk.model.UnifiedSpendingKey import cash.z.ecc.android.sdk.model.WalletBalance import cash.z.ecc.android.sdk.model.Zatoshi import cash.z.ecc.android.sdk.model.ZcashNetwork import cash.z.ecc.android.sdk.type.AddressType import cash.z.ecc.android.sdk.type.ConsensusMatchType import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow /** * Mocked Synchronizer that can be used instead of the production SdkSynchronizer e.g. for tests. */ @Suppress("TooManyFunctions", "UNUSED_PARAMETER") internal class MockSynchronizer : CloseableSynchronizer { override val latestBirthdayHeight: BlockHeight get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val latestHeight: BlockHeight get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val network: ZcashNetwork get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val networkHeight: StateFlow<BlockHeight?> get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override var onChainErrorHandler: ((BlockHeight, BlockHeight) -> Any)? get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") set(value) {} override var onCriticalErrorHandler: ((Throwable?) -> Boolean)? get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") set(value) {} override var onProcessorErrorHandler: ((Throwable?) -> Boolean)? get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") set(value) {} override var onSetupErrorHandler: ((Throwable?) -> Boolean)? get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") set(value) {} override var onSubmissionErrorHandler: ((Throwable?) -> Boolean)? get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") set(value) {} override val orchardBalances: StateFlow<WalletBalance?> get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val processorInfo: Flow<CompactBlockProcessor.ProcessorInfo> get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val progress: Flow<PercentDecimal> get() = TODO("Not yet implemented") override val saplingBalances: StateFlow<WalletBalance?> get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val status: Flow<Synchronizer.Status> get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override val transactions: Flow<List<TransactionOverview>> get() = TODO("Not yet implemented") override val transparentBalance: StateFlow<Zatoshi?> get() = error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") override fun close() { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override fun getMemos(transactionOverview: TransactionOverview): Flow<String> { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun getNearestRewindHeight(height: BlockHeight): BlockHeight { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override fun getRecipients(transactionOverview: TransactionOverview): Flow<TransactionRecipient> { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun getSaplingAddress(account: Account): String { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun getTransparentAddress(account: Account): String { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun getTransparentBalance(tAddr: String): Zatoshi { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun getUnifiedAddress(account: Account): String { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun isValidShieldedAddr(address: String): Boolean { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun isValidTransparentAddr(address: String): Boolean { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun isValidUnifiedAddr(address: String): Boolean { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun quickRewind() { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun refreshUtxos( account: Account, since: BlockHeight ): Int? { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun rewindToNearestHeight(height: BlockHeight) { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun sendToAddress( usk: UnifiedSpendingKey, amount: Zatoshi, toAddress: String, memo: String ): Long { return 1 } override suspend fun shieldFunds( usk: UnifiedSpendingKey, memo: String ): Long { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun validateAddress(address: String): AddressType = AddressType.Unified override suspend fun validateConsensusBranch(): ConsensusMatchType { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } override suspend fun getExistingDataDbFilePath( context: Context, network: ZcashNetwork, alias: String ): String { error("Intentionally not implemented in ${MockSynchronizer::class.simpleName} implementation.") } companion object { fun new() = MockSynchronizer() } }
185
null
15
25
359d4a5eea03dfb3c1ffbc5df1baca1c6f7917a7
7,399
zashi-android
MIT License