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
app/src/main/java/dev/gmarques/bancodedados/data/room/entidades/relacoes/InstanciaComPropriedades.kt
GilianMarques
598,830,131
false
null
package dev.gmarques.bancodedados.data.room.entidades.relacoes import androidx.room.Embedded import androidx.room.Relation import dev.gmarques.bancodedados.data.room.entidades.PropriedadeEntidade import dev.gmarques.bancodedados.data.room.entidades.InstanciaEntidade /** * Data class para recuperar do banco de dados objetos "Instancia" com seus propriedades em uma unica query * @see InstanciaDao */ data class InstanciaComPropriedades( @Embedded val instancia: InstanciaEntidade, @Relation(parentColumn = "uid", entityColumn = "instancia_uid") val propriedades: List<PropriedadeEntidade>, )
0
Kotlin
0
0
411e3a70650b78811c510723aa3b79efdd3c938a
611
BancoDeDados
MIT License
shepherd-web/src/test/kotlin/ui/LoginRouteTest.kt
mvysny
644,365,109
false
{"Kotlin": 181865, "Java": 784, "HTML": 497, "TypeScript": 275, "CSS": 85}
package com.github.mvysny.shepherd.web.ui import com.github.mvysny.kaributesting.v10._expectOne import com.github.mvysny.kaributesting.v10._get import com.github.mvysny.kaributesting.v10._login import com.github.mvysny.kaributools.navigateTo import com.github.mvysny.shepherd.web.AbstractAppTest import com.vaadin.flow.component.login.LoginForm import org.junit.jupiter.api.Test import kotlin.test.expect class LoginRouteTest : AbstractAppTest() { @Test fun projectListRouteProtected() { navigateTo<ProjectListRoute>() _expectOne<LoginRoute>() } @Test fun unsuccessfulLogin() { _get<LoginForm>()._login("mavi@vaadin.com", "nbusr123") _expectOne<LoginRoute>() expect(true) { _get<LoginForm>().isError } } @Test fun successfulLogin() { _get<LoginForm>()._login("mavi@vaadin.com", "admin") _expectOne<ProjectListRoute>() } }
5
Kotlin
1
1
04cd05a974e8b0a57ffa53eeec7dbdf24ca61a73
905
shepherd-java-client
Apache License 2.0
resources-generator/src/main/kotlin/dev/icerock/gradle/generator/android/AndroidAssetsGenerator.kt
krottv
393,746,734
true
{"Kotlin": 198697}
/* * Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.gradle.generator.android import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.KModifier import dev.icerock.gradle.generator.AssetsGenerator import dev.icerock.gradle.generator.NOPObjectBodyExtendable import dev.icerock.gradle.generator.ObjectBodyExtendable import org.gradle.api.file.SourceDirectorySet import java.io.File class AndroidAssetsGenerator( sourceDirectorySet: SourceDirectorySet ) : AssetsGenerator(sourceDirectorySet), ObjectBodyExtendable by NOPObjectBodyExtendable() { override fun generateResources( assetsGenerationDir: File, resourcesGenerationDir: File, files: List<AssetSpec> ) { files.forEach { if (it is AssetSpecFile) { it.file.copyTo(File(assetsGenerationDir, it.pathRelativeToBase)) } else if (it is AssetSpecDirectory) { generateResources(assetsGenerationDir, resourcesGenerationDir, it.assets) } } } override fun getClassModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL) override fun getPropertyModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL) override fun getPropertyInitializer(fileSpec: AssetSpecFile) = CodeBlock.of("AssetResource(path = %S)", fileSpec.pathRelativeToBase) }
0
Kotlin
0
0
cfa806e850e2b761a8ac06db54eae5237f114fd9
1,419
moko-resources
Apache License 2.0
plugins/contracts/contracts-subplugins/src/org/jetbrains/kotlin/contracts/contextual/safebuilders/CallVerifier.kt
demiurg906
125,360,148
true
{"Kotlin": 31706399, "Java": 7644320, "JavaScript": 152543, "HTML": 68656, "Lex": 18275, "IDL": 10060, "ANTLR": 9803, "Shell": 6769, "Groovy": 5466, "CSS": 4679, "Batchfile": 4437}
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.contracts.contextual.safebuilders import org.jetbrains.kotlin.contracts.contextual.cfg.ContextContracts import org.jetbrains.kotlin.contracts.contextual.model.Context import org.jetbrains.kotlin.contracts.contextual.model.ContextVerifier import org.jetbrains.kotlin.contracts.description.InvocationKind import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.psi.KtElement internal class CallVerifier( private val functionReference: FunctionReference, private val expectedKind: InvocationKind, val sourceElement: KtElement ) : ContextVerifier { override val family = CallFamily // TODO: UNKNOWN and ZERO reports to lambda, others to calls override fun verify(contexts: List<Context>, diagnosticSink: DiagnosticSink, declaredContracts: ContextContracts) { val context = contexts.first() as? CallContext ?: throw AssertionError() val actualKind = context.calls[functionReference]?.kind ?: InvocationKind.ZERO if (!isSatisfied(expectedKind, actualKind)) { val message = "${functionReference.functionDescriptor.name} call mismatch: expected $expectedKind, actual $actualKind" diagnosticSink.report(Errors.CONTEXTUAL_EFFECT_WARNING.on(sourceElement, message)) } } private fun isSatisfied(expected: InvocationKind, actual: InvocationKind): Boolean { if (expected == InvocationKind.ZERO || expected == InvocationKind.UNKNOWN) throw AssertionError() if (actual == InvocationKind.UNKNOWN) return false if (actual == expected) return true if (expected == InvocationKind.AT_MOST_ONCE && (actual == InvocationKind.ZERO || actual == InvocationKind.EXACTLY_ONCE)) return true if (expected == InvocationKind.AT_LEAST_ONCE && actual == InvocationKind.EXACTLY_ONCE) return true return false } }
0
Kotlin
0
0
9731c7eab974cd9dfab9dc48c71bc5988f3eb97c
2,091
kotlin
Apache License 2.0
src/main/kotlin/no/nav/familie/ba/sak/kjerne/tidslinje/komposisjon/TidslinjeSomKomprimerer.kt
navikt
224,639,942
false
{"Kotlin": 6310108, "Gherkin": 535764, "PLpgSQL": 4478, "Shell": 1628, "Dockerfile": 196}
package no.nav.familie.ba.sak.kjerne.tidslinje.komposisjon import no.nav.familie.ba.sak.kjerne.tidslinje.Tidslinje import no.nav.familie.ba.sak.kjerne.tidslinje.tidspunkt.Tidsenhet import no.nav.familie.ba.sak.kjerne.tidslinje.tidsrom /** * Extension-funksjon som slår sammen påfølgende perioder der innholdet er likt * Benytter tidslinjeFraTidspunkt, som bygger sammenslåtte perioder som default */ fun <I, T : Tidsenhet> Tidslinje<I, T>.slåSammenLike(): Tidslinje<I, T> = tidsrom().tidslinjeFraTidspunkt { tidspunkt -> innholdForTidspunkt(tidspunkt) }
8
Kotlin
1
9
bd5a056879c1f09d01e9b7fd76ffcf4a2a407379
563
familie-ba-sak
MIT License
src/main/kotlin/org/cdb/homunculus/controller/AlertController.kt
CodeDrillBrigade
714,769,385
false
{"Kotlin": 190419, "Dockerfile": 336}
package org.cdb.homunculus.controller import io.ktor.server.application.call import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Routing import io.ktor.server.routing.route import kotlinx.coroutines.flow.toList import org.cdb.homunculus.logic.AlertLogic import org.cdb.homunculus.models.Alert import org.cdb.homunculus.models.embed.AlertStatus import org.cdb.homunculus.models.identifiers.EntityId import org.cdb.homunculus.models.security.Permissions import org.cdb.homunculus.requests.authenticatedDelete import org.cdb.homunculus.requests.authenticatedGet import org.cdb.homunculus.requests.authenticatedPost import org.cdb.homunculus.requests.authenticatedPut import org.koin.ktor.ext.inject fun Routing.alertController() = route("/alert") { val alertLogic by inject<AlertLogic>() authenticatedGet("/{alertId}") { val alertId = checkNotNull(call.parameters["alertId"]) { "Alert Id must not be null" } call.respond(alertLogic.get(EntityId(alertId))) } authenticatedGet("") { call.respond(alertLogic.getAll().toList()) } authenticatedPost("", permissions = setOf(Permissions.MANAGE_NOTIFICATIONS)) { val alertToCreate = call.receive<Alert>() call.respond(alertLogic.create(alertToCreate)) } authenticatedPut("", permissions = setOf(Permissions.MANAGE_NOTIFICATIONS)) { val alertToUpdate = call.receive<Alert>() call.respond(alertLogic.modify(alertToUpdate)) } authenticatedPost("/byIds") { val alertIds = call.receive<Set<EntityId>>() require(alertIds.isNotEmpty()) { "Alert Ids must not be null or empty" } call.respond(alertLogic.getByIds(alertIds)) } authenticatedGet("/idsByName") { val query = requireNotNull(call.request.queryParameters["query"]) { "query must not be null." } call.respond(alertLogic.searchIds(query)) } authenticatedDelete("/{alertId}", permissions = setOf(Permissions.MANAGE_NOTIFICATIONS)) { val alertId = checkNotNull(call.parameters["alertId"]) { "Alert Id must not be null" } call.respond(alertLogic.delete(EntityId(alertId))) } authenticatedPut("/{alertId}/status", permissions = setOf(Permissions.MANAGE_NOTIFICATIONS)) { val alertId = checkNotNull(call.parameters["alertId"]) { "Alert Id must not be null" } val status = requireNotNull( call.request.queryParameters["status"]?.let { AlertStatus.valueOf(it) }, ) { "Status must not be null." } call.respond(alertLogic.setStatus(EntityId(alertId), status)) } authenticatedGet("/byActivationMaterial") { val materialId = checkNotNull(call.parameters["materialId"]) { "Material Id must not be null" } call.respond(alertLogic.listByAcceptedMaterial(EntityId(materialId))) } authenticatedPost("/addToExclusions") { val materialId = checkNotNull(call.parameters["materialId"]) { "Material Id must not be null" } val alertIds = call.receive<Set<EntityId>>() call.respond(alertLogic.addMaterialToExclusions(EntityId(materialId), alertIds)) } }
0
Kotlin
0
0
9830788175ad4ecf8e0a8d8a08b8c1f1c075f4cf
3,009
Homunculus
MIT License
shop/src/main/java/com/tezro/api/shop/client/data/requests/SendMessageRequestBody.kt
tezro-official
376,328,822
false
null
package com.tezro.api.shop.client.data.requests import com.google.gson.annotations.SerializedName import com.tezro.api.shop.client.data.common.MessageEntityBody internal data class SendMessageRequestBody( @SerializedName("message") val message: String, @SerializedName("entities") val entities: List<MessageEntityBody>? )
0
Kotlin
0
4
3952247894d8aca9097d69861b0482fff10be9b1
331
open-api
Apache License 2.0
src/main/kotlin/jp/ac/osaka_u/sdl/nil/usecase/preprocess/kotlin/KotlinTransformer.kt
kusumotolab
295,970,504
false
null
package jp.ac.osaka_u.sdl.nil.usecase.preprocess.kotlin import jp.ac.osaka_u.sdl.nil.NILConfig import jp.ac.osaka_u.sdl.nil.parser.kotlin.KotlinLexer import jp.ac.osaka_u.sdl.nil.parser.kotlin.KotlinParser import jp.ac.osaka_u.sdl.nil.parser.kotlin.KotlinParserBaseListener import jp.ac.osaka_u.sdl.nil.usecase.preprocess.AntlrTransformer import org.antlr.v4.runtime.Parser import org.antlr.v4.runtime.ParserRuleContext import org.antlr.v4.runtime.Token import org.antlr.v4.runtime.tree.ParseTreeListener class KotlinTransformer(config: NILConfig) : AntlrTransformer( config, ::KotlinLexer, ::KotlinParser ) { override fun createVisitor(action: (ParserRuleContext) -> Unit): ParseTreeListener = object : KotlinParserBaseListener() { override fun enterFunctionDeclaration(ctx: KotlinParser.FunctionDeclarationContext) = action(ctx) } override fun Parser.extractRuleContext(): ParserRuleContext = (this as KotlinParser).kotlinFile() override fun Token.isNegligible(): Boolean = this.text.run { this[0] == '\n' || this[0] == ' ' || this[0] == '\r' || this.isEmpty() || this.startsWith("//") || this.startsWith("/*") } }
0
null
3
13
d43a91e9a5ebef9d20c900046c9d6aa2b3b03b95
1,261
NIL
MIT License
Test/app/src/main/java/com/newrelic/coretest/MainActivity.kt
newrelic
149,266,412
false
{"Gradle": 9, "Markdown": 2, "Java Properties": 5, "YAML": 1, "Shell": 2, "Text": 1, "Ignore List": 9, "Batchfile": 2, "INI": 3, "Proguard": 5, "Java": 23, "XML": 37, "Kotlin": 12}
package com.newrelic.coretest import android.os.Bundle import android.util.Log import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.newrelic.coretest.tests.* class MainActivity : AppCompatActivity() { lateinit var textView : TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById<TextView>(R.id.text_view) val testArray = arrayOf(Test1(), Test2(), Test3(), Test4(), Test5(), Test6(), Test7()) appendLine("Running " + testArray.size + " tests...\n\n\n") Thread(Runnable { kotlin.run { testArray.forEach { it.doTest(::testResult) } } }).start() } fun testResult(name: String, result: Boolean) { runOnUiThread { Log.v("CoreTest", "Test Result called = " + name + " " + result) appendLine(name + "\t\t" + (if (result) "✅" else "❌") + "\n\n") } } fun appendLine(text: String) { textView.text = textView.text.toString() + text } }
0
Java
10
5
5b73a5f05bccb359195981aa17941b02e081ed3e
1,229
video-agent-android
Apache License 2.0
src/graphics/renderers/SquareRenderer.kt
abocquet
117,430,584
false
null
package graphics.renderers import graphics.DrawRequest import models.AbstractObject open class SquareRenderer : AbstractRenderer() { override fun draw(obj: AbstractObject, r: DrawRequest, offset: Int, delta_t: Double) { r.rect(obj.position.x.toInt() - offset, obj.position.y.toInt(), obj.dimension.width, obj.dimension.height) } }
1
null
1
1
080598a5420a5cfaed76a8e9fb6e882ab79a6307
352
autoplay
The Unlicense
j2k/tests/testData/fileOrElement/nullability/MethodReturnsNullInAnonymousClass.kt
zarechenskiy
27,313,453
true
{"Markdown": 21, "XML": 504, "Ant Build System": 33, "Ignore List": 8, "Kotlin": 14560, "Java": 4036, "Protocol Buffer": 2, "Roff": 18, "Roff Manpage": 4, "Text": 3020, "JAR Manifest": 1, "INI": 6, "HTML": 102, "Groovy": 7, "Gradle": 62, "Maven POM": 39, "Java Properties": 10, "CSS": 10, "JavaScript": 53, "JFlex": 3, "Shell": 8, "Batchfile": 8}
// ERROR: Return type of 'get' is not a subtype of the return type of overridden member public abstract fun get(): kotlin.String defined in Getter trait Getter { public fun get(): String } class C { fun foo(b: Boolean): String { val getter = object : Getter { override fun get(): String? { return null } } return "" } }
0
Java
0
0
cb9c28e73fc3f88d8e08ec7661ac169434c8311f
396
kotlin
Apache License 2.0
src/main/kotlin/com/firsttimeinforever/intellij/pdf/viewer/ui/editor/PdfFileEditor.kt
NikolaiSviridov
292,094,300
true
{"Kotlin": 99005, "TypeScript": 29859, "Less": 1350, "HTML": 301}
package com.firsttimeinforever.intellij.pdf.viewer.ui.editor import com.firsttimeinforever.intellij.pdf.viewer.ui.editor.panel.PdfEditorPanelProvider import com.firsttimeinforever.intellij.pdf.viewer.ui.editor.panel.PdfFileEditorPanel import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorLocation import com.intellij.openapi.fileEditor.FileEditorState import com.intellij.openapi.fileEditor.FileEditorStateLevel import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import java.beans.PropertyChangeListener import javax.swing.JComponent class PdfFileEditor(private val project: Project, virtualFile: VirtualFile): FileEditor { val viewPanel: PdfFileEditorPanel = PdfEditorPanelProvider.createPanel(project, virtualFile) init { Disposer.register(this, viewPanel) viewPanel.addPageChangeListener { notifyPageChanged(it) } notifyPageChanged(pageState) } private fun notifyPageChanged(pageState: DocumentPageState) { project.messageBus.syncPublisher(DocumentPageStateListener.DOCUMENT_PAGE_STATE).run { pageStateChanged(pageState) } } fun reloadDocument() = viewPanel.reloadDocument() fun increaseScale() = viewPanel.increaseScale() fun decreaseScale() = viewPanel.decreaseScale() fun nextPage() = viewPanel.nextPage() fun previousPage() = viewPanel.previousPage() fun findNext() = viewPanel.findNext() fun findPrevious() = viewPanel.findPrevious() val pageState get() = viewPanel.run { DocumentPageState(currentPageNumber, pagesCount) } override fun isModified(): Boolean = false override fun addPropertyChangeListener(listener: PropertyChangeListener) = Unit override fun getName(): String = NAME override fun setState(state: FileEditorState) { if (state !is PdfFileEditorState) { return } viewPanel.currentPageNumber = state.page } override fun getState(level: FileEditorStateLevel): FileEditorState { return PdfFileEditorState(viewPanel.currentPageNumber) } override fun getComponent(): JComponent = viewPanel override fun getPreferredFocusedComponent(): JComponent? = viewPanel override fun <T : Any?> getUserData(key: Key<T>): T? = null override fun <T : Any?> putUserData(key: Key<T>, value: T?) = Unit override fun getCurrentLocation(): FileEditorLocation? = null override fun isValid(): Boolean = true override fun removePropertyChangeListener(listener: PropertyChangeListener) = Unit override fun dispose() = Unit companion object { private const val NAME = "Pdf Viewer File Editor" } }
0
Kotlin
0
0
7b0959e038a781fc5e98db60e6ccb6373f740709
2,852
intellij-pdf-viewer
MIT License
oauth/src/main/kotlin/io/solarconnect/security/oauth/auth/OAuthAuthenticationManager.kt
solarconnect-io
108,113,733
false
{"Gradle": 6, "Markdown": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Java": 5, "Kotlin": 52, "Groovy": 2}
package io.solarconnect.security.oauth.auth import io.solarconnect.security.core.auth.FindUserAuthorityService import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.core.Authentication import org.springframework.security.core.GrantedAuthority /** * @author chaeeung.e * @since 2017-10-30 */ class OAuthAuthenticationManager<USER_ID> : AuthenticationManager { private val signingKey: String private val findUserAuthorityService: FindUserAuthorityService<USER_ID> constructor(signingKey: String, findUserAuthorityService: FindUserAuthorityService<USER_ID>) { this.signingKey = signingKey this.findUserAuthorityService = findUserAuthorityService } override fun authenticate(authentication: Authentication): Authentication { //JwtPreAuthenticationToken if (authentication is OAuthAuthenticationToken) { return authentication } var principal: OAuthUser = authentication.principal as OAuthUser var authorities: Collection<GrantedAuthority> = authentication.authorities return OAuthAuthenticationToken(principal, authorities) } }
1
null
1
1
94e4d8e907bbc607c1bd7c9d12d352b4729b5ef6
1,111
spring-security-business
MIT License
src/main/kotlin/no/nav/klage/oppgave/api/controller/CleanupHjelpemidlerController.kt
navikt
297,650,936
false
null
package no.nav.klage.oppgave.api.controller import no.nav.klage.oppgave.config.SecurityConfiguration import no.nav.klage.oppgave.exceptions.MissingTilgangException import no.nav.klage.oppgave.service.AdminService import no.nav.klage.oppgave.service.CleanupHjelpemidlerService import no.nav.klage.oppgave.service.InnloggetSaksbehandlerService import no.nav.klage.oppgave.util.getSecureLogger import no.nav.security.token.support.core.api.ProtectedWithClaims import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* @RestController @ProtectedWithClaims(issuer = SecurityConfiguration.ISSUER_AAD) class CleanupHjelpemidlerController( private val adminService: AdminService, private val innloggetSaksbehandlerService: InnloggetSaksbehandlerService, private val cleanupHjelpemidlerService: CleanupHjelpemidlerService, ) { companion object { private val secureLogger = getSecureLogger() } @GetMapping("/internal/log-wrong-tema", produces = ["application/json"]) @ResponseStatus(HttpStatus.OK) fun logWrongTemaForHjelpemidler() { if (!innloggetSaksbehandlerService.isKabalOppgavestyringAlleEnheter()) { throw MissingTilgangException("User does not have the role OppgavestyringAlleEnheter") } try { secureLogger.debug("Log documents that have wrong tema in regards to HJE") cleanupHjelpemidlerService.logJournalpostsWeNeedToPatch() } catch (e: Exception) { secureLogger.warn("Failed to log documents that have wrong tema in regards to HJE", e) throw e } } }
3
Kotlin
1
1
b06e34fbd2fef35a0d7fb2c44439cd018ffdad36
1,635
kabal-api
MIT License
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/runners/codegen/AbstractComposeLikeAbstractBytecodeTextTest.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.test.runners.codegen import org.jetbrains.kotlin.test.FirParser import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder import org.jetbrains.kotlin.test.services.configuration.ComposeLikeConfigurator abstract class AbstractComposeLikeFirAbstractBytecodeTextTestBase(parser: FirParser): AbstractFirBytecodeTextTestBase(parser) { override fun configure(builder: TestConfigurationBuilder) { super.configure(builder) with(builder) { useConfigurators(::ComposeLikeConfigurator) } } } open class AbstractComposeLikeIrBytecodeTextTest(): AbstractIrBytecodeTextTest() { override fun configure(builder: TestConfigurationBuilder) { super.configure(builder) with(builder) { useConfigurators(::ComposeLikeConfigurator) } } } open class AbstractComposeLikeFirLightTreeBytecodeTextTest : AbstractComposeLikeFirAbstractBytecodeTextTestBase(FirParser.LightTree)
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,189
kotlin
Apache License 2.0
app/src/main/kotlin/com/yizhenwind/keeper/ui/account/create/CreateAccountFragment.kt
WangZhiYao
658,053,133
false
{"Kotlin": 91950}
package com.yizhenwind.keeper.ui.account.create import androidx.fragment.app.viewModels import com.yizhenwind.keeper.base.BaseFragment import com.yizhenwind.keeper.common.ext.navigateUp import com.yizhenwind.keeper.common.ext.showSnack import com.yizhenwind.keeper.databinding.FragmentCreateAccountBinding import dagger.hilt.android.AndroidEntryPoint /** * * * @author WangZhiYao * @since 2023/6/22 */ @AndroidEntryPoint class CreateAccountFragment : BaseFragment<CreateAccountViewModel, FragmentCreateAccountBinding, CreateAccountViewState, CreateAccountSideEffect>( FragmentCreateAccountBinding::inflate ) { override val viewModel by viewModels<CreateAccountViewModel>() override fun initData() { super.initData() binding.viewModel = viewModel } override fun initView() { } override suspend fun render(state: CreateAccountViewState) { binding.viewState = state } override suspend fun handleSideEffect(sideEffect: CreateAccountSideEffect) { when (sideEffect) { is ShowSnake -> binding.root.showSnack(sideEffect.message) CreateAccountSuccess -> navigateUp() } } }
2
Kotlin
0
2
fcea6e7ce6ea9d99d08d28873d8187d1881c5ffe
1,192
Keeper
Apache License 2.0
ktlint/src/main/kotlin/com/github/shyiko/ktlint/internal/EditorConfig.kt
msdgwzhy6
112,148,154
true
{"Kotlin": 214508, "Shell": 7817, "Python": 6083, "Batchfile": 3012, "Ruby": 830}
package com.github.shyiko.ktlint.internal import java.io.ByteArrayInputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.Properties class EditorConfig private constructor ( val parent: EditorConfig?, val path: Path, private val data: Map<String, String> ) : Map<String, String> by data { companion object { fun of(dir: String) = of(Paths.get(dir)) fun of(dir: Path) = generateSequence(locate(dir)) { seed -> locate(seed.parent.parent) } // seed.parent == .editorconfig dir .map { it to lazy { load(it) } } .let { seq -> // stop when .editorconfig with "root = true" is found, go deeper otherwise var prev: Pair<Path, Lazy<Map<String, Map<String, String>>>>? = null seq.takeWhile { pair -> (prev?.second?.value?.get("")?.get("root")?.toBoolean()?.not() ?: true).also { prev = pair } } } .toList() .asReversed() .fold(null as EditorConfig?) { parent, (path, data) -> EditorConfig(parent, path, (parent?.data ?: emptyMap()) + flatten(data.value)) } private fun locate(dir: Path?): Path? = when (dir) { null -> null else -> dir.resolve(".editorconfig").let { if (Files.exists(it)) it else locate(dir.parent) } } private fun flatten(data: LinkedHashMap<String, Map<String, String>>): Map<String, String> { val map = mutableMapOf<String, String>() val patternsToSearchFor = arrayOf("*", "*.kt", "*.kts") for ((sectionName, section) in data) { if (sectionName == "") { continue } val patterns = try { parseSection(sectionName.substring(1, sectionName.length - 1)) } catch (e: Exception) { throw RuntimeException("ktlint failed to parse .editorconfig section \"$sectionName\"" + " (please report at https://github.com/shyiko/ktlint)", e) } if (patternsToSearchFor.any { patterns.contains(it) }) { map.putAll(section.toMap()) } } return map.toSortedMap() } private fun load(path: Path) = linkedMapOf<String, Map<String, String>>().also { map -> object : Properties() { private var section: MutableMap<String, String>? = null override fun put(key: Any, value: Any): Any? { val sectionName = (key as String).trim() if (sectionName.startsWith('[') && sectionName.endsWith(']') && value == "") { section = mutableMapOf<String, String>().also { map.put(sectionName, it) } } else { val section = section ?: mutableMapOf<String, String>().also { section = it; map.put("", it) } section[key] = value.toString() } return null } }.load(ByteArrayInputStream(Files.readAllBytes(path))) } internal fun parseSection(sectionName: String): List<String> { val result = mutableListOf<String>() fun List<List<String>>.collect0(i: Int = 0, str: Array<String?>, acc: MutableList<String>) { if (i == str.size) { acc.add(str.joinToString("")) return } for (k in 0 until this[i].size) { str[i] = this[i][k] collect0(i + 1, str, acc) } } // [["*.kt"], ["", "s"], ["~"]] -> [*.kt~, *.kts~] fun List<List<String>>.collect(): List<String> = mutableListOf<String>().also { this.collect0(0, arrayOfNulls<String>(this.size), it) } val chunks: MutableList<MutableList<String>> = mutableListOf() chunks.add(mutableListOf()) var l = 0 var r = 0 var partOfBraceExpansion = false for (c in sectionName) { when (c) { ',' -> { chunks.last().add(sectionName.substring(l, r)) l = r + 1 if (!partOfBraceExpansion) { result += chunks.collect() chunks.clear() chunks.add(mutableListOf()) } } '{', '}' -> { if (partOfBraceExpansion == (c == '}')) { chunks.last().add(sectionName.substring(l, r)) l = r + 1 chunks.add(mutableListOf()) partOfBraceExpansion = !partOfBraceExpansion } } } r++ } chunks.last().add(sectionName.substring(l, r)) result += chunks.collect() return result } } }
0
Kotlin
0
1
f3ca6b2a9f079dc6584c10b8ee7b2db76dce147e
5,436
ktlint
MIT License
src/main/kotlin/com/masdiq/plugins/Session.kt
mas-diq
651,884,974
false
null
package com.masdiq.plugins import com.masdiq.model.auth.UserSession import io.ktor.server.application.* import io.ktor.server.sessions.* import io.ktor.util.* import java.io.File fun Application.configureSession() { install(Sessions) { val secretEncryptKey = hex("<KEY>") val secretAuthKey = hex("<KEY>") cookie<UserSession>( name = "USER_SESSION", storage = directorySessionStorage(File(".sessions")) ) { // cookie.maxAge = 30.minutes // cookie.secure = true transform(SessionTransportTransformerEncrypt(secretEncryptKey, secretAuthKey)) } } }
0
Kotlin
1
0
57d49ef031600916b9fb28c474386d5981b90816
652
akia-backend-ktor-v1
Apache License 2.0
data/src/iosMain/kotlin/in/surajsau/jisho/data/expected/IosDriverFactory.kt
surajsau
489,927,815
false
null
package `in`.surajsau.jisho.data.expected import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.drivers.native.NativeSqliteDriver import `in`.surajsau.jisho.data.db.Jisho import org.koin.core.scope.Scope actual fun Scope.createDriver(databaseName: String): SqlDriver { return NativeSqliteDriver(Jisho.Schema, databaseName) }
0
Kotlin
0
1
161bbb0225d5c57dbbc9467140c3a9dee38b0f64
352
Multiplatform-Jisho
Apache License 2.0
src/main/kotlin/de/javaclub/playground/hexagonal/domain/DeletionStatistic.kt
cryptoki
228,270,982
false
null
package de.javaclub.playground.hexagonal.domain data class DeletionStatistic( val successful: List<DeletionProof>, val failure: List<DeletionProof>, val repaired: List<DeletionProof>)
0
Kotlin
0
1
40af542fd2f0c74784f933ddc3b4473c11a9c857
208
playground-hexagonal
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Messageadd.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup public val BulkGroup.Messageadd: ImageVector get() { if (_messageadd != null) { return _messageadd!! } _messageadd = Builder(name = "Messageadd", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(22.0f, 7.4302f) verticalLineTo(13.4302f) curveTo(22.0f, 14.9302f, 21.5f, 16.1802f, 20.62f, 17.0602f) curveTo(19.75f, 17.9302f, 18.5f, 18.4302f, 17.0f, 18.4302f) verticalLineTo(20.5602f) curveTo(17.0f, 21.3602f, 16.11f, 21.8402f, 15.45f, 21.4002f) lineTo(11.0f, 18.4302f) horizontalLineTo(8.88f) curveTo(8.96f, 18.1302f, 9.0f, 17.8202f, 9.0f, 17.5002f) curveTo(9.0f, 16.4802f, 8.61f, 15.5402f, 7.97f, 14.8302f) curveTo(7.25f, 14.0102f, 6.18f, 13.5002f, 5.0f, 13.5002f) curveTo(3.88f, 13.5002f, 2.86f, 13.9602f, 2.13f, 14.7102f) curveTo(2.04f, 14.3102f, 2.0f, 13.8802f, 2.0f, 13.4302f) verticalLineTo(7.4302f) curveTo(2.0f, 4.4302f, 4.0f, 2.4302f, 7.0f, 2.4302f) horizontalLineTo(17.0f) curveTo(20.0f, 2.4302f, 22.0f, 4.4302f, 22.0f, 7.4302f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.5f, 11.25f) horizontalLineTo(8.5f) curveTo(8.09f, 11.25f, 7.75f, 10.91f, 7.75f, 10.5f) curveTo(7.75f, 10.09f, 8.09f, 9.75f, 8.5f, 9.75f) horizontalLineTo(15.5f) curveTo(15.91f, 9.75f, 16.25f, 10.09f, 16.25f, 10.5f) curveTo(16.25f, 10.91f, 15.91f, 11.25f, 15.5f, 11.25f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.21f, 13.5098f) curveTo(4.12f, 13.4398f, 3.0f, 13.8398f, 2.17f, 14.6698f) curveTo(0.61f, 16.2298f, 0.61f, 18.7598f, 2.17f, 20.3298f) curveTo(2.7f, 20.8598f, 3.35f, 21.2098f, 4.04f, 21.3798f) curveTo(4.42f, 21.4798f, 4.82f, 21.5098f, 5.22f, 21.4898f) curveTo(6.17f, 21.4498f, 7.1f, 21.0698f, 7.83f, 20.3398f) curveTo(8.86f, 19.3098f, 9.21f, 17.8598f, 8.88f, 16.5498f) curveTo(8.72f, 15.8598f, 8.36f, 15.2098f, 7.83f, 14.6798f) curveTo(7.11f, 13.9498f, 6.17f, 13.5598f, 5.21f, 13.5098f) close() moveTo(7.24f, 17.4798f) curveTo(7.24f, 17.6898f, 7.16f, 17.8698f, 7.02f, 18.0098f) curveTo(6.88f, 18.1498f, 6.7f, 18.2298f, 6.49f, 18.2298f) horizontalLineTo(5.75f) verticalLineTo(19.0098f) curveTo(5.75f, 19.2198f, 5.67f, 19.3998f, 5.53f, 19.5398f) curveTo(5.39f, 19.6798f, 5.21f, 19.7598f, 5.0f, 19.7598f) curveTo(4.59f, 19.7598f, 4.25f, 19.4198f, 4.25f, 19.0098f) verticalLineTo(18.2298f) horizontalLineTo(3.5f) curveTo(3.09f, 18.2298f, 2.75f, 17.8898f, 2.75f, 17.4798f) curveTo(2.75f, 17.0698f, 3.09f, 16.7298f, 3.5f, 16.7298f) horizontalLineTo(4.25f) verticalLineTo(16.0198f) curveTo(4.25f, 15.6098f, 4.59f, 15.2698f, 5.0f, 15.2698f) curveTo(5.41f, 15.2698f, 5.75f, 15.6098f, 5.75f, 16.0198f) verticalLineTo(16.7298f) horizontalLineTo(6.49f) curveTo(6.91f, 16.7298f, 7.24f, 17.0698f, 7.24f, 17.4798f) close() } } .build() return _messageadd!! } private var _messageadd: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
5,167
VuesaxIcons
MIT License
core/kotlin/src/main/java/com/pilinhas/android/core/kotlin/extensions/FlowExtensions.kt
pilinhasapp
587,541,347
false
null
package com.pilinhas.android.core.kotlin.extensions import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapConcat import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map inline fun <T, R> Flow<T?>.mapIfNotNull( crossinline transform: suspend (value: T) -> R ): Flow<R?> = map { value -> value?.let { transform(it) } } fun <T> Flow<T>.mapToUnit(): Flow<Unit> = map { } @OptIn(FlowPreview::class) inline fun <T> Flow<T?>.flatMapConcatIfNull( crossinline transform: suspend () -> Flow<T> ): Flow<T> = flatMapConcat { value -> value?.let { flowOf(it) } ?: transform() } @OptIn(FlowPreview::class) inline fun <T> Flow<List<T>?>.flatMapConcatIfNullOrEmpty( crossinline transform: suspend () -> Flow<List<T>> ): Flow<List<T>> = flatMapConcat { value -> value?.takeIf { it.isNotEmpty() }?.let { flowOf(it) } ?: transform() } @OptIn(FlowPreview::class) inline fun <T1, T2> Flow<T1>.onEachFlow(crossinline flow: (value: T1) -> Flow<T2>): Flow<T1> = flatMapConcat { result1 -> flow(result1).map { result1 } } inline fun <T, R> Flow<List<T>>.mapListItemsAsync(crossinline transform: suspend (value: T) -> R): Flow<List<R>> = map { it.mapAsync(transform) } inline fun <reified T1, reified T2> Flow<T1>.combineToPair(flowTwo: Flow<T2>): Flow<Pair<T1, T2>> = combine(flowTwo) { resultOne, resultTwo -> resultOne to resultTwo }
0
Kotlin
0
0
075edd796b36203b4950567aecd303e22a330b43
1,468
Android
MIT License
app/src/main/kotlin/com/igorwojda/showcase/base/delegate/FragmentViewBindingDelegate.kt
igorwojda
158,460,787
false
null
package com.igorwojda.showcase.base.delegate import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import androidx.viewbinding.ViewBinding import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty inline fun <reified T : ViewBinding> Fragment.viewBinding() = FragmentViewBindingDelegate(T::class.java, this) class FragmentViewBindingDelegate<T : ViewBinding>( bindingClass: Class<T>, private val fragment: Fragment ) : ReadOnlyProperty<Fragment, T> { private var binding: T? = null private val bindMethod = bindingClass.getMethod("bind", View::class.java) init { fragment.lifecycle.addObserver(object : DefaultLifecycleObserver { val viewLifecycleOwnerLiveDataObserver = Observer<LifecycleOwner?> { val viewLifecycleOwner = it ?: return@Observer viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { binding = null } }) } override fun onCreate(owner: LifecycleOwner) { fragment.viewLifecycleOwnerLiveData.observeForever( viewLifecycleOwnerLiveDataObserver ) } override fun onDestroy(owner: LifecycleOwner) { fragment.viewLifecycleOwnerLiveData.removeObserver( viewLifecycleOwnerLiveDataObserver ) } }) } @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: Fragment, property: KProperty<*>): T { binding?.let { return it } val lifecycle = fragment.viewLifecycleOwner.lifecycle if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) { error("Cannot access view bindings. View lifecycle is ${lifecycle.currentState}!") } val invoke = bindMethod.invoke(null, thisRef.requireView()) as T return invoke.also { this.binding = it } } }
36
Kotlin
762
5,527
f7919d0a9a718433b85583b285b1b99e19df27f0
2,263
android-showcase
MIT License
app/src/main/java/org/cavedon/takehome/model/Starship.kt
fcavedon
538,230,343
false
null
package org.cavedon.takehome.model data class Starship(val name: String, val model: String, val length: String)
0
Kotlin
0
0
a972a1165df6789a383215ad7daafd7bb38d4444
114
TakeHomeTemplate
Apache License 2.0
mpp/src/commonMain/kotlin/com.w10group.hertzdictionary/manager/FileReadManagerService.kt
qiaoyuang
119,500,508
false
null
package com.w10group.hertzdictionary.manager /** * Created by Administrator on 2018/7/8. * 本地文件读取并显示服务 */ internal expect suspend fun readFileToString(fileName: String): List<String> typealias KV = Pair<String, String> internal expect suspend fun readFileToKV( fileName: String): List<KV>
0
Kotlin
2
10
46e494cd5a60e853bd49cc9b7589ac2b38ea2dab
295
HertzDictionary
Apache License 2.0
src/main/kotlin/me/liuli/jbs/utils/WordSelector.kt
UnlegitMC
460,058,925
false
{"Kotlin": 16092}
package me.liuli.jbs.utils import me.liuli.jbs.JByteStopper class WordSelector(val words: List<String> = JByteStopper.configuration.randomWords) { var count = 0 fun select(): String { val index = count++ % words.size return words[index] + if(count / words.size > 1) count / words.size else "" } }
0
Kotlin
2
5
f649fc759e3e6a40e45ad34cafac3bc4f6267b6c
327
JByteStopper
MIT License
app/src/main/java/dev/liinahamari/follower/receivers/LowBatteryReceiver.kt
liinahamari
328,799,879
false
null
/* * Copyright 2020-2021 liinahamari * * 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 dev.liinahamari.follower.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import dev.liinahamari.follower.FollowerApp import dev.liinahamari.follower.helper.BatteryStateHandlingUseCase import javax.inject.Inject class LowBatteryReceiver : BroadcastReceiver() { @Inject lateinit var batteryStateHandlingUseCase: BatteryStateHandlingUseCase override fun onReceive(context: Context, intent: Intent) { (context.applicationContext as FollowerApp).appComponent.inject(this) batteryStateHandlingUseCase.execute() } }
24
Kotlin
0
1
8932c08fbb0aa99b086e927007f06777afeabe7c
1,711
Follower
MIT License
android/app/src/main/java/com/github/apognu/push/MessagingService.kt
apognu
437,890,775
false
{"Kotlin": 23458, "Rust": 4451}
package com.github.apognu.push import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.TaskStackBuilder import com.github.apognu.push.model.Message import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.squareup.picasso.Picasso import java.text.SimpleDateFormat import java.util.* @SuppressLint("MissingFirebaseInstanceTokenRefresh") class MessagingService : FirebaseMessagingService() { private val channelId = "notifications" private val dateFormat = SimpleDateFormat("dd MMM yyyy • HH:mm", Locale.US) override fun onMessageReceived(message: RemoteMessage) { val uid = message.messageId ?: "" val title = message.data["title"] ?: "" val body = message.data["body"] ?: "" val banner = message.data["banner"] ?: "" val topic = message.from?.removePrefix("/topics/") ?: "" val color = message.data["color"] ?: "" val date = Date(message.sentTime) (application as Pouche).messageRepository.insert( Message(0, uid, title, body, banner, dateFormat.format(date), topic, color) ) notify(Random().nextInt(), title, body, banner) super.onMessageReceived(message) } private fun notify(id: Int, title: String, body: String, banner: String) { createChannel() val intent = TaskStackBuilder.create(this).run { addNextIntentWithParentStack(Intent(this@MessagingService, MainActivity::class.java)) getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } val bannerDrawable = try { if (banner.isNotEmpty()) { Picasso.get().load(banner).get() } else { null } } catch (_: Exception) { null } val builder = NotificationCompat.Builder(this, channelId) .setContentIntent(intent) .setSmallIcon(R.drawable.ic_notifications_black_24dp) .setLargeIcon(bannerDrawable) .setContentTitle(title) .setContentText(body) .setPriority(NotificationCompat.PRIORITY_HIGH) .setDefaults(NotificationCompat.DEFAULT_ALL) .setStyle( NotificationCompat.BigPictureStyle().bigPicture(bannerDrawable).bigLargeIcon(null) ) with(NotificationManagerCompat.from(this)) { notify(id, builder.build()) } } private fun createChannel() { val name = "Notifications" val descriptionText = "Important information about this app" val importance = NotificationManager.IMPORTANCE_HIGH NotificationChannel(channelId, name, importance).apply { description = descriptionText (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) .createNotificationChannel(this) } } }
0
Kotlin
0
0
ed1a50fc5702ed6f52a3a6547b82ed02902310da
3,100
pouche
MIT License
oppgave-endret/src/main/kotlin/no/nav/helse/sparkel/oppgaveendret/GosysOppgaveEndretProducer.kt
navikt
341,650,641
false
null
package no.nav.helse.sparkel.oppgaveendret import java.time.LocalDateTime import java.util.UUID import net.logstash.logback.argument.StructuredArguments.keyValue import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.RapidsConnection import no.nav.helse.sparkel.oppgaveendret.oppgave.Oppgave import org.slf4j.LoggerFactory class GosysOppgaveEndretProducer( private val rapidsConnection: RapidsConnection ) { private val logger = LoggerFactory.getLogger(this::class.java) private val sikkerlogg = LoggerFactory.getLogger("tjenestekall") private val identer: MutableSet<String> = mutableSetOf() fun onPacket(oppgave: Oppgave) { logger.info("Har folkeregisterident for oppgave med id: ${oppgave.id}") val førsteGang = identer.add(oppgave.ident) if (!førsteGang) sikkerlogg.info("Sender ikke duplikat melding for ${oppgave.ident}") } private fun packetAndPublish(fødselsnummer: String) { val meldingId = UUID.randomUUID() val packet: JsonMessage = JsonMessage.newMessage( mapOf( "@event_name" to "gosys_oppgave_endret", "@id" to meldingId, "@opprettet" to LocalDateTime.now(), "fødselsnummer" to fødselsnummer ) ) sikkerlogg.info( "Publiserer gosys_oppgave_endret for {}, {}", keyValue("@id", meldingId), keyValue("fødselsnummer", fødselsnummer) ) rapidsConnection.publish(fødselsnummer, packet.toJson()) } fun shipIt() { identer.onEach { ident -> packetAndPublish(ident) }.clear() } }
1
Kotlin
1
2
7a4704c6c15e0699ef49be291a483bd8965350ab
1,658
helse-sparkelapper
MIT License
src/main/kotlin/io/kstud/gui/KGLScreen.kt
minecraft-simon
724,721,438
false
{"Kotlin": 14160, "GLSL": 734, "Java": 508}
package io.kstud.gui import net.minecraft.client.MinecraftClient import net.minecraft.client.gui.DrawContext import net.minecraft.client.gui.screen.Screen import net.minecraft.text.Text import org.lwjgl.BufferUtils import org.lwjgl.opengl.GL20.* import org.lwjgl.opengl.GL30.glBindVertexArray import org.lwjgl.opengl.GL30.glGenVertexArrays import glm_.* import glm_.mat4x4.Mat4 import glm_.vec2.Vec2 import glm_.vec3.Vec3 import io.kstud.gui.containers.Container import io.kstud.gui.containers.VBoxContainer import io.kstud.gui.widgets.ColorRect import kotlin.math.sin /** * Minecraft displays content by switching between screens, so if we press R, this screen will be displayed. */ class KGLScreen(initialWidth: Int, initialHeight: Int) : Screen(Text.literal("KGLScreen")) { private var viewMatrix: Mat4 = Mat4(); private var projectionMatrix: Mat4 = Mat4(); private var screenHeight: Int = 0; var currentTime: Float = 0.f private val vaoID: Int private val vboID: Int private val mainContainer: Container = VBoxContainer() // Rectangle vertices private val vertexArray = floatArrayOf( // position x, y, z -0.5f, -0.5f, 0.0f, // Bottom left vertex 0.5f, -0.5f, 0.0f, // Bottom right vertex 0.5f, 0.5f, 0.0f, // Top right vertex -0.5f, 0.5f, 0.0f // Top left vertex ) // Define the indices to create two triangles forming a rectangle private val indices = intArrayOf( 0, 1, 2, 2, 3, 0 ) private val shaderProgram: ShaderProgram = ShaderProgram("test.vert", "test.frag") /** * init is the constructor for Kotlin classes. */ init { println("init $initialWidth $initialHeight") updateProjection(initialWidth, initialHeight) screenHeight = initialHeight // Generate VAO and VBO buffer objects, and send to GPU vaoID = glGenVertexArrays() glBindVertexArray(vaoID) // Create a float buffer of vertices val vertexBuffer = BufferUtils.createFloatBuffer(vertexArray.size) vertexBuffer.put(vertexArray).flip() // Create VBO and upload the vertex buffer vboID = glGenBuffers() glBindBuffer(GL_ARRAY_BUFFER, vboID) glBufferData(GL_ARRAY_BUFFER, vertexBuffer, GL_STATIC_DRAW) // Add the vertex attribute pointers glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0) glEnableVertexAttribArray(0) // Create an element buffer object (EBO) to handle indices val eboID = glGenBuffers() glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboID) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW) // build the ui var cr1 = ColorRect(100, 100, color = Vec3(0, 1, 0)) cr1.position(Vec2(0, 0)) var cr2 = ColorRect(100, 100, color = Vec3(1,0,0)) cr2.position(Vec2(100, 100)) var cr3 = ColorRect(100, 100, color = Vec3(1,1,0)) cr3.position(Vec2(200, 200)) var cr4 = ColorRect(100, 100, color = Vec3(0,1,1)) cr4.position(Vec2(300, 300)) mainContainer.addChild(cr1) mainContainer.addChild(cr2) mainContainer.addChild(cr3) mainContainer.addChild(cr4) } fun createOrthographicProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Mat4 { return Mat4().apply { this[0][0] = 2.0f / (right - left) this[1][1] = 2.0f / (top - bottom) this[2][2] = -2.0f / (far - near) this[3][0] = -(right + left) / (right - left) this[3][1] = -(top + bottom) / (top - bottom) this[3][2] = -(far + near) / (far - near) this[3][3] = 1.0f } } fun updateProjection(width: Int, height: Int) { projectionMatrix = createOrthographicProjectionMatrix(0.f, width.toFloat(), 0.f, height.toFloat(), 0.f, 1.f) } /** * render() is called every time Minecraft renders a new frame, and it draws the custom stuff on top of the game. */ override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { val _delta = delta / 10.f glDisable(GL_CULL_FACE) currentTime += _delta // render OpenGL stuff shaderProgram.use() shaderProgram.setUniform("view", viewMatrix) shaderProgram.setUniform("projection", projectionMatrix) shaderProgram.setUniform("screen_height", screenHeight) glBindVertexArray(vaoID) glEnableVertexAttribArray(0) // render ui mainContainer.render(shaderProgram, vaoID, indices.size) // var model = Mat4() // model = model.translate(10.f, 10.f + sin(currentTime * 2.f) * 250, 0.f) // model = model.scale(100.f, 100.f, 1.f) // shaderProgram.setUniform("model", model) //// glDrawArrays(GL_TRIANGLES, 0, indices.size) // // Draw the rectangle using indices //// glDrawElements(GL_TRIANGLES, indices.size, GL_UNSIGNED_INT, 0) // // model = Mat4() // model = model.translate(300.f, 100.f - sin(currentTime * 2.f) * 250, 0.f) // model = model.scale(100.f, 100.f, 1.f) // shaderProgram.setUniform("model", model) //// glDrawArrays(GL_TRIANGLES, 0, indices.size) glDisableVertexAttribArray(0) glBindVertexArray(0) glUseProgram(0) } /** * Called when the mouse is moved. * Uncomment the println to see the mouse coordinates in the console. */ override fun mouseMoved(mouseX: Double, mouseY: Double) { //println("Mouse moved: $mouseX, $mouseY") } /** * Called when the mouse is clicked. */ override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean { println("Mouse clicked: $mouseX, $mouseY, $button") return true } /** * Called when the window is resized. */ override fun resize(client: MinecraftClient?, width: Int, height: Int) { println("Resized: $width, $height") println("Window size ${client!!.window.width} ${client.window.height}") println("Window size ${client.window.framebufferWidth} ${client.window.framebufferHeight}") updateProjection(client.window.width, client.window.height) // updateProjection(width, height) screenHeight = client.window.height // screenHeight = height } /** * This method prevents Minecraft from pausing the game when the KGL screen is displayed. */ override fun shouldPause(): Boolean { return false } }
0
Kotlin
0
1
482dd603273191c324204dfbd7cafa9c87e219e7
6,616
kgl-dev
Creative Commons Zero v1.0 Universal
day_13/src/main/kotlin/io/github/zebalu/advent2020/BusReader.kt
zebalu
317,448,231
false
null
package io.github.zebalu.advent2020 object BusReader { fun readLines(lines: List<String>): BusFinder { val regex = Regex("(\\d+)") val now = lines[0].toInt() val buses = regex.findAll(lines[1]).map { it.groupValues[1] }.map { it.toInt() }.toList() return BusFinder(now, buses) } fun readBusRequest(lines: List<String>): List<Pair<Long, Long>> { val result = mutableListOf<Pair<Long, Long>>() lines[1].split(",").forEachIndexed { index, string -> if (isNumber(string)) { result += getFrequencyModuloPair(string.toLong(), index.toLong()) } } return result } private fun isNumber(string: String): Boolean { try { string.toInt() return true } catch (e: Exception) { return false } } private fun getFrequencyModuloPair(frequency: Long, arrivesAt: Long): Pair<Long, Long> = if (arrivesAt == 0L) Pair(frequency, arrivesAt) else if (arrivesAt < frequency) Pair(frequency, frequency - arrivesAt) else Pair(frequency, frequency - (arrivesAt % frequency)) }
0
Kotlin
0
1
ca54c64a07755ba044440832ba4abaa7105cdd6e
1,007
advent2020
Apache License 2.0
app/src/main/java/com/omongole/fred/yomovieapp/presentation/common/Imageshimmer.kt
EngFred
724,071,728
false
{"Kotlin": 244248}
package com.omongole.fred.yomovieapp.presentation.common import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun AnimatedImageShimmerEffect() { val shimmerColors = listOf( Color.LightGray.copy(alpha = 0.6f), Color.LightGray.copy(alpha = 0.2f), Color.LightGray.copy(alpha = 0.6f), ) val transition = rememberInfiniteTransition(label = "") val translateAnimation = transition.animateFloat( initialValue = 0f, targetValue = 400f, animationSpec = infiniteRepeatable( animation = tween( durationMillis = 1000, easing = FastOutSlowInEasing ), repeatMode = RepeatMode.Reverse ), label = "" ) val brush = Brush.linearGradient( colors = shimmerColors, start = Offset.Zero, end = Offset(translateAnimation.value, translateAnimation.value) ) ImageShimmerItem(brush = brush ) } @Composable fun ImageShimmerItem(brush: Brush ) { Spacer( modifier = Modifier .height(200.dp) .width(145.dp) .clip(RoundedCornerShape(8.dp)) .background(brush) ) Spacer(modifier = Modifier.width(7.dp)) } @Preview(showBackground = true) @Composable fun ImageShimmerPreview() { ImageShimmerItem( brush = Brush.linearGradient( colors = listOf( Color.LightGray.copy(alpha = 0.6f), Color.LightGray.copy(alpha = 0.2f), Color.LightGray.copy(alpha = 0.6f), ) ) ) }
0
Kotlin
0
0
8a1a747c8edde86fe63595f318e157f3bd6de630
2,444
Cinema-app
MIT License
src/commonMain/kotlin/it/krzeminski/snakeyaml/engine/kmp/schema/JsonSchema.kt
krzema12
642,543,787
false
{"Kotlin": 510818, "Java": 392097}
package it.krzeminski.snakeyaml.engine.kmp.schema import it.krzeminski.snakeyaml.engine.kmp.resolver.JsonScalarResolver import it.krzeminski.snakeyaml.engine.kmp.resolver.ScalarResolver expect open class JsonSchema( scalarResolver: ScalarResolver = JsonScalarResolver(), ) : Schema
10
Kotlin
0
16
e3918f3f13f968204113fec508eb3df113fa2eff
288
snakeyaml-engine-kmp
Apache License 2.0
app/src/main/java/co/sirano/news/di/UseCaseModule.kt
siranoB
721,450,145
false
{"Kotlin": 65891}
package co.sirano.news.di import co.sirano.news.domain.usercase.GetNoLocalFileImgArticleEntityListUserCase import co.sirano.news.domain.usercase.GetNoLocalFileImgArticleEntityListUserCaseImpl import co.sirano.news.domain.usercase.GetTopHeadLinesUseCase import co.sirano.news.domain.usercase.GetTopHeadLinesUseCaseImpl import co.sirano.news.domain.usercase.InsertImgLocalFileUserCase import co.sirano.news.domain.usercase.InsertImgLocalFileUserCaseImpl import co.sirano.news.domain.usercase.UpdateArticleEntityUserCase import co.sirano.news.domain.usercase.UpdateArticleEntityUserCaseImpl import co.sirano.news.domain.usercase.UpdateShowArticleEntityUserCase import co.sirano.news.domain.usercase.UpdateShowArticleEntityUserCaseImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class UseCaseModule { @Singleton @Binds abstract fun bindsGetTopHeadLinesUseCase(useCase: GetTopHeadLinesUseCaseImpl): GetTopHeadLinesUseCase @Singleton @Binds abstract fun bindsUpdateArticleEntityUserCase(useCase: UpdateArticleEntityUserCaseImpl): UpdateArticleEntityUserCase @Singleton @Binds abstract fun bindsUpdateShowArticleEntityUserCase(useCase: UpdateShowArticleEntityUserCaseImpl): UpdateShowArticleEntityUserCase @Singleton @Binds abstract fun bindsGetNoLocalFileImgArticleEntityListUserCase(useCase: GetNoLocalFileImgArticleEntityListUserCaseImpl): GetNoLocalFileImgArticleEntityListUserCase @Singleton @Binds abstract fun bindsInsertImgLocalFileUserCase(useCase: InsertImgLocalFileUserCaseImpl): InsertImgLocalFileUserCase }
0
Kotlin
0
0
5c8f86413c9043832dd97520d0b2e7e044ae767c
1,740
NewsApi
Apache License 2.0
components/finances/src/androidMain/kotlin/com/nikitakrapo/monkeybusiness/finances/accounts/BankAccountCardShimmer.kt
nikitakrapo
529,813,711
false
null
package com.nikitakrapo.monkeybusiness.finances.accounts import androidx.compose.foundation.background 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Surface import androidx.compose.material3.MaterialTheme import androidx.compose.material3.surfaceColorAtElevation import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.nikitakrapo.monkeybusiness.design.theme.MonkeyTheme import com.valentinilk.shimmer.Shimmer import com.valentinilk.shimmer.ShimmerBounds import com.valentinilk.shimmer.rememberShimmer import com.valentinilk.shimmer.shimmer @Composable fun BankAccountCardShimmer( modifier: Modifier = Modifier, shimmer: Shimmer, ) { Row( modifier = modifier .clip(MaterialTheme.shapes.medium) .background(MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp)) .shimmer(shimmer) .padding(14.dp), ) { Box( modifier = Modifier .clip(MaterialTheme.shapes.medium) .background(MaterialTheme.colorScheme.secondaryContainer) .size(44.dp), ) Spacer(modifier = Modifier.size(16.dp)) Column { Box( modifier = Modifier .size( width = 72.dp, height = 14.dp ) .clip(RoundedCornerShape(2.dp)) .background(MaterialTheme.colorScheme.secondaryContainer), ) Spacer(modifier = Modifier.size(6.dp)) Box( modifier = Modifier .size( width = 108.dp, height = 14.dp ) .clip(RoundedCornerShape(2.dp)) .background(MaterialTheme.colorScheme.secondaryContainer), ) Spacer(modifier = Modifier.size(10.dp)) LazyRow { items(3) { SmallBankCardShimmer(shimmer = shimmer) Spacer(modifier = Modifier.size(10.dp)) } } } } } @Preview @Composable fun BankAccountCardShimmer_Preview() { MonkeyTheme { Surface { val shimmer = rememberShimmer(shimmerBounds = ShimmerBounds.Window) BankAccountCardShimmer(shimmer = shimmer) } } }
0
Kotlin
0
3
e71b42c3a60dbd34f7f018235157172de6b46a9c
2,912
Monkey-Business
Apache License 2.0
app/src/main/java/com/irofactory/hyperchess/model/game/Resolution.kt
HectorH06
769,393,396
false
{"Kotlin": 177547}
package com.irofactory.hyperchess.model.game enum class Resolution { IN_PROGRESS, CHECKMATE, STALEMATE, DRAW_BY_REPETITION, INSUFFICIENT_MATERIAL }
0
Kotlin
0
0
ca36db9b813ccf8527e305137d3c0b6588ab23a4
153
Hyperchess
Apache License 2.0
core/mobile/src/main/kotlin/com/boswelja/smartwatchextensions/core/watches/status/WatchStatusRepositoryImpl.kt
boswelja
103,805,743
false
{"Kotlin": 496889}
package com.boswelja.smartwatchextensions.core.watches.status import com.boswelja.watchconnection.core.discovery.DiscoveryClient import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapLatest internal class WatchStatusRepositoryImpl( private val discoveryClient: DiscoveryClient ) : WatchStatusRepository { @OptIn(ExperimentalCoroutinesApi::class) override fun getStatusFor(watchId: String): Flow<ConnectionMode> { return discoveryClient.connectionModeFor(watchId) .mapLatest { when (it) { com.boswelja.watchconnection.common.discovery.ConnectionMode.Disconnected -> ConnectionMode.Disconnected com.boswelja.watchconnection.common.discovery.ConnectionMode.Internet -> ConnectionMode.Internet com.boswelja.watchconnection.common.discovery.ConnectionMode.Bluetooth -> ConnectionMode.Bluetooth } } } }
11
Kotlin
0
25
ec7e9ad4c98e18a9a4b5c07f1d39f6c0b1fbfd65
1,079
SmartwatchExtensions
Apache License 2.0
src/main/kotlin/gauravbrills/ignite/web/CacheController.kt
gauravbrills
177,508,970
false
null
package gauravbrills.ignite.web import gauravbrills.ignite.cache.Trade import org.apache.ignite.Ignite import org.apache.ignite.cache.query.SqlFieldsQuery import org.apache.ignite.cache.query.TextQuery import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Mono import java.util.LinkedList import javax.cache.Cache import gauravbrills.ignite.TaskRunner import org.apache.ignite.cluster.ClusterNode @RestController @RequestMapping("/caches") class CacheController(private val ignite: Ignite, private val taskRunner: TaskRunner) { @GetMapping("/", produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) @ResponseBody fun cache(): Mono<Collection<String>> { return Mono.fromCallable { ignite.cacheNames() } } // Creates Dynamic Cache with BinarObject @PostMapping("/", produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) @ResponseBody fun createDynamicCache(schema: List<Map<String, String>>) { } @PostMapping("/runDistributedTask", produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) @ResponseBody fun runDistributedTask() { } @PostMapping("/{cacheName}/query", produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) @ResponseBody fun query(@PathVariable cacheName: String, @RequestBody query: String): Mono<LinkedList<Map<String, Any?>>> { val data = LinkedList<Map<String, Any?>>(); val q = ignite.getOrCreateCache<String, Any>(cacheName).withKeepBinary<String, Any>() .query(SqlFieldsQuery(query)) val iter = q.iterator(); while (iter.hasNext()) { val row = HashMap<String, Any?>() val next = iter.next() for (i in 0..next.size - 1) { row.put(q.getFieldName(i), next.get(i)); } data.add(row); } return Mono.fromCallable { data } } @GetMapping("/{cacheName}/freeText", produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) @ResponseBody fun freeText(@PathVariable cacheName: String, @RequestParam q: String): Mono<LinkedList<Map<String, Trade>>> { val data = LinkedList<Map<String, Trade>>(); val cursor = ignite.getOrCreateCache<String, Any>(cacheName).withKeepBinary<String, Any>() .query(TextQuery<String, Trade>(Trade::class.java, q)) val iter = cursor.iterator(); while (iter.hasNext()) { val row = HashMap<String, Trade>() val next = iter.next() row.put(next.getKey(), next.getValue()); data.add(row); } return Mono.fromCallable { data } } }
0
Kotlin
0
2
e6845319e5354527a8b4081c0903579b3caf5dd8
2,845
ignite-playground
Apache License 2.0
shared/src/commonMain/kotlin/com/ramitsuri/podcasts/viewmodel/QueueViewModel.kt
ramitsuri
760,212,962
false
{"Kotlin": 545554, "Shell": 9622, "Swift": 296}
package com.ramitsuri.podcasts.viewmodel import com.ramitsuri.podcasts.model.PlayingState import com.ramitsuri.podcasts.model.ui.QueueViewState import com.ramitsuri.podcasts.repositories.EpisodesRepository import com.ramitsuri.podcasts.settings.Settings import com.ramitsuri.podcasts.utils.EpisodeController import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class QueueViewModel internal constructor( episodeController: EpisodeController, settings: Settings, private val episodesRepository: EpisodesRepository, ) : ViewModel(), EpisodeController by episodeController { private val _state = MutableStateFlow(QueueViewState()) val state = _state.asStateFlow() init { viewModelScope.launch { combine( episodesRepository.getQueueFlow(), episodesRepository.getCurrentEpisode(), settings.getPlayingStateFlow(), ) { subscribedEpisodes, currentlyPlayingEpisode, playingState -> val currentlyPlaying = if (playingState == PlayingState.PLAYING || playingState == PlayingState.LOADING) { currentlyPlayingEpisode } else { null } Triple(subscribedEpisodes, currentlyPlaying, playingState) }.collect { (subscribedEpisodes, currentlyPlayingEpisode, playingState) -> _state.update { it.copy( episodes = subscribedEpisodes, currentlyPlayingEpisodeId = currentlyPlayingEpisode?.id, currentlyPlayingEpisodeState = playingState, ) } } } } fun onEpisodeRearrangementRequested( position1: Int, position2: Int, ) { viewModelScope.launch { val currentlyAtPosition1 = _state.value.episodes.getOrNull(position1) val currentlyAtPosition2 = _state.value.episodes.getOrNull(position2) if (currentlyAtPosition1 != null && currentlyAtPosition2 != null) { episodesRepository.updateQueuePositions( currentlyAtPosition1.id, currentlyAtPosition2.queuePosition, currentlyAtPosition2.id, currentlyAtPosition1.queuePosition, ) } } } }
0
Kotlin
0
1
ff807a58e7aa3dad1f2f3f50c2de65b16b744795
2,580
podcasts
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/UpRight.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline 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.Outline.UpRight: ImageVector get() { if (_upRight != null) { return _upRight!! } _upRight = Builder(name = "UpRight", 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(6.41f, 23.0f) curveToRelative(-1.07f, 0.0f, -2.07f, -0.42f, -2.83f, -1.17f) lineToRelative(-1.41f, -1.41f) curveToRelative(-0.76f, -0.76f, -1.17f, -1.76f, -1.17f, -2.83f) reflectiveCurveToRelative(0.42f, -2.07f, 1.17f, -2.83f) lineToRelative(7.17f, -7.17f) lineToRelative(-1.47f, -1.47f) curveToRelative(-0.87f, -0.88f, -1.12f, -2.13f, -0.64f, -3.27f) curveToRelative(0.47f, -1.14f, 1.54f, -1.85f, 2.77f, -1.85f) horizontalLineToRelative(9.01f) curveToRelative(2.2f, 0.0f, 4.0f, 1.8f, 4.0f, 4.0f) horizontalLineToRelative(0.0f) verticalLineTo(14.0f) curveToRelative(0.0f, 1.23f, -0.7f, 2.29f, -1.84f, 2.77f) curveToRelative(-1.14f, 0.47f, -2.39f, 0.23f, -3.27f, -0.64f) lineToRelative(-1.48f, -1.48f) lineToRelative(-7.17f, 7.17f) curveToRelative(-0.76f, 0.76f, -1.76f, 1.17f, -2.83f, 1.17f) close() moveTo(10.0f, 3.0f) curveToRelative(-0.62f, 0.0f, -0.86f, 0.47f, -0.92f, 0.62f) curveToRelative(-0.06f, 0.14f, -0.22f, 0.65f, 0.21f, 1.09f) lineToRelative(2.18f, 2.18f) curveToRelative(0.19f, 0.19f, 0.29f, 0.44f, 0.29f, 0.71f) reflectiveCurveToRelative(-0.11f, 0.52f, -0.29f, 0.71f) lineToRelative(-7.88f, 7.88f) curveToRelative(-0.38f, 0.38f, -0.59f, 0.88f, -0.59f, 1.41f) reflectiveCurveToRelative(0.21f, 1.04f, 0.59f, 1.41f) lineToRelative(1.41f, 1.41f) curveToRelative(0.76f, 0.76f, 2.07f, 0.76f, 2.83f, 0.0f) lineToRelative(7.88f, -7.88f) curveToRelative(0.39f, -0.39f, 1.02f, -0.39f, 1.41f, 0.0f) lineToRelative(2.18f, 2.18f) curveToRelative(0.44f, 0.43f, 0.94f, 0.27f, 1.09f, 0.21f) curveToRelative(0.14f, -0.06f, 0.62f, -0.3f, 0.61f, -0.92f) verticalLineTo(5.0f) curveToRelative(0.0f, -1.1f, -0.9f, -2.0f, -2.0f, -2.0f) horizontalLineTo(10.0f) reflectiveCurveToRelative(0.0f, 0.0f, 0.0f, 0.0f) close() } } .build() return _upRight!! } private var _upRight: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,560
icons
MIT License
src/me/anno/gpu/pipeline/LightRequest.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
package me.anno.gpu.pipeline import me.anno.ecs.components.light.LightComponent import org.joml.Matrix4x3d import org.joml.Matrix4x3f class LightRequest(var light: LightComponent, var drawMatrix: Matrix4x3d, var invCamSpaceMatrix: Matrix4x3f) { fun set(l: LightComponent, t: Matrix4x3d, i: Matrix4x3f) { light = l drawMatrix = t invCamSpaceMatrix = i } }
0
Kotlin
3
24
013af4d92e0f89a83958008fbe1d1fdd9a10e992
388
RemsEngine
Apache License 2.0
src/main/kotlin/rs/dusk/network/codec/download/decode/DownloadConnectedDecoder.kt
FailZombie
324,388,128
true
{"Kotlin": 85527, "Java": 4112}
package rs.dusk.network.codec.download.decode import rs.dusk.core.network.packet.PacketMetaData import rs.dusk.core.network.packet.access.PacketReader import rs.dusk.network.codec.download.DownloadServiceMessageDecoder import rs.dusk.network.codec.download.DownloadServiceRequestOpcodes.CONNECTED import rs.dusk.network.codec.download.decode.message.DownloadConnected /** * @author Tyluur <itstyluur@gmail.com> * @since December 17, 2020 */ @PacketMetaData(opcodes = [CONNECTED], length = 3) class DownloadConnectedDecoder : DownloadServiceMessageDecoder<DownloadConnected>() { override fun decode(packet : PacketReader) : DownloadConnected { val value = packet.readMedium() return DownloadConnected(value) } }
0
null
0
0
5f9e53a1575f3c547314ef0f8da86fb2556fc7b3
725
dusk
Creative Commons Attribution 3.0 Unported
src/KaraLib/src/kara/HtmlTemplate.kt
azhuchkov
28,307,744
true
{"Kotlin": 233283, "CSS": 144766, "JavaScript": 8745, "Java": 820}
package kara import kotlin.html.* import java.util.ArrayList import javax.servlet.http.HttpServletResponse public open class HtmlTemplateView<T : Template<HTML>>(val template: T, val build: T.() -> Unit) : ActionResult { override fun writeResponse(context: ActionContext) { writeResponse(context.response) } fun writeResponse(response: HttpServletResponse) { response.setContentType("text/html") val writer = response.getWriter()!! val view = this@HtmlTemplateView val page = HTML() with(template) { with(view) { build() } with(page) { render() } } writer.write(page.toString()) writer.flush() } }
0
Kotlin
0
0
5835eb69d4e2577bc40eb85644bfd14c13d6a455
713
kara
Apache License 2.0
app/src/main/java/com/kenkoro/taurus/client/feature/dictionaries/presentation/util/DictionariesScreenShared.kt
kenkoro
746,982,789
false
{"Kotlin": 272290, "JavaScript": 64}
package com.kenkoro.taurus.client.feature.dictionaries.presentation.util import com.kenkoro.taurus.client.feature.profile.domain.User import com.kenkoro.taurus.client.feature.shared.components.util.NavItemWithNavigation data class DictionariesScreenShared( val user: User?, val currentRoute: String, val items: List<NavItemWithNavigation>, )
4
Kotlin
0
4
f14526cccbf81ab247cae532709efe57b63b71f5
349
taurus
Apache License 2.0
autopage/src/main/java/com/qdedu/autopage/AutoJ.kt
smartbackme
347,809,468
false
null
package com.qdedu.autopage import android.app.Activity import androidx.fragment.app.Fragment import java.lang.reflect.Method /** * @author shidawei * 创建日期:2021/3/12 * 描述:自动跳转工具 */ const val SUFFIX = "Ap" object AutoJ { fun inject(activity: Activity) { try { val clazz: Class<*> = activity.javaClass val injectorClazz = Class.forName(clazz.`package`.name +"." + SUFFIX + clazz.simpleName) val method: Method = injectorClazz.getMethod("inject", clazz) method.invoke(null,activity) } catch (e: Exception) { e.printStackTrace() } } fun inject(fragment: Fragment) { try { val clazz: Class<*> = fragment.javaClass val injectorClazz = Class.forName(clazz.`package`.name +"." + SUFFIX + clazz.simpleName) val method: Method = injectorClazz.getMethod("inject", clazz) method.invoke(null,fragment) } catch (e: Exception) { e.printStackTrace() } } }
0
Kotlin
1
34
1e12a18cb0fe43c6c72866829d5fdf9d501606c6
1,034
AutoPage
MIT License
coroutines/src/jsMain/kotlin/dev/schlaubi/stdx/coroutines/SuspendLazy.kt
DRSchlaubi
475,237,145
false
null
package dev.schlaubi.stdx.coroutines /** * Creates a [SuspendLazy] implementation using [LazyThreadSafetyMode.NONE] as JS doesn't provide thread safety. * * @see SuspendLazy */ public actual fun <T> suspendLazy(initializer: SuspendingInitializer<T>): SuspendLazy<T> = UnsafeSuspendLazyImpl(initializer) /** * Creates a [SuspendLazy] implementation using [LazyThreadSafetyMode.NONE] as JS doesn't provide thread safety. * * @see SuspendLazy */ public actual fun <T> suspendLazy(mode: LazyThreadSafetyMode, initializer: SuspendingInitializer<T>): SuspendLazy<T> = suspendLazy(initializer)
0
Kotlin
4
11
59af3e837653129fba270c83866bafd0944a9c4b
601
stdx.kt
Apache License 2.0
coroutines/src/jsMain/kotlin/dev/schlaubi/stdx/coroutines/SuspendLazy.kt
DRSchlaubi
475,237,145
false
null
package dev.schlaubi.stdx.coroutines /** * Creates a [SuspendLazy] implementation using [LazyThreadSafetyMode.NONE] as JS doesn't provide thread safety. * * @see SuspendLazy */ public actual fun <T> suspendLazy(initializer: SuspendingInitializer<T>): SuspendLazy<T> = UnsafeSuspendLazyImpl(initializer) /** * Creates a [SuspendLazy] implementation using [LazyThreadSafetyMode.NONE] as JS doesn't provide thread safety. * * @see SuspendLazy */ public actual fun <T> suspendLazy(mode: LazyThreadSafetyMode, initializer: SuspendingInitializer<T>): SuspendLazy<T> = suspendLazy(initializer)
0
Kotlin
4
11
59af3e837653129fba270c83866bafd0944a9c4b
601
stdx.kt
Apache License 2.0
app/src/main/java/volovyk/thenullpointer/ui/ConfirmationDialog.kt
oleksandrvolovyk
706,337,016
false
{"Kotlin": 52861}
package volovyk.thenullpointer.ui import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import volovyk.thenullpointer.R @Composable fun ConfirmationDialog( shown: Boolean, title: String, description: String, onConfirm: () -> Unit, onDismiss: () -> Unit = {} ) { if (shown) { AlertDialog( onDismissRequest = { onDismiss() }, title = { Text(title) }, text = { Text(description) }, confirmButton = { Button( onClick = { onConfirm() }) { Text(stringResource(R.string.confirm)) } }, dismissButton = { Button( onClick = { onDismiss() }) { Text(stringResource(R.string.dismiss)) } } ) } }
0
Kotlin
0
0
c88aa66746ca673e3ac7b44dacf0766d44c06feb
1,188
the-null-pointer-android-client
MIT License
src/star02.kt
a-red-christmas
112,728,147
false
null
fun main(args: Array<String>) { val input = args[0] var i = 0 var sum = 0 for (n in input) { val halfway = atoi(halfwayElement(input, i)) val current = atoi(n) if (current == halfway) sum += halfway i += 1 } println(sum) } fun halfwayElement(s: String, i: Int) : Char { return s[(i + s.length / 2) % s.length] }
0
Kotlin
0
0
14e50f42c6550110b7007088af96f0260f4ac887
389
aoc2017-kt
Apache License 2.0
src/main/kotlin/io/maslick/revolutto/DIConf.kt
maslick
208,226,196
false
null
package io.maslick.revolutto import io.ktor.util.KtorExperimentalAPI import org.koin.core.KoinApplication import org.koin.dsl.bind import org.koin.dsl.module val businessLogicModule = module { single<ITransaction> { Transaction(get()) } single<IBalance> { Balance(get()) } } val dbModule = module { single<IRepo> { DummyRepo() } bind IRepo::class } val diModules = listOf(businessLogicModule, dbModule) @KtorExperimentalAPI fun KoinApplication.loadDIConfiguration() = modules(diModules)
0
Kotlin
0
2
8932690a9445bd33a5104a63defd6a43483f9bed
503
revolutto
MIT License
src/main/kotlin/org/skellig/plugin/language/teststep/psi/lexer/LexerArrayProcessor.kt
skellig-framework
309,154,374
false
null
package org.skellig.plugin.language.teststep.psi.lexer import org.skellig.plugin.language.teststep.psi.SkelligTestStepTokenTypes import org.skellig.plugin.language.teststep.psi.lexer.SkelligTestStepLexer.Companion.ARRAY_STATE import org.skellig.plugin.language.teststep.psi.lexer.SkelligTestStepLexer.Companion.STATE_DEFAULT import org.skellig.plugin.language.teststep.psi.lexer.SkelligTestStepLexer.Companion.STATE_INSIDE_STRING class LexerArrayProcessor : LexerCharProcessor { override fun process(c: Char, lexer: SkelligTestStepLexer): Boolean { if ((c == '[' || c == ']') && lexer.myState != STATE_INSIDE_STRING) { lexer.myCurrentToken = if (c == '[') { lexer.arraysCount++ lexer.myState = ARRAY_STATE SkelligTestStepTokenTypes.ARRAY_OPEN_BRACKET } else { lexer.arraysCount-- lexer.myState = STATE_DEFAULT SkelligTestStepTokenTypes.ARRAY_CLOSE_BRACKET } lexer.myPosition++ return true } return false } }
0
Kotlin
0
1
9eb8fef6f1054bcd0a3cbc4fcbefbebe64655397
1,165
skellig-intellij-plugin
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/js/intl/LocaleMatcher.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package js.intl import seskar.js.JsValue sealed external interface LocaleMatcher { companion object { @JsValue("lookup") val lookup: LocaleMatcher @JsValue("best fit") val bestFit: LocaleMatcher } }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
287
types-kotlin
Apache License 2.0
app/src/main/java/com/faigenbloom/familybudget/common/FloatingActionButton.kt
ZakharchenkoWork
706,155,222
false
{"Kotlin": 746176}
package com.faigenbloom.familybudget.common import android.annotation.SuppressLint import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically 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.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.MaterialTheme.typography import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.faigenbloom.familybudget.R import com.faigenbloom.familybudget.ui.theme.FamillySpandingsTheme const val MENU_FLOATING_BUTTON = "MENU_FLOATING_BUTTON" @SuppressLint("UnusedTransitionTargetStateParameter") @Composable fun FloatingActionMenu( modifier: Modifier = Modifier, state: FloatingMenuState?, ) { state?.let { floatingState -> var filterFabState by rememberSaveable { mutableStateOf(FilterFabState.COLLAPSED) } Column( modifier = modifier .fillMaxSize() .padding(16.dp), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Bottom), ) { floatingState.items?.let { items -> FilterFabMenu( items = items, visible = filterFabState == FilterFabState.EXPANDED, ) } floatingState.alwaysVisibleButton?.let { item -> if (item.isShown) { MenuItem( state = item, ) } } FilterFab( state = filterFabState, icon = floatingState.icon, onClick = { state -> floatingState.onMenuClick?.let { it.invoke() } ?: kotlin.run { filterFabState = state } }, ) } } } @Composable fun FilterFab( modifier: Modifier = Modifier, state: FilterFabState, @DrawableRes icon: Int, onClick: (FilterFabState) -> Unit, ) { FloatingActionButton( modifier = modifier .semantics { contentDescription = MENU_FLOATING_BUTTON }, elevation = FloatingActionButtonDefaults.elevation(defaultElevation = 0.dp), onClick = { onClick( if (state == FilterFabState.EXPANDED) { FilterFabState.COLLAPSED } else { FilterFabState.EXPANDED }, ) }, containerColor = colorScheme.onBackground, shape = CircleShape, ) { Icon( painter = painterResource(icon), contentDescription = null, tint = colorScheme.primary, ) } } enum class FilterFabState { EXPANDED, COLLAPSED } @Composable fun FilterFabMenu( visible: Boolean, items: List<MenuItemState>, modifier: Modifier = Modifier, ) { val enterTransition = remember { expandVertically( expandFrom = Alignment.Bottom, animationSpec = tween(150, easing = FastOutSlowInEasing), ) + fadeIn( initialAlpha = 0.3f, animationSpec = tween(150, easing = FastOutSlowInEasing), ) } val exitTransition = remember { shrinkVertically( shrinkTowards = Alignment.Bottom, animationSpec = tween(150, easing = FastOutSlowInEasing), ) + fadeOut( animationSpec = tween(150, easing = FastOutSlowInEasing), ) } AnimatedVisibility(visible = visible, enter = enterTransition, exit = exitTransition) { Column( modifier = modifier .fillMaxWidth(), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(16.dp), ) { items.forEach { menuItem -> if (menuItem.isShown) { MenuItem( state = menuItem, ) } } } } } @Composable fun MenuItem( modifier: Modifier = Modifier, state: MenuItemState, ) { Row( modifier = modifier .clickable { state.onClick() }, horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically, ) { MenuLabel(label = state.label) MenuButton(item = state) } } @Composable fun MenuButton( modifier: Modifier = Modifier, item: MenuItemState, ) { item.icon?.let { icon -> FloatingActionButton( modifier = modifier .size(32.dp) .clearAndSetSemantics { contentDescription = item.semantics }, shape = CircleShape, containerColor = colorScheme.onBackground, onClick = item.onClick, ) { Icon( modifier = Modifier .size(16.dp) .aspectRatio(1f), painter = painterResource(icon), contentDescription = null, tint = colorScheme.primary, ) } } } @Composable fun MenuLabel( @StringRes label: Int, modifier: Modifier = Modifier, ) { Box( modifier = modifier .background( color = colorScheme.onBackground, shape = RoundedCornerShape(4.dp), ), ) { Text( modifier = Modifier .padding(horizontal = 8.dp, vertical = 4.dp), text = stringResource(id = label), color = colorScheme.primary, style = typography.labelMedium, maxLines = 1, ) } } data class FloatingMenuState( val icon: Int, val items: List<MenuItemState>? = null, val onMenuClick: (() -> Unit)? = null, val alwaysVisibleButton: MenuItemState? = null, ) data class MenuItemState( val isShown: Boolean = true, @StringRes val label: Int, val icon: Int? = null, val onClick: () -> Unit, val semantics: String = "", ) @Preview @Composable fun MenuPreview() { FamillySpandingsTheme { Surface(modifier = Modifier.fillMaxSize()) { FloatingActionMenu( state = FloatingMenuState( icon = R.drawable.icon_edit, items = listOf( MenuItemState( label = R.string.button_ok, icon = R.drawable.icon_plus_outlined, onClick = {}, ), MenuItemState( label = R.string.button_cancel, icon = R.drawable.icon_delete, onClick = {}, ), ), ), ) } } }
0
Kotlin
0
0
e81fa66d6afd5b79d3299583a73378c3ee1463ca
8,874
FamilyBudget
Apache License 2.0
feature/search/src/main/java/com/mrl/pixiv/search/viewmodel/result/SearchResultMiddleware.kt
master-lzh
656,227,310
false
{"Kotlin": 499117}
package com.mrl.pixiv.search.viewmodel.result import com.mrl.pixiv.common.viewmodel.Middleware import com.mrl.pixiv.data.search.SearchIllustQuery import com.mrl.pixiv.repository.SearchRepository import com.mrl.pixiv.util.queryParams import org.koin.core.annotation.Factory @Factory class SearchResultMiddleware( private val searchRepository: SearchRepository, ) : Middleware<SearchResultState, SearchResultAction>() { override suspend fun process(state: SearchResultState, action: SearchResultAction) { when (action) { is SearchResultAction.SearchIllust -> searchIllust(action) is SearchResultAction.SearchIllustNext -> searchIllustNext(action) else -> Unit } } private fun searchIllust(action: SearchResultAction.SearchIllust) { launchNetwork { requestHttpDataWithFlow( request = searchRepository.searchIllust( SearchIllustQuery( word = action.searchWords, sort = state().searchFilter.sort, searchTarget = state().searchFilter.searchTarget, searchAiType = state().searchFilter.searchAiType, ) ), ) { dispatch( SearchResultAction.UpdateSearchIllustsResult( illusts = it.illusts, nextUrl = it.nextUrl, initial = true, ) ) } } } private fun searchIllustNext(action: SearchResultAction.SearchIllustNext) { launchNetwork { requestHttpDataWithFlow( request = searchRepository.searchIllustNext(action.nextUrl.queryParams) ) { dispatch( SearchResultAction.UpdateSearchIllustsResult( illusts = it.illusts, nextUrl = it.nextUrl, initial = false, ) ) } } } }
1
Kotlin
0
19
d23c86171381d7f2e43e647fdb72feac155a6ff3
2,108
PiPixiv
Apache License 2.0
Plugin/src/main/kotlin/cn/ctcraft/ctonlinereward/bukkit/menu/actions/Action.kt
CoderKuo
751,503,116
false
{"Kotlin": 133399, "Java": 2251, "JavaScript": 2}
package cn.ctcraft.ctonlinereward.bukkit.menu.actions import cn.ctcraft.ctonlinereward.common.CtOnlineRewardProxyPlayer interface Action<T> { val values: List<T> fun call(player: CtOnlineRewardProxyPlayer?, map: Map<String, Any>?): Any? }
0
Kotlin
0
1
5422c5efc83c34c348db8d8f799b93120bc72de3
251
CtOnlineReward2
Creative Commons Zero v1.0 Universal
android/app/src/main/java/com/algorand/android/assetsearch/data/mapper/AssetSearchDTOMapper.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.algorand.android.assetsearch.data.mapper import com.algorand.android.assetsearch.domain.model.AssetSearchDTO import com.algorand.android.models.AssetSearchResponse import javax.inject.Inject class AssetSearchDTOMapper @Inject constructor( private val collectibleSearchDTOMapper: CollectibleSearchDTOMapper, private val verificationTierDTODecider: VerificationTierDTODecider ) { fun mapToAssetSearchDTO(response: AssetSearchResponse): AssetSearchDTO { return AssetSearchDTO( assetId = response.assetId, fullName = response.fullName, shortName = response.shortName, logo = response.logo, verificationTier = verificationTierDTODecider.decideVerificationTierDTO(response.verificationTier), collectible = collectibleSearchDTOMapper.mapToCollectibleSearchDTO(response.collectible), usdValue = response.usdValue ) } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
1,526
pera-wallet
Apache License 2.0
app/shared/bitkey-primitives/fake/src/commonMain/kotlin/build/wallet/bitkey/socrec/UnendorsedTrustedContactFake.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.bitkey.socrec import build.wallet.crypto.PublicKey import build.wallet.encrypt.XCiphertext import okio.ByteString.Companion.encodeUtf8 val UnendorsedTrustedContactFake = UnendorsedTrustedContact( recoveryRelationshipId = "someRelationshipId", trustedContactAlias = TrustedContactAlias("someContact"), enrollmentPakeKey = PublicKey("deadbeef"), enrollmentKeyConfirmation = "".encodeUtf8(), sealedDelegatedDecryptionKey = XCiphertext("deadbeef"), authenticationState = TrustedContactAuthenticationState.UNAUTHENTICATED )
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
554
bitkey
MIT License
src/main/kotlin/grd/kotlin/authapi/jwt/JwtRequestFilter.kt
gardehal
708,548,046
false
{"Kotlin": 468271, "Shell": 612, "HTML": 331}
package grd.kotlin.authapi.jwt import grd.kotlin.authapi.Log import grd.kotlin.authapi.services.JwtService import grd.kotlin.authapi.settings.Settings import jakarta.servlet.FilterChain import jakarta.servlet.ServletException import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import kotlinx.coroutines.runBlocking import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Primary import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.web.authentication.WebAuthenticationDetailsSource import org.springframework.stereotype.Service import org.springframework.web.filter.OncePerRequestFilter import java.io.IOException @Primary @Service class JwtRequestFilter : OncePerRequestFilter() { @Autowired private lateinit var settings: Settings @Autowired private lateinit var jwtTokenUtil: JwtUtil private lateinit var jwtService: JwtService private var repositoryInitiated = false @Throws(ServletException::class, IOException::class) override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) = runBlocking { if(!repositoryInitiated) { jwtService = JwtService() repositoryInitiated = true } val requestTokenHeader = request.getHeader(settings.server.authenticationHeader) var username: String? = null var jwtToken: String? = null if(requestTokenHeader == null) { Log.main.info("JWT token was not found with header {header}, {function}", settings.server.authenticationHeader, this.toString()) chain.doFilter(request, response) return@runBlocking } else if(!requestTokenHeader.startsWith(settings.jwt.tokenPrefix!!)) { val tokenStart = requestTokenHeader.substring(0, 7) Log.main.info("JWT token does not begin with prefix {prefix}, {actualTokenStart}, {header}, {function}", settings.jwt.tokenPrefix!!, tokenStart, settings.server.authenticationHeader, this.toString()) chain.doFilter(request, response) return@runBlocking } else { try { // JWT Token is in the form "Bearer <token>". Remove Bearer word and get only the Token jwtToken = requestTokenHeader.substring(7) username = jwtTokenUtil.getUsernameFromToken(jwtToken) } catch(e: Exception) { Log.main.info("JWT token was invalid, {message}, {function}", e.message, this.toString()) // e.printStackTrace() } } // Once we get the token validate it. if(username != null && SecurityContextHolder.getContext().authentication == null) { val user = jwtService.findByUsernameEmail(username) // If token is valid configure Spring Security to manually set authentication if(jwtTokenUtil.validateToken(jwtToken!!, user)) { val g = GrantedAuthority { user.role.toString() } val gl = listOf(g) val usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken(user, user.id, gl) usernamePasswordAuthenticationToken.details = WebAuthenticationDetailsSource().buildDetails(request) // After setting the Authentication in the context, we specify // that the current user is authenticated. So it passes the Spring Security Configurations successfully. SecurityContextHolder.getContext().authentication = usernamePasswordAuthenticationToken } } chain.doFilter(request, response) } }
0
Kotlin
0
0
14ed0a4f310f90c32880bfd1d0eacbe4c8780bd0
4,007
kotlin-auth-api
MIT License
zedge/src/main/java/net/suyambu/zedge/Zedge.kt
whoisjeeva
380,497,906
false
{"Kotlin": 21809}
package net.suyambu.zedge import net.suyambu.zedge.data.* import org.json.JSONObject import sh.fearless.hiper.Hiper import sh.fearless.hiper.controllers.Caller import java.net.URLEncoder class Zedge { companion object { const val API_URL = "https://api-gateway.zedge.net/" @Volatile private var wallInstance: Wallpaper? = null @Volatile private var ringInstance: Ringtone? = null fun getWallpaperInstance() = wallInstance ?: synchronized(this) { wallInstance ?: Zedge().Wallpaper() } fun getRingtoneInstance() = ringInstance ?: synchronized(this) { ringInstance ?: Zedge().Ringtone() } } private val hiper = Hiper.getInstance().async() private val trendingQuery = "\n query browse(\$input: BrowseAsUgcInput!) {\n browseAsUgc(input: \$input) {\n ...browseContentItemsResource\n }\n }\n \n fragment browseContentItemsResource on BrowseContentItems {\n page\n total\n items {\n ... on BrowseWallpaper {\n id\n contentType\n title\n tags\n imageUrl\n placeholderUrl\n licensed\n }\n\n ... on BrowseRingtone {\n id\n contentType\n title\n tags\n imageUrl\n placeholderUrl\n licensed\n meta {\n durationMs\n previewUrl\n gradientStart\n gradientEnd\n }\n }\n }\n }\n\n " private val directUrlQuery = "\n query contentDownloadUrl(\$itemId: ID!) {\n contentDownloadUrlAsUgc(itemId: \$itemId)\n }\n " private val searchQuery = "\n query search(\$input: SearchAsUgcInput!) {\n searchAsUgc(input: \$input) {\n ...browseContentItemsResource\n }\n }\n \n fragment browseContentItemsResource on BrowseContentItems {\n page\n total\n items {\n ... on BrowseWallpaper {\n id\n contentType\n title\n tags\n imageUrl\n placeholderUrl\n licensed\n }\n\n ... on BrowseRingtone {\n id\n contentType\n title\n tags\n imageUrl\n placeholderUrl\n licensed\n meta {\n durationMs\n previewUrl\n gradientStart\n gradientEnd\n }\n }\n }\n }\n\n " inner class Ringtone { fun trending(page: Int, callback: ZedgeAudio.() -> Unit): Caller { val json = JSONObject(""" {"variables":{"input":{"contentType":"RINGTONE","page":$page,"size":24}}} """.trimIndent()) json.put("query", trendingQuery) val queue = hiper.post(API_URL, json=json) queue.resolve { resp -> var obj = JSONObject(resp.text!!) if (obj.has("errors")) { val out = ZedgeAudio( page = page, pageCount = 0, audios = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback.invoke(out) } else { obj = obj.getJSONObject("data").getJSONObject("browseAsUgc") val audios = ArrayList<Audio>() val items = obj.getJSONArray("items") for (i in 0 until items.length()) { val item = items.getJSONObject(i) audios.add(Audio( id = item.getString("id"), imageUrl = item.getString("imageUrl"), licensed = item.getBoolean("licensed"), title = item.getString("title"), audioUrl = item.getJSONObject("meta").getString("previewUrl"), gradientStart = item.getJSONObject("meta").getString("gradientStart"), gradientEnd = item.getJSONObject("meta").getString("gradientEnd") )) } val out = ZedgeAudio( page = page, pageCount = obj.getInt("total"), audios = audios, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback.invoke(out) } } queue.reject { resp -> val out = ZedgeAudio( page = page, pageCount = 0, audios = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback.invoke(out) } queue.catch { throw it } return queue.execute() } fun search(query: String, page: Int, callback: ZedgeAudio.() -> Unit): Caller { val json = JSONObject(""" {"variables":{"input":{"contentType":"RINGTONE","keyword":"${URLEncoder.encode(query.replace("\"", ""), "UTF-8")}","page":$page,"size":24}}} """.trimIndent()) json.put("query", searchQuery) val queue = hiper.post(API_URL, json = json) queue.resolve { resp -> var obj = JSONObject(resp.text!!) if (obj.has("errors")) { val out = ZedgeAudio( page = page, pageCount = 0, audios = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } else { obj = obj.getJSONObject("data").getJSONObject("searchAsUgc") val audios = ArrayList<Audio>() val items = obj.getJSONArray("items") for (i in 0 until items.length()) { val item = items.getJSONObject(i) audios.add(Audio( id = item.getString("id"), imageUrl = item.getString("imageUrl"), licensed = item.getBoolean("licensed"), title = item.getString("title"), audioUrl = item.getJSONObject("meta").getString("previewUrl"), gradientStart = item.getJSONObject("meta").getString("gradientStart"), gradientEnd = item.getJSONObject("meta").getString("gradientEnd") )) } val out = ZedgeAudio( page = page, pageCount = obj.getInt("total"), audios = audios, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } } queue.reject { resp -> val out = ZedgeAudio( page = page, pageCount = 0, audios = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } queue.catch { throw it } return queue.execute() } } inner class Wallpaper { fun search(query: String, page: Int, callback: ZedgeImage.() -> Unit): Caller { val json = JSONObject(""" {"variables":{"input":{"contentType":"WALLPAPER","keyword":"${URLEncoder.encode(query.replace("\"", ""), "UTF-8")}","page":$page,"size":24}}} """.trimIndent()) json.put("query", searchQuery) val queue = hiper.post(API_URL, json = json) queue.resolve { resp -> var obj = JSONObject(resp.text!!) if (obj.has("errors")) { val out = ZedgeImage( page = page, pageCount = 0, images = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } else { obj = obj.getJSONObject("data").getJSONObject("searchAsUgc") val images = ArrayList<Image>() val items = obj.getJSONArray("items") for (i in 0 until items.length()) { val item = items.getJSONObject(i) images.add(Image( id = item.getString("id"), imageUrl = item.getString("imageUrl"), licensed = item.getBoolean("licensed"), title = item.getString("title") )) } val out = ZedgeImage( page = page, pageCount = obj.getInt("total"), images = images, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } } queue.reject { resp -> val out = ZedgeImage( page = page, pageCount = 0, images = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } queue.catch { throw it } return queue.execute() } fun directUrl(itemId: String, callback: ZedgeUrl.() -> Unit): Caller { val json = JSONObject(""" {"variables":{"itemId":"$itemId"}} """.trimIndent()) json.put("query", directUrlQuery) val queue = hiper.post(API_URL, json = json) queue.resolve { resp -> val obj = JSONObject(resp.text!!) if (obj.has("errors")) { callback(ZedgeUrl( url = null, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text )) } else { val url = obj.getJSONObject("data").getString("contentDownloadUrlAsUgc") callback(ZedgeUrl( url = url, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text )) } } queue.reject { resp -> callback(ZedgeUrl( url = null, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text )) } queue.catch { throw it } return queue.execute() } fun trending(page: Int, callback: ZedgeImage.() -> Unit): Caller { val json = JSONObject(""" {"variables":{"input":{"contentType":"WALLPAPER","page":$page,"size":24}}} """.trimIndent()) json.put("query", trendingQuery) val queue = hiper.post(API_URL, json=json) queue.resolve { resp -> var obj = JSONObject(resp.text!!) if (obj.has("errors")) { val out = ZedgeImage( page = page, pageCount = 0, images = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } else { obj = obj.getJSONObject("data").getJSONObject("browseAsUgc") val images = ArrayList<Image>() val items = obj.getJSONArray("items") for (i in 0 until items.length()) { val item = items.getJSONObject(i) images.add(Image( id = item.getString("id"), imageUrl = item.getString("imageUrl"), licensed = item.getBoolean("licensed"), title = item.getString("title") )) } val out = ZedgeImage( page = page, pageCount = obj.getInt("total"), images = images, statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } } queue.reject { resp -> val out = ZedgeImage( page = page, pageCount = 0, images = listOf(), statusMessage = resp.message, statusCode = resp.statusCode, isSuccessful = resp.isSuccessful, isRedirect = resp.isRedirect, headers = resp.headers, contentText = resp.text ) callback(out) } queue.catch { throw it } return queue.execute() } } }
0
Kotlin
1
2
36b1e7fc28b7ea3211e5705a153ab31bd05dcfec
16,534
zedge
MIT License
connectors/http/src/jvmMain/kotlin/com/river/connector/http/CustomHttpRequestBuilder.kt
River-Kt
539,201,163
false
{"Kotlin": 450835, "Shell": 268, "Python": 126}
package com.river.connector.http import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.jdk9.asPublisher import java.net.URI import java.net.http.HttpHeaders import java.net.http.HttpRequest import java.net.http.HttpRequest.BodyPublisher import java.net.http.HttpRequest.BodyPublishers.* import java.net.http.HttpRequest.newBuilder import java.nio.ByteBuffer import java.nio.charset.Charset import java.util.concurrent.Flow.Publisher /** * A class that builds HTTP requests with custom features like query parameters and authorization. * * @property method An HTTP method to be used in the request. * @property other A builder instance of HttpRequest.Builder used to build the HTTP request. */ class CustomHttpRequestBuilder( private val method: HttpMethod, private val other: HttpRequest.Builder = newBuilder().method(method.name, noBody()) ) : HttpRequest.Builder by other { private val queryParameters = mutableMapOf<String, List<String>>() /** * Adds multiple headers and overrides the old values * * @param headers The headers to be overridden. * @return Returns this builder instance. */ fun setHeaders( headers: Map<String, List<String>> ): CustomHttpRequestBuilder { headers.forEach { (key, values) -> setHeader(key, values.firstOrNull()) values.drop(1).forEach { header(key, it) } } return this } /** * Adds a query parameter with a single value. * * @param name The name of the query parameter. * @param value The value of the query parameter. * @return Returns this builder instance. */ fun query( name: String, value: String ): CustomHttpRequestBuilder = query(name, listOf(value)) /** * Adds a query parameter with multiple values. * * @param name The name of the query parameter. * @param values The values of the query parameter. * @return Returns this builder instance. */ fun query( name: String, vararg values: String ): CustomHttpRequestBuilder = query(name, values.toList()) /** * Adds a query parameter with a list of values. * * @param name The name of the query parameter. * @param values The values of the query parameter. * @return Returns this builder instance. */ fun query( name: String, values: List<String> ): CustomHttpRequestBuilder { queryParameters[name]?.let { queryParameters[name] = it + values } return this } /** * Set a query parameter with a list of values. * * @param name The name of the query parameter. * @param values The values of the query parameter. * @return Returns this builder instance. */ fun setQuery( name: String, values: List<String> ): CustomHttpRequestBuilder { queryParameters[name] = values return this } /** * Set a query parameter with a list of values. * * @param name The name of the query parameter. * @param values The values of the query parameter. * @return Returns this builder instance. */ fun setQueryParameters( parameters: Map<String, List<String>> ): CustomHttpRequestBuilder { queryParameters.clear() queryParameters.putAll(parameters) return this } /** * Sets the URI of the request. * * @param uri The URI to set. * @return Returns the HttpRequest.Builder instance. */ override fun uri(uri: URI): HttpRequest.Builder = other.uri( when { queryParameters.isEmpty() -> uri else -> { queryParameters .toList() .flatMap { (key, values) -> values.map { key to it } } .joinToString(separator = "&", prefix = "?") { (key, value) -> "$key=$value" } .let { URI("$uri$it") } } } ) /** * Sets the Content-Type of the HTTP request. * * @param value The value of the Content-Type. * @return Returns the HttpRequest.Builder instance. */ fun contentType( value: String ): HttpRequest.Builder = header("Content-Type", value) /** * Sets the Accept of the HTTP request. * * @param value The value of the Accept. * @return Returns the HttpRequest.Builder instance. */ fun accept( value: String ): HttpRequest.Builder = header("Accept", value) /** * Adds an authorization to the HTTP request. * * @param f A function to create an Authorization object. * @return Returns the HttpRequest.Builder instance. */ inline fun authorization( f: Authorization.Companion.() -> Authorization ): HttpRequest.Builder = header( "Authorization", f(Authorization.Companion).headerValue() ) /** * Sets the body of the HTTP request as a String. * * @param value The value of the request body. * @param charset The charset to be used, default is Charset.defaultCharset(). * @return Returns the HttpRequest.Builder instance. */ fun stringBody( value: String, charset: Charset = Charset.defaultCharset() ): HttpRequest.Builder = body(ofString(value, charset)) /** * Sets the body of the HTTP request as a ByteArray. * * @param value The value of the request body. * @return Returns the HttpRequest.Builder instance. */ fun byteArrayBody( value: ByteArray ): HttpRequest.Builder = body(ofByteArray(value)) /** * Sets the body of the HTTP request as a Flow<ByteBuffer>. * * @param value The value of the request body. * @param contentLength The content length of the request body. * @return Returns the HttpRequest.Builder instance. */ fun flowBody( value: Flow<ByteBuffer>, contentLength: Long? = null ): HttpRequest.Builder = publisherBody( body = fromPublisher(value.asPublisher()), contentLength = contentLength ) /** * Sets the body of the HTTP request as a Publisher<ByteBuffer>. * * @param body The body of the request. * @param contentLength The content length of the request body. * @return Returns the HttpRequest.Builder instance. */ fun publisherBody( body: Publisher<ByteBuffer>, contentLength: Long? = null ): HttpRequest.Builder = when (contentLength) { null, 0L -> body(fromPublisher(body)) else -> body(fromPublisher(body, contentLength)) } /** * Sets the body of the HTTP request. * * @param body The BodyPublisher object. * @return Returns the HttpRequest.Builder instance. */ fun body( body: BodyPublisher, ): HttpRequest.Builder = method(method.name, body) }
30
Kotlin
3
79
9841047b27268172a42e0e1ec74b095c0202a2cc
7,092
river
MIT License
app/src/main/java/com/floatworld/diacsc/composes/login/signUpPage.kt
sheepthefather
718,470,059
false
{"Kotlin": 196025}
package com.floatworld.diacsc.composes.login import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer 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.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.floatworld.diacsc.R import com.floatworld.diacsc.loginActivity.viewModel.LoginViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun SignUpPage(){ val context= LocalContext.current Column(modifier = Modifier .fillMaxWidth() .padding(10.dp) ) { val model:LoginViewModel= viewModel() OutlinedTextField(modifier = Modifier.fillMaxWidth(), leadingIcon = { Icon( painter = painterResource(id = R.drawable.baseline_person_outline_24), contentDescription = "用户名图标" ) },value = model.name.value, onValueChange = {model.name.value=it}, label = { Text(text = "用户名") }, isError = model.isError(model.name.value)) OutlinedTextField(modifier = Modifier.fillMaxWidth(), leadingIcon = { Icon(painter = painterResource(id = R.drawable.baseline_ket_24), contentDescription = "密码图标") },value = model.passwd.value, onValueChange = {model.passwd.value=it}, label = { Text(text = "密码") }, visualTransformation = {text-> TransformedText(AnnotatedString("*".repeat(text.length)), OffsetMapping.Identity) }, isError = model.isError(model.passwd.value) || model.passwd.value!=model.repeatPasswd.value) OutlinedTextField(modifier = Modifier.fillMaxWidth(), leadingIcon = { Icon(painter = painterResource(id = R.drawable.baseline_ket_24), contentDescription = "密码图标") },value = model.repeatPasswd.value, onValueChange = {model.repeatPasswd.value=it}, label = { Text(text = "再次输入密码") }, visualTransformation = {text-> TransformedText(AnnotatedString("*".repeat(text.length)), OffsetMapping.Identity) },isError = model.isError(model.repeatPasswd.value) || model.passwd.value!=model.repeatPasswd.value) Spacer(modifier = Modifier.height(50.dp)) Button(modifier = Modifier .align(Alignment.CenterHorizontally) .size(height = 50.dp, width = 200.dp), shape= MaterialTheme.shapes.small,onClick = { model.signUp(context) }) { Text(text = "注册") } } }
0
Kotlin
0
0
bf389165e4fe65eb4dee8044134a5d1dfddcd55e
3,322
Diacsc
Apache License 2.0
composeApp/src/commonMain/kotlin/feature/main/entity/DisplayExt.kt
FrankieShao
815,291,399
false
{"Kotlin": 347190, "Swift": 657}
package feature.main.entity import core.domain.model.Configure import core.domain.model.Media import core.domain.model.Movie import core.domain.model.TVShow import ui.DisplayItem /** * @author <NAME> * @created 03/06/2024 * Description: Display Item Extension */ fun Movie.toDisplayItem(configure: Configure?) = DisplayItem.Movie( movieId = id.toString(), posterUrl = configure?.urlPrefix + posterPath, backdropUrl = configure?.urlPrefix + backdropPath, ) fun TVShow.toDisplayItem(configure: Configure?) = DisplayItem.Movie( movieId = id.toString(), posterUrl = configure?.urlPrefix + posterPath, backdropUrl = configure?.urlPrefix + backdropPath, ) fun Media.toDisplayItem(configure: Configure?) = when (this) { is Movie -> toDisplayItem(configure) is TVShow -> toDisplayItem(configure) else -> throw IllegalArgumentException("Unknown media type") }
0
Kotlin
0
0
5137399a0b2d5554aa49377ed5d853cfece5dc68
896
FlickFusion
MIT License
app/src/main/java/com/cngal/app/uistate/article/SingleArticleUiState.kt
CnGal
648,083,407
false
{"Kotlin": 421043}
package com.cngal.app.uistate.article class SingleArticleUiState { var link :String="" var shareText :String="" }
0
Kotlin
1
2
6703376adae97557825f39d7492a04b3aee55729
122
cngal-jetpack-app
MIT License
libs/core-search/src/main/kotlin/openBook/model/Book.kt
Arslanka-Educational
784,642,540
false
{"Kotlin": 121240}
package openBook.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonValue import openBook.model.BookStatus /** * * @param id * @param bookInfoId * @param libraryId library this is in * @param status */ data class Book( @get:JsonProperty("id", required = true) val id: java.util.UUID, @get:JsonProperty("bookInfoId") val bookInfoId: java.util.UUID? = null, @get:JsonProperty("libraryId") val libraryId: java.util.UUID? = null, @get:JsonProperty("status") val status: BookStatus? = null ) { }
1
Kotlin
0
4
fba88651674e394bf2b302095fa3ff5fdc3cfc13
602
OpenBook
Apache License 2.0
app/src/main/java/com/example/android/unscramble/ui/game/GameFragment.kt
codeitashu5
391,960,342
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.unscramble.ui.game import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.android.unscramble.R import com.example.android.unscramble.databinding.GameFragmentBinding import com.google.android.material.dialog.MaterialAlertDialogBuilder /** * Fragment where the game is played, contains the game logic. */ class GameFragment : Fragment() { //this is property delegation private val viewModel: GameViewModel by viewModels() // Binding object instance with access to the views in the game_fragment.xml layout private lateinit var binding: GameFragmentBinding // Create a ViewModel the first time the fragment is created. // If the fragment is re-created, it receives the same GameViewModel instance created by the // first fragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout XML file and return a binding object instance binding = DataBindingUtil.inflate( inflater, R.layout.game_fragment, container, false ) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //providing data to the data variables in the layout file binding.gameViewModel = viewModel binding.maxNoOfWords = MAX_NO_OF_WORDS //adding livecycle owner binding.lifecycleOwner = viewLifecycleOwner // Setup a click listener for the Submit and Skip buttons. binding.submit.setOnClickListener { onSubmitWord() } binding.skip.setOnClickListener { onSkipWord() } // Update the UI for the initial value for currentScrambled word /*observer fro currentScrambledWord viewModel.currentScrambledWord.observe(viewLifecycleOwner,{ newWord-> binding.textViewUnscrambledWord.text = newWord })*/ /*observer for score viewModel.score.observe(viewLifecycleOwner,{ newScore-> binding.score.text = getString(R.string.score,newScore) })*/ /*observer for currentWordCount viewModel.currentWordcount.observe(viewLifecycleOwner,{ newCount-> binding.wordCount.text = getString(R.string.word_count,newCount,MAX_NO_OF_WORDS) })*/ } //Checks the user's word, and updates the score accordingly. //Displays the next scrambled word. private fun onSubmitWord() { val playerWord = binding.textInputEditText.text.toString() if(viewModel.isUserWordCorrect(playerWord)){ setErrorTextField(false) if (!viewModel.nextWord()) { showAlertDialog() } } else{ setErrorTextField(true) } } //Skips the current word without changing the score. //Increases the word count. private fun onSkipWord() { if(viewModel.nextWord()){ setErrorTextField(false) }else{ showAlertDialog() } } //restart the game. private fun restartGame() { setErrorTextField(false) viewModel.reInitialize() setErrorTextField(false) } //Exits the game. private fun exitGame() { activity?.finish() } //Sets and resets the text field error status. private fun setErrorTextField(error: Boolean) { if (error) { binding.textField.isErrorEnabled = true binding.textField.error = getString(R.string.try_again) } else { binding.textField.isErrorEnabled = false binding.textInputEditText.text = null } } //function to create dialog private fun showAlertDialog(){ MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.congratulations) .setMessage(getString(R.string.you_scored,viewModel.score.value)) .setCancelable(false) .setNegativeButton(getString(R.string.exit)) { _,_-> exitGame() } .setPositiveButton(R.string.play_again){ _,_-> restartGame() } .show() } }
0
Kotlin
0
0
a29fce0bcf625804ca6f7bf335307bef22520f7f
5,154
ViewModel
Apache License 2.0
GreenGarbageApp/app/src/main/java/com/example/greengarbageapp/activities/MainActivity.kt
DIT113-V22
471,135,351
false
{"Kotlin": 51182, "GDScript": 15484, "C++": 6087, "GAP": 348}
package com.example.greengarbageapp.activities import android.media.AudioManager import android.media.MediaPlayer import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import com.example.greengarbageapp.R import com.example.greengarbageapp.databinding.ActivityMainBinding import java.io.IOException class MainActivity : AppCompatActivity(){ private lateinit var drawerLayout: DrawerLayout private lateinit var appBarConfiguration : AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main) drawerLayout = binding.drawerLayout val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment val navController = navHostFragment.navController NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout) appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout) NavigationUI.setupWithNavController(binding.navView, navController) navController.addOnDestinationChangedListener { navController: NavController, navDestination: NavDestination, bundle: Bundle? -> if (navDestination.id == navController.graph.startDestinationId) { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) } else { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) } } } override fun onSupportNavigateUp(): Boolean { val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment val navController = navHostFragment.navController return NavigationUI.navigateUp(navController, appBarConfiguration) } private var mediaPlayer=MediaPlayer() private val url = "https://www.bensound.com/bensound-music/bensound-ukulele.mp3" fun playSong(view: View) { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC) mediaPlayer.isLooping = true if(!mediaPlayer.isPlaying){ Toast.makeText(this,"Music is playing", Toast.LENGTH_SHORT).show() try { mediaPlayer.setDataSource(url) mediaPlayer.prepare() mediaPlayer.start() } catch (e: IOException) { e.printStackTrace() } }else { Toast.makeText(this,"Music stopped", Toast.LENGTH_SHORT).show() try { mediaPlayer.pause() mediaPlayer.stop() mediaPlayer.reset() } catch (e: IOException) { e.printStackTrace() } } } } // Create an ArrayAdapter
0
Kotlin
2
1
cf51b6b85e58a14f83a1d8cc2036f2d4641cf413
3,296
group-07
MIT License
web/src/main/kotlin/showdown.web/ui/common/HookTest.kt
bbassett
337,838,734
true
{"Kotlin": 100750, "HTML": 1189, "CSS": 661, "JavaScript": 419}
package showdown.web.ui.common import materialui.components.snackbar.enums.SnackbarOriginHorizontal import materialui.components.snackbar.enums.SnackbarOriginVertical import materialui.components.snackbar.horizontal import materialui.components.snackbar.snackbar import materialui.components.snackbar.vertical import materialui.lab.components.alert.alert import materialui.lab.components.alert.enums.AlertSeverity import materialui.lab.components.alert.enums.AlertVariant import react.RBuilder import react.RProps import react.child import react.functionalComponent import react.useEffect import react.useState fun RBuilder.mySnackbar(message:String,onClose:()->Unit) { child(mySnackbar){ attrs.snackbarMessage=message attrs.onClose=onClose } } external interface MySnackbarProps : RProps { var snackbarMessage: String var onClose:()->Unit } val mySnackbar = functionalComponent<MySnackbarProps> {props-> val text = props.snackbarMessage val (visible, setVisibility) = useState(true) snackbar { attrs { anchorOrigin { this.horizontal= SnackbarOriginHorizontal.left this.vertical= SnackbarOriginVertical.bottom } this.open = visible autoHideDuration=5000 onClose={_,_-> setVisibility(false) props.onClose() } } alert { attrs { severity= AlertSeverity.info variant= AlertVariant.filled } +text } } }
0
null
0
0
953b63110280dba9952cdde4436ee828e27ea5de
1,594
Showdown
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/PuppyApplication.kt
vivart
342,747,093
false
null
/* * 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 * * 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.example.androiddevchallenge import android.app.Application import com.example.androiddevchallenge.di.appModule import org.koin.android.BuildConfig import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.GlobalContext.startKoin import org.koin.core.logger.Level class PuppyApplication : Application() { override fun onCreate() { super.onCreate() // Start Koin startKoin { androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE) androidContext(this@PuppyApplication) modules(appModule) } } }
0
Kotlin
0
0
ffc1e71ec5bf57e742a8e1032a8606bad144b6fb
1,274
puppy
Apache License 2.0
common/src/main/java/com/yuriikonovalov/common/data/sources/UpdateBiometricAuthenticationOnSourceImpl.kt
yuriikonovalov
563,974,428
false
{"Kotlin": 872022}
package com.yuriikonovalov.common.data.sources import com.yuriikonovalov.common.application.usecases.datasources.UpdateBiometricAuthenticationOnSource import com.yuriikonovalov.common.data.local.AppPreferences import javax.inject.Inject class UpdateBiometricAuthenticationOnSourceImpl @Inject constructor( private val appPreferences: AppPreferences ) : UpdateBiometricAuthenticationOnSource { override suspend fun updateBiometricAuthenticationOn(on: Boolean) { appPreferences.updateBiometricAuthenticationOn(on) } }
0
Kotlin
0
0
8063508f836512fc8f8a0ba18f794bb895ee2449
537
budgethub
MIT License
common/src/commonMain/kotlin/com/artemchep/keyguard/feature/duplicates/DuplicatesScreen.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.feature.duplicates import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import com.artemchep.keyguard.feature.duplicates.list.DuplicatesListRoute import com.artemchep.keyguard.feature.navigation.NavigationRouter import com.artemchep.keyguard.feature.twopane.TwoPaneNavigationContent import com.artemchep.keyguard.ui.screenMaxWidthCompact @Composable fun DuplicatesScreen( args: DuplicatesRoute.Args, ) { val initialRoute = remember(args) { DuplicatesListRoute( args = args, ) } NavigationRouter( id = DuplicatesRoute.ROUTER_NAME, initial = initialRoute, ) { backStack -> TwoPaneNavigationContent( backStack, detailPaneMaxWidth = screenMaxWidthCompact, ) } }
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
830
keyguard-app
Linux Kernel Variant of OpenIB.org license
base_component/src/main/java/com/william/base_component/manager/ActivityStackManager.kt
Seachal
357,416,143
true
{"Kotlin": 166552, "Java": 22100}
package com.william.base_component.manager import android.app.Activity import java.util.* /** * @author William * @date 2020/4/17 11:44 * Class Comment:Activity Stack Manager */ object ActivityStackManager { private var mActivityStack: Stack<Activity> = Stack() /** * push in */ fun addActivity(activity: Activity) { mActivityStack.push(activity) } /** * pop out */ private fun removeActivity(activity: Activity) { mActivityStack.remove(activity) } /** * get current instance/top instance in the stack */ fun getCurrentActivity(): Activity? { if (mActivityStack.size > 0) { return mActivityStack[mActivityStack.size - 1] } return null } /** * check the activity instance is exist */ fun checkActivity(cla: Class<*>): Boolean { for (activity in mActivityStack) { return activity.javaClass == cla } return false } /** * end the specified activity class */ fun endActivity(cla: Class<*>) { for (activity in mActivityStack) { if (activity.javaClass == cla) { activity.finish() } } } /** * end the specified activity instance */ fun endActivity(activity: Activity?) { if (activity != null) { removeActivity(activity) activity.finish() } } /** * end specified instances */ fun endActivities(vararg actCls: Class<out Activity>) { try { val buf: MutableList<Activity> = ArrayList() val size = mActivityStack.size for (i in size - 1 downTo 0) { val activity = mActivityStack[i] for (actCl in actCls) { if (activity.javaClass != actCl) { buf.add(activity) } } } for (activity in buf) { endActivity(activity) } } catch (e: NullPointerException) { e.printStackTrace() } catch (e: Exception) { e.printStackTrace() } } /** * end all activity instance */ fun endAllActivity() { var activity: Activity? while (mActivityStack.isNotEmpty()) { activity = mActivityStack.pop() activity?.finish() } } /** * end top of the specified instance */ fun endToActivity(actCls: Class<out Activity>, isIncludeSelf: Boolean): Boolean { val buf: MutableList<Activity> = ArrayList() val size = mActivityStack.size var activity: Activity for (i in size - 1 downTo 0) { activity = mActivityStack[i] if (activity.javaClass.isAssignableFrom(actCls)) { for (a in buf) { a.finish() } return true } else if (i == size - 1 && isIncludeSelf) { buf.add(activity) } else if (i != size - 1) { buf.add(activity) } } return false } }
0
null
0
0
e4dc012c41c599055e62316e2055daad3177fb9c
3,202
EasyKotlin
Apache License 2.0
libraries/core/src/main/java/com/n27/core/presentation/detail/entities/DetailState.kt
Narsuf
52,900,182
false
{"Kotlin": 247331}
package com.n27.core.presentation.detail.entities import com.n27.core.domain.election.Election sealed class DetailState { object Loading : DetailState() data class Error(val error: String? = null) : DetailState() data class Content(val election: Election) : DetailState() }
1
Kotlin
0
2
b61771d2c984840e21f4a8dfd4fb67dcb9480d73
289
Elections
Apache License 2.0
src/main/kotlin/dokerplp/bot/model/service/FaqService.kt
dokerplp
407,882,967
false
{"Kotlin": 55171}
package dokerplp.bot.model.service import dokerplp.bot.model.entity.FaqEntity import org.springframework.stereotype.Service @Service interface FaqService { fun findAll(): MutableIterable<FaqEntity> fun save(entity: FaqEntity): FaqEntity fun getById(id: Long): FaqEntity? fun deleteAll() }
0
Kotlin
0
0
b3c530a3c7aff82a9072348ba036b364f33d0769
306
abit-vt-bot
Apache License 2.0
src/main/kotlin/mobi/appcent/openai/apis/EngineApi.kt
AppcentMobile
624,070,344
false
null
package mobi.appcent.openai.apis import mobi.appcent.openai.common.UrlConstant import mobi.appcent.openai.infrastructure.* import mobi.appcent.openai.models.Engine import mobi.appcent.openai.models.ListEnginesResponse /** * Created by erenalpaslan on 5.04.2023 */ class EngineApi: BaseApi() { /** * Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability. * * @return ListEnginesResponse */ fun listEngines(): ListEnginesResponse { val localVariableConfig = RequestConfig( RequestMethod.GET, UrlConstant.ENGINES_URL ) val response = apiClient.request<ListEnginesResponse>( localVariableConfig ) return when (response.responseType) { ResponseType.Success -> (response as Success<*>).data as ListEnginesResponse ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error") ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error") } } /** * Retrieves a model instance, providing basic information about it such as the owner and availability. * * @param engineId The ID of the engine to use for this request * @return Engine */ fun retrieveEngine(engineId: String): Engine { val localVariableConfig = RequestConfig( RequestMethod.GET, "${UrlConstant.ENGINES_URL}/" + engineId ) val response = apiClient.request<Engine>( localVariableConfig ) return when (response.responseType) { ResponseType.Success -> (response as Success<*>).data as Engine ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error") ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error") } } }
1
Kotlin
0
6
0bcf3b69ff1ba8e337113f74e4b0fb8880b28c06
2,066
ACMOpenAI-Android
MIT License
app/src/main/java/com/example/cupcake/model/OrderViewModel.kt
eduardobape
409,770,117
false
{"Kotlin": 20836}
package com.example.cupcake.model import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.* private const val PRICE_PER_CUPCAKE = 2.00 private const val PRICE_FOR_SAME_DAY_PICKUP = 3.00 class OrderViewModel : ViewModel() { private val _quantity = MutableLiveData<Int>() val quantity: LiveData<Int> = _quantity private val _flavors: MutableLiveData<MutableList<String>> = MutableLiveData<MutableList<String>>() val flavors: LiveData<MutableList<String>> = _flavors private val _date = MutableLiveData<String>() val date: LiveData<String> = _date private val _price = MutableLiveData<Double>() val price: LiveData<String> = Transformations.map(_price) { NumberFormat.getCurrencyInstance().format(it) } private val _userName = MutableLiveData<String>() val userName: LiveData<String> = _userName val dateOptions = getPickupOptions() init { _flavors.value = mutableListOf() resetOrder() } fun setQuantity(numberCupcakes: Int) { _quantity.value = numberCupcakes updatePrice() } fun addFlavour(flavor: String) { _flavors.value?.add(flavor) } fun removeFlavour(flavor: String) { _flavors.value?.remove(flavor) } fun setDate(pickupDate: String) { _date.value = pickupDate updatePrice() } fun setUserName(userName: String) { _userName.value = userName } fun hasNoFlavorSet(): Boolean { return _flavors.value.isNullOrEmpty() } fun getPickupOptions(): List<String> { val options = mutableListOf<String>() val formatter = SimpleDateFormat("E MMM d", Locale.getDefault()) val calendar = Calendar.getInstance() repeat(4) { options.add(formatter.format(calendar.time)) calendar.add(Calendar.DAY_OF_MONTH, 1) } return options } fun resetOrder() { _quantity.value = 0 _flavors.value?.clear() _date.value = dateOptions[0] _userName.value = "" _price.value = 0.0 } private fun updatePrice() { var calculatedPrice = (_quantity.value ?: 0) * PRICE_PER_CUPCAKE if (_date.value == dateOptions[0]) { calculatedPrice += PRICE_FOR_SAME_DAY_PICKUP } _price.value = calculatedPrice } }
0
Kotlin
0
0
b2978df383aad38c528ca8e99f93754c16f7b8fc
2,528
cupcake-android-app
Apache License 2.0
app/src/main/java/com/softwarehut/mvpplayground/domain/splash/SplashView.kt
softwarehutpl
139,710,457
false
{"Kotlin": 49242}
package com.softwarehut.mvpplayground.domain.splash import com.softwarehut.mvp.domain.paramless.View interface SplashView : View { fun navigateToIntroductionScreen() }
0
Kotlin
0
0
fe91f41fad6413a8dabd3b3e9e1e0826e8cd7553
174
MvpPlayground
Apache License 2.0
样例/数据容器.kts
PPKunOfficial
475,409,421
false
{"Kotlin": 3830}
//数组 //1.arrayOf创建数组 //arrayOf创建一个数组并且传递元素给变量,及 val n = arrayOf(1,2,3) //arrayOf()内部可以填任意类型 //Example val arrayOfCreate = arrayOf(false, 1, "二", "3") //2.arrayOfNulls创建数组 //创建指定大小且所有元素都为空的数组 //集合中的元素必须被定义(也就是说必须元素类型相同)! val arrayOfNullsCreate = arrayOfNulls<String>(5) //(暂时不明白) 3.动态创建数组 // 用接受数组大小以及一个方法参数的Array构造方法 // 用作参数的方法能够返回给定索引的每个元素初始值 // 创建一个 Array<String> 初始化为 ["0", "1", "4", "9", "16"] val asc = Array(5) { i -> (i * i).toString() } asc.forEach { println(it) } // 1.创建并初始化一个IntArray [1,2,3,4,5] val intArray = intArrayOf(1, 2, 3, 4, 5) // 2.创建一个长度为5的空整数数组 val intArray2 = IntArray(5) // 3.创建一个长度为5且值全为100的数组 val intArray3 = IntArray(5) { 100 } // 4.注意这里it是它索引下标值,所以这是创建一个长度为5的IntArray [0, 2, 4, 6, 8] val intArray4 = IntArray(5) { it * 2 } //获取元素 //获得intArray第0个元素 // [1, 2, 3, 4, 5] //下标:0 1 2 3 4 println(intArray[0]) //获取数组前5个元素 println(intArray.component5()) //for循环-遍历元素 for (item in intArray) { print("$item ") } println() //for循环-遍历下标 for (item in intArray.indices) { println("$item -> ${intArray[item]}") } println() //for循环-遍历元素(带索引 for ((index, item) in intArray.withIndex()) { println("$index->$item") } //forEach遍历数组 intArray.forEach { println(it) } //forEach遍历数组(带索引 intArray.forEachIndexed { index, item -> println("$index -> $item") } //数组翻转 intArray.reverse()
0
Kotlin
0
0
c31e739d268f8f72485951c23619118649863af0
1,317
kotlinLearning
MIT License
courses/dicoding-android-ml/06-mediapipe/Latihan MediaPipe (image classification)/app/src/main/java/io/github/mrgsrylm/mycamera/ImageClassifierHelper.kt
mrgsrylm
740,344,950
false
{"Kotlin": 897760, "Swift": 3686, "Dart": 2768, "Java": 1281, "Shell": 1130, "JavaScript": 870}
package io.github.mrgsrylm.mycamera import android.content.Context import android.graphics.Bitmap import android.os.SystemClock import android.util.Log import androidx.camera.core.ImageProxy import com.google.mediapipe.framework.image.BitmapImageBuilder import com.google.mediapipe.tasks.components.containers.Classifications import com.google.mediapipe.tasks.core.BaseOptions import com.google.mediapipe.tasks.vision.core.ImageProcessingOptions import com.google.mediapipe.tasks.vision.core.RunningMode import com.google.mediapipe.tasks.vision.imageclassifier.ImageClassifier class ImageClassifierHelper( val threshold: Float = 0.1f, val maxResults: Int = 3, val modelName: String = "mobilenet_v1.tflite", val runningMode: RunningMode = RunningMode.LIVE_STREAM, val context: Context, val classifierListener: ClassifierListener? ) { private var imageClassifier: ImageClassifier? = null init { setupImageClassifier() } private fun setupImageClassifier() { val optionsBuilder = ImageClassifier.ImageClassifierOptions.builder() .setScoreThreshold(threshold) .setMaxResults(maxResults) .setRunningMode(runningMode) if (runningMode == RunningMode.LIVE_STREAM) { optionsBuilder.setResultListener { result, image -> val finishTimeMs = SystemClock.uptimeMillis() val inferenceTime = finishTimeMs - result.timestampMs() classifierListener?.onResults( result.classificationResult().classifications(), inferenceTime ) } optionsBuilder.setErrorListener { error -> classifierListener?.onError(error.message.toString()) } } val baseOptionsBuilder = BaseOptions.builder() .setModelAssetPath(modelName) optionsBuilder.setBaseOptions(baseOptionsBuilder.build()) try { imageClassifier = ImageClassifier.createFromOptions( context, optionsBuilder.build() ) } catch (e: IllegalStateException) { classifierListener?.onError(context.getString(R.string.image_classifier_failed)) Log.e(TAG, e.message.toString()) } } fun classifyImage(image: ImageProxy) { if (imageClassifier == null) { setupImageClassifier() } val mpImage = BitmapImageBuilder(toBitmap(image)).build() val imageProcessingOptions = ImageProcessingOptions.builder() .setRotationDegrees(image.imageInfo.rotationDegrees) .build() val inferenceTime = SystemClock.uptimeMillis() imageClassifier?.classifyAsync(mpImage, imageProcessingOptions, inferenceTime) } private fun toBitmap(image: ImageProxy): Bitmap { val bitmapBuffer = Bitmap.createBitmap( image.width, image.height, Bitmap.Config.ARGB_8888 ) image.use { bitmapBuffer.copyPixelsFromBuffer(image.planes[0].buffer) } image.close() return bitmapBuffer } interface ClassifierListener { fun onError(error: String) fun onResults( results: List<Classifications>?, inferenceTime: Long ) } companion object { private const val TAG = "ImageClassifierHelper" } }
0
Kotlin
0
1
a119e6b1a8cdbec7c00be2467a5ca78a395cde40
3,424
kotlin-sandbox
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/models/adjudications/AdjudicationsOffenceDetails.kt
ministryofjustice
572,524,532
false
{"Kotlin": 574045, "Python": 32511, "Shell": 13474, "Dockerfile": 1154, "Makefile": 684}
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.adjudications class AdjudicationsOffenceDetails( val offenceCode: Number? = null, val offenceRule: AdjudicationsOffenceRule? = null, val victimPrisonersNumber: String? = null, val victimStaffUsername: String? = null, val victimOtherPersonsName: String? = null, )
2
Kotlin
1
2
4d87385fc9811122e0f1ba8734a6068d9e231d32
338
hmpps-integration-api
MIT License
app/src/main/java/com/jacobgb24/smashrandomizer/controller/CharactersAdapter.kt
jacobgb24
176,039,141
false
null
package com.jacobgb24.smashrandomizer.controller import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import com.jacobgb24.smashrandomizer.R import com.jacobgb24.smashrandomizer.model.Character import com.jacobgb24.smashrandomizer.setHelp import kotlinx.android.synthetic.main.item_pool_character.view.* class CharactersAdapter(private val context: Context, var characterList: ArrayList<Character>): BaseAdapter() { override fun getCount(): Int { return characterList.size } override fun getItem(position: Int): Any { return characterList[position] } override fun getItemId(position: Int): Long { return position.toLong() } class CharacterViewHolder(val v: View) { private var image: ImageView = v.image_character_icon fun bind(character: Character) { with(image) { setHelp(character.name) setImageDrawable(character.iconDrawable) } } } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val viewHolder: CharacterViewHolder? if (convertView == null) { val charView = LayoutInflater.from(context).inflate(R.layout.item_pool_character, parent, false) viewHolder = CharacterViewHolder(charView) charView.tag = viewHolder } else { viewHolder = convertView.tag as CharacterViewHolder } viewHolder.bind(characterList[position]) return viewHolder.v } }
0
Kotlin
0
0
3cd8a538f1690b5392d1f1246680a3a71d60bffc
1,688
SmashRandomizer
MIT License
src/main/kotlin/ru/vevteev/tgbot/bot/commands/UnknownCommandExecutor.kt
v4eii
680,279,098
false
{"Kotlin": 52245, "Dockerfile": 88}
package ru.vevteev.tgbot.bot.commands import org.springframework.context.MessageSource import org.springframework.stereotype.Component import org.telegram.telegrambots.meta.api.objects.Update import ru.vevteev.tgbot.bot.TelegramLongPollingBotExt import ru.vevteev.tgbot.extension.createSendMessage import ru.vevteev.tgbot.extension.createSticker import ru.vevteev.tgbot.extension.getMessage import ru.vevteev.tgbot.extension.locale import java.util.* @Component class UnknownCommandExecutor(private val messageSource: MessageSource) : CommandExecutor { override fun commandName(): String = "" override fun commandDescription(locale: Locale): String? = null override fun apply(command: String): Boolean = false override fun perform(update: Update, bot: TelegramLongPollingBotExt, arguments: List<String>) { update.run { bot.execute(createSendMessage(messageSource.getMessage("msg.unknown", locale(arguments)))) bot.execute(createSticker("CAACAgIAAxkBAAEKDl5k3oUfA5Vf4ZiyG2URcZFlq4m0eAACrx4AAq0g0EoW-WsFcEaYfjAE")) } } }
0
Kotlin
0
0
95b45466fc03583226f55ccaffe510f32c4723eb
1,081
tg-bot
MIT License
androidboilerplate/src/main/java/com/curiosityio/androidboilerplate/util/InternetConnectionUtil.kt
curiosityio
75,494,815
false
null
package com.curiosityio.androidboilerplate.util import android.content.Context import android.net.ConnectivityManager import android.provider.Settings import java.io.IOException import java.net.HttpURLConnection import java.net.URL open class InternetConnectionUtil() { companion object { fun isAnyInternetConnected(context: Context): Boolean { val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } fun isRotationEnabled(context: Context): Boolean { return Settings.System.getInt(context.contentResolver, Settings.System.ACCELEROMETER_ROTATION, 0) == 1 } fun isNetworkConnectedAnyType(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } fun isConnectedToWifi(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val info = connectivityManager.activeNetworkInfo return info != null && info.type == ConnectivityManager.TYPE_WIFI } fun isConnectedToWifiAndInternetConnected(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val info = connectivityManager.activeNetworkInfo return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_WIFI } fun isConnectedToMobile(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val info = connectivityManager.activeNetworkInfo return info != null && info.type == ConnectivityManager.TYPE_MOBILE } fun isConnectedToMobileAndInternetConnected(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val info = connectivityManager.activeNetworkInfo return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE } @Throws(IOException::class) fun pingServer(context: Context): Boolean { if (!isAnyInternetConnected(context)) return false try { val urlConnection = URL("http://clients3.google.com/generate_204").openConnection() as HttpURLConnection urlConnection.setRequestProperty("User-Agent", "Android") urlConnection.setRequestProperty("Connection", "close") urlConnection.connectTimeout = 1500 urlConnection.connect() return urlConnection.responseCode === 204 && urlConnection.contentLength === 0 } catch (e: IOException) { throw e } } } }
3
Kotlin
0
8
2b8b8db04e02e1487c9429b62972b18c64320696
3,305
AndroidBoilerplate
MIT License
data/database/src/main/java/com/kafka/data/dao/EntityDao.kt
vipulyaara
612,950,214
false
{"Kotlin": 635130, "JavaScript": 440999, "HTML": 11959, "CSS": 7888, "Shell": 2974}
package com.kafka.data.dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Update import com.kafka.data.entities.BaseEntity interface EntityDao<in E : BaseEntity> { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(entity: E): Long @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(vararg entity: E) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(entities: List<E>) @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun update(entity: E) }
5
Kotlin
10
86
fa64a43602eecac8b93ae9e8b713f6d29ba90727
588
Kafka
Apache License 2.0
libs/tangleLib034/src/main/java/tangle/benchmark/tangleLib034/TangleLib034Fragment.kt
RBusarow
415,108,675
false
null
package tangle.benchmark.tangleLib034 import androidx.fragment.app.Fragment import tangle.fragment.ContributesFragment import tangle.fragment.FragmentInject import tangle.fragment.FragmentInjectFactory import tangle.inject.TangleParam import javax.inject.Inject @ContributesFragment(Unit::class) class TangleLib034Fragment @Inject constructor() : Fragment()
0
Kotlin
0
1
b271faeb36f8f57977dd2b43d276098e1932f4eb
360
tangle-benchmark-project
Apache License 2.0
app/src/main/java/io/github/tonnyl/mango/data/Shot.kt
magicknight
114,423,707
true
{"Kotlin": 374834, "HTML": 31219}
/* * Copyright (c) 2017 Lizhaotailang * * 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 io.github.tonnyl.mango.data import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import java.util.* /** * Created by lizhaotailang on 2017/6/29. * * { * "id" : 471756, * "title" : "Sasquatch", * "description" : "<p>Quick, messy, five minute sketch of something that might become a fictional something.</p>", * "width" : 400, * "height" : 300, * "images" : { * "hidpi" : null, * "normal" : "https://d13yacurqjgara.cloudfront.net/users/1/screenshots/471756/sasquatch.png", * "teaser" : "https://d13yacurqjgara.cloudfront.net/users/1/screenshots/471756/sasquatch_teaser.png" * }, * "views_count" : 4372, * "likes_count" : 149, * "comments_count" : 27, * "attachments_count" : 0, * "rebounds_count" : 2, * "buckets_count" : 8, * "created_at" : "2012-03-15T01:52:33Z", * "updated_at" : "2012-03-15T02:12:57Z", * "html_url" : "https://dribbble.com/shots/471756-Sasquatch", * "attachments_url" : "https://api.dribbble.com/v1/shots/471756/attachments", * "buckets_url" : "https://api.dribbble.com/v1/shots/471756/buckets", * "comments_url" : "https://api.dribbble.com/v1/shots/471756/comments", * "likes_url" : "https://api.dribbble.com/v1/shots/471756/likes", * "projects_url" : "https://api.dribbble.com/v1/shots/471756/projects", * "rebounds_url" : "https://api.dribbble.com/v1/shots/471756/rebounds", * "animated" : false, * "tags" : [ * "fiction", * "sasquatch", * "sketch", * "wip" * ], * "user" : { * "id" : 1, * "name" : "<NAME>", * "username" : "simplebits", * "html_url" : "https://dribbble.com/simplebits", * "avatar_url" : "https://d13yacurqjgara.cloudfront.net/users/1/avatars/normal/dc.jpg?1371679243", * "bio" : "Co-founder &amp; designer of <a href=\"https://dribbble.com/dribbble\">@Dribbble</a>. Principal of SimpleBits. Aspiring clawhammer banjoist.", * "location" : "Salem, MA", * "links" : { * "web" : "http://simplebits.com", * "twitter" : "https://twitter.com/simplebits" * }, * "buckets_count" : 10, * "comments_received_count" : 3395, * "followers_count" : 29262, * "followings_count" : 1728, * "likes_count" : 34954, * "likes_received_count" : 27568, * "projects_count" : 8, * "rebounds_received_count" : 504, * "shots_count" : 214, * "teams_count" : 1, * "can_upload_shot" : true, * "type" : "Player", * "pro" : true, * "buckets_url" : "https://dribbble.com/v1/users/1/buckets", * "followers_url" : "https://dribbble.com/v1/users/1/followers", * "following_url" : "https://dribbble.com/v1/users/1/following", * "likes_url" : "https://dribbble.com/v1/users/1/likes", * "shots_url" : "https://dribbble.com/v1/users/1/shots", * "teams_url" : "https://dribbble.com/v1/users/1/teams", * "created_at" : "2009-07-08T02:51:22Z", * "updated_at" : "2014-02-22T17:10:33Z" * }, * "team" : { * "id" : 39, * "name" : "Dribbble", * "username" : "dribbble", * "html_url" : "https://dribbble.com/dribbble", * "avatar_url" : "https://d13yacurqjgara.cloudfront.net/users/39/avatars/normal/apple-flat-precomposed.png?1388527574", * "bio" : "Show and tell for designers. This is Dribbble on Dribbble.", * "location" : "Salem, MA", * "links" : { * "web" : "http://dribbble.com", * "twitter" : "https://twitter.com/dribbble" * }, * "buckets_count" : 1, * "comments_received_count" : 2037, * "followers_count" : 25011, * "followings_count" : 6120, * "likes_count" : 44, * "likes_received_count" : 15811, * "members_count" : 7, * "projects_count" : 4, * "rebounds_received_count" : 416, * "shots_count" : 91, * "can_upload_shot" : true, * "type" : "Team", * "pro" : false, * "buckets_url" : "https://dribbble.com/v1/users/39/buckets", * "followers_url" : "https://dribbble.com/v1/users/39/followers", * "following_url" : "https://dribbble.com/v1/users/39/following", * "likes_url" : "https://dribbble.com/v1/users/39/likes", * "members_url" : "https://dribbble.com/v1/teams/39/members", * "shots_url" : "https://dribbble.com/v1/users/39/shots", * "team_shots_url" : "https://dribbble.com/v1/users/39/teams", * "created_at" : "2009-08-18T18:34:31Z", * "updated_at" : "2014-02-14T22:32:11Z" * } * } */ data class Shot( @SerializedName("id") var id: Long, @SerializedName("title") @Expose var title: String, @SerializedName("description") @Expose var description: String?, @SerializedName("width") @Expose var width: Int, @SerializedName("height") @Expose var height: Int, @SerializedName("images") @Expose var images: Images, @SerializedName("views_count") @Expose var viewsCount: Int, @SerializedName("likes_count") @Expose var likesCount: Int, @SerializedName("comments_count") @Expose var commentsCount: Int, @SerializedName("attachments_count") @Expose var attachmentsCount: Int, @SerializedName("rebounds_count") @Expose var reboundsCount: Int, @SerializedName("buckets_count") @Expose var bucketsCount: Int, @SerializedName("created_at") @Expose var createdAt: Date, @SerializedName("updated_at") @Expose var updatedAt: Date, @SerializedName("html_url") @Expose var htmlUrl: String, @SerializedName("attachments_url") @Expose var attachmentsUrl: String, @SerializedName("buckets_url") @Expose var bucketsUrl: String, @SerializedName("comments_url") @Expose var commentsUrl: String, @SerializedName("likes_url") @Expose var likesUrl: String, @SerializedName("projects_url") @Expose var projectsUrl: String, @SerializedName("rebounds_url") @Expose var reboundsUrl: String, @SerializedName("animated") @Expose var animated: Boolean, @SerializedName("tags") @Expose var tags: List<String>, @SerializedName("user") @Expose var user: User?, @SerializedName("team") @Expose var team: Team? ) : Parcelable { constructor(parcel: Parcel) : this( id = parcel.readLong(), title = parcel.readString(), description = parcel.readString(), width = parcel.readInt(), height = parcel.readInt(), images = parcel.readParcelable(Images::class.java.classLoader), viewsCount = parcel.readInt(), likesCount = parcel.readInt(), commentsCount = parcel.readInt(), attachmentsCount = parcel.readInt(), reboundsCount = parcel.readInt(), bucketsCount = parcel.readInt(), createdAt = Date(parcel.readLong()), updatedAt = Date(parcel.readLong()) , htmlUrl = parcel.readString(), attachmentsUrl = parcel.readString(), bucketsUrl = parcel.readString(), commentsUrl = parcel.readString(), likesUrl = parcel.readString(), projectsUrl = parcel.readString(), reboundsUrl = parcel.readString(), animated = parcel.readByte() != 0.toByte(), tags = parcel.createStringArrayList(), user = parcel.readParcelable(User::class.java.classLoader), team = parcel.readParcelable(Team::class.java.classLoader) ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeLong(id) parcel.writeString(title) parcel.writeString(description) parcel.writeInt(width) parcel.writeInt(height) parcel.writeParcelable(images, flags) parcel.writeInt(viewsCount) parcel.writeInt(likesCount) parcel.writeInt(commentsCount) parcel.writeInt(attachmentsCount) parcel.writeInt(reboundsCount) parcel.writeInt(bucketsCount) parcel.writeLong(createdAt.time) parcel.writeLong(updatedAt.time) parcel.writeString(htmlUrl) parcel.writeString(attachmentsUrl) parcel.writeString(bucketsUrl) parcel.writeString(commentsUrl) parcel.writeString(likesUrl) parcel.writeString(projectsUrl) parcel.writeString(reboundsUrl) parcel.writeByte(if (animated) 1.toByte() else 0.toByte()) parcel.writeStringList(tags) parcel.writeParcelable(user, flags) parcel.writeParcelable(team, flags) } override fun describeContents() = 0 companion object CREATOR : Parcelable.Creator<Shot> { override fun createFromParcel(parcel: Parcel): Shot { return Shot(parcel) } override fun newArray(size: Int): Array<Shot?> { return arrayOfNulls(size) } } }
0
Kotlin
0
0
063046c23618f9682860b669c58d4ef8384f1217
10,092
Mango
MIT License
domain/src/main/java/com/sedsoftware/yaptalker/domain/repository/LoginSessionRepository.kt
alerm-sml
123,927,915
true
{"Kotlin": 509954, "IDL": 1260, "Shell": 1229, "Prolog": 939, "Java": 823, "CSS": 50}
package com.sedsoftware.yaptalker.domain.repository import com.sedsoftware.yaptalker.domain.entity.BaseEntity import io.reactivex.Completable import io.reactivex.Single /** * Interface that represents a Repository for getting user login session related data. */ interface LoginSessionRepository { fun getLoginSessionInfo(): Single<BaseEntity> fun requestSignIn(userLogin: String, userPassword: String, anonymously: Boolean): Completable fun requestSignOut(userKey: String): Completable }
0
Kotlin
0
0
6c06171d2af44b0bb9b7809221b2f594d2354102
501
YapTalker
Apache License 2.0
app/src/main/java/com/nullpointer/runningcompose/ui/screens/statistics/componets/GraphRuns.kt
Hcnc100
492,511,541
false
null
package com.nullpointer.runningcompose.ui.screens.statistics.componets import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.layout.layout import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.nullpointer.runningcompose.R import com.nullpointer.runningcompose.models.Run import com.nullpointer.runningcompose.models.types.MetricType import com.nullpointer.runningcompose.ui.share.mpGraph.MpGraphAndroid @Composable fun GraphRuns( list: List<Run>, modifier: Modifier = Modifier, metricType: MetricType, ) { Column(modifier = modifier) { Text( stringResource(R.string.title_graph_statisctis), modifier = Modifier .padding(5.dp) .fillMaxWidth(), textAlign = TextAlign.Center) Row(verticalAlignment = Alignment.CenterVertically) { Text( modifier = Modifier .vertical() .rotate(-90f) .padding(1.dp).fillMaxWidth(.4f), text = stringResource(R.string.title_avg_speed_run_graph), style = MaterialTheme.typography.caption, maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center ) MpGraphAndroid(list = list, modifier = Modifier .fillMaxWidth() .fillMaxHeight(.9f), metricType = metricType) } Text(text = stringResource(R.string.title_runs_order_date_graph), style = MaterialTheme.typography.caption, modifier = Modifier.align(Alignment.CenterHorizontally), maxLines = 1, overflow = TextOverflow.Ellipsis ) } } fun Modifier.vertical() = layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.height, placeable.width) { placeable.place( x = -(placeable.width / 2 - placeable.height / 2), y = -(placeable.height / 2 - placeable.width / 2) ) } }
0
Kotlin
4
9
0f8906c0033dd111a35f1f69bde29e31a024af28
2,532
RunningCompose
MIT License
app/src/main/java/com/example/compose_tflite/plantsApi_feature/model/DummyData.kt
YadavYashvant
702,524,655
false
{"Kotlin": 50160}
package com.example.compose_tflite.plantsApi_feature.model data class DummyData( val title: String )
0
Kotlin
1
1
c21752f583a8a23fb3ec849f743adb8c6ee4c6bb
106
CropGuard
MIT License
common/src/main/java/net/sistr/flexibleguns/entity/util/HasSenseMemory.kt
SistrScarlet
437,250,021
false
{"Kotlin": 239434, "Java": 36089}
package net.sistr.flexibleguns.entity.util interface HasSenseMemory { fun getSenseMemory(): SenseMemory }
0
Kotlin
0
2
c00fbbfbd98a253f971cb9f5c87a4cf3eef9b6a2
112
FlexibleGuns
MIT License
features/currencyexchange/presentation/src/androidMain/kotlin/com/mindera/kmpexample/currencyexchange/language/LanguageApp.kt
Mindera
767,105,015
false
{"Kotlin": 89862, "Swift": 422}
package com.mindera.kmpexample.currencyexchange.language import android.app.Application import android.content.Context open class LanguageApp : Application() { override fun attachBaseContext(base: Context) { super.attachBaseContext(LocaleHelper.setLocale(base, LocaleHelper.getLanguageSharedPreference(base) )) } }
0
Kotlin
0
1
1c24d2aeade48da855424296ca036e6c1da1c1b3
353
Android-KMP-Template
Apache License 2.0
TennisLabExposed/src/main/kotlin/repositories/maquina/IMaquinaEncordarRepository.kt
idanirf
578,303,195
false
{"Kotlin": 247706}
package repositories.maquina import models.MaquinaEncordar import repositories.ICRUDRepository /** * I maquina encordar repository * * @constructor Create empty I maquina encordar repository */ interface IMaquinaEncordarRepository: ICRUDRepository<MaquinaEncordar, Int> { }
0
Kotlin
2
2
618af3cdf691a44ba5ad4c0993b3aae0d0728f08
279
AD-P2-jsanchez-drodriguez-amaldonado
MIT License
auth/requester/src/main/kotlin/com/walletconnect/requester/ui/connect/pairing_select/PairingSelectionDialogFragment.kt
WalletConnect
435,951,419
false
null
package com.walletconnect.requester.ui.connect.pairing_select import android.os.Bundle import android.view.View import androidx.fragment.app.DialogFragment import androidx.navigation.fragment.findNavController import androidx.navigation.navGraphViewModels import com.walletconnect.requester.R import com.walletconnect.requester.databinding.DialogPairingSelectionBinding import com.walletconnect.requester.ui.connect.ConnectViewModel import com.walletconnect.sample_common.BottomVerticalSpaceItemDecoration class PairingSelectionDialogFragment : DialogFragment(R.layout.dialog_pairing_selection) { private val viewModel: ConnectViewModel by navGraphViewModels(R.id.connectGraph) private var _binding: DialogPairingSelectionBinding? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = DialogPairingSelectionBinding.bind(view).also { _binding = it } // val pairings = SignClient.getListOfSettledPairings().mapNotNull { pairing -> // pairing.metaData?.let { metadata -> metadata.icons.first() to metadata.name } // } with(binding.rvSettledPairings) { addItemDecoration(BottomVerticalSpaceItemDecoration(16)) adapter = PairingSelectionAdapter(emptyList()) { pairingTopicPosition -> binding.clpbLoading.show() viewModel.connectToWallet(pairingTopicPosition) } } binding.btnNewPairing.setOnClickListener { findNavController().navigate(R.id.action_dialog_pairing_selection_to_dialog_pairing_generation) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
131
Kotlin
51
148
f54e9ebe97869065b15e307d16be8e5bee7635d0
1,758
WalletConnectKotlinV2
Apache License 2.0
app/src/main/java/com/evourse/instaclone/HomeFeedApis.kt
dayashanknar
736,360,187
false
{"Kotlin": 38103}
package com.evourse.instaclone import com.evourse.instaclone.model.FeedResponseApi import retrofit2.http.GET import retrofit2.http.Query interface HomeFeedApis { @GET("/venCon") suspend fun getMixContent(@Query("page") page: Int): FeedResponseApi }
0
Kotlin
0
0
72d4d9f1e711327c3cdf139ec935b9b82827f2ad
259
anonym
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/rds/ParameterGroupClusterBindOptionsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.rds import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import software.amazon.awscdk.services.rds.ParameterGroupClusterBindOptions /** * Options for `IParameterGroup.bindToCluster`. Empty for now, but can be extended later. * * 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.rds.*; * ParameterGroupClusterBindOptions parameterGroupClusterBindOptions = * ParameterGroupClusterBindOptions.builder().build(); * ``` */ @CdkDslMarker public class ParameterGroupClusterBindOptionsDsl { private val cdkBuilder: ParameterGroupClusterBindOptions.Builder = ParameterGroupClusterBindOptions.builder() public fun build(): ParameterGroupClusterBindOptions = cdkBuilder.build() }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,092
awscdk-dsl-kotlin
Apache License 2.0
androidx/app/src/main/java/com/dxn/agventure/features/consumer/ui/home/ConsumerHome.kt
pallavi-sahu
607,486,054
false
{"Kotlin": 45286}
package com.dxn.agventure.features.consumer.ui.home import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.hilt.navigation.fragment.hiltNavGraphViewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.dxn.agventure.R import com.dxn.agventure.databinding.ConsumerHomeFragmentBinding import com.dxn.agventure.features.auth.AuthActivity import com.google.firebase.auth.FirebaseAuth import kotlinx.coroutines.flow.collect import javax.inject.Inject class ConsumerHome : Fragment() { private var _binding: ConsumerHomeFragmentBinding? = null private val binding get() = _binding!! private val viewModel by hiltNavGraphViewModels<ConsumerHomeViewModel>(R.id.consumer_navigation) @Inject lateinit var firebaseAuth: FirebaseAuth override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = ConsumerHomeFragmentBinding.inflate(inflater, container, false) initUi() return binding.root } private fun initUi() { val productListAdapter = ProductListAdapter({}, {}) binding.productsRecycler.adapter = productListAdapter binding.productsRecycler.layoutManager = GridLayoutManager(requireContext(), 2, RecyclerView.VERTICAL, false) binding.signOut.setOnClickListener { firebaseAuth.signOut() startActivity(Intent(requireActivity(), AuthActivity::class.java)) } lifecycleScope.launchWhenCreated { viewModel.products.collect { uiState -> when (uiState) { is ConsumerHomeViewModel.HomeUiState.Success -> { productListAdapter.products = uiState.products productListAdapter.notifyDataSetChanged() } is ConsumerHomeViewModel.HomeUiState.Loading -> { } is ConsumerHomeViewModel.HomeUiState.Error -> { } } } } } }
0
Kotlin
0
0
3af007fd871e5d1f882a6956bbcf442fb88de821
2,314
Agventure
MIT License
src/main/kotlin/io/github/glyphmods/solarpowered/content/optics/network/manager/ClientOpticalNetworkManager.kt
GlyphMods
756,582,855
false
{"Kotlin": 48642}
package io.github.glyphmods.solarpowered.content.optics.network.manager import io.github.glyphmods.solarpowered.content.optics.network.ClientOpticalNetwork import io.github.glyphmods.solarpowered.content.optics.network.OpticalNetworkChangePacket import net.minecraft.client.Minecraft import net.minecraft.client.multiplayer.ClientLevel import net.minecraftforge.network.NetworkEvent import java.util.function.Supplier data object ClientOpticalNetworkManager : AbstractOpticalNetworkManager<ClientLevel>() { private fun getOrCreateNetwork(level: ClientLevel, id: Long) = networks.getOrPut(level) { hashMapOf() } .getOrPut(id) { ClientOpticalNetwork(id, level) } as ClientOpticalNetwork fun handleNetworkChangePacket(packet: OpticalNetworkChangePacket, ctx: Supplier<NetworkEvent.Context>) { val level = Minecraft.getInstance().level!! assert(level.dimension() == packet.dimension) { "Received a network sync packet for network ${packet.id} in ${packet.dimension.location()}, but we're in ${ level.dimension().location() }!" } val network = getOrCreateNetwork(level, packet.id) network.handleChangePacket(packet) ctx.get().packetHandled = true } }
0
Kotlin
0
1
fd81b33db221154addde67f59cd705689a9723cc
1,268
SolarPowered
MIT License
src/main/kotlin/kotlinmud/event/factory/FightEventFactory.kt
danielmunro
241,230,796
false
null
package kotlinmud.event.factory import kotlinmud.event.impl.Event import kotlinmud.event.impl.FightStartedEvent import kotlinmud.event.impl.KillEvent import kotlinmud.event.type.EventType import kotlinmud.mob.fight.Round import kotlinmud.mob.model.Fight import kotlinmud.mob.model.Mob import kotlinmud.mob.type.Disposition fun createKillEvent(fight: Fight): Event<KillEvent> { val winner = if (fight.mob1.disposition == Disposition.DEAD) fight.mob2 else fight.mob1 return Event( EventType.KILL, KillEvent(fight, winner, fight.getOpponentFor(winner)!!) ) } fun createFightStartedEvent(fight: Fight, mob: Mob, target: Mob): Event<FightStartedEvent> { return Event( EventType.FIGHT_STARTED, FightStartedEvent(fight, mob, target) ) } fun createFightRoundEvent(round: Round): Event<Round> { return Event(EventType.FIGHT_ROUND, round) }
0
Kotlin
1
9
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
891
kotlinmud
MIT License
src/main/kotlin/kotlinmud/event/factory/FightEventFactory.kt
danielmunro
241,230,796
false
null
package kotlinmud.event.factory import kotlinmud.event.impl.Event import kotlinmud.event.impl.FightStartedEvent import kotlinmud.event.impl.KillEvent import kotlinmud.event.type.EventType import kotlinmud.mob.fight.Round import kotlinmud.mob.model.Fight import kotlinmud.mob.model.Mob import kotlinmud.mob.type.Disposition fun createKillEvent(fight: Fight): Event<KillEvent> { val winner = if (fight.mob1.disposition == Disposition.DEAD) fight.mob2 else fight.mob1 return Event( EventType.KILL, KillEvent(fight, winner, fight.getOpponentFor(winner)!!) ) } fun createFightStartedEvent(fight: Fight, mob: Mob, target: Mob): Event<FightStartedEvent> { return Event( EventType.FIGHT_STARTED, FightStartedEvent(fight, mob, target) ) } fun createFightRoundEvent(round: Round): Event<Round> { return Event(EventType.FIGHT_ROUND, round) }
0
Kotlin
1
9
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
891
kotlinmud
MIT License
app/src/main/java/com/boolder/boolder/utils/extension/CameraOptionsExtensions.kt
boolder-org
566,723,758
false
{"Kotlin": 532905}
package com.boolder.boolder.utils.extension import com.mapbox.maps.CameraOptions fun CameraOptions.coerceZoomAtLeast(minZoom: Double): CameraOptions { val zoom = zoom ?: return this return CameraOptions.Builder() .center(center) .padding(padding) .bearing(bearing) .pitch(pitch) .zoom(zoom.coerceAtLeast(minZoom)) .build() }
11
Kotlin
12
26
dd93a7b9c29ee0eec80b63a62de4b5eea7203f6e
384
boolder-android
MIT License
app/src/main/java/top/jiecs/screener/ui/settings/SettingsAdapter.kt
jiesou
727,220,282
false
{"Kotlin": 21536}
package top.jiecs.screener.ui.settings; public class SettingsAdapter { }
2
Kotlin
1
19
f60884251cf5dc0d59f8bf369c4123958c345531
74
Android-Screener
MIT License