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
base/src/main/kotlin/browser/contextMenus/ContextType.kt
DATL4G
372,873,797
false
null
package browser.contextMenus import kotlin.String /** * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of * all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is * used to add menu items to the context menu that appears when clicking the app icon in the * launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported * in a launcher context menu. */ public enum class ContextType( private val `value`: String, ) { all("all"), page("page"), frame("frame"), selection("selection"), link("link"), editable("editable"), image("image"), video("video"), audio("audio"), launcher("launcher"), browser_action("browser_action"), page_action("page_action"), action("action"), ; public override fun toString(): String = value }
0
Kotlin
1
37
ab2a825dd8dd8eb704278f52c603dbdd898d1875
888
Kromex
Apache License 2.0
base/src/main/kotlin/browser/contextMenus/ContextType.kt
DATL4G
372,873,797
false
null
package browser.contextMenus import kotlin.String /** * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of * all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is * used to add menu items to the context menu that appears when clicking the app icon in the * launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported * in a launcher context menu. */ public enum class ContextType( private val `value`: String, ) { all("all"), page("page"), frame("frame"), selection("selection"), link("link"), editable("editable"), image("image"), video("video"), audio("audio"), launcher("launcher"), browser_action("browser_action"), page_action("page_action"), action("action"), ; public override fun toString(): String = value }
0
Kotlin
1
37
ab2a825dd8dd8eb704278f52c603dbdd898d1875
888
Kromex
Apache License 2.0
plugins/kotlin/completion/testData/basic/multifile/EnumCompanionMethods/EnumCompanionMethods.kt
ingokegel
72,937,917
false
null
// FIR_COMPARISON package test enum class E { ; companion object { fun method1() { } } } fun E.Companion.method2() { } fun main() { E.m<caret> } // EXIST: method1 // EXIST: method2
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
216
intellij-community
Apache License 2.0
library/src/main/java/com/kroegerama/kaiteki/retrofit/listing/Listing.kt
MaTriXy
133,508,234
false
null
package com.kroegerama.kaiteki.retrofit.listing import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import com.kroegerama.kaiteki.retrofit.dsl.enqueue import retrofit2.Call enum class Status { RUNNING, SUCCESS, FAILED } sealed class NetworkState( val status: Status ) { object LOADED : NetworkState(Status.SUCCESS) object LOADING : NetworkState(Status.RUNNING) data class Error(val message: String?, val code: Int? = null) : NetworkState(Status.FAILED) override fun toString(): String { return status.toString() } } data class Listing<T>( val result: LiveData<T>, val networkState: LiveData<NetworkState>, val retry: () -> Unit ) fun <T> Call<T>.createListing(fetchNow: Boolean = true, successHook: ((T?) -> Unit)? = null): Listing<T> { val liveData = MutableLiveData<T>() val networkState = MutableLiveData<NetworkState>() val block: Call<T>.() -> Unit = { networkState.postValue(NetworkState.LOADING) enqueue { onFailure { t -> networkState.postValue(NetworkState.Error(t.message)) } onSuccess { liveData.postValue(body()) successHook?.invoke(body()) networkState.postValue(NetworkState.LOADED) } onNoSuccess { networkState.postValue(NetworkState.Error("Response Code: ${code()}", code())) } } } if (fetchNow) { apply(block) } return Listing(liveData, networkState, { clone().apply(block) }) }
1
null
1
1
c6d74d72c9d8b8f7adfc24e69728a3a3ffb35dad
1,619
retrofit-kaiteki
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/MoodOutlined.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/MoodOutlined") @file:JsNonModule package mui.icons.material @JsName("default") external val MoodOutlined: SvgIconComponent
10
Kotlin
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
206
kotlin-wrappers
Apache License 2.0
vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt
onap
115,762,948
false
null
/*- * ============LICENSE_START======================================================= * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.vid.job.command import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate import org.onap.vid.job.Job import org.onap.vid.job.impl.JobSharedData import org.onap.vid.model.RequestReferencesContainer import org.onap.vid.model.serviceInstantiation.ServiceInstantiation import org.onap.vid.mso.RestObject import org.onap.vid.services.AsyncInstantiationBusinessLogic import org.onap.vid.services.AuditService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.util.* @Service class MsoResultHandlerService @Autowired constructor(private val asyncInstantiationBL: AsyncInstantiationBusinessLogic, private val auditService: AuditService) { companion object { private val LOGGER = EELFLoggerDelegate.getLogger(MsoResultHandlerService::class.java) } fun getRequest(jobSharedData: JobSharedData): ServiceInstantiation { return jobSharedData.request as ServiceInstantiation } fun handleRootResponse(sharedData: JobSharedData, msoResponse: RestObject<RequestReferencesContainer>): MsoResult { val jobUUID:UUID = sharedData.jobUuid return if (msoResponse.statusCode in 200..399) { val jobStatus = Job.JobStatus.IN_PROGRESS val msoResourceIds = MsoResourceIds(msoResponse.get().requestReferences.requestId, msoResponse.get().requestReferences.instanceId) auditService.auditVidStatus(jobUUID, jobStatus) setInitialRequestAuditStatusFromMso(jobUUID, msoResourceIds.requestId) asyncInstantiationBL.updateServiceInfo(jobUUID) { x -> x.jobStatus = jobStatus x.serviceInstanceId = msoResourceIds.instanceId x.msoRequestId = UUID.fromString(msoResourceIds.requestId) } asyncInstantiationBL.addResourceInfo(sharedData, jobStatus, msoResourceIds.instanceId) MsoResult(Job.JobStatus.COMPLETED_WITH_NO_ACTION, msoResourceIds) } else { auditService.setFailedAuditStatusFromMso(jobUUID, null, msoResponse.statusCode, msoResponse.raw) asyncInstantiationBL.addFailedResourceInfo(sharedData, msoResponse) return MsoResult(Job.JobStatus.FAILED) } } fun handleResponse(sharedData: JobSharedData, msoResponse: RestObject<RequestReferencesContainer>, actionDescription: String): MsoResult { return if (msoResponse.statusCode in 200..399) { val msoResourceIds = MsoResourceIds(msoResponse.get().requestReferences.requestId, msoResponse.get().requestReferences.instanceId) LOGGER.debug(EELFLoggerDelegate.debugLogger, "Successfully sent $actionDescription. Request id: ${msoResourceIds.requestId}") asyncInstantiationBL.addResourceInfo(sharedData, Job.JobStatus.IN_PROGRESS, msoResourceIds.instanceId) MsoResult(Job.JobStatus.COMPLETED_WITH_NO_ACTION, msoResourceIds) } else { LOGGER.debug(EELFLoggerDelegate.debugLogger, "Failed to $actionDescription. Details: ${msoResponse.raw}") asyncInstantiationBL.addFailedResourceInfo(sharedData, msoResponse) MsoResult(Job.JobStatus.FAILED) } } private fun setInitialRequestAuditStatusFromMso(jobUUID: UUID, requestId: String) { val initialMsoRequestStatus = "REQUESTED" auditService.auditMsoStatus(jobUUID, initialMsoRequestStatus, requestId, null) } }
4
null
5
6
8cef7fbeed5b8f1255535fcf1cf0c7304df6d447
4,437
archived-vid
Apache License 2.0
library/src/main/java/kr/open/rhpark/library/ui/fragment/RootFragment.kt
Rhpark
873,389,276
false
{"Kotlin": 68838}
package kr.open.rhpark.library.ui.fragment import android.content.Intent import android.content.pm.PackageManager import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import kr.open.rhpark.library.debug.logcat.Logx import kr.open.rhpark.library.system.permission.PermissionListener import kr.open.rhpark.library.system.service.SystemServiceManagerInfo import kr.open.rhpark.library.ui.view.snackbar.DefaultSnackBar import kr.open.rhpark.library.ui.view.toast.DefaultToast public abstract class RootFragment : Fragment() { protected val toast: DefaultToast by lazy { DefaultToast(requireContext()) } protected val snackBar: DefaultSnackBar by lazy { DefaultSnackBar(requireView()) } protected val systemServiceManagerInfo: SystemServiceManagerInfo by lazy { SystemServiceManagerInfo(requireContext()) } private var permissionListener: PermissionListener? = null private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> val allPermissionsGranted = permissions.all { it.value } Logx.d("allPermissionsGranted $allPermissionsGranted") if (allPermissionsGranted) { permissionListener?.let { it.onAllPermissionGranted() } } else { permissionListener?.let { it.onPermissionsDenied(permissions.keys.toList()) } } } protected fun requestPermissions( permissions: List<String>, onAllPermissionGranted: () -> Unit, onPermissionsDenied: (deniedPermissions: List<String>) -> Unit ) { Logx.d("permissions $permissions") permissionListener = PermissionListener(onAllPermissionGranted, onPermissionsDenied) val permissionsToRequest = permissions.filter { ContextCompat.checkSelfPermission(requireContext(), it) != PackageManager.PERMISSION_GRANTED }.toTypedArray() if(permissionsToRequest.isNullOrEmpty()) { permissionListener?.let { it.onAllPermissionGranted() } } else { requestPermissionLauncher.launch(permissionsToRequest) } } protected fun startActivity(activity: Class<*>?) { startActivity(Intent(requireContext(), activity)) } protected fun startActivity(activity: Class<*>?, vararg intentFlags: Int) { val intent = Intent(requireContext(), activity).apply { intentFlags.forEach { addFlags(it) } } startActivity(intent) } }
0
Kotlin
0
1
75bd0e72c973dffbd0d270e187a651f8a8ec051e
2,588
library_01
MIT License
multisrc/overrides/madara/flextapescans/src/FlexTapeScans.kt
kevin01523
612,636,298
false
null
package eu.kanade.tachiyomi.extension.en.flextapescans import eu.kanade.tachiyomi.multisrc.madara.Madara import eu.kanade.tachiyomi.source.model.Page import org.jsoup.nodes.Document import java.text.SimpleDateFormat import java.util.Locale class FlexTapeScans : Madara( "Flex Tape Scans", "https://flextapescans.com", "en", dateFormat = SimpleDateFormat("MM/dd/yyy", Locale.ROOT) ) { override val useNewChapterEndpoint = false override fun pageListParse(document: Document): List<Page> { val blocked = document.select(".content-blocked").first() if (blocked != null) { throw Exception(blocked.text()) // You need to be contributor to read this chapter } return super.pageListParse(document) } }
9
null
99
9
8ca7f06a4fdfbfdd66520a4798c8636274263428
771
tachiyomi-extensions
Apache License 2.0
src/main/kotlin/nl/nilsrijkaart/widm/game/GameSlot.kt
Nils-Rijkaart
655,419,206
false
null
package nl.nilsrijkaart.widm.game import java.util.* data class GameSlot(var color: GameColor, var role: GameRole, var location: LocationData? = null, var player: UUID? = null)
0
Kotlin
0
0
11baf339b5fba5befdf8b2cdd2771076c729d08e
178
widm-spigot-plugin
MIT License
instrumentation/ktor/ktor-2.0/library/src/test/kotlin/io/opentelemetry/instrumentation/ktor/v2_0/client/KtorHttpClientTest.kt
open-telemetry
210,933,087
false
null
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.instrumentation.ktor.v2_0.client import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.http.* import io.opentelemetry.context.Context import io.opentelemetry.extension.kotlin.asContextElement import io.opentelemetry.instrumentation.testing.junit.http.AbstractHttpClientTest import io.opentelemetry.instrumentation.testing.junit.http.HttpClientInstrumentationExtension import io.opentelemetry.instrumentation.testing.junit.http.HttpClientResult import io.opentelemetry.instrumentation.testing.junit.http.HttpClientTestOptions import io.opentelemetry.instrumentation.testing.junit.http.HttpClientTestOptions.DEFAULT_HTTP_ATTRIBUTES import io.opentelemetry.semconv.trace.attributes.SemanticAttributes import kotlinx.coroutines.* import org.junit.jupiter.api.extension.RegisterExtension import java.net.URI class KtorHttpClientTest : AbstractHttpClientTest<HttpRequestBuilder>() { override fun buildRequest(requestMethod: String, uri: URI, requestHeaders: MutableMap<String, String>) = HttpRequestBuilder(uri.toURL()).apply { method = HttpMethod.parse(requestMethod) requestHeaders.forEach { (header, value) -> headers.append(header, value) } } override fun sendRequest(request: HttpRequestBuilder, method: String, uri: URI, headers: MutableMap<String, String>) = runBlocking { CLIENT.request(request).status.value } override fun sendRequestWithCallback( request: HttpRequestBuilder, method: String, uri: URI, headers: MutableMap<String, String>, httpClientResult: HttpClientResult, ) { CoroutineScope(Dispatchers.Default + Context.current().asContextElement()).launch { try { val statusCode = CLIENT.request(request).status.value httpClientResult.complete(statusCode) } catch (e: Throwable) { httpClientResult.complete(e) } } } override fun configure(optionsBuilder: HttpClientTestOptions.Builder) { with(optionsBuilder) { disableTestReadTimeout() // this instrumentation creates a span per each physical request // related issue https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/5722 disableTestRedirects() setHttpAttributes { DEFAULT_HTTP_ATTRIBUTES - setOf(SemanticAttributes.NET_PROTOCOL_NAME, SemanticAttributes.NET_PROTOCOL_VERSION) } setSingleConnectionFactory { host, port -> KtorHttpClientSingleConnection(host, port) { installTracing() } } } } companion object { @JvmStatic @RegisterExtension private val TESTING = HttpClientInstrumentationExtension.forLibrary() private val CLIENT = HttpClient(CIO) { install(HttpRedirect) installTracing() } private fun HttpClientConfig<*>.installTracing() { install(KtorClientTracing) { setOpenTelemetry(TESTING.openTelemetry) setCapturedRequestHeaders(listOf(AbstractHttpClientTest.TEST_REQUEST_HEADER)) setCapturedResponseHeaders(listOf(AbstractHttpClientTest.TEST_RESPONSE_HEADER)) } } } }
405
null
623
1,383
dd6a1a9c0e1da1cb2a2cc1ed130ab4a4b69ff3e7
3,218
opentelemetry-java-instrumentation
Apache License 2.0
game/src/main/kotlin/gg/rsmod/game/model/combat/SlayerAssignment.kt
2011Scape
578,880,245
false
null
package gg.rsmod.game.model.combat /** * @author Alycia <https://github.com/alycii> */ enum class SlayerAssignment(val identifier: String) { BIRD("Birds"), BANSHEE("Banshees"), BEAR("Bears"), CAVE_BUG("Cave Bugs"), CAVE_SLIME("Cave Slimes"), CAVE_CRAWLER("Cave Crawlers"), CRAWLING_HAND("Crawling Hands"), COCKATRICE("Cockatrice"), DESERT_LIZARD("Desert Lizards"), DOG("Dogs"), DWARF("Dwarves"), GREEN_DRAGON("Green Dragons"), GHOST("Ghosts"), GOBLIN("Goblins"), HILL_GIANT("Hill Giants"), ICEFIEND("Icefiends"), LESSER_DEMON("Lesser Demons"), MINOTAUR("Minotaurs"), MOSS_GIANT("Moss Giants"), MONKEY("Monkeys"), PYREFIEND("Pyrefiends"), ROCK_SLUG("Rockslugs"), SCORPION("Scorpions"), SKELETON("Skeletons"), SPIDER("Spiders"), WOLF("Wolves"), HELLHOUNDS("Hellhounds"), ZOMBIE("Zombies"), BAT("Bats"), COW("Cows"), ICE_WARRIOR("Ice Warriors"), ICE_GIANT("Ice Giants"); }
39
null
87
34
e5400cc71bfa087164153d468979c5a3abc24841
1,000
game
Apache License 2.0
ui/compose/src/commonMain/kotlin/dev/avatsav/linkding/ui/compose/widgets/SwipeToDismissListItem.kt
avatsav
576,855,763
false
null
package dev.avatsav.linkding.ui.shared import androidx.compose.animation.AnimatedContent import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.SwipeToDismissBox import androidx.compose.material3.SwipeToDismissBoxState import androidx.compose.material3.SwipeToDismissBoxValue import androidx.compose.material3.SwipeToDismissBoxValue.EndToStart import androidx.compose.material3.SwipeToDismissBoxValue.Settled import androidx.compose.material3.SwipeToDismissBoxValue.StartToEnd import androidx.compose.material3.rememberSwipeToDismissBoxState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalHapticFeedback import dev.avatsav.linkding.ui.extensions.circularReveal import kotlinx.coroutines.flow.distinctUntilChanged @Stable data class SwipeToDismissAction( val onSwipeToDismissTriggered: () -> Unit, val backgroundColour: Color, val canDismiss: Boolean, val content: @Composable BoxScope.(dismissing: Boolean) -> Unit, ) @OptIn(ExperimentalMaterial3Api::class) @Composable fun SwipeToDismissListItem( modifier: Modifier = Modifier, startToEndAction: SwipeToDismissAction, endToStartAction: SwipeToDismissAction, backgroundColor: Color = Color.Transparent, content: @Composable (dismissState: SwipeToDismissBoxState) -> Unit, ) { val dismissState = rememberSwipeToDismissBoxState( confirmValueChange = { dismissValue -> when (dismissValue) { StartToEnd -> { startToEndAction.onSwipeToDismissTriggered.invoke() startToEndAction.canDismiss } EndToStart -> { endToStartAction.onSwipeToDismissTriggered.invoke() endToStartAction.canDismiss } Settled -> false } }, positionalThreshold = { totalDistance -> 0.35f * totalDistance }, ) SwipeToDismissBox( state = dismissState, backgroundContent = { SwipeDismissBackgroundContent( dismissState, startToEndAction, endToStartAction, backgroundColor, ) }, modifier = modifier, enableDismissFromStartToEnd = true, enableDismissFromEndToStart = true, content = { content(dismissState) }, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun SwipeDismissBackgroundContent( dismissState: SwipeToDismissBoxState, startAction: SwipeToDismissAction, endAction: SwipeToDismissAction, backgroundColor: Color = Color.Transparent, ) { if (dismissState.dismissDirection == Settled) return val haptics = LocalHapticFeedback.current var dismissing: Boolean by remember { mutableStateOf(false) } LaunchedEffect(Unit) { snapshotFlow { dismissState.targetValue.willDismiss() }.distinctUntilChanged() .collect { dismissing = it } } LaunchedEffect(dismissing) { if (dismissing) { haptics.performHapticFeedback(HapticFeedbackType.LongPress) } } AnimatedContent( targetState = Pair(dismissState.dismissDirection, dismissing), transitionSpec = { fadeIn(tween(220), if (targetState.second) 1f else 0f) togetherWith fadeOut( tween(220), if (targetState.second) 1f else 0f, ) }, ) { (dismissDirection, dismissing) -> val revealSize = remember { Animatable(if (dismissing) 0.0f else 1f) } LaunchedEffect(dismissing) { if (dismissing) { revealSize.snapTo(0f) revealSize.animateTo(1f, tween(400)) } } val activatedColor = when (dismissDirection) { StartToEnd -> if (dismissing) startAction.backgroundColour else backgroundColor EndToStart -> if (dismissing) endAction.backgroundColour else backgroundColor else -> backgroundColor } Box( Modifier.fillMaxSize() .circularReveal( progress = revealSize.asState(), centerOffset = Offset( x = if (dismissDirection == StartToEnd) 0.1f else 0.9f, y = 0.5f, ), ).background(activatedColor), ) { val alignment: Alignment = when (dismissDirection) { StartToEnd -> Alignment.CenterStart else -> Alignment.CenterEnd } Box(Modifier.fillMaxHeight().align(alignment)) { when (dismissDirection) { StartToEnd -> startAction.content(this, dismissing) EndToStart -> endAction.content(this, dismissing) else -> {} } } } } } @OptIn(ExperimentalMaterial3Api::class) private fun SwipeToDismissBoxValue.willDismiss(): Boolean { return this == StartToEnd || this == EndToStart }
4
null
0
9
011bdd9eabd2d224ebd5ea379256ed71575d89e8
6,079
linkding-apps
MIT License
idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedLastOrNull.kt
JetBrains
278,369,660
false
null
// WITH_RUNTIME val x = listOf(1, 3, 2).<caret>sorted().lastOrNull()
0
Kotlin
29
71
b6789690db56407ae2d6d62746fb69dc99d68c84
68
intellij-kotlin
Apache License 2.0
src/main/kotlin/no/nav/tilleggsstonader/sak/opplysninger/aktivitet/AktiviteterDto.kt
navikt
685,490,225
false
{"Kotlin": 2077992, "Gherkin": 52290, "HTML": 48650, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.opplysninger.aktivitet import no.nav.tilleggsstonader.kontrakter.aktivitet.AktivitetArenaDto import java.time.LocalDate data class AktiviteterDto( val periodeHentetFra: LocalDate, val periodeHentetTil: LocalDate, val aktiviteter: List<AktivitetArenaDto>, )
5
Kotlin
1
0
459e2ef7fcc857882a810d4527cb3f8ec18954d0
307
tilleggsstonader-sak
MIT License
src/main/kotlin/br/com/jiratorio/jira/domain/JiraChangelog.kt
jirareport
126,883,660
false
{"Kotlin": 628412, "Dockerfile": 302}
package br.com.jiratorio.jira.domain import java.time.LocalDateTime data class JiraChangelog( val from: String? = null, val to: String? = null, val field: String? = null, var created: LocalDateTime )
12
Kotlin
12
21
845540e238f47fbd05c1f7f6839152545521c63e
223
jirareport
MIT License
plugins/kotlin/idea/tests/testData/refactoring/bindToElement/changeImport/ChangeImport.kt
ingokegel
72,937,917
false
null
// FILE: test/ChangeImport.kt // BIND_TO test.bar.A package test import test.foo.A fun foo() { val x = <caret>A() } // FILE: test/foo/A.kt package test.foo class A { } // FILE: test/bar/A.kt package test.bar class A { }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
229
intellij-community
Apache License 2.0
src/main/kotlin/no/nav/tilleggsstonader/sak/vilkår/vilkårperiode/evaluering/EvalueringVilkårperiode.kt
navikt
685,490,225
false
{"Kotlin": 1330983, "HTML": 33935, "Gherkin": 11561, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.evaluering import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.AktivitetType import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.DelvilkårVilkårperiode import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.MålgruppeType import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.ResultatDelvilkårperiode import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.ResultatVilkårperiode import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.domain.VilkårperiodeType import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.DelvilkårAktivitetDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.DelvilkårMålgruppeDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.DelvilkårVilkårperiodeDto import no.nav.tilleggsstonader.sak.vilkår.vilkårperiode.dto.VurderingDto data class ResultatEvaluering( val delvilkår: DelvilkårVilkårperiode, val resultat: ResultatVilkårperiode, ) object EvalueringVilkårperiode { fun evaulerVilkårperiode(type: VilkårperiodeType, delvilkår: DelvilkårVilkårperiodeDto): ResultatEvaluering { return when { type is MålgruppeType && delvilkår is DelvilkårMålgruppeDto -> EvalueringMålgruppe.utledResultat(type, delvilkår) type is AktivitetType && delvilkår is DelvilkårAktivitetDto -> EvalueringAktivitet.utledResultat(type, delvilkår) else -> error("Ugyldig kombinasjon type=$type delvilkår=${delvilkår.javaClass.simpleName}") } } fun VurderingDto?.tilVurdering(resultat: ResultatDelvilkårperiode) = DelvilkårVilkårperiode.Vurdering( svar = this?.svar, resultat = resultat, ) }
3
Kotlin
1
0
9e361dc0c4187917899adea204cf6fda924d6fc4
1,772
tilleggsstonader-sak
MIT License
lib_base/src/main/java/com/czl/lib_base/base/IBaseView.kt
cdalwyn
336,133,347
false
null
package com.czl.lib_base.base interface IBaseView { /** * 初始化界面传递参数 */ fun initParam() /** * 初始化数据 */ fun initData() /** * 初始化界面观察者的监听 */ fun initViewObservable() }
1
null
70
267
77298b416cc15f168499c0b29c8f9017e6c187ca
221
PlayAndroid
Apache License 2.0
android/data/src/main/java/any/data/backup/BackupManagerImpl.kt
dokar3
572,488,513
false
null
package any.data.backup import android.content.Context import any.base.util.Dirs import any.base.util.FileUtil import any.base.util.ZipUtil import any.base.util.isHttpUrl import any.data.db.AppDatabase import any.data.db.PostContentDatabase import any.data.entity.AppDataType import any.data.entity.Bookmark import any.data.entity.Post import any.data.entity.PostContent import any.data.entity.ServiceManifest import any.data.entity.ServiceResource import any.data.entity.User import any.data.json.Json import any.data.json.fromJson import any.data.json.toJson import any.data.service.ServiceInstaller import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream class BackupManagerImpl( context: Context, private val json: Json = Json, ) : BackupManager { private val context = context.applicationContext private val appDatabase by lazy { AppDatabase.get(context) } private val postContentDatabase by lazy { PostContentDatabase.get(context) } private val serviceInstaller by lazy { ServiceInstaller.getDefault(context) } override suspend fun open( file: File ): List<BackupItem> = withContext(Dispatchers.IO) { val tempDir = newTempDir() // Unzip backup archive ZipUtil.unzip(file, tempDir) // Find backup items val extractedFiles = tempDir.listFiles() ?: emptyArray() val filenameToTypeMap = AppDataType.values().associateBy { getBackupFilename(it) } extractedFiles.mapNotNull { val type = filenameToTypeMap[it.name] ?: return@mapNotNull null BackupItem(type = type, file = it) } } override suspend fun importableCounts( items: List<BackupItem> ): List<Int> = withContext(Dispatchers.IO) { items.map { item -> val entityType = when (item.type) { AppDataType.Services -> { return@map getManifestCount(item.file) } AppDataType.Users -> { Json.parameterizedType<List<User>>() } AppDataType.PostContents -> { Json.parameterizedType<List<PostContent>>() } AppDataType.Posts -> { Json.parameterizedType<List<Post>>() } AppDataType.Bookmarks -> { Json.parameterizedType<List<Bookmark>>() } } try { item.file.inputStream() .use { reader -> json.fromJson<List<*>>(reader, entityType) }!! .size } catch (e: Exception) { e.printStackTrace() 0 } } } override suspend fun import( items: List<BackupItem> ): List<Result<Int>> = withContext(Dispatchers.IO) { // Import items.map { importItem(type = it.type, input = it.file) } } override suspend fun exportableCounts(types: List<AppDataType>): List<Int> { val db = AppDatabase.get(context) val postContentDb = PostContentDatabase.get(context) return types.map { when (it) { AppDataType.Services -> db.serviceDao().count() AppDataType.Users -> db.userDao().count() AppDataType.Posts -> db.postDao().count() AppDataType.Bookmarks -> db.bookmarkDao().count() AppDataType.PostContents -> postContentDb.postContentDao().count() } } } override suspend fun export( types: List<AppDataType>, output: File ): List<Result<Int>> = withContext(Dispatchers.IO) { val tempDir = newTempDir() val items = types.map { BackupItem( type = it, file = File(tempDir, getBackupFilename(it)), ) } // Export to json files val results = items.map { exportItem(type = it.type, output = it.file) } // Compress json files to archive ZipUtil.zip( inputs = items.map { it.file }, output = output, ) // Clear json files items.forEach { it.file.deleteRecursively() } results } private fun newTempDir(): File { val dir = Dirs.backupTempDir(context) if (!dir.exists() && !dir.createNewFile()) { throw IOException("Cannot create dir: $dir") } return dir } private fun getBackupFilename(type: AppDataType): String { return when (type) { AppDataType.Services -> "services" // folder AppDataType.Users -> "users.json" AppDataType.Posts -> "posts.json" AppDataType.Bookmarks -> "bookmarks.json" AppDataType.PostContents -> "post_contents.json" } } private fun getManifestCount(servicesDir: File): Int { val serviceDirs = servicesDir.listFiles { dir, _ -> dir.isDirectory } ?: return 0 return serviceDirs.count { serviceDir -> val manifest = File(serviceDir, SERVICE_MANIFEST_FILENAME) try { manifest.inputStream().use { json.fromJson<ServiceManifest>(it) } != null } catch (e: Exception) { e.printStackTrace() false } } } /** * Import posts/bookmarks from json file */ private suspend fun importItem( type: AppDataType, input: File, ): Result<Int> = withContext(Dispatchers.IO) { try { // Read and import val count = when (type) { AppDataType.Services -> { importServices(input) } AppDataType.Users -> { input.inputStream().use { importUsers(it) } } AppDataType.Posts -> { input.inputStream().use { importPosts(it) } } AppDataType.Bookmarks -> { input.inputStream().use { importBookmarks(it) } } AppDataType.PostContents -> { input.inputStream().use { importPostContents(it) } } } Result.success(count) } catch (e: Exception) { e.printStackTrace() Result.failure(e) } } private suspend fun importServices(servicesDir: File): Int { val serviceDirs = servicesDir.listFiles { dir, _ -> dir.isDirectory } ?: return 0 var importedCount = 0 for (serviceDir in serviceDirs) { val manifest = File(serviceDir, SERVICE_MANIFEST_FILENAME) if (!manifest.exists()) { continue } val service = serviceInstaller.installFromManifest(manifest) if (service != null) { appDatabase.serviceDao().add(service) importedCount++ } } return importedCount } private suspend fun importUsers(inputStream: InputStream): Int { val type = Json.parameterizedType<List<User>>() val users = json.fromJson<List<User>>(inputStream, type) if (users.isNullOrEmpty()) { return 0 } appDatabase.userDao().add(users) return users.size } private suspend fun importPosts(inputStream: InputStream): Int { val type = Json.parameterizedType<List<Post>>() val posts = json.fromJson<List<Post>>(inputStream, type) if (posts.isNullOrEmpty()) { return 0 } appDatabase.postDao().add(posts) return posts.size } private suspend fun importBookmarks(inputStream: InputStream): Int { val type = Json.parameterizedType<List<Bookmark>>() val bookmarks = json.fromJson<List<Bookmark>>(inputStream, type) if (bookmarks.isNullOrEmpty()) { return 0 } appDatabase.bookmarkDao().add(bookmarks) return bookmarks.size } private suspend fun importPostContents(inputStream: InputStream): Int { val type = Json.parameterizedType<List<PostContent>>() val contents = json.fromJson<List<PostContent>>(inputStream, type) if (contents.isNullOrEmpty()) { return 0 } postContentDatabase.postContentDao().add(contents) return contents.size } /** * Export posts/bookmarks to json file */ private suspend fun exportItem( type: AppDataType, output: File ): Result<Int> = withContext(Dispatchers.IO) { try { // Export val count = when (type) { AppDataType.Services -> { exportServices(output) } AppDataType.Users -> { output.outputStream().use { exportUsers(it) } } AppDataType.Posts -> { output.outputStream().use { exportPosts(it) } } AppDataType.Bookmarks -> { output.outputStream().use { exportBookmarks(it) } } AppDataType.PostContents -> { output.outputStream().use { exportPostContents(it) } } } Result.success(count) } catch (e: Exception) { e.printStackTrace() Result.failure(e) } } private suspend fun exportServices(dir: File): Int { if (!dir.exists() && !dir.mkdirs()) { throw Exception("Cannot create dir: $dir") } val services = appDatabase.serviceDao().getAll() for (service in services) { val serviceFolder = File(dir, FileUtil.buildValidFatFilename(service.id)) serviceFolder.mkdir() val updatedResources = mutableMapOf<ServiceResource.Type, String>() for (res in service.resources()) { val type = res.type val path = res.path if (path.isEmpty() || path.isHttpUrl()) { continue } val src = File(path) val dst = File(serviceFolder, src.name) if (src.exists()) { // Local file src.copyTo(dst) } else if (FileUtil.isAssetsFile(path)) { // Assets file FileUtil.readAssetsFile(context, path).use { input -> dst.outputStream().use { output -> input.copyTo(output) } } } updatedResources[type] = dst.name } // Write manifest val localResources = updatedResources.map { ServiceResource(it.key, it.value) } val updatedService = service.copy(localResources = localResources) val manifest = File(serviceFolder, SERVICE_MANIFEST_FILENAME) manifest.outputStream().use { json.toJson(updatedService, it) } } return services.size } private suspend fun exportUsers(outputStream: OutputStream): Int { val users = appDatabase.userDao().getAll() json.toJson(users, outputStream) return users.size } private suspend fun exportPosts(outputStream: OutputStream): Int { val posts = appDatabase.postDao().getAll() json.toJson(posts, outputStream) return posts.size } private suspend fun exportBookmarks(outputStream: OutputStream): Int { val bookmarks = appDatabase.bookmarkDao().getAll() json.toJson(bookmarks, outputStream) return bookmarks.size } private suspend fun exportPostContents(outputStream: OutputStream): Int { val contents = postContentDatabase.postContentDao().getAll() json.toJson(contents, outputStream) return contents.size } companion object { private const val SERVICE_MANIFEST_FILENAME = "manifest.json" } }
8
Kotlin
0
9
cc4258cdc6822d28d596ec061bab4dd67bfe6c44
12,645
any
Apache License 2.0
src/main/kotlin/io/github/cheesesandteam/koreanchat/plugin/KoreanChatPlugin.kt
CheeseSandTeam
622,410,016
false
null
package io.github.cheesesandteam.koreanchat.plugin import org.bukkit.plugin.java.JavaPlugin @Suppress("unused") class KoreanChatPlugin : JavaPlugin() { override fun onEnable() { TODO("Log Plugin Enable and Register Event Listener to hook chat") } }
0
Kotlin
0
4
9c4e16defc9ba11b7efd4039aec51af74875eded
267
korean-chat
MIT License
advent-of-code/src/main/kotlin/DayTen.kt
pauliancu97
518,083,754
false
null
class DayTen { private fun getNextOccurrenceString(string: String): String { var currentOccurrence = 1 var nextString = "" for (index in 1 until string.length) { if (string[index] != string[index - 1]) { nextString += "${currentOccurrence}${string[index - 1]}" currentOccurrence = 1 } else { currentOccurrence++ } } nextString += "${currentOccurrence}${string.last()}" return nextString } private fun getFinalOccurrenceString(string: String, numOfIterations: Int): String { var currentString = string repeat(numOfIterations) { currentString = getNextOccurrenceString(currentString) } return currentString } fun solvePartOne() { println(getFinalOccurrenceString("1113222113", 50).length) } } fun main() { DayTen().solvePartOne() }
0
Kotlin
0
0
3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6
944
advent-of-code-2015
MIT License
database_manager/src/main/java/com/wordpress/anujsaxenadev/database_manager/helpers/map_helper/MapDatabaseHelper.kt
anujsaxenadev
715,621,535
false
{"Kotlin": 50772, "HTML": 489, "JavaScript": 225, "CSS": 90}
package com.wordpress.anujsaxenadev.database_manager.helpers.map_helper interface MapDatabaseHelper{ /** * Check if Resource Entry is there in Database * @param resourceId Id of the resource to check * * @return [Result] of `true` - if resource exists, `false` - if resource does not exist, [Throwable] - if there is some error happened during check. */ suspend fun checkResourceExist(resourceId: String): Result<Boolean> /** * Get the Resource Name of the given `resourceId` * * @param resourceId Id of the resource * * @return [Result] of Name of the resource saved. [Throwable] - if there is some error happened during get call. */ suspend fun getResourceName(resourceId: String): Result<String> /** * Save the Resource with given resource id and generate the resource name * * @param resourceId Id of the resource * * @return [Result] of name of the resource saved. [Throwable] - if there is some error happened during get call. */ suspend fun storeResourceAndGetFileName(resourceId: String): Result<String> }
0
Kotlin
0
0
ca08006644fbf64fcb709f02ffb9d2d4e42678b1
1,127
GoogleMaps
MIT License
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day23.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoc2015.utils.instructionset.SimpleInstructionSet import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.machine.Machine import nl.jstege.adventofcode.aoccommon.utils.machine.Program import nl.jstege.adventofcode.aoccommon.utils.machine.Simulator /** * * @author <NAME> */ class Day23 : Day(title = "Opening the Turing Lock") { private companion object Configuration { private const val OUTPUT_REGISTER = "b" } override fun first(input: Sequence<String>) = run(input.toList(), mapOf()) override fun second(input: Sequence<String>) = run(input.toList(), mapOf("a" to 1)) private fun run(input: List<String>, registers: Map<String, Int>): Int { val machine = Machine() machine.registers.putAll(registers) Simulator( Program.assemble( input, machine, { SimpleInstructionSet.assemble(it, machine) }), machine ).run() return machine.registers[OUTPUT_REGISTER] } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
1,126
AdventOfCode
MIT License
src/main/kotlin/github/cheng/engine/TelegramBot.kt
YiGuan-z
702,319,315
false
{"Kotlin": 84112}
package github.cheng.engine import com.github.kotlintelegrambot.dispatch import com.github.kotlintelegrambot.logging.LogLevel import github.cheng.TelegramResources import github.cheng.application.Application import github.cheng.application.ApplicationEngine import github.cheng.application.env.getListOrNull import github.cheng.application.env.getStringOrNull import github.cheng.module.bot.bot import github.cheng.module.mkdirImageFinder import github.cheng.module.thisLogger object TelegramBot : ApplicationEngine { override fun create(application: Application): Application { with(application) { configGlobalResource() mkdirImageFinder() configBot() } return application } override fun Application.start() { instance(bot).startPolling().also { thisLogger<Application>().info("机器人已启动") } } override fun Application.stop() { instance(bot).stopPolling() } } context (Application) private fun configGlobalResource() { appEnvironment.property("bot.lang.default").getStringOrNull()?.let { TelegramResources.defaultLang = it } appEnvironment.property("bot.master").getStringOrNull()?.let { TelegramResources.adminName = it } appEnvironment.property("bot.images.file_storage").getStringOrNull()?.let { TelegramResources.imageStorage = it } appEnvironment.property("bot.images.max_images").getStringOrNull()?.let { TelegramResources.maxImages = it.toInt() } appEnvironment.property("bot.images.sticker_sources").getListOrNull()?.let { TelegramResources.stickerSources = it } } private fun Application.configBot() { install(bot) { token = appEnvironment.config("bot").property("tg_token").getString() logLevel = LogLevel.Error dispatch { val dispatcher = this botDispatcherModules.forEach { (_, botDispatcherModule) -> botDispatcherModule.apply { dispatcher.dispatch() } logger.info("Bot Dispatcher Module loaded: {}", botDispatcherModule.dispatcherName) logger.info("Bot Dispatcher Module description: {}", botDispatcherModule.description) } } } }
0
Kotlin
0
0
4eda85449d70767f9cb2c66aaa794731828b5f63
2,251
telegram-stickers-collect-bot
MIT License
core/runtime/src/main/kotlin/edu/byu/uapi/server/types/ResponseMetadata.kt
byu-oit
130,911,554
false
null
package edu.byu.uapi.server.types import edu.byu.uapi.model.UAPISortOrder import edu.byu.uapi.spi.SpecConstants import edu.byu.uapi.spi.SpecConstants.Metadata import edu.byu.uapi.spi.rendering.Renderable import edu.byu.uapi.spi.rendering.Renderer import java.time.Instant import kotlin.Int import kotlin.String import kotlin.let import edu.byu.uapi.spi.SpecConstants.Collections.Metadata as CollectionMeta import edu.byu.uapi.spi.SpecConstants.FieldSets.Metadata as FieldSetMeta sealed class ResponseMetadata : Renderable { abstract val validationResponse: ValidationResponse abstract val validationInformation: List<String> abstract val cache: CacheMeta? final override fun render(renderer: Renderer<*>) { renderer.tree(Metadata.ValidationResponse.KEY, validationResponse) if (validationInformation.isNotEmpty()) { renderer.valueArray(Metadata.KEY_VALIDATION_INFORMATION, validationInformation) } cache?.let { renderer.tree(Metadata.Cache.KEY, it) } renderExtras(renderer) } abstract fun renderExtras(renderer: Renderer<*>) } data class ClaimsResponseMetadata( override val validationResponse: ValidationResponse = ValidationResponse.OK, override val validationInformation: List<String> = emptyList(), override val cache: CacheMeta? = null ): ResponseMetadata() { override fun renderExtras(renderer: Renderer<*>) { } } object EmptyResponseMetadata : ResponseMetadata() { override val validationResponse = ValidationResponse(204, "No Content") override val validationInformation = emptyList<String>() override val cache: CacheMeta? = null override fun renderExtras(renderer: Renderer<*>) { } } data class UAPIErrorMetadata( override val validationResponse: ValidationResponse, override val validationInformation: List<String> ) : ResponseMetadata() { override fun renderExtras(renderer: Renderer<*>) { } override val cache: CacheMeta? = null } data class CollectionMetadata( val collectionSize: Int, val sortMetadata: SortableCollectionMetadata? = null, val searchMetadata: SearchableCollectionMetadata? = null, val subsetMetadata: CollectionSubsetMetadata? = null, override val validationResponse: ValidationResponse = ValidationResponse.OK, override val validationInformation: List<String> = emptyList(), override val cache: CacheMeta? = null ) : ResponseMetadata() { override fun renderExtras(renderer: Renderer<*>) { renderer.value(CollectionMeta.KEY_COLLECTION_SIZE, collectionSize) sortMetadata?.render(renderer) searchMetadata?.render(renderer) subsetMetadata?.render(renderer) } } data class CollectionSubsetMetadata( val subsetSize: Int, val subsetStart: Int, val defaultSubsetSize: Int, val maxSubsetSize: Int ) : Renderable { override fun render(renderer: Renderer<*>) { renderer.value(CollectionMeta.KEY_SUBSET_SIZE, subsetSize) renderer.value(CollectionMeta.KEY_SUBSET_START, subsetStart) renderer.value(CollectionMeta.KEY_SUBSET_DEFAULT_SIZE, defaultSubsetSize) renderer.value(CollectionMeta.KEY_SUBSET_MAX_SIZE, maxSubsetSize) } } data class SortableCollectionMetadata( val sortPropertiesAvailable: List<String>, val sortPropertiesDefault: List<String>, val sortOrderDefault: UAPISortOrder ) : Renderable { override fun render(renderer: Renderer<*>) { renderer.valueArray(CollectionMeta.KEY_SORT_PROPERTIES_AVAILABLE, sortPropertiesAvailable) renderer.valueArray(CollectionMeta.KEY_SORT_PROPERTIES_DEFAULT, sortPropertiesDefault) renderer.value(CollectionMeta.KEY_SORT_ORDER_DEFAULT, sortOrderDefault) } } data class SearchableCollectionMetadata( val searchContextsAvailable: Map<String, Collection<String>> ) : Renderable { override fun render(renderer: Renderer<*>) { renderer.tree(CollectionMeta.KEY_SEARCH_CONTEXTS_AVAILABLE) { searchContextsAvailable.entries.forEach { e -> valueArray(e.key, e.value) } } } } data class UAPIResourceMeta( override val validationResponse: ValidationResponse = ValidationResponse.OK, override val validationInformation: List<String> = emptyList(), override val cache: CacheMeta? = null ) : ResponseMetadata() { override fun renderExtras(renderer: Renderer<*>) { } } data class ValidationResponse( val code: Int = 200, val message: String = "OK" ) : Renderable { override fun render(renderer: Renderer<*>) { renderer.value(Metadata.ValidationResponse.KEY_CODE, code) renderer.value(Metadata.ValidationResponse.KEY_MESSAGE, message) } companion object { val OK = ValidationResponse() } // @JsonIgnore val successful = code in 200..299 } data class CacheMeta( val dateTime: Instant ) : Renderable { override fun render(renderer: Renderer<*>) { renderer.value(Metadata.Cache.KEY_DATE_TIME, dateTime) } } data class FieldsetsMetadata( val fieldSetsReturned: Set<String>, val fieldSetsAvailable: Set<String>, val fieldSetsDefault: Set<String> = setOf(SpecConstants.FieldSets.VALUE_BASIC), val contextsAvailable: Map<String, Set<String>> = emptyMap(), override val validationResponse: ValidationResponse = ValidationResponse.OK, override val validationInformation: List<String> = emptyList(), override val cache: CacheMeta? = null ) : ResponseMetadata() { override fun renderExtras(renderer: Renderer<*>) { renderer.valueArray(FieldSetMeta.KEY_FIELD_SETS_RETURNED, fieldSetsReturned) renderer.valueArray(FieldSetMeta.KEY_FIELD_SETS_AVAILABLE, fieldSetsAvailable) renderer.valueArray(FieldSetMeta.KEY_FIELD_SETS_DEFAULT, fieldSetsDefault) if (contextsAvailable.isNotEmpty()) { renderer.tree(FieldSetMeta.KEY_CONTEXTS_AVAILABLE) { contextsAvailable.forEach { k, v -> renderer.valueArray(k, v) } } } } }
16
Kotlin
0
0
1ca0e357a1b00cf11c1e1c9a1b00af4455d6d30c
6,054
kotlin-uapi
Apache License 2.0
integration/kotlinx-coroutines-guava/test/ListenableFutureTest.kt
r4zzz4k
149,841,473
true
{"Kotlin": 1764492, "CSS": 8215, "JavaScript": 2505, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 356}
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.experimental.guava import com.google.common.util.concurrent.* import kotlinx.coroutines.experimental.* import kotlinx.coroutines.experimental.CancellationException import org.hamcrest.core.* import org.junit.* import org.junit.Assert.* import java.io.* import java.util.concurrent.* class ListenableFutureTest : TestBase() { @Before fun setup() { ignoreLostThreads("ForkJoinPool.commonPool-worker-") } @Test fun testSimpleAwait() { val service = MoreExecutors.listeningDecorator(ForkJoinPool.commonPool()) val future = GlobalScope.future { service.submit(Callable<String> { "O" }).await() + "K" } assertThat(future.get(), IsEqual("OK")) } @Test fun testAwaitWithContext() = runTest { val future = SettableFuture.create<Int>() val deferred = async { withContext(Dispatchers.Default) { future.await() } } future.set(1) assertEquals(1, deferred.await()) } @Test fun testAwaitWithContextCancellation() = runTest(expected = {it is IOException}) { val future = SettableFuture.create<Int>() val deferred = async { withContext(Dispatchers.Default) { future.await() } } deferred.cancel(IOException()) deferred.await() } @Test fun testCompletedFuture() { val toAwait = SettableFuture.create<String>() toAwait.set("O") val future = GlobalScope.future { toAwait.await() + "K" } assertThat(future.get(), IsEqual("OK")) } @Test fun testWaitForFuture() { val toAwait = SettableFuture.create<String>() val future = GlobalScope.future { toAwait.await() + "K" } assertFalse(future.isDone) toAwait.set("O") assertThat(future.get(), IsEqual("OK")) } @Test fun testCompletedFutureExceptionally() { val toAwait = SettableFuture.create<String>() toAwait.setException(IllegalArgumentException("O")) val future = GlobalScope.future { try { toAwait.await() } catch (e: RuntimeException) { assertThat(e, IsInstanceOf(IllegalArgumentException::class.java)) e.message!! } + "K" } assertThat(future.get(), IsEqual("OK")) } @Test fun testWaitForFutureWithException() { val toAwait = SettableFuture.create<String>() val future = GlobalScope.future { try { toAwait.await() } catch (e: RuntimeException) { assertThat(e, IsInstanceOf(IllegalArgumentException::class.java)) e.message!! } + "K" } assertFalse(future.isDone) toAwait.setException(IllegalArgumentException("O")) assertThat(future.get(), IsEqual("OK")) } @Test fun testExceptionInsideCoroutine() { val service = MoreExecutors.listeningDecorator(ForkJoinPool.commonPool()) val future = GlobalScope.future { if (service.submit(Callable<Boolean> { true }).await()) { throw IllegalStateException("OK") } "fail" } try { future.get() fail("'get' should've throw an exception") } catch (e: ExecutionException) { assertThat(e.cause, IsInstanceOf(IllegalStateException::class.java)) assertThat(e.cause!!.message, IsEqual("OK")) } } @Test fun testCompletedDeferredAsListenableFuture() = runBlocking { expect(1) val deferred = async(start = CoroutineStart.UNDISPATCHED) { expect(2) // completed right away "OK" } expect(3) val future = deferred.asListenableFuture() assertThat(future.await(), IsEqual("OK")) finish(4) } @Test fun testWaitForDeferredAsListenableFuture() = runBlocking { expect(1) val deferred = async { expect(3) // will complete later "OK" } expect(2) val future = deferred.asListenableFuture() assertThat(future.await(), IsEqual("OK")) // await yields main thread to deferred coroutine finish(4) } @Test fun testAsListenableFutureThrowable() { val deferred = GlobalScope.async { throw OutOfMemoryError() } val future = deferred.asListenableFuture() try { future.get() } catch (e: ExecutionException) { assertTrue(future.isDone) assertTrue(e.cause is OutOfMemoryError) } } @Test fun testCancellableAwait() = runBlocking { expect(1) val toAwait = SettableFuture.create<String>() val job = launch(start = CoroutineStart.UNDISPATCHED) { expect(2) try { toAwait.await() // suspends } catch (e: CancellationException) { expect(5) // should throw cancellation exception throw e } } expect(3) job.cancel() // cancel the job toAwait.set("fail") // too late, the waiting job was already cancelled expect(4) // job processing of cancellation was scheduled, not executed yet yield() // yield main thread to job finish(6) } }
0
Kotlin
0
0
d1be1c9d970e29fcc177bb3767087af48935d400
5,645
kotlinx.coroutines
Apache License 2.0
components/resources/library/src/commonMain/kotlin/org/jetbrains/compose/resources/StringResources.kt
JetBrains
293,498,508
false
null
package org.jetbrains.compose.resources import androidx.compose.runtime.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.jetbrains.compose.resources.vector.xmldom.Element import org.jetbrains.compose.resources.vector.xmldom.NodeList private val SimpleStringFormatRegex = Regex("""%(\d)\$[ds]""") /** * Represents a string resource in the application. * * @param id The unique identifier of the resource. * @param key The key used to retrieve the string resource. * @param items The set of resource items associated with the string resource. */ @OptIn(InternalResourceApi::class) @ExperimentalResourceApi @Immutable class StringResource @InternalResourceApi constructor(id: String, val key: String, items: Set<ResourceItem>) : Resource(id, items) private sealed interface StringItem { data class Value(val text: String) : StringItem data class Array(val items: List<String>) : StringItem } private val stringsCacheMutex = Mutex() private val parsedStringsCache = mutableMapOf<String, Deferred<Map<String, StringItem>>>() //@TestOnly internal fun dropStringsCache() { parsedStringsCache.clear() } private suspend fun getParsedStrings( path: String, resourceReader: ResourceReader ): Map<String, StringItem> = coroutineScope { val deferred = stringsCacheMutex.withLock { parsedStringsCache.getOrPut(path) { //LAZY - to free the mutex lock as fast as possible async(start = CoroutineStart.LAZY) { parseStringXml(path, resourceReader) } } } deferred.await() } private suspend fun parseStringXml(path: String, resourceReader: ResourceReader): Map<String, StringItem> { val nodes = resourceReader.read(path).toXmlElement().childNodes val strings = nodes.getElementsWithName("string").associate { element -> val rawString = element.textContent.orEmpty() element.getAttribute("name") to StringItem.Value(handleSpecialCharacters(rawString)) } val arrays = nodes.getElementsWithName("string-array").associate { arrayElement -> val items = arrayElement.childNodes.getElementsWithName("item").map { element -> val rawString = element.textContent.orEmpty() handleSpecialCharacters(rawString) } arrayElement.getAttribute("name") to StringItem.Array(items) } return strings + arrays } /** * Retrieves a string using the specified string resource. * * @param resource The string resource to be used. * @return The retrieved string resource. * * @throws IllegalArgumentException If the provided ID is not found in the resource file. */ @ExperimentalResourceApi @Composable fun stringResource(resource: StringResource): String { val resourceReader = LocalResourceReader.current val str by rememberResourceState(resource, { "" }) { env -> loadString(resource, resourceReader, env) } return str } /** * Loads a string using the specified string resource. * * @param resource The string resource to be used. * @return The loaded string resource. * * @throws IllegalArgumentException If the provided ID is not found in the resource file. */ @ExperimentalResourceApi suspend fun getString(resource: StringResource): String = loadString(resource, DefaultResourceReader, getResourceEnvironment()) @OptIn(ExperimentalResourceApi::class) private suspend fun loadString( resource: StringResource, resourceReader: ResourceReader, environment: ResourceEnvironment ): String { val path = resource.getPathByEnvironment(environment) val keyToValue = getParsedStrings(path, resourceReader) val item = keyToValue[resource.key] as? StringItem.Value ?: error("String ID=`${resource.key}` is not found!") return item.text } /** * Retrieves a formatted string using the specified string resource and arguments. * * @param resource The string resource to be used. * @param formatArgs The arguments to be inserted into the formatted string. * @return The formatted string resource. * * @throws IllegalArgumentException If the provided ID is not found in the resource file. */ @ExperimentalResourceApi @Composable fun stringResource(resource: StringResource, vararg formatArgs: Any): String { val resourceReader = LocalResourceReader.current val args = formatArgs.map { it.toString() } val str by rememberResourceState(resource, { "" }) { env -> loadString(resource, args, resourceReader, env) } return str } /** * Loads a formatted string using the specified string resource and arguments. * * @param resource The string resource to be used. * @param formatArgs The arguments to be inserted into the formatted string. * @return The formatted string resource. * * @throws IllegalArgumentException If the provided ID is not found in the resource file. */ @ExperimentalResourceApi suspend fun getString(resource: StringResource, vararg formatArgs: Any): String = loadString( resource, formatArgs.map { it.toString() }, DefaultResourceReader, getResourceEnvironment() ) @OptIn(ExperimentalResourceApi::class) private suspend fun loadString( resource: StringResource, args: List<String>, resourceReader: ResourceReader, environment: ResourceEnvironment ): String { val str = loadString(resource, resourceReader, environment) return SimpleStringFormatRegex.replace(str) { matchResult -> args[matchResult.groupValues[1].toInt() - 1] } } /** * Retrieves a list of strings using the specified string array resource. * * @param resource The string resource to be used. * @return A list of strings representing the items in the string array. * * @throws IllegalStateException if the string array with the given ID is not found. */ @ExperimentalResourceApi @Composable fun stringArrayResource(resource: StringResource): List<String> { val resourceReader = LocalResourceReader.current val array by rememberResourceState(resource, { emptyList() }) { env -> loadStringArray(resource, resourceReader, env) } return array } /** * Loads a list of strings using the specified string array resource. * * @param resource The string resource to be used. * @return A list of strings representing the items in the string array. * * @throws IllegalStateException if the string array with the given ID is not found. */ @ExperimentalResourceApi suspend fun getStringArray(resource: StringResource): List<String> = loadStringArray(resource, DefaultResourceReader, getResourceEnvironment()) @OptIn(ExperimentalResourceApi::class) private suspend fun loadStringArray( resource: StringResource, resourceReader: ResourceReader, environment: ResourceEnvironment ): List<String> { val path = resource.getPathByEnvironment(environment) val keyToValue = getParsedStrings(path, resourceReader) val item = keyToValue[resource.key] as? StringItem.Array ?: error("String array ID=`${resource.key}` is not found!") return item.items } private fun NodeList.getElementsWithName(name: String): List<Element> = List(length) { item(it) } .filterIsInstance<Element>() .filter { it.localName == name } //https://developer.android.com/guide/topics/resources/string-resource#escaping_quotes /** * Replaces * * '\n' -> new line * * '\t' -> tab * * '\uXXXX' -> unicode symbol * * '\\' -> '\' * * @param string The input string to handle. * @return The string with special characters replaced according to the logic. */ internal fun handleSpecialCharacters(string: String): String { val unicodeNewLineTabRegex = Regex("""\\u[a-fA-F\d]{4}|\\n|\\t""") val doubleSlashRegex = Regex("""\\\\""") val doubleSlashIndexes = doubleSlashRegex.findAll(string).map { it.range.first } val handledString = unicodeNewLineTabRegex.replace(string) { matchResult -> if (doubleSlashIndexes.contains(matchResult.range.first - 1)) matchResult.value else when (matchResult.value) { "\\n" -> "\n" "\\t" -> "\t" else -> matchResult.value.substring(2).toInt(16).toChar().toString() } }.replace("""\\""", """\""") return handledString }
1,293
null
1058
14,559
04edeed084d9882d3a28950a11e722a3eb2860c7
8,266
compose-multiplatform
Apache License 2.0
samples/src/jvmMain/kotlin/okio/samples/GoldenValue.kt
square
17,812,502
false
{"Kotlin": 1559919, "Java": 43685, "Shell": 1180}
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio.samples import java.io.IOException import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.Serializable import okio.Buffer import okio.ByteString import okio.ByteString.Companion.decodeBase64 class KotlinGoldenValue { fun run() { val point = Point(8.0, 15.0) val pointBytes = serialize(point) println(pointBytes.base64()) val goldenBytes = ( "rO0ABXNyACRva2lvLnNhbXBsZXMuS290bGluR29sZGVuVmFsdWUkUG9pbnRF9yaY7cJ9EwIAA" + "kQAAXhEAAF5eHBAIAAAAAAAAEAuAAAAAAAA" ).decodeBase64()!! val decoded = deserialize(goldenBytes) as Point assertEquals(point, decoded) } @Throws(IOException::class) private fun serialize(o: Any?): ByteString { val buffer = Buffer() ObjectOutputStream(buffer.outputStream()).use { objectOut -> objectOut.writeObject(o) } return buffer.readByteString() } @Throws(IOException::class, ClassNotFoundException::class) private fun deserialize(byteString: ByteString): Any? { val buffer = Buffer() buffer.write(byteString) ObjectInputStream(buffer.inputStream()).use { objectIn -> val result = objectIn.readObject() if (objectIn.read() != -1) throw IOException("Unconsumed bytes in stream") return result } } internal class Point(var x: Double, var y: Double) : Serializable private fun assertEquals( a: Point, b: Point, ) { if (a.x != b.x || a.y != b.y) throw AssertionError() } } fun main() { KotlinGoldenValue().run() }
89
Kotlin
1178
8,795
0f6c9cf31101483e6ee9602e80a10f7697c8f75a
2,119
okio
Apache License 2.0
app/src/main/java/com/kylecorry/trail_sense/tools/depth/ui/ToolDepthFragment.kt
TomasCartman
343,114,452
true
{"Kotlin": 521339}
package com.kylecorry.trail_sense.tools.depth.ui import android.hardware.SensorManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.kylecorry.trail_sense.R import com.kylecorry.trail_sense.databinding.FragmentToolDepthBinding import com.kylecorry.trail_sense.shared.FormatService import com.kylecorry.trail_sense.shared.UserPreferences import com.kylecorry.trail_sense.shared.sensors.SensorService import com.kylecorry.trailsensecore.domain.depth.DepthService import com.kylecorry.trailsensecore.domain.units.DistanceUnits import com.kylecorry.trailsensecore.domain.units.Pressure import com.kylecorry.trailsensecore.domain.units.PressureUnits import com.kylecorry.trailsensecore.domain.units.UnitService import com.kylecorry.trailsensecore.infrastructure.persistence.Cache import com.kylecorry.trailsensecore.infrastructure.system.UiUtils import com.kylecorry.trailsensecore.infrastructure.time.Throttle import kotlin.math.max class ToolDepthFragment : Fragment() { private var _binding: FragmentToolDepthBinding? = null private val binding get() = _binding!! private val sensorService by lazy { SensorService(requireContext()) } private val barometer by lazy { sensorService.getBarometer() } private val depthService = DepthService() private val unitService = UnitService() private val formatService by lazy { FormatService(requireContext()) } private val userPrefs by lazy { UserPreferences(requireContext()) } private val cache by lazy { Cache(requireContext()) } private val throttle = Throttle(20) private var lastDepth: Float = 0f private var maxDepth: Float = 0f private lateinit var units: DistanceUnits override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentToolDepthBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (cache.getBoolean("cache_dialog_tool_depth") != true) { UiUtils.alert( requireContext(), getString(R.string.disclaimer_message_title), getString(R.string.depth_disclaimer) ){ cache.putBoolean("cache_dialog_tool_depth", true) } } } override fun onResume() { super.onResume() units = if (userPrefs.distanceUnits == UserPreferences.DistanceUnits.Meters) { DistanceUnits.Meters } else { DistanceUnits.Feet } barometer.start(this::update) } override fun onPause() { super.onPause() barometer.stop(this::update) } fun update(): Boolean { if (throttle.isThrottled()) { return true } val depth = depthService.calculateDepth( Pressure(barometer.pressure, PressureUnits.Hpa), Pressure(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, PressureUnits.Hpa) ).distance if (lastDepth == 0f && depth > 0) { maxDepth = depth } lastDepth = depth maxDepth = max(depth, maxDepth) val converted = unitService.convert(depth, DistanceUnits.Meters, units) val formatted = formatService.formatDepth(converted, units) val convertedMax = unitService.convert(maxDepth, DistanceUnits.Meters, units) val formattedMax = formatService.formatDepth(convertedMax, units) binding.depth.text = formatted binding.maxDepth.text = getString(R.string.max_depth, formattedMax) return true } }
0
null
0
0
7be12f2be2136fc6b3f713665bd36d931466d893
3,891
Trail-Sense
MIT License
app/src/main/java/net/attilaszabo/peopledemo/data/sources/uinames/models/PersonNetwork.kt
atoka93
152,560,205
false
null
package net.attilaszabo.peopledemo.data.sources.uinames.models import com.google.gson.annotations.SerializedName class PersonNetwork { @SerializedName("name") var name: String = "" @SerializedName("surname") var surname: String = "" @SerializedName("gender") var gender: String = "" @SerializedName("region") var region: String = "" @SerializedName("age") var age: Int = 0 @SerializedName("title") var title: String = "" @SerializedName("phone") var phone: String = "" @SerializedName("birthday") var birthday: BirthdayNetwork = BirthdayNetwork() @SerializedName("email") var email: String = "" @SerializedName("password") var password: String = "" @SerializedName("credit_card") var creditCard: CreditCardNetwork = CreditCardNetwork() @SerializedName("photo") var photo: String = "" }
0
Kotlin
0
1
2bd1fbcc03d4a97766329a8a2410fe7149a548f8
896
android-people-demo
Apache License 2.0
src/main/kotlin/com/liamxsage/energeticstorage/items/mineskin/SkinTexture.kt
CoasterFreakDE
812,938,765
false
{"Kotlin": 150672, "Java": 1534}
package com.liamxsage.energeticstorage.items.mineskin import java.util.* data class SkinTexture( val name: String, val uuid: UUID, val texture: Texture ) { companion object { fun fromMineSkinResponse(response: MineSkinResponse): SkinTexture { return SkinTexture( name = "skin${response.uuid.take(7)}", uuid = UUID.fromString(response.data.uuid), texture = response.data.texture ) } } }
0
Kotlin
0
1
6b5d559e76dd5f52397719ae5ebaf9f1d8876c8f
497
EnergeticStorage-Reborn
MIT License
app/src/main/java/ir/apptune/antispam/features/permission/PermissionsFragment.kt
SirLordPouya
241,154,265
false
null
package ir.apptune.antispam.features.permission import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import ir.apptune.antispam.R import ir.apptune.antispam.utils.checkNeededPermissions import kotlinx.android.synthetic.main.empty_state_layout.* import kotlinx.android.synthetic.main.permissions_fragment.* /** * This page shows a list of permissions that are required by the app, but user hasn't given the permission yet * */ class PermissionsFragment : Fragment() { private val adapter: PermissionsAdapter by lazy { PermissionsAdapter { ActivityCompat.requestPermissions(requireActivity(), arrayOf(it), 100) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.permissions_fragment, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) recycler.adapter = adapter } override fun onResume() { super.onResume() checkPermissionsStatus() } private fun checkPermissionsStatus() { val list = checkNeededPermissions(requireContext()) if (list.isEmpty()) showEmptyState() else { hideEmptyState() adapter.submitList(list) } } private fun hideEmptyState() { recycler.visibility = View.VISIBLE layoutCallLogEmpty.visibility = View.GONE } private fun showEmptyState() { recycler.visibility = View.GONE layoutCallLogEmpty.visibility = View.VISIBLE txtCallLogEmpty.text = getString(R.string.all_permissions_are_granted) imgCallLogEmpty.setImageResource(R.drawable.ic_check) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) checkPermissionsStatus() } }
0
Kotlin
1
9
fb620efe5ac319057f854ca91e810887d295feb6
2,125
AntiSpam
Apache License 2.0
app/src/main/java/com/fabler/jetflix/ui/components/Card.kt
pushpalroy
373,171,748
false
null
package com.fabler.jetflix.ui.components import androidx.compose.foundation.BorderStroke import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.fabler.jetflix.ui.theme.JetFlixTheme @Composable fun Card( modifier: Modifier = Modifier, shape: Shape = MaterialTheme.shapes.medium, color: Color = JetFlixTheme.colors.uiBackground, contentColor: Color = JetFlixTheme.colors.textPrimary, border: BorderStroke? = null, elevation: Dp = 1.dp, content: @Composable () -> Unit ) { JetFlixSurface( modifier = modifier, shape = shape, color = color, contentColor = contentColor, elevation = elevation, border = border, content = content ) }
0
Kotlin
12
47
e6041f5b23e06ac6b0da2f185fb67d8832bff632
912
jetflix
Apache License 2.0
owntracks-android-2.4/project/app/src/main/java/org/owntracks/android/ui/welcome/FinishFragment.kt
wir3z
737,346,188
false
{"Kotlin": 577231, "Groovy": 303581, "Java": 233010, "Python": 1535, "Shell": 959}
package org.owntracks.android.ui.welcome import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import dagger.hilt.android.AndroidEntryPoint import org.owntracks.android.databinding.UiWelcomeFinishBinding import org.owntracks.android.ui.preferences.PreferencesActivity import javax.inject.Inject @AndroidEntryPoint class FinishFragment @Inject constructor() : WelcomeFragment() { private val viewModel: WelcomeViewModel by activityViewModels() private lateinit var binding: UiWelcomeFinishBinding override fun shouldBeDisplayed(context: Context) = true override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { binding = UiWelcomeFinishBinding.inflate(inflater, container, false) binding.uiFragmentWelcomeFinishOpenPreferences.setOnClickListener { viewModel.setWelcomeIsAtEnd() startActivity( Intent(requireContext(), PreferencesActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } ) } return binding.root } override fun onResume() { super.onResume() viewModel.setWelcomeIsAtEnd() } }
0
Kotlin
3
4
a515ba358d3467267e9d662564152f5d7613991a
1,424
hubitat
Apache License 2.0
xbrick-app/src/main/java/cn/zzstc/lzm/LifeCycleInjector.kt
zz-xlab
226,285,739
false
null
package cn.zzstc.lzm import android.app.Application import androidx.fragment.app.FragmentManager import cn.zzstc.lzm.common.app.IAppLifeCycle import cn.zzstc.lzm.common.app.ILifecycleInjector import com.orhanobut.logger.Logger class LifeCycleInjector :ILifecycleInjector{ override fun injectAppLifeCycle( application: Application?, appLifeCycles: List<IAppLifeCycle?>? ) { Logger.d("application onCreate") } override fun injectActivityLifeCycle( application: Application?, activityLifecycleCallbacks: List<Application.ActivityLifecycleCallbacks?>? ) { } override fun injectFragmentLifeCycle( application: Application?, fragmentLifecycleCallbacks: List<FragmentManager.FragmentLifecycleCallbacks?>? ) { } override fun priority()=1 }
0
Kotlin
0
0
30451c741c85bdfaf7e2963b33bc7e4967263799
834
xbrick-app
Apache License 2.0
app/src/main/java/com/example/restaurantapp/viewmodel/UserViewModel.kt
bartaliskrisztian
311,770,400
false
null
package com.example.restaurantapp.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.restaurantapp.db.RestaurantDatabase import com.example.restaurantapp.model.User import com.example.restaurantapp.repository.UserRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class UserViewModel(application: Application): AndroidViewModel(application) { lateinit var users: LiveData<List<User>> private val repository: UserRepository var usedUser = MutableLiveData<User>() var currentUser = MutableLiveData<User>() init { val userDao = RestaurantDatabase.getDatabase(application).userDao() repository = UserRepository(userDao) } // getting the user by username or email address fun loadCurrentUser(username: String, email: String) { viewModelScope.launch(Dispatchers.IO) { currentUser.postValue(repository.getUserByUsernameOrEmail(username, email)) } } // loading all registered users fun loadUsers() { viewModelScope.launch(Dispatchers.IO) { users = repository.users } } // getting all users with specific username or email (should be 1 or 0) // needed for checking if the given username or email is used by another user fun getUsersForRegistration(username: String, email: String) { val result = MutableLiveData<User>() viewModelScope.launch(Dispatchers.IO) { val user = repository.getUserByUsernameOrEmail(username, email) result.postValue(user) } usedUser = result } // getting user by username/email and password, needed for log the user in fun getUsersForLogin(username: String, password: String) { val result = MutableLiveData<User>() viewModelScope.launch(Dispatchers.IO) { val user = repository.getUserByUsernameAndPassword(username, password) result.postValue(user) } usedUser = result } // adding one user to db fun addUser(user: User) { viewModelScope.launch (Dispatchers.IO) { repository.addUser(user) } } }
0
Kotlin
0
1
38edcaf00f842c2cee533a16747bc3b647e9d0a0
2,321
OnPlate
MIT License
lib-expandablebottombar/src/main/java/github/com/st235/lib_expandablebottombar/ExpandableBottomBar.kt
st235
173,377,910
false
{"Gradle": 5, "INI": 3, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 1, "XML": 58, "Kotlin": 51, "Java": 1, "YAML": 1}
package github.com.st235.lib_expandablebottombar import android.animation.Animator import android.annotation.TargetApi import android.content.Context import android.graphics.Color import android.graphics.Outline import android.graphics.Rect import android.os.Build import android.os.Parcelable import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.ViewOutlineProvider import androidx.annotation.* import androidx.annotation.IntRange import androidx.constraintlayout.widget.ConstraintLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.marginBottom import github.com.st235.lib_expandablebottombar.ExpandableBottomBar.ItemStyle.Companion.toItemStyle import github.com.st235.lib_expandablebottombar.behavior.ExpandableBottomBarBehavior import github.com.st235.lib_expandablebottombar.parsers.ExpandableBottomBarParser import github.com.st235.lib_expandablebottombar.state.BottomBarSavedState import github.com.st235.lib_expandablebottombar.utils.* /** * Widget, which implements bottom bar navigation pattern */ class ExpandableBottomBar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.exb_expandableButtonBarDefaultStyle ) : ConstraintLayout(context, attrs, defStyleAttr), CoordinatorLayout.AttachedBehavior { internal enum class ItemStyle(private val id: Int) { NORMAL(0), OUTLINE(1), STROKE(2); companion object { fun Int.toItemStyle(): ItemStyle = values().find { it.id == this } ?: throw IllegalArgumentException("Cannot find style for id $this") } } private val bounds = Rect() @FloatRange(from = 0.0, to = 1.0) private val itemBackgroundOpacity: Float @FloatRange(from = 0.0) private val itemBackgroundCornerRadius: Float @IntRange(from = 0) private val menuItemHorizontalMargin: Int @IntRange(from = 0) private val menuItemVerticalMargin: Int @IntRange(from = 0) private val menuHorizontalPadding: Int @IntRange(from = 0) private val menuVerticalPadding: Int @ColorInt private val itemInactiveColor: Int @ColorInt private val globalBadgeColor: Int @ColorInt private val globalBadgeTextColor: Int private val transitionDuration: Int private val menuImpl: MenuImpl private val styleController: StyleController private val stateController = ExpandableBottomBarStateController(this) @FloatRange(from = 0.0) private var backgroundCornerRadius: Float = 0F set(value) { field = value if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { invalidateOutline() } } val menu: Menu get() { return menuImpl } var onItemSelectedListener: OnItemClickListener? get() { return menu.onItemSelectedListener } set(value) { menu.onItemSelectedListener = value } var onItemReselectedListener: OnItemClickListener? get() { return menu.onItemReselectedListener } set(value) { menu.onItemReselectedListener = value } private var animator: Animator? = null init { if (id == View.NO_ID) { id = View.generateViewId() } contentDescription = resources.getString(R.string.accessibility_description) val typedArray = context.obtainStyledAttributes( attrs, R.styleable.ExpandableBottomBar, defStyleAttr, R.style.ExpandableBottomBar ) itemBackgroundOpacity = typedArray.getFloat(R.styleable.ExpandableBottomBar_exb_itemBackgroundOpacity, 0.2F) itemBackgroundCornerRadius = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_itemBackgroundCornerRadius, 30F.toPx()) transitionDuration = typedArray.getInt(R.styleable.ExpandableBottomBar_exb_transitionDuration, 100) itemInactiveColor = typedArray.getColor(R.styleable.ExpandableBottomBar_exb_itemInactiveColor, Color.BLACK) menuItemHorizontalMargin = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_item_horizontal_margin, 5F.toPx()).toInt() menuItemVerticalMargin = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_item_vertical_margin, 5F.toPx()).toInt() menuHorizontalPadding = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_item_horizontal_padding, 15F.toPx()).toInt() menuVerticalPadding = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_item_vertical_padding, 10F.toPx()).toInt() globalBadgeColor = typedArray.getColor(R.styleable.ExpandableBottomBar_exb_notificationBadgeBackgroundColor, Color.RED) globalBadgeTextColor = typedArray.getColor(R.styleable.ExpandableBottomBar_exb_notificationBadgeTextColor, Color.WHITE) val rawItemsStyle = typedArray.getInt(R.styleable.ExpandableBottomBar_exb_itemStyle, 0) styleController = StyleController.create(style = rawItemsStyle.toItemStyle()) val backgroundColor = typedArray.getColor(R.styleable.ExpandableBottomBar_exb_backgroundColor, Color.WHITE) backgroundCornerRadius = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_backgroundCornerRadius, 0F) background = DrawableHelper.createShapeDrawable(color = backgroundColor, cornerRadius = backgroundCornerRadius, opacity = 1.0F) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { elevation = typedArray.getDimension(R.styleable.ExpandableBottomBar_exb_elevation, 16F.toPx()) outlineProvider = ExpandableBottomBarOutlineProvider() clipToOutline = true } val menuItemFactory = MenuItemFactory( this, styleController, menuVerticalPadding, menuHorizontalPadding, itemBackgroundCornerRadius, itemBackgroundOpacity, itemInactiveColor, globalBadgeColor, globalBadgeTextColor ) menuImpl = MenuImpl(this, menuItemFactory, menuItemHorizontalMargin, menuItemVerticalMargin, transitionDuration.toLong()) val menuId = typedArray.getResourceId(R.styleable.ExpandableBottomBar_exb_items, View.NO_ID) if (menuId != View.NO_ID) { val barParser = ExpandableBottomBarParser(context) val items = barParser.inflate(menuId) for (item in items) { menuImpl.add(item) } } typedArray.recycle() } override fun getBehavior(): CoordinatorLayout.Behavior<*> = ExpandableBottomBarBehavior<ExpandableBottomBar>() override fun setBackgroundColor(@ColorInt color: Int) { setBackgroundColor(color, backgroundCornerRadius) } fun setBackgroundColor(@ColorInt color: Int, @FloatRange(from = 0.0) backgroundCornerRadius: Float) { this.backgroundCornerRadius = backgroundCornerRadius background = DrawableHelper.createShapeDrawable(color = color, cornerRadius = backgroundCornerRadius, opacity = 1.0F) } fun setBackgroundColorRes(@ColorRes colorRes: Int) { setBackgroundColor(ContextCompat.getColor(context, colorRes), backgroundCornerRadius) } fun setBackgroundColorRes(@ColorRes colorRes: Int, @DimenRes backgroundCornerRadiusRes: Int) { setBackgroundColor(ContextCompat.getColor(context, colorRes), resources.getDimension(backgroundCornerRadiusRes)) } override fun onAttachedToWindow() { super.onAttachedToWindow() val lp = layoutParams if (lp is CoordinatorLayout.LayoutParams) { lp.insetEdge = Gravity.BOTTOM } } override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() return stateController.store(superState) } override fun onRestoreInstanceState(state: Parcelable?) { if (state !is BottomBarSavedState) { super.onRestoreInstanceState(state) return } super.onRestoreInstanceState(state.superState) stateController.restore(state) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) bounds.set(0, 0, w, h) } /** * Shows the bottom bar */ fun show() { cancelRunningAnimation() animator = AnimationHelper.translateViewTo(this, 0F) animator?.start() } /** * Hides the bottom bar */ fun hide() { cancelRunningAnimation() animator = AnimationHelper.translateViewTo(this, getMaxScrollDistance()) animator?.start() } private fun getMaxScrollDistance(): Float { val childHeight = if (ViewCompat.isLaidOut(this)) height else measuredHeight return childHeight.toFloat() + marginBottom } private fun cancelRunningAnimation() { if (animator?.isRunning == true) { animator?.cancel() animator = null } } internal class ExpandableBottomBarStateController( private val expandableBottomBar: ExpandableBottomBar ) { fun store(superState: Parcelable?): Parcelable { val selectedItem = expandableBottomBar.menu.selectedItem return BottomBarSavedState(selectedItem?.id, superState) } fun restore(stateBottomBar: BottomBarSavedState) { val selectedItemId = stateBottomBar.selectedItem expandableBottomBar.menu.doSilently { menu -> if (selectedItemId != null) { try { menu.select(selectedItemId) } catch (e: IllegalArgumentException) { // catch exception here as it is possible that // menu item do not exists and should be added later menu.deselect() } } } } private inline fun Menu.doSilently(scope: (menu: Menu) -> Unit) { val selectedItemListener = onItemSelectedListener val reselectedItemListener = onItemReselectedListener onItemSelectedListener = null onItemReselectedListener = null scope(this) onItemSelectedListener = selectedItemListener onItemReselectedListener = reselectedItemListener } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private inner class ExpandableBottomBarOutlineProvider : ViewOutlineProvider() { override fun getOutline(view: View?, outline: Outline?) { outline?.setRoundRect(bounds, clamp(backgroundCornerRadius, 0F, min(height, width) / 2F)) } } }
2
Kotlin
60
783
a0abc55616b9f711e41e3a38b0af0cccda24d0c9
10,830
ExpandableBottomBar
MIT License
src/main/kotlin/xveon/roadmap/util/PosGroup.kt
XVNexus
633,999,690
false
null
package xveon.roadmap import net.minecraft.util.math.BlockPos import org.joml.Vector3d import kotlin.math.roundToInt class PosGroup { private val positions = mutableSetOf<BlockPos>() var center = BlockPos(0, 0, 0) fun getPositions(): MutableSet<BlockPos> { return positions } fun getPosCount(): Int { return positions.count() } fun addPos(pos: BlockPos): Boolean { val result = positions.add(pos) if (result) calculateCenter() return result } fun removePos(pos: BlockPos): Boolean { val result = positions.remove(pos) if (result) calculateCenter() return result } fun clearPositions(): Boolean { if (positions.isEmpty()) return false positions.clear() center = BlockPos(0, 0, 0) return true } fun containsPos(pos: BlockPos): Boolean { return positions.contains(pos) } fun isPosNear(pos: BlockPos, range: Int): Boolean { val centerVec = Vector3d(center.x.toDouble(), center.y.toDouble(), center.z.toDouble()) val posVec = Vector3d(pos.x.toDouble(), pos.y.toDouble(), pos.z.toDouble()) return centerVec.distance(posVec) <= range } fun calculateCenter() { var result = BlockPos(0, 0, 0) for (pos in positions) result = result.add(pos) val count = positions.count().toDouble() center = BlockPos((result.x / count).roundToInt(), (result.y / count).roundToInt(), (result.z / count).roundToInt()) } }
0
Kotlin
0
0
a03d400c26459f4a5fd8190723648971011c7f0f
1,548
roadmap
Apache License 2.0
src/main/kotlin/xveon/roadmap/util/PosGroup.kt
XVNexus
633,999,690
false
null
package xveon.roadmap import net.minecraft.util.math.BlockPos import org.joml.Vector3d import kotlin.math.roundToInt class PosGroup { private val positions = mutableSetOf<BlockPos>() var center = BlockPos(0, 0, 0) fun getPositions(): MutableSet<BlockPos> { return positions } fun getPosCount(): Int { return positions.count() } fun addPos(pos: BlockPos): Boolean { val result = positions.add(pos) if (result) calculateCenter() return result } fun removePos(pos: BlockPos): Boolean { val result = positions.remove(pos) if (result) calculateCenter() return result } fun clearPositions(): Boolean { if (positions.isEmpty()) return false positions.clear() center = BlockPos(0, 0, 0) return true } fun containsPos(pos: BlockPos): Boolean { return positions.contains(pos) } fun isPosNear(pos: BlockPos, range: Int): Boolean { val centerVec = Vector3d(center.x.toDouble(), center.y.toDouble(), center.z.toDouble()) val posVec = Vector3d(pos.x.toDouble(), pos.y.toDouble(), pos.z.toDouble()) return centerVec.distance(posVec) <= range } fun calculateCenter() { var result = BlockPos(0, 0, 0) for (pos in positions) result = result.add(pos) val count = positions.count().toDouble() center = BlockPos((result.x / count).roundToInt(), (result.y / count).roundToInt(), (result.z / count).roundToInt()) } }
0
Kotlin
0
0
a03d400c26459f4a5fd8190723648971011c7f0f
1,548
roadmap
Apache License 2.0
funcify-feature-eng-schema/src/main/kotlin/funcify/feature/schema/directive/alias/AliasCoordinatesRegistry.kt
anticipasean
458,910,592
false
{"Kotlin": 2751524, "HTML": 1817}
package funcify.feature.schema.directive.alias import graphql.schema.FieldCoordinates import kotlinx.collections.immutable.ImmutableSet import kotlinx.collections.immutable.persistentMapOf /** * @author smccarron * @created 2023-08-22 */ interface AliasCoordinatesRegistry { companion object { fun empty(): AliasCoordinatesRegistry { return DefaultAliasCoordinatesRegistry( fieldAliasesByCoordinates = persistentMapOf(), fieldArgumentAliasesByLocation = persistentMapOf() ) } } fun registerFieldWithAlias( fieldCoordinates: FieldCoordinates, alias: String ): AliasCoordinatesRegistry fun registerFieldArgumentWithAlias( fieldArgumentLocation: Pair<FieldCoordinates, String>, alias: String ): AliasCoordinatesRegistry fun isAliasForField(alias: String): Boolean { return getFieldsWithAlias(alias).isNotEmpty() } fun isAliasForFieldArgument(alias: String): Boolean { return getFieldArgumentsWithAlias(alias).isNotEmpty() } fun getFieldsWithAlias(alias: String): ImmutableSet<FieldCoordinates> fun getFieldArgumentsWithAlias(alias: String): ImmutableSet<Pair<FieldCoordinates, String>> fun getAllAliasesForField(fieldCoordinates: FieldCoordinates): ImmutableSet<String> fun getAllAliasesForFieldArgument( fieldCoordinates: FieldCoordinates, argumentName: String ): ImmutableSet<String> { return getAllAliasesForFieldArgument( fieldArgumentLocation = fieldCoordinates to argumentName ) } fun getAllAliasesForFieldArgument( fieldArgumentLocation: Pair<FieldCoordinates, String> ): ImmutableSet<String> }
0
Kotlin
0
0
851ad6c0e7480ce72df32fd0e3d021909c4536f9
1,758
funcify-feature-eng
Apache License 2.0
app/src/main/java/br/com/programadordeelite/gdc/codelab/debugging/calc/CalcFragment.kt
treslines
346,119,037
false
null
package br.com.programadordeelite.gdc.codelab.debugging.calc import android.os.Bundle import android.util.Log import android.view.View import androidx.fragment.app.Fragment import br.com.programadordeelite.gdc.R import br.com.programadordeelite.gdc.databinding.FragmentCalcBinding import timber.log.Timber import java.lang.IllegalArgumentException // LINK PARA VC SE APROFUNDAR NOS ESTUDOS // https://developer.android.com/studio/command-line/adb.html class CalcFragment : Fragment(R.layout.fragment_calc) { private val calculator by lazy { Calculator() } private lateinit var binding: FragmentCalcBinding private val logTag by lazy { CalcFragment::class.java.simpleName } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentCalcBinding.bind(view) binding.operationAddBtn.setOnClickListener { compute(Calculator.Operator.ADD) } binding.operationSubBtn.setOnClickListener { compute(Calculator.Operator.SUB) } binding.operationDivBtn.setOnClickListener { compute(Calculator.Operator.DIV) } binding.operationMulBtn.setOnClickListener { compute(Calculator.Operator.MUL) } } private fun compute(operation: Calculator.Operator) { try { // Observar variavel val operandOne = binding.operandOneEditText.text.toString().toDouble() val operandTwo = binding.operandTwoEditText.text.toString().toDouble() // TODO: rfer criar filtro para minhas tarefas binding.operationResultTextView.setText( when (operation) { Calculator.Operator.ADD -> calculator.add(operandOne, operandTwo).toString() Calculator.Operator.SUB -> calculator.sub(operandOne, operandTwo).toString() Calculator.Operator.MUL -> calculator.mul(operandOne, operandTwo).toString() Calculator.Operator.DIV -> try { val division = calculator.div(operandOne, operandTwo) if(division.isFinite()) division.toString() else throw IllegalArgumentException("Illegal Division") } catch (iae: IllegalArgumentException) { Timber.i("IllegalArgumentException Com Timber") // Timber sem exception Log.e(logTag, "IllegalArgumentException Com LogCat", iae) // para exemplificar o uso de Log getString(R.string.computationError) } } ) } catch (nfe: NumberFormatException) { Timber.e(nfe, "NumberFormatException com Timber") // para exemplificar o uso do timber - com exception binding.operationResultTextView.setText(getString(R.string.computationError)) return } } }
0
Kotlin
9
67
1ff9f927390e4da543951fe0d1adc155d2ac8fd5
2,866
aad
Apache License 2.0
tests/async/spring-task-execution-3.1/src/main/kotlin/com/epam/test/drill/compatibility/SimpleAsyncService.kt
Drill4J
761,674,114
false
{"Kotlin": 127593}
/** * Copyright 2020 - 2022 EPAM Systems * * 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.epam.test.drill.compatibility import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service import java.util.concurrent.CompletableFuture import java.util.concurrent.Future @Service open class SimpleAsyncService { @Async open fun doAsyncTask(task: () -> String): Future<String> { val result = task() return CompletableFuture.completedFuture(result) } }
2
Kotlin
0
0
c9539cd872247ca4200c772d884a850f08adccbe
1,033
internal-compatibility-matrix-tests
Apache License 2.0
src/main/kotlin/io/github/tmcreative1/playwright/remote/engine/handle/element/impl/ElementHandle.kt
TMcreative1
344,872,041
false
{"Kotlin": 1474337, "JavaScript": 10814, "HTML": 10152, "CSS": 2547}
package io.github.tmcreative1.playwright.remote.engine.handle.element.impl import com.google.gson.JsonObject import io.github.tmcreative1.playwright.remote.core.enums.ElementState import io.github.tmcreative1.playwright.remote.core.enums.ScreenshotType.JPEG import io.github.tmcreative1.playwright.remote.core.enums.ScreenshotType.PNG import io.github.tmcreative1.playwright.remote.domain.BoundingBox import io.github.tmcreative1.playwright.remote.domain.file.FilePayload import io.github.tmcreative1.playwright.remote.domain.serialize.SerializedError import io.github.tmcreative1.playwright.remote.engine.frame.api.IFrame import io.github.tmcreative1.playwright.remote.engine.handle.element.api.IElementHandle import io.github.tmcreative1.playwright.remote.engine.handle.js.impl.JSHandle import io.github.tmcreative1.playwright.remote.engine.options.CheckOptions import io.github.tmcreative1.playwright.remote.engine.options.InputValueOptions import io.github.tmcreative1.playwright.remote.engine.options.SelectOption import io.github.tmcreative1.playwright.remote.engine.options.element.* import io.github.tmcreative1.playwright.remote.engine.parser.IParser.Companion.fromJson import io.github.tmcreative1.playwright.remote.engine.processor.ChannelOwner import io.github.tmcreative1.playwright.remote.engine.serialize.CustomGson.Companion.gson import io.github.tmcreative1.playwright.remote.engine.serialize.Serialization.Companion.deserialize import io.github.tmcreative1.playwright.remote.engine.serialize.Serialization.Companion.parseStringList import io.github.tmcreative1.playwright.remote.engine.serialize.Serialization.Companion.serializeArgument import io.github.tmcreative1.playwright.remote.engine.serialize.Serialization.Companion.toJsonArray import io.github.tmcreative1.playwright.remote.engine.serialize.Serialization.Companion.toProtocol import io.github.tmcreative1.playwright.remote.utils.Utils.Companion.toFilePayloads import io.github.tmcreative1.playwright.remote.utils.Utils.Companion.writeToFile import java.nio.file.Path import java.util.* class ElementHandle(parent: ChannelOwner, type: String, guid: String, initializer: JsonObject) : JSHandle( parent, type, guid, initializer ), IElementHandle { override fun boundingBox(): BoundingBox? { val json = sendMessage("boundingBox")!!.asJsonObject if (!json.has("value")) { return null } return fromJson(json["value"], BoundingBox::class.java) } override fun check(options: CheckOptions?) { val params = gson().toJsonTree(options ?: CheckOptions {}).asJsonObject sendMessage("check", params) } override fun click(options: ClickOptions?) { val params = gson().toJsonTree(options ?: ClickOptions {}).asJsonObject sendMessage("click", params) } override fun contentFrame(): IFrame? { val json = sendMessage("contentFrame")!!.asJsonObject if (!json.has("frame")) { return null } return messageProcessor.getExistingObject(json["frame"].asJsonObject["guid"].asString) } override fun doubleClick(options: DoubleClickOptions?) { val params = gson().toJsonTree(options ?: DoubleClickOptions {}).asJsonObject sendMessage("dblclick", params) } override fun dispatchEvent(type: String, eventInit: Any?) { val params = JsonObject() params.addProperty("type", type) params.add("eventInit", gson().toJsonTree(serializeArgument(eventInit))) sendMessage("dispatchEvent", params) } override fun evalOnSelector(selector: String, expression: String, arg: Any?): Any { return evalOnSelector(selector, expression, arg, "evalOnSelector") } override fun evalOnSelectorAll(selector: String, expression: String, arg: Any?): Any { return evalOnSelector(selector, expression, arg, "evalOnSelectorAll") } private fun evalOnSelector(selector: String, expression: String, arg: Any?, method: String): Any { val params = JsonObject() params.addProperty("selector", selector) params.addProperty("expression", expression) params.add("arg", gson().toJsonTree(serializeArgument(arg))) val json = sendMessage(method, params) val value = fromJson(json!!.asJsonObject["value"], SerializedError.SerializedValue::class.java) return deserialize(value) } override fun fill(value: String, options: FillOptions?) { val params = gson().toJsonTree(options ?: FillOptions {}).asJsonObject params.addProperty("value", value) sendMessage("fill", params) } override fun focus() { sendMessage("focus") } override fun getAttribute(name: String): String? { val params = JsonObject() params.addProperty("name", name) val json = sendMessage("getAttribute", params)!!.asJsonObject return if (json.has("value")) json["value"].asString else null } override fun hover(options: HoverOptions?) { val params = gson().toJsonTree(options ?: HoverOptions {}).asJsonObject sendMessage("hover", params) } override fun innerHTML(): String { val json = sendMessage("innerHTML")!!.asJsonObject return json["value"].asString } override fun innerText(): String { val json = sendMessage("innerText")!!.asJsonObject return json["value"].asString } override fun inputValue(options: InputValueOptions?): String { val params = gson().toJsonTree(options ?: InputValueOptions {}).asJsonObject val json = sendMessage("inputValue", params)!!.asJsonObject return json["value"].asString } override fun isChecked(): Boolean { val json = sendMessage("isChecked")!!.asJsonObject return json["value"].asBoolean } override fun isDisabled(): Boolean { val json = sendMessage("isDisabled")!!.asJsonObject return json["value"].asBoolean } override fun isEditable(): Boolean { val json = sendMessage("isEditable")!!.asJsonObject return json["value"].asBoolean } override fun isEnabled(): Boolean { val json = sendMessage("isEnabled")!!.asJsonObject return json["value"].asBoolean } override fun isHidden(): Boolean { val json = sendMessage("isHidden")!!.asJsonObject return json["value"].asBoolean } override fun isVisible(): Boolean { val json = sendMessage("isVisible")!!.asJsonObject return json["value"].asBoolean } override fun ownerFrame(): IFrame? { val json = sendMessage("ownerFrame")!!.asJsonObject if (!json.has("frame")) { return null } return messageProcessor.getExistingObject(json["frame"].asJsonObject["guid"].asString) } override fun press(key: String, options: PressOptions?) { val params = gson().toJsonTree(options ?: PressOptions {}).asJsonObject params.addProperty("key", key) sendMessage("press", params) } override fun querySelector(selector: String): IElementHandle? { val params = JsonObject() params.addProperty("selector", selector) val json = sendMessage("querySelector", params) val element = json!!.asJsonObject.getAsJsonObject("element") ?: return null return messageProcessor.getExistingObject(element["guid"].asString) } override fun querySelectorAll(selector: String): List<IElementHandle>? { val params = JsonObject() params.addProperty("selector", selector) val json = sendMessage("querySelectorAll", params) val elements = json!!.asJsonObject["elements"].asJsonArray ?: return null val handles = arrayListOf<IElementHandle>() for (item in elements) { handles.add(messageProcessor.getExistingObject(item.asJsonObject["guid"].asString)) } return handles } override fun screenshot(options: ScreenshotOptions?): ByteArray { val opt = options ?: ScreenshotOptions {} if (opt.type == null) { opt.type = PNG if (opt.path != null) { val fileName = opt.path!!.fileName.toString() val extStart = fileName.lastIndexOf('.') if (extStart != -1) { val extension = fileName.substring(extStart).lowercase() if (".jpeg" == extension || ".jpg" == extension) { opt.type = JPEG } } } } val params = gson().toJsonTree(opt).asJsonObject params.remove("path") val json = sendMessage("screenshot", params)!!.asJsonObject val buffer = Base64.getDecoder().decode(json["binary"].asString) if (opt.path != null) { writeToFile(buffer, opt.path!!) } return buffer } override fun scrollIntoViewIfNeeded(options: ScrollIntoViewIfNeededOptions?) { val params = gson().toJsonTree(options ?: ScrollIntoViewIfNeededOptions {}).asJsonObject sendMessage("scrollIntoViewIfNeeded", params) } override fun selectOption(value: String?, options: SelectOptionOptions?): List<String> { val values = if (value == null) null else arrayOf(value) return selectOption(values, options) } override fun selectOption(value: IElementHandle?, options: SelectOptionOptions?): List<String> { val values = if (value == null) null else arrayOf(value) return selectOption(values, options) } override fun selectOption(values: Array<String>?, options: SelectOptionOptions?): List<String> { if (values == null) { return selectOption(emptyArray<SelectOption>(), options) } return selectOption(values.map { value -> SelectOption { it.value = value } }.toTypedArray(), options) } override fun selectOption(value: SelectOption?, options: SelectOptionOptions?): List<String> { val values = if (value == null) null else arrayOf(value) return selectOption(values, options) } override fun selectOption(values: Array<IElementHandle>?, options: SelectOptionOptions?): List<String> { val params = gson().toJsonTree(options ?: SelectOptionOptions {}).asJsonObject if (values != null) { params.add("elements", toProtocol(values)) } return selectOption(params) } override fun selectOption(values: Array<SelectOption>?, options: SelectOptionOptions?): List<String> { val params = gson().toJsonTree(options ?: SelectOptionOptions {}).asJsonObject if (values != null) { params.add("options", gson().toJsonTree(values)) } return selectOption(params) } private fun selectOption(params: JsonObject): List<String> { val json = sendMessage("selectOption", params)!!.asJsonObject return parseStringList(json["values"].asJsonArray) } override fun selectText(options: SelectTextOptions?) { val params = gson().toJsonTree(options ?: SelectTextOptions {}).asJsonObject sendMessage("selectText", params) } override fun setInputFiles(files: Path, options: SetInputFilesOptions?) { setInputFiles(arrayOf(files), options) } override fun setInputFiles(files: Array<Path>, options: SetInputFilesOptions?) { setInputFiles(toFilePayloads(files), options) } override fun setInputFiles(files: FilePayload, options: SetInputFilesOptions?) { setInputFiles(arrayOf(files), options) } override fun setInputFiles(files: Array<FilePayload>, options: SetInputFilesOptions?) { val params = gson().toJsonTree(options ?: SetInputFilesOptions {}).asJsonObject params.add("files", toJsonArray(files)) sendMessage("setInputFiles", params) } override fun tap(options: TapOptions?) { val params = gson().toJsonTree(options ?: TapOptions {}).asJsonObject sendMessage("tap", params) } override fun textContent(): String? { val json = sendMessage("textContent")!!.asJsonObject return if (json.has("value")) json["value"].asString else null } override fun type(text: String, options: TypeOptions?) { val params = gson().toJsonTree(options ?: TypeOptions {}).asJsonObject params.addProperty("text", text) sendMessage("type", params) } override fun uncheck(options: UncheckOptions?) { val params = gson().toJsonTree(options ?: UncheckOptions {}).asJsonObject sendMessage("uncheck", params) } override fun waitForElementState(state: ElementState?, options: WaitForElementStateOptions?) { if (state == null) { throw IllegalArgumentException("State cannot be null") } val params = gson().toJsonTree(options ?: WaitForElementStateOptions {}).asJsonObject params.addProperty("state", state.toString().lowercase()) sendMessage("waitForElementState", params) } override fun waitForSelector(selector: String, options: WaitForElementStateOptions?): IElementHandle? { val params = gson().toJsonTree(options ?: WaitForElementStateOptions {}).asJsonObject params.addProperty("selector", selector) val json = sendMessage("waitForSelector", params) val element = json!!.asJsonObject["element"].asJsonObject ?: return null return messageProcessor.getExistingObject(element["guid"].asString) } override fun asElement(): IElementHandle { return this } }
0
Kotlin
0
1
a4b4d3fe199f0a3e7d740feded801ecd5e2b9992
13,644
playwright-remote
MIT License
kt/godot-library/src/main/kotlin/godot/gen/godot/VisualShaderNodeTexture2DArray.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.GodotBaseType import godot.core.TypeManager import godot.core.VariantType.NIL import godot.core.VariantType.OBJECT import godot.core.memory.TransferContext import godot.util.VoidPtr import kotlin.Boolean import kotlin.Int import kotlin.Suppress /** * A 2D texture uniform array to be used within the visual shader graph. * * Translated to `uniform sampler2DArray` in the shader language. */ @GodotBaseType public open class VisualShaderNodeTexture2DArray : VisualShaderNodeSample3D() { /** * A source texture array. Used if [godot.VisualShaderNodeSample3D.source] is set to [godot.VisualShaderNodeSample3D.SOURCE_TEXTURE]. */ public var textureArray: Texture2DArray? get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getTextureArrayPtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as Texture2DArray?) } set(`value`) { TransferContext.writeArguments(OBJECT to value) TransferContext.callMethod(rawPtr, MethodBindings.setTextureArrayPtr, NIL) } public override fun new(scriptIndex: Int): Boolean { callConstructor(ENGINECLASS_VISUALSHADERNODETEXTURE2DARRAY, scriptIndex) return true } public companion object internal object MethodBindings { public val setTextureArrayPtr: VoidPtr = TypeManager.getMethodBindPtr("VisualShaderNodeTexture2DArray", "set_texture_array") public val getTextureArrayPtr: VoidPtr = TypeManager.getMethodBindPtr("VisualShaderNodeTexture2DArray", "get_texture_array") } }
64
null
39
580
fd1af79075e7b918200aba3302496b70c76a2028
2,003
godot-kotlin-jvm
MIT License
app/src/main/java/com/example/parstagram/fragments/ComposeFragment.kt
mi-zhao
474,761,614
false
null
package com.example.parstagram.fragments import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.example.parstagram.LoginActivity import com.example.parstagram.MainActivity import com.example.parstagram.Post import com.example.parstagram.R import com.parse.ParseFile import com.parse.ParseUser import java.io.File class ComposeFragment : Fragment() { val photoFileName = "photo.jpg" var photoFile: File? = null val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1034 lateinit var ivPreview: ImageView override fun onCreateView( // which layout file to use inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_compose, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Set onClickListeners and setup logic ivPreview = view.findViewById(R.id.imageView) // 1. Set the description of the post // 2. A button to launch the camera to take a picture // 3. An ImageView to show the picture the user has taken // 4. A button to save and send the post to our Parse server view.findViewById<Button>(R.id.btnSubmit).setOnClickListener { // Send post to server without an image // Get the inputted description val description = view.findViewById<EditText>(R.id.description).text.toString() val user = ParseUser.getCurrentUser() if (photoFile != null) { Toast.makeText(requireContext(), "Post has been uploaded!", Toast.LENGTH_SHORT).show() submitPost(description, user, photoFile!!) } else { // error log message // show a toast to let user to take a picture } } view.findViewById<Button>(R.id.btnTakePicture).setOnClickListener { // Launch camera to let user take picture onLaunchCamera() } view.findViewById<Button>(R.id.btnLogOut).setOnClickListener { ParseUser.logOut() Toast.makeText(requireContext(), "You have been logged out!", Toast.LENGTH_SHORT).show() val currentUser = ParseUser.getCurrentUser() // this will now be null val intent = Intent(requireContext(), LoginActivity::class.java) startActivity(intent) } } // Send Post object to our Parse server fun submitPost(description: String, user: ParseUser, file: File) { // Create the Post object val post = Post() post.setDescription(description) post.setUser(user) post.setImage(ParseFile(file)) post.saveInBackground { exception -> // Send the data into the Parse server if (exception != null) { Log.e(MainActivity.TAG, "Error while saving post") exception.printStackTrace() // SHhow a toast to tell user something went wrong with saving post } else { Log.i(MainActivity.TAG, "Successfully saved post") // resetting the EditText field to be empty // Reset the ImageView to empty } } } fun onLaunchCamera() { // create Intent to take a picture and return control to the calling application val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // Create a File reference for future access photoFile = getPhotoFileUri(photoFileName) // wrap File object into a content provider // required for API >= 24 // See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher if (photoFile != null) { val fileProvider: Uri = FileProvider.getUriForFile(requireContext(), "com.codepath.fileprovider", photoFile!!) intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider) // If you call startActivityForResult() using an intent that no app can handle, your app will crash. // So as long as the result is not null, it's safe to use the intent. // If you call startActivityForResult() using an intent that no app can handle, your app will crash. // So as long as the result is not null, it's safe to use the intent. if (intent.resolveActivity(requireContext().packageManager) != null) { // Start the image capture intent to take photo startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) } } } // Returns the File for a photo stored on disk given the fileName fun getPhotoFileUri(fileName: String): File { // Get safe storage directory for photos // Use `getExternalFilesDir` on Context to access package-specific directories. // This way, we don't need to request external read/write runtime permissions. val mediaStorageDir = File(requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), MainActivity.TAG) // Create the storage directory if it does not exist if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) { Log.d(MainActivity.TAG, "failed to create directory") } // Return the file target for the photo based on filename return File(mediaStorageDir.path + File.separator + fileName) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == AppCompatActivity.RESULT_OK) { // by this point we have the camera photo on disk val takenImage = BitmapFactory.decodeFile(photoFile!!.absolutePath) // RESIZE BITMAP, see section below // Load the taken image into a preview ivPreview.setImageBitmap(takenImage) } else { // Result was a failure Toast.makeText(requireContext(), "Picture wasn't taken!", Toast.LENGTH_SHORT).show() } } } }
2
Kotlin
0
0
33b3a751766da2042a3d5476c5070d5de7cebe39
6,827
Parstagram
Apache License 2.0
app/src/main/kotlin/org/artembogomolova/demo/webapp/main/dao/repo/CoreRepositories.kt
bogomolov-a-a
307,182,964
false
null
package org.artembogomolova.demo.webapp.main.dao.repo import org.artembogomolova.demo.webapp.main.domain.core.Person import org.artembogomolova.demo.webapp.main.domain.core.PhysicalAddress import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface IPersonRepository : CrudRepository<Person, Long> @Repository interface IPhysicalAddressRepository : CrudRepository<PhysicalAddress, Long>
1
Kotlin
0
0
8b533b736e75ab2fca39888b3a3953e3810c121d
458
demo-spring-simple-webapp-with-tls
Apache License 2.0
godot-kotlin-idea-plugin/src/main/kotlin/godot/idea/Settings.kt
raniejade
166,207,411
false
null
package godot.idea import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.Configurable import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBLabel import com.intellij.ui.layout.panel import javax.swing.JComponent class Settings: Configurable { private val logger = logger<Settings>() private val godotKotlin = ServiceManager.getService(GodotKotlin::class.java) private var modified = false private lateinit var godotExecutableField: TextFieldWithBrowseButton override fun isModified(): Boolean { return modified } override fun getDisplayName(): String { return "Godot Kotlin" } override fun apply() { godotKotlin.godotExecutable = godotExecutableField.text } override fun createComponent(): JComponent { return panel { row { cell { label("Godot Executable") godotExecutableField = textFieldWithBrowseButton( value = godotKotlin.godotExecutable, fileChooserDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor(), fileChosen = ::executableSelected ) } } } } override fun reset() { modified = false } private fun executableSelected(executable: VirtualFile): String { // todo: verify selected file val path = executable.path if (path != godotKotlin.godotExecutable) { modified = true } return path } }
12
Kotlin
4
51
5c1bb2a1f1d2187375bf50c0445b42c88f37989f
1,698
godot-kotlin
MIT License
quantity-pickers/src/test/kotlin/com/decathlon/vitamin/compose/quantity/pickers/utils/Variant.kt
Decathlon
492,727,156
false
{"Kotlin": 5008802}
package com.decathlon.vitamin.compose.quantity.pickers.utils internal enum class Variant { Primary }
14
Kotlin
24
232
7cbe1b995f9037593f13a8457650b1a7bc270597
102
vitamin-compose
Apache License 2.0
app/src/main/java/com/example/viewmodelfragments/Fragment3.kt
edmondzhang2001
643,592,224
false
{"Kotlin": 25300}
package com.example.viewmodelfragments import android.os.Bundle import android.text.Editable import android.text.TextWatcher import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController class Fragment3 : Fragment() { private val viewModel: MainActivityViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_3, container, false) val title = view.findViewById<TextView>(R.id.titleTextView) val saveButton = view.findViewById<Button>(R.id.saveButton) val markEditText = view.findViewById<EditText>(R.id.markEditText) val termSpinner = view.findViewById<Spinner>(R.id.termEditText) val descriptionEditText = view.findViewById<EditText>(R.id.descriptionEditText) val wdSwitch = view.findViewById<Switch>(R.id.wdSwitch) val cancelButton = view.findViewById<Button>(R.id.cancelButton) var isDescriptionEdited = false var isMarkEdited = false val adapter = ArrayAdapter.createFromResource(requireContext(), R.array.term_options, android.R.layout.simple_spinner_item ) title.text = viewModel.selectedEntry!!.courseName descriptionEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { isDescriptionEdited = true } override fun afterTextChanged(s: Editable?) {} }) markEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { isMarkEdited = true } override fun afterTextChanged(s: Editable?) {} }) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) termSpinner.adapter = adapter wdSwitch.setOnCheckedChangeListener { buttonView, isChecked -> markEditText.isEnabled = !isChecked } var selectedTerm = viewModel.selectedEntry!!.term val selectedTermIndex = Terms.values().indexOf(selectedTerm) termSpinner.setSelection(selectedTermIndex) termSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { selectedTerm = Terms.values()[position] // Do something with the selected color } override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing } } cancelButton.setOnClickListener { findNavController().navigateUp() } saveButton.setOnClickListener { val entry = viewModel.selectedEntry if (entry != null) { if (isDescriptionEdited)entry.description = descriptionEditText.text.toString() if (!wdSwitch.isChecked) { if (isMarkEdited)entry.mark = markEditText.text.toString().toInt() } entry.wd = wdSwitch.isChecked entry.term = selectedTerm entry.findColor(entry.context) } findNavController().navigateUp() } // Inflate the layout for this fragment // (note fragment 3 layout includes fragment 1 and fragment 2!) return view } }
0
Kotlin
0
0
5aa4f6d09e681cafe5a566a62f52b7334e0ca86c
3,801
My-Mark-Manager
MIT License
CleanArchitectureAndroid/app/src/main/java/com/example/cleanarchitectureandroid/domain/usecases/MovieDetailUseCase.kt
velmurugan-murugesan
159,637,287
false
null
package com.example.cleanarchitectureandroid.domain.usecases import com.example.cleanarchitectureandroid.data.MovieDetail import com.example.cleanarchitectureandroid.data.MovieDetailRepositoryImpl import javax.inject.Inject class MovieDetailUseCase @Inject constructor(private val movieDetailRepositoryImpl: MovieDetailRepositoryImpl): SingleUseCase<MovieDetail> { override suspend fun execute() = movieDetailRepositoryImpl.getMovieDetail() }
1
Java
1
6
8c2e8b2a0e8f33b5e8c0ea66890756e02577fa54
449
AndriodSamples
Apache License 2.0
app/src/main/java/com/resep/resepmasakan/adapter/IngredientsAdapter.kt
tenriawa861
442,127,751
false
{"Java": 127511, "Kotlin": 44050}
package com.resep.resepmasakan.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.resep.resepmasakan.R import com.resep.resepmasakan.model.ModelIngredients class IngredientsAdapter(private val modelIngredients: List<ModelIngredients>) : RecyclerView.Adapter<IngredientsAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_ingredients, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val data = modelIngredients[position] holder.tvIngredients.text = data.strIngredient } override fun getItemCount(): Int { return modelIngredients.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var tvIngredients: TextView init { tvIngredients = itemView.findViewById(R.id.tvIngredients) } } }
1
null
1
1
f2cecb11249dc468ef42af5208df7ec8ae569e0c
1,148
resep.in
Apache License 2.0
app/src/main/java/com/nickming/kotlinlearning/ui/splash/SplashActivity.kt
nickming
94,009,580
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 41, "Kotlin": 29}
package com.nickming.kotlinlearning.ui.splash import android.Manifest import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.nickming.kotlinlearning.R import com.nickming.kotlinlearning.base.toast import com.nickming.kotlinlearning.ui.weather.WeatherActivity import com.tbruyelle.rxpermissions.Permission import com.tbruyelle.rxpermissions.RxPermissions import kotlinx.android.synthetic.main.activity_splash.* import rx.Observer class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) var permission = RxPermissions(this) permission.requestEach(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(object : Observer<Permission> { override fun onNext(t: Permission?) { if (t != null) { if (t.granted) { } else if (t.shouldShowRequestPermissionRationale) { toast("请给予权限:" + t.name) } else { toast("请给予权限" + t.name) } } } override fun onCompleted() { welcomeTv.postDelayed({ var intent = Intent(this@SplashActivity, WeatherActivity::class.java) startActivity(intent) finish() }, 1500) } override fun onError(e: Throwable?) { } }) } }
0
Kotlin
0
4
c5cbac38ebebd6e67094314346d515b567a90c45
1,969
KotlinWeather
MIT License
app/src/main/kotlin/com/ttvnp/ttj_asset_android_client/presentation/ui/presenter/target/SendAmountFormByStellarPresenterTarget.kt
ttvnp
109,772,404
false
null
package com.ttvnp.ttj_asset_android_client.presentation.ui.presenter.target import com.ttvnp.ttj_asset_android_client.domain.model.AssetType interface SendAmountFormByStellarPresenterTarget : BasePresenterTarget { fun navigateToConfirm(assetType: AssetType, amount: Long) fun onValidation(addressError: Int?, memoError: Int?, amountError: Int?) }
5
Kotlin
1
1
3a99c9d5b8362dbc5785c8849b8680405acb6a3a
357
ttj-asset-android-client
Apache License 1.1
lib/core/src/main/kotlin/at/sigmoid/transaction/retry/TransactionRetryHandler.kt
strassl
350,731,832
false
null
package at.sigmoid.transaction.retry import org.slf4j.LoggerFactory import kotlin.math.pow import kotlin.math.roundToLong import kotlin.random.Random class TransactionRetriesExceededException(message: String, cause: Throwable) : RuntimeException(message, cause) private data class TransactionRetryState( val active: Boolean, val noRetry: Boolean ) interface TransactionRetryScope<T> { val type: RetryScopeType fun proceed(): T } enum class RetryScopeType { /** * Transaction may be retried at this scope (but must not) */ CAN_RETRY, /** * Transaction cannot be retried at this scope (but may be retried at another scope) */ CAN_NOT_RETRY, /** * Transaction must not be retried ever (e.g. if it has side effects) */ MUST_NOT_RETRY } typealias Sleeper = (Long) -> Unit /** * Retries nested transactional function calls. This class is meant to intercept every transaction scope (e.g. every * method call annotated with @Transactional) and will attempt to retry at the outermost scope. * All transaction calls are assumed to occur on the same thread. * The retry handler is thread safe. * @param maxRetries the maximum number of times the call shall be retried * @param minDelayMs the minimum time between subsequent retries in ms * @param delayMultiplier the multiplicative factor for the exponential backoff * @param isRetryableException predicate whether a transaction is a retryable transaciton failure * @param random source of randomness for fuzziness in backoff * @param sleeper function to block the execution for an arbitrary number of ms. Only used for testing - you most * likely want to use Thread::sleep for any production use case */ class TransactionRetryHandler @JvmOverloads constructor( private val maxRetries: Int, private val minDelayMs: Long, private val delayMultiplier: Double, private val isRetryableException: (e: Throwable) -> Boolean, // Mostly used for tests private val random: Random = Random.Default, private val sleeper: Sleeper = Thread::sleep ) { companion object { private val LOGGER = LoggerFactory.getLogger(TransactionRetryHandler::class.java) } private val _state = ThreadLocal.withInitial { cleanState() } private var state: TransactionRetryState get() = _state.get() set(value) = _state.set(value) @Throws(Throwable::class) fun <T> handle(scope: TransactionRetryScope<T>): T { // If a method is marked as NoRetry, it poisons the entire current transaction if (scope.type === RetryScopeType.MUST_NOT_RETRY) { state = state.copy(noRetry = true) } // If we are in an existing transaction we just go on as usual, retries happen at the outermost layer if (state.active) { return scope.proceed() } // Transaction cannot be retried at this point, just call it if (scope.type == RetryScopeType.CAN_NOT_RETRY) { return scope.proceed() } val prevState = state try { var currentTry = 0 while (true) { state = prevState.copy(active = true) val throwable: Throwable try { return scope.proceed() } catch (t: Throwable) { throwable = t } if (isRetryableException(throwable)) { if (state.noRetry) { // If some method is marked as no-retry, we stop here and just fail throw TransactionRetriesExceededException("Marked as no-retry", throwable) } // The initial try is round 0 (we always try at least one time) // After this we are going to retry at most MAX_RETRIES times // e.g. if MAX_RETRIES=3 then we have at most // 0 (always) -> 1 -> 2 -> 3 -> abort if (currentTry < maxRetries) { // We wait at least MIN_DELAY_MS ms long and the back off // Also randomize the base backoff time to be between [MIN_DELAY_MS and 2*MIN_DELAY_MS] // to reduce the likelihood of two conflicting transactions being executed at the same time again // Therefore the wait time is baseBackoff * delayMultiplier^currentTry e.g. // try 0: baseBackoff * 1 // try 1: baseBackoff * delayMultiplier // try 2: baseBackoff * delayMultiplier^2 // try 3: baseBackoff * delayMultiplier^3 // ... // Note that baseBackoff is randomized again each time to reduce impact of "unlucky" requests val randFactor = random.nextDouble() val baseBackoff = minDelayMs * (1 + randFactor) val delayMs = (baseBackoff * delayMultiplier.pow(currentTry)).roundToLong() LOGGER.debug("Serialization problem in transaction - retrying in $delayMs ms ($currentTry of $maxRetries)", throwable) sleeper(delayMs) } else { // We did attempt to retry the transaction but it did not work out LOGGER.warn("Maximum number of transaction retries ($maxRetries) exceeded, aborting") throw TransactionRetriesExceededException("Maximum number of transaction retries ($maxRetries) exceeded", throwable) } } else { // It is an entirely different exception, just rethrow it throw throwable } currentTry += 1 } } finally { state = prevState } } private fun cleanState(): TransactionRetryState { return TransactionRetryState(active = false, noRetry = false) } }
0
Kotlin
0
0
01de18cdabebaecfedc6019531467d0f87ac9e95
6,078
transaction-retry
MIT License
src/test/kotlin/nl/knaw/huc/di/rd/BenchmarkTest.kt
HuygensING
216,852,499
false
null
package nl.knaw.huc.di.rd import arrow.core.Either import nl.knaw.huc.di.rd.tag.tagml.parser.TAGMLParser.Companion.checkWellFormedness import nl.knaw.huc.di.rd.tag.tagml.tokenizer.LSPToken import nl.knaw.huc.di.rd.tag.tagml.tokenizer.TAGMLTokenizer import nl.knaw.huc.di.rd.tag.util.showErrorLocation import org.assertj.core.api.Assertions import org.junit.Ignore import org.junit.Test class BenchmarkTest { @Ignore @Test(timeout = 10_000) fun parseSmallTAGML() { parseTAGMLFile("small.tagml") } @Ignore @Test(timeout = 10_000) fun parseMediumTAGML() { parseTAGMLFile("medium.tagml") } @Ignore @Test(timeout = 10_000) fun parseLargeTAGML() { parseTAGMLFile("large.tagml") } private fun parseTAGMLFile(s: String) { val tagml = this::class.java.getResource(s).readText(Charsets.UTF_8) assertTAGMLisWellFormed(tagml) } private fun assertTAGMLisWellFormed(tagml: String) { mapTokenizedTAGML(tagml) { Assertions.assertThat(checkWellFormedness(it).isWellFormed).isTrue() } } private inline fun mapTokenizedTAGML(tagml: String, funk: (tokens: List<LSPToken>) -> Unit) { when (val result = TAGMLTokenizer.tokenize(tagml)) { is Either.Left -> { showErrorLocation(tagml, result) Assertions.fail("Parsing failed: ${result.a}") } is Either.Right -> funk(result.b) } } }
0
Kotlin
0
2
a072d7b19476b61831a0580ff30bd7537a55bdfc
1,469
tagml-language-server
Apache License 2.0
app/app/src/main/java/com/example/party_lojo_game/utils/messages/InfoLojoToastLength.kt
ajloinformatico
381,492,665
false
null
package com.example.party_lojo_game.utils.messages import android.widget.Toast enum class InfoLojoToastLength(val value: Int) { LENGTH_LONG(value = Toast.LENGTH_LONG), LENGTH_SHORT(value = Toast.LENGTH_SHORT) }
0
Kotlin
0
0
dc0b3f5b64110f2e528020d1851a73031fb25871
221
party-lojo-game
MIT License
src/main/kotlin/com/mg/jfr/JfrParser.kt
mgrzaslewicz
730,873,740
false
{"Kotlin": 25664}
package com.mg.jfr import com.mg.jfr.* import jdk.jfr.consumer.RecordingFile import mu.KLogging import java.io.DataInputStream import java.io.IOException import java.nio.file.Path import kotlin.io.path.inputStream class JfrParser(private val jfrFile: Path, private val listener: JfrEventListener) { private companion object : KLogging() private class EventHeader(val eventSizeIncludingHeader: Leb128Long, val eventType: Leb128Long) { val headerBytes: ByteArray = eventSizeIncludingHeader.bytes + eventType.bytes fun payloadSize(): Int = (eventSizeIncludingHeader.value - headerBytes.size).toInt() } private val countingStream by lazy { CountingInputStream(jfrFile.inputStream().buffered()) } private val dataStream by lazy { DataInputStream(countingStream) } private val jdkJfrRecording by lazy { RecordingFile(jfrFile) } private fun streamPosition(): Long = countingStream.count fun parse() { jdkJfrRecording.use { dataStream.use { var chunkCounter = 1 while (dataStream.available() > 0) { logger.debug { "Parsing $jfrFile chunk $chunkCounter ..." } val header: ChunkHeader = ChunkHeader.read(dataStream, absoluteChunkStart = streamPosition()) listener.onChunkStart(header) parseChunk(header) listener.onChunkEnd() chunkCounter++ } } } } private fun parseChunk(chunkHeader: ChunkHeader) { while (streamPosition() < chunkHeader.absoluteChunkEnd) { val eventSize = dataStream.readLongLeb128() if (eventSize > 0) { val eventType = dataStream.readLongLeb128() parseEvent(EventHeader(eventSize, eventType)) } else { throw IllegalStateException("Unexpected event size: $eventSize at position ${streamPosition()}") } } } @Throws(IOException::class) private fun parseEvent(eventHeader: EventHeader) { val eventPayload = getBytes(eventHeader.payloadSize()) val eventBytes = eventHeader.headerBytes + eventPayload when (eventHeader.eventType.value) { 0L -> listener.onMetadata(eventBytes) 1L -> listener.onConstantPoolEvent(eventBytes) else -> listener.onEvent(jdkJfrRecording.readEvent(), eventBytes) } } @Throws(IOException::class) private fun getBytes(eventPayloadSize: Int) = ByteArray(eventPayloadSize).apply { dataStream.read(this, 0, eventPayloadSize) } }
0
Kotlin
0
0
643ad7eb0a3cfdadd42198964bbdecf41dec5c94
2,643
jfr-filter
Apache License 2.0
plugin-bazel-event-service/src/main/kotlin/bazel/messages/MessageFactoryImpl.kt
JetBrains
143,697,750
false
{"Kotlin": 301052, "Java": 12799, "Gherkin": 2393, "Starlark": 1836, "ANTLR": 1173, "Batchfile": 375, "CSS": 34}
package bazel.messages import bazel.messages.handlers.clean import jetbrains.buildServer.messages.serviceMessages.BlockClosed import jetbrains.buildServer.messages.serviceMessages.BlockOpened import jetbrains.buildServer.messages.serviceMessages.BuildStatus import jetbrains.buildServer.messages.serviceMessages.ServiceMessage class MessageFactoryImpl : MessageFactory { override fun createMessage(text: String) = Message(text.clean(), Normal) override fun createTraceMessage(text: String) = Message("> ".apply(Color.Trace) + text.clean().replace("\n", "").replace("\r", ""), Normal, null) override fun createErrorMessage(error: String, errorDetails: String?) = Message(error.clean(), Error, errorDetails) override fun createFlowStarted(flowId: String, parentFlowId: String) = FlowStarted(flowId, parentFlowId) override fun createFlowFinished(flowId: String) = FlowFinished(flowId) override fun createBuildStatus(text: String, success: Boolean) = BuildStatus(text.clean(), if (success) Normal else Error) override fun createBuildProblem(description: String, projectId: String, errorId: String): ServiceMessage { val hash = Integer.toHexString(Pair(projectId, errorId).hashCode()) return BuildProblem(description.clean(), "$hash-$projectId-$errorId".take(60)) } override fun createBlockOpened(blockName: String, description: String): ServiceMessage = BlockOpened(blockName.clean(), description.clean()) override fun createBlockClosed(blockName: String): ServiceMessage = BlockClosed(blockName.clean()) override fun createImportData(type: String, path: String): ServiceMessage = ImportData(type, path) companion object { private const val Normal = "NORMAL" private const val Error = "ERROR" } }
6
Kotlin
7
14
6ff893ae8c3e6a8260568698d28df16b915593a6
1,902
teamcity-bazel-plugin
Apache License 2.0
rain/src/main/java/com/rapidsos/rain/data/profile/PhoneNumber.kt
johndpope
192,260,729
false
{"Kotlin": 351294, "Shell": 212}
package com.rapidsos.rain.data.profile import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.rapidsos.rain.data.profile.values.PhoneNumberValue data class PhoneNumber(@SerializedName("value") @Expose var value: List<PhoneNumberValue> = arrayListOf(), @SerializedName("type") @Expose var type: String = "", @SerializedName("display_name") @Expose var displayName: String = "")
0
Kotlin
0
1
465a1dfbe3d3a9d99418e9b23fb0c6e8790c36c6
472
era-android
Apache License 2.0
app/src/main/java/com/uszkaisandor/mvvmnewsapp/features/bookmarks/BookmarksFragment.kt
uszkaisandor
452,427,609
false
null
package com.uszkaisandor.mvvmnewsapp.features.bookmarks import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView.Adapter.StateRestorationPolicy.* import com.uszkaisandor.mvvmnewsapp.MainActivity import com.uszkaisandor.mvvmnewsapp.R import com.uszkaisandor.mvvmnewsapp.databinding.FragmentBookmarksBinding import com.uszkaisandor.mvvmnewsapp.shared.NewsArticleListAdapter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect @AndroidEntryPoint class BookmarksFragment : Fragment(R.layout.fragment_bookmarks), MainActivity.OnBottomNavigationFragmentReselectedListener { private val viewModel: BookmarksViewModel by viewModels() private var currentBinding: FragmentBookmarksBinding? = null private val binding get() = currentBinding!! override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) currentBinding = FragmentBookmarksBinding.bind(view) val bookmarksAdapter = NewsArticleListAdapter( onItemClick = { article -> val uri = Uri.parse(article.url) val intent = Intent(Intent.ACTION_VIEW, uri) requireActivity().startActivity(intent) }, onBookmarkClick = { article -> viewModel.onBookmarkClick(article) } ) bookmarksAdapter.stateRestorationPolicy = PREVENT_WHEN_EMPTY binding.apply { recyclerView.apply { adapter = bookmarksAdapter layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) } viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.bookmarks.collect { bookmarkedArticles -> bookmarkedArticles?.let { safeBookmarkedArticles -> bookmarksAdapter.submitList(safeBookmarkedArticles) textViewNoBookmarks.isVisible = safeBookmarkedArticles.isEmpty() recyclerView.isVisible = safeBookmarkedArticles.isNotEmpty() } } } } setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_bookmarks, menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_delete_all_bookmarks -> { viewModel.onDeleteAllBookmarks() true } else -> super.onOptionsItemSelected(item) } override fun onBottomNavigationFragmentReselected() { binding.recyclerView.smoothScrollToPosition(0) } override fun onDestroyView() { super.onDestroyView() binding.recyclerView.adapter = null currentBinding = null } }
0
Kotlin
0
0
ab78e9ca40784c5c2ecc221abe035c2fce93f099
3,300
mealdeas-android
Apache License 2.0
src/app/src/main/java/com/huawei/demo/health/auth/HealthKitCloudLogin.kt
Michael134-bit
356,821,014
true
{"Kotlin": 106384}
/* * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. */ package com.huawei.demo.health.auth import android.app.Activity import java.util.function.Consumer import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.appcompat.app.AppCompatActivity import com.google.gson.JsonParser import com.huawei.demo.health.OkHttpUtilCallback import com.huawei.demo.health.R import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request /** * Huawei ID signing In and authorization By restful API * * @since 2020-09-23 */ class HealthKitCloudLogin : AppCompatActivity() { // webview to html private var mWebView: WebView? = null // okhttp3 OkHttpClient to send request private val mClient = OkHttpClient() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_health_cloud_login) // init WebView config initWebView() } private fun initWebView() { mWebView = this.findViewById(R.id.webView) mWebView!!.settings.javaScriptEnabled = true mWebView!!.settings.useWideViewPort = true mWebView!!.settings.loadWithOverviewMode = true mWebView!!.settings.builtInZoomControls = true mWebView!!.settings.displayZoomControls = false mWebView!!.settings.setSupportZoom(true) // Customize the WebViewClient and Override the shouldOverrideUrlLoading method to query AccessToken after // Huawei ID sign In success. It is used only in the sample code, in the actual scenario, this query can be // processed on the callback page. mWebView!!.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { Log.i(TAG, request.toString()) val url = request.url.toString() // Intercept redirect_uri to query access token. if (url.startsWith("http://www.example.com")) { val code = request.url.getQueryParameter("code") queryAccessToken(code) return true } // others only call super method return super.shouldOverrideUrlLoading(view, request) } } mWebView!!.loadUrl(CLOUD_AUTH) } /** * Use the authorization code to generate the access token. * * @param code Authorization Code */ private fun queryAccessToken(code: String?) { // 1. Build access token request val request = buildAtRequest(code) // 2. Sending an asynchronous HTTP Request to generate the access token, and build user-defined Callback for // response. This Callback init with an anonymous Consumer to get access token and start // HealthKitAuthCloudActivity for check HUAWEI Health authorization result. mClient.newCall(request).enqueue( OkHttpUtilCallback(Consumer<String> { response -> // Parse response to get access token val jsonObject = JsonParser().parse(response).asJsonObject val accessToken = jsonObject.get("access_token").asString // Set accessToken result to HealthKitAuthCloudActivity val intent = Intent() intent.putExtra("accessToken", accessToken) setResult(Activity.RESULT_OK, intent) finish() }) ) } /** * Build restful request to generate the access token * * @param code Authorization Code from sign in HUAWEI ID * @return Request to generate the access token */ private fun buildAtRequest(code: String?): Request { val requestBody = FormBody.Builder().add("code", code!!) .add("grant_type", "authorization_code") .add("client_id", CLIENT_ID) .add("client_secret", CLIENT_SECRET) .add("redirect_uri", REDIRECT_URI) .build() return Request.Builder().url(CLOUD_TOKEN) .header("Content-Type", "application/x-www-form-urlencoded") .post(requestBody) .build() } companion object { private val TAG = "HealthKitCloudLogin" // the app ID information generated by the Developer Alliance when creating the Server application private val CLIENT_ID = "{appid}" // the secret information generated by the Developer Alliance when creating the Server application private val CLIENT_SECRET = "{secret}" // The value of redirect_uri must be the same as the Redirect_URI registered by developer, this only for example. private val REDIRECT_URI = "http://www.example.com" // URL to query access token private val CLOUD_TOKEN = "https://oauth-login.cloud.huawei.com/oauth2/v3/token" /** * URL of Huawei ID signing In and authorization Health Kit scopes * The value of redirect_uri must be the same as the Redirect_URI registered by developer, this only for example. */ private val CLOUD_AUTH = "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize?response_type=code&client_id=101489619&redirect_uri=http%3a%2f%2fwww.example.com&scope=https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fheightweight.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fgoals.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Findex.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fstep.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fdistance.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fspeed.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fcalories.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fpulmonary.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fstrength.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Factivity.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Flocation.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fbodyfat.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fsleep.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fheartrate.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fstress.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Frelaxtraining.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fnutrition.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fhearthealth.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fbloodglucose.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fbloodpressure.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Foxygensaturation.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Fbodytemperature.both+https%3A%2F%2Fwww.huawei.com%2Fhealthkit%2Freproductive.both&access_type=offline&display=touch" } }
0
null
0
0
381787a0de31fb0b87fd9700d9e5f45964649416
6,916
hms-health-demo-kotlin
Apache License 2.0
src/main/kotlin/example/apaddon/goals/ChatGoal.kt
KonoTyran
845,242,361
false
{"Kotlin": 2601, "Java": 1013}
package example.apaddon.goals import com.google.gson.annotations.SerializedName import dev.koifysh.randomizer.ArchipelagoRandomizer import dev.koifysh.randomizer.registries.APGoal import net.fabricmc.fabric.api.message.v1.ServerMessageEvents import net.minecraft.network.chat.ChatType import net.minecraft.network.chat.Component import net.minecraft.network.chat.PlayerChatMessage import net.minecraft.server.level.ServerPlayer import net.minecraft.world.BossEvent class ChatGoal : APGoal() { @SerializedName("required_message") val requiredMessage: String = "Hello, World!" // will get overwritten by the data in the apmc file override val hasBossBar: Boolean = true override var isComplete: Boolean = false override val bossBarColor: BossEvent.BossBarColor = BossEvent.BossBarColor.BLUE override val bossBarCurrentValue: Int = 1 override val bossBarMaxValue: Int = 1 override val bossBarOverlay: BossEvent.BossBarOverlay = BossEvent.BossBarOverlay.PROGRESS override val bossBarName: Component get() = Component.literal("Say \"$requiredMessage\"") override fun start() { ServerMessageEvents.CHAT_MESSAGE.register(this::chatMessage) ArchipelagoRandomizer.server.playerList.players.forEach { it.sendSystemMessage(Component.literal("Say \"$requiredMessage\" to complete this goal.")) } } private fun chatMessage(chatMessage: PlayerChatMessage, serverPlayer: ServerPlayer, bound: ChatType.Bound) { if (isComplete) return if (chatMessage.decoratedContent().string == requiredMessage) { isComplete = true checkCompletion() } } }
0
Kotlin
0
0
ba5e1e328c7762bbdd8eb829fc4ceaf7870d4cba
1,675
chat-goal-example
Creative Commons Zero v1.0 Universal
src/main/kotlin/objects/item/DeferredItemTypeImpl.kt
2xsaiko
123,460,493
false
null
package therealfarfetchd.quacklib.objects.item import net.minecraft.util.ResourceLocation import therealfarfetchd.quacklib.api.core.Unsafe import therealfarfetchd.quacklib.api.core.unsafe import therealfarfetchd.quacklib.api.item.component.ItemComponent import therealfarfetchd.quacklib.api.objects.item.Item import therealfarfetchd.quacklib.api.objects.item.ItemBehavior import therealfarfetchd.quacklib.api.objects.item.ItemType import therealfarfetchd.quacklib.api.objects.item.MCItemType import therealfarfetchd.quacklib.api.render.model.Model class DeferredItemTypeImpl(registryName: ResourceLocation) : ItemTypeBase(registryName) { init { instances += this } var realInstance: ItemType? = null override fun Unsafe.toMCItemType(): MCItemType = unsafe { realInstance?.toMCItemType() } ?: crash() override fun create(amount: Int, meta: Int): Item = realInstance?.create(amount, meta) ?: crash() override val behavior: ItemBehavior get() = realInstance?.behavior ?: crash() override val components: List<ItemComponent> get() = realInstance?.components ?: crash() override val model: Model get() = realInstance?.model ?: crash() override fun toString(): String = realInstance?.toString() ?: "unresolved deferred item '$registryName'" @Suppress("NOTHING_TO_INLINE") private inline fun crash(): Nothing = error("Item not resolved yet! Come back after init is done") companion object { var instances: Set<DeferredItemTypeImpl> = emptySet() var isInit = true } }
6
Kotlin
2
4
76c9a55f186c699fb4458f2a4a40a483ab3e3ef2
1,625
QuackLib
MIT License
okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt
yhaiqi87
308,867,574
true
null
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.InetAddress import java.util.concurrent.TimeUnit import java.util.logging.Handler import java.util.logging.Level import java.util.logging.LogManager import java.util.logging.LogRecord import java.util.logging.Logger import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.http2.Http2 import okhttp3.testing.Flaky import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement /** * Apply this rule to all tests. It adds additional checks for leaked resources and uncaught * exceptions. * * Use [newClient] as a factory for a OkHttpClient instances. These instances are specifically * configured for testing. */ class OkHttpClientTestRule : TestRule { private val clientEventsList = mutableListOf<String>() private var testClient: OkHttpClient? = null private var uncaughtException: Throwable? = null var logger: Logger? = null var recordEvents = true var recordTaskRunner = false var recordFrames = false private val testLogHandler = object : Handler() { override fun publish(record: LogRecord) { val name = record.loggerName val recorded = (recordTaskRunner && name == TaskRunner::class.java.name) || (recordFrames && name == Http2::class.java.name) if (recorded) { synchronized(clientEventsList) { clientEventsList.add(record.message) } } } override fun flush() { } override fun close() { } }.apply { level = Level.FINEST } private fun applyLogger(fn: Logger.() -> Unit) { Logger.getLogger(OkHttpClient::class.java.`package`.name).fn() Logger.getLogger(OkHttpClient::class.java.name).fn() Logger.getLogger(Http2::class.java.name).fn() Logger.getLogger(TaskRunner::class.java.name).fn() } fun wrap(eventListener: EventListener) = object : EventListener.Factory { override fun create(call: Call) = ClientRuleEventListener(eventListener) { addEvent(it) } } fun wrap(eventListenerFactory: EventListener.Factory) = object : EventListener.Factory { override fun create(call: Call) = ClientRuleEventListener(eventListenerFactory.create(call)) { addEvent(it) } } /** * Returns an OkHttpClient for tests to use as a starting point. * * The returned client installs a default event listener that gathers debug information. This will * be logged if the test fails. * * This client is also configured to be slightly more deterministic, returning a single IP * address for all hosts, regardless of the actual number of IP addresses reported by DNS. */ fun newClient(): OkHttpClient { var client = testClient if (client == null) { client = OkHttpClient.Builder() .dns(SINGLE_INET_ADDRESS_DNS) // Prevent unexpected fallback addresses. .eventListenerFactory(object : EventListener.Factory { override fun create(call: Call) = ClientRuleEventListener { addEvent(it) } }) .build() testClient = client } return client } fun newClientBuilder(): OkHttpClient.Builder { return newClient().newBuilder() } @Synchronized private fun addEvent(event: String) { if (recordEvents) { logger?.info(event) synchronized(clientEventsList) { clientEventsList.add(event) } } } @Synchronized private fun initUncaughtException(throwable: Throwable) { if (uncaughtException == null) { uncaughtException = throwable } } fun ensureAllConnectionsReleased() { testClient?.let { val connectionPool = it.connectionPool connectionPool.evictAll() assertEquals(0, connectionPool.connectionCount()) } } private fun ensureAllTaskQueuesIdle() { val entryTime = System.nanoTime() for (queue in TaskRunner.INSTANCE.activeQueues()) { // We wait at most 1 second, so we don't ever turn multiple lost threads into // a test timeout failure. val waitTime = (entryTime + 1_000_000_000L - System.nanoTime()) if (!queue.idleLatch().await(waitTime, TimeUnit.NANOSECONDS)) { TaskRunner.INSTANCE.cancelAll() fail("Queue still active after 1000 ms") } } } override fun apply( base: Statement, description: Description ): Statement { return object : Statement() { override fun evaluate() { val defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler { _, throwable -> initUncaughtException(throwable) } val taskQueuesWereIdle = TaskRunner.INSTANCE.activeQueues().isEmpty() var failure: Throwable? = null try { applyLogger { addHandler(testLogHandler) level = Level.FINEST useParentHandlers = false } base.evaluate() if (uncaughtException != null) { throw AssertionError("uncaught exception thrown during test", uncaughtException) } logEventsIfFlaky(description) } catch (t: Throwable) { failure = t logEvents() throw t } finally { LogManager.getLogManager().reset() Thread.setDefaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler) try { ensureAllConnectionsReleased() releaseClient() } catch (ae: AssertionError) { // Prefer keeping the inflight failure, but don't release this in-use client. if (failure != null) { failure.addSuppressed(ae) } else { failure = ae } } try { if (taskQueuesWereIdle) { ensureAllTaskQueuesIdle() } } catch (ae: AssertionError) { // Prefer keeping the inflight failure, but don't release this in-use client. if (failure != null) { failure.addSuppressed(ae) } else { failure = ae } } if (failure != null) { throw failure } } } private fun releaseClient() { testClient?.dispatcher?.executorService?.shutdown() } } } private fun logEventsIfFlaky(description: Description) { if (isTestFlaky(description)) { logEvents() } } private fun isTestFlaky(description: Description): Boolean { return description.annotations.any { it.annotationClass == Flaky::class } || description.testClass.annotations.any { it.annotationClass == Flaky::class } } @Synchronized private fun logEvents() { // Will be ineffective if test overrides the listener synchronized(clientEventsList) { println("Events (${clientEventsList.size})") for (e in clientEventsList) { println(e) } } } companion object { /** * A network that resolves only one IP address per host. Use this when testing route selection * fallbacks to prevent the host machine's various IP addresses from interfering. */ private val SINGLE_INET_ADDRESS_DNS = object : Dns { override fun lookup(hostname: String): List<InetAddress> { val addresses = Dns.SYSTEM.lookup(hostname) return listOf(addresses[0]) } } } }
7
null
0
1
fea8fbba5fd9eadf3f88b91c1479290a60e6d462
8,023
okhttp
Apache License 2.0
billMan/src/main/kotlin/com/weesnerdevelopment/billman/bill/occurrence/BillOccurrenceRouter.kt
adamWeesner
239,233,558
false
null
package com.weesnerdevelopment.billman.bill.occurrence import io.ktor.server.routing.* interface BillOccurrenceRouter { fun setup(routing: Routing) }
2
Kotlin
1
1
bfb3161173d75ea43acd990e9a024210cd1b87e7
155
weesnerDevelopment
MIT License
compiler/testData/diagnostics/tests/traitWithRequired/manyRequirementsDisallowed.kt
chashnikov
14,658,474
false
null
open class A open class B trait C : A, <!MANY_CLASSES_IN_SUPERTYPE_LIST!>B<!>
0
null
0
1
88a261234860ff0014e3c2dd8e64072c685d442d
79
kotlin
Apache License 2.0
api/src/main/kotlin/com/seedcompany/cordtables/components/tables/common/org_chart_position_graph/CreateRead.kt
CordField
409,237,733
false
null
package com.seedcompany.cordtables.components.tables.common.org_chart_position_graph import com.seedcompany.cordtables.common.ErrorType import com.seedcompany.cordtables.common.Utility import com.seedcompany.cordtables.components.tables.common.org_chart_position_graph.* import com.seedcompany.cordtables.components.tables.common.org_chart_position_graph.CommonOrgChartPositionGraphCreateRequest import com.seedcompany.cordtables.components.tables.common.org_chart_position_graph.Create import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.ResponseBody import javax.sql.DataSource data class CommonOrgChartPositionGraphCreateReadRequest( val token: String? = null, val orgChartPositionGraph: orgChartPositionGraphInput, ) data class CommonOrgChartPositionGraphCreateReadResponse( val error: ErrorType, val orgChartPositionGraph: orgChartPositionGraph? = null, ) @CrossOrigin(origins = ["http://localhost:3333", "https://dev.cordtables.com", "https://cordtables.com", "*"]) @Controller("CommonOrgChartPositionGraphCreateRead") class CreateRead( @Autowired val util: Utility, @Autowired val ds: DataSource, @Autowired val create: Create, @Autowired val read: Read, ) { @PostMapping("common/org-chart-position-graph/create-read") @ResponseBody fun createReadHandler(@RequestBody req: CommonOrgChartPositionGraphCreateReadRequest): CommonOrgChartPositionGraphCreateReadResponse { val createResponse = create.createHandler( CommonOrgChartPositionGraphCreateRequest( token = req.token, orgChartPositionGraph = req.orgChartPositionGraph ) ) if (createResponse.error != ErrorType.NoError) { return CommonOrgChartPositionGraphCreateReadResponse(error = createResponse.error) } val readResponse = read.readHandler( CommonOrgChartPositionGraphReadRequest( token = req.token, id = createResponse!!.id ) ) return CommonOrgChartPositionGraphCreateReadResponse(error = readResponse.error, orgChartPositionGraph = readResponse.orgChartPositionGraph) } }
93
Kotlin
1
3
7e5588a8b3274917f9a5df2ffa12d27db23fb909
2,475
cordtables
MIT License
src/test/kotlin/com/cillu/mediator/commands/config/wrongconstructor/CreateCommandHandler.kt
thecillu
520,490,197
false
null
package com.cillu.mediator.commands.config.wrongconstructor import com.cillu.mediator.Item import com.cillu.mediator.annotations.CommandHandler import com.cillu.mediator.annotations.Inject import com.cillu.mediator.commands.ICommandHandler import com.cillu.mediator.commands.domain.CreateCommand2 import com.cillu.mediator.services.ITestRepository @CommandHandler class CreateCommandHandler(var wrongParam: Any): ICommandHandler<CreateCommand2>, Exception(){ @Inject lateinit var testRepository: ITestRepository override fun handle(command: CreateCommand2): Item { var item = Item.create(command.name); testRepository.sayhello() return item } }
5
Kotlin
0
0
f41327a9b6611573230a98fbee7bbd3a05192ed6
688
mediatork
MIT License
app/src/main/java/com/example/bike/riders/di/scope/PerApplication.kt
MuhammadHamzaVD
344,044,600
false
null
package com.example.bike.riders.di.scope import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class PerApplication
0
Kotlin
0
0
260655b120c309ae483e82b9a2b7b8adeb1a23a7
155
bikerider
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Profiledelete.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.Profiledelete: ImageVector get() { if (_profiledelete != null) { return _profiledelete!! } _profiledelete = Builder(name = "Profiledelete", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 2.0f) curveTo(9.38f, 2.0f, 7.25f, 4.13f, 7.25f, 6.75f) curveTo(7.25f, 9.32f, 9.26f, 11.4f, 11.88f, 11.49f) curveTo(11.96f, 11.48f, 12.04f, 11.48f, 12.1f, 11.49f) curveTo(12.12f, 11.49f, 12.13f, 11.49f, 12.15f, 11.49f) curveTo(12.16f, 11.49f, 12.16f, 11.49f, 12.17f, 11.49f) curveTo(14.73f, 11.4f, 16.74f, 9.32f, 16.75f, 6.75f) curveTo(16.75f, 4.13f, 14.62f, 2.0f, 12.0f, 2.0f) close() } 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(17.0809f, 14.1499f) curveTo(14.2909f, 12.2899f, 9.7409f, 12.2899f, 6.9309f, 14.1499f) curveTo(5.6609f, 14.9999f, 4.9609f, 16.1499f, 4.9609f, 17.3799f) curveTo(4.9609f, 18.6099f, 5.6609f, 19.7499f, 6.9209f, 20.5899f) curveTo(8.3209f, 21.5299f, 10.1609f, 21.9999f, 12.0009f, 21.9999f) curveTo(13.8409f, 21.9999f, 15.6809f, 21.5299f, 17.0809f, 20.5899f) curveTo(18.3409f, 19.7399f, 19.0409f, 18.5999f, 19.0409f, 17.3599f) curveTo(19.0309f, 16.1299f, 18.3409f, 14.9899f, 17.0809f, 14.1499f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0593f, 17.3799f) lineTo(13.9393f, 16.4999f) curveTo(14.2293f, 16.2099f, 14.2293f, 15.7299f, 13.9393f, 15.4399f) curveTo(13.6493f, 15.1499f, 13.1693f, 15.1499f, 12.8793f, 15.4399f) lineTo(11.9993f, 16.3199f) lineTo(11.1193f, 15.4399f) curveTo(10.8293f, 15.1499f, 10.3493f, 15.1499f, 10.0593f, 15.4399f) curveTo(9.7693f, 15.7299f, 9.7693f, 16.2099f, 10.0593f, 16.4999f) lineTo(10.9393f, 17.3799f) lineTo(10.0593f, 18.2599f) curveTo(9.7693f, 18.5499f, 9.7693f, 19.0299f, 10.0593f, 19.3199f) curveTo(10.2093f, 19.4699f, 10.3993f, 19.5399f, 10.5893f, 19.5399f) curveTo(10.7793f, 19.5399f, 10.9693f, 19.4699f, 11.1193f, 19.3199f) lineTo(11.9993f, 18.4399f) lineTo(12.8793f, 19.3199f) curveTo(13.0293f, 19.4699f, 13.2193f, 19.5399f, 13.4093f, 19.5399f) curveTo(13.5993f, 19.5399f, 13.7893f, 19.4699f, 13.9393f, 19.3199f) curveTo(14.2293f, 19.0299f, 14.2293f, 18.5499f, 13.9393f, 18.2599f) lineTo(13.0593f, 17.3799f) close() } } .build() return _profiledelete!! } private var _profiledelete: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,370
VuesaxIcons
MIT License
test-utils/src/main/java/org/p2p/wallet/utils/MutableListQueue.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.wallet.utils /** * MutableListQueue as type alias of Mutable List */ typealias MutableListQueue<T> = MutableList<T> /** * Pushes item to [MutableListQueue] * @param item Item to be pushed */ fun <T> MutableListQueue<T>.push(item: T) = add(item) /** * Pops (removes and return) first item from [MutableListQueue] * @return item Last item if [MutableListQueue] is not empty, null otherwise */ fun <T> MutableListQueue<T>.pop(): T? = if (isNotEmpty()) removeAt(0) else null /** * Peeks (return) last item from [MutableListQueue] * @return item Last item if [MutableListQueue] is not empty, null otherwise */ fun <T> MutableListQueue<T>.front(): T? = if (isNotEmpty()) this[0] else null /** * Peeks (return) last item from [MutableListQueue] * @return item Last item if [MutableListQueue] is not empty, null otherwise */ fun <T> MutableListQueue<T>.back(): T? = if (isNotEmpty()) this[lastIndex] else null inline fun <reified T> mutableListQueueOf(vararg elements: T): MutableListQueue<T> = mutableListOf(*elements)
8
Kotlin
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
1,048
key-app-android
MIT License
src/main/kotlin/us/whodag/acquire/obj/tile/TileId.kt
Odoh
111,036,546
false
null
package us.whodag.acquire.obj.tile /** * Unique identifier for Tiles. * * @property name the name of the tile ("1-A") */ data class TileId(val name: String): Comparable<TileId> { constructor(number: String, letter: String) : this("$number-$letter") override fun compareTo(other: TileId): Int { val (thisNum, thisChar) = this.split() val (otherNum, otherChar) = other.split() if (thisNum.compareTo(otherNum) == 0) { return thisChar.compareTo(otherChar) } return thisNum.compareTo(otherNum) } override fun toString(): String = name } /** Split the name of a tile into its number of letter components. */ fun TileId.split(): Pair<Int, Char> { val split = name.split("-") return Pair(split[0].toInt(), split[1].toCharArray()[0]) }
0
Kotlin
0
2
4be3b11c1141e2e9d28135c203531c75eafdd2f0
809
acquire
MIT License
app/src/main/java/cn/wthee/pcrtool/data/db/repository/EventRepository.kt
wthee
277,015,110
false
{"Kotlin": 1656782}
package cn.wthee.pcrtool.data.db.repository import cn.wthee.pcrtool.data.db.dao.EventDao import cn.wthee.pcrtool.utils.LogReportUtil import cn.wthee.pcrtool.utils.compareAllTypeEvent import javax.inject.Inject /** * 剧情活动 Repository * * @param eventDao */ class EventRepository @Inject constructor(private val eventDao: EventDao) { suspend fun getAllEvents(limit: Int) = try { eventDao.getAllEvents(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getAllEvents") emptyList() } suspend fun getStoryDetails(storyId: Int) = eventDao.getStoryDetails(storyId) suspend fun getDropEvent(limit: Int) = try { eventDao.getDropEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getDropEvent") emptyList() } suspend fun getMissionEvent(limit: Int) = try { eventDao.getMissionEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getMissionEvent") emptyList() } suspend fun getLoginEvent(limit: Int) = try { eventDao.getLoginEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getLoginEvent") emptyList() } suspend fun getFortuneEvent(limit: Int) = try { eventDao.getFortuneEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getFortuneEvent") emptyList() } suspend fun getTowerEvent(limit: Int) = try { eventDao.getTowerEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getTowerEvent") emptyList() } suspend fun getSpDungeonEvent(limit: Int) = try { eventDao.getSpDungeonEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getSpDungeonEvent") emptyList() } suspend fun getFaultEvent(limit: Int) = try { eventDao.getFaultEvent(limit) } catch (_: Exception) { emptyList() } suspend fun getFreeGachaEvent(limit: Int) = try { eventDao.getFreeGachaEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getFreeGachaList#type") emptyList() } suspend fun getBirthdayList() = try { eventDao.getBirthdayList().sortedWith(compareAllTypeEvent()) } catch (e: Exception) { LogReportUtil.upload(e, "getBirthdayList") emptyList() } suspend fun getClanBattleEvent(limit: Int) = try { eventDao.getClanBattleEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getClanBattleEvent") emptyList() } suspend fun getColosseumEvent(limit: Int) = try { eventDao.getColosseumEvent(limit) } catch (e: Exception) { LogReportUtil.upload(e, "getColosseumEvent") emptyList() } }
1
Kotlin
5
90
c60547933372fbbc595da93c7b0ea30319bbf124
2,774
pcr-tool
Apache License 2.0
application/src/main/kotlin/dev/hypest/pis/payments/domain/ordertopay/PayOrderHandler.kt
PIS22Z
557,250,063
false
{"Kotlin": 118874, "Groovy": 79090, "Dockerfile": 145}
package dev.hypest.pis.payments.domain.ordertopay import jakarta.inject.Singleton import java.util.UUID interface PayOrderHandler { fun pay(command: PayOrderCommand): UUID } @Singleton class PayOrderHandlerImpl( private val orderToPayRepository: OrderToPayRepository ) : PayOrderHandler { override fun pay(command: PayOrderCommand): UUID { val order = orderToPayRepository.load(command.orderId) ?: throw OrderToPayNotFoundException(command.orderId) order.pay() orderToPayRepository.save(order) return order.id } } data class PayOrderCommand( val orderId: UUID )
0
Kotlin
0
0
a5eab87108f49a6355362682b94b7c49d5dd421b
631
backend
MIT License
app/src/main/java/io/github/omisie11/coronatracker/data/remote/model/CountriesRemote.kt
OMIsie11
248,815,717
false
null
package io.github.omisie11.coronatracker.data.remote.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class CountriesRemote( @Json(name = "countries") val countries: List<CountryRemote> )
0
Kotlin
8
20
d3054dfb3bce52e4a3c33667aed2e837818a283b
258
CovidNow
Apache License 2.0
dd-sdk-android/src/test/kotlin/com/datadog/android/core/internal/persistence/file/single/SingleItemDataWriterTest.kt
roy-m-organ
372,127,056
true
{"Kotlin": 3161847, "Java": 218303, "C": 78947, "Shell": 56287, "C++": 27621, "Python": 4516, "CMake": 2042}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.core.internal.persistence.file.single import com.datadog.android.core.internal.persistence.DataWriter import com.datadog.android.core.internal.persistence.Serializer import com.datadog.android.core.internal.persistence.file.FileHandler import com.datadog.android.core.internal.persistence.file.FileOrchestrator import com.datadog.android.utils.forge.Configurator import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyZeroInteractions import com.nhaarman.mockitokotlin2.whenever import fr.xgouchet.elmyr.annotation.Forgery import fr.xgouchet.elmyr.annotation.StringForgery import fr.xgouchet.elmyr.junit5.ForgeConfiguration import fr.xgouchet.elmyr.junit5.ForgeExtension import java.io.File import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.Extensions import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.junit.jupiter.MockitoSettings import org.mockito.quality.Strictness import org.mockito.stubbing.Answer @Extensions( ExtendWith(MockitoExtension::class), ExtendWith(ForgeExtension::class) ) @MockitoSettings(strictness = Strictness.LENIENT) @ForgeConfiguration(Configurator::class) internal class SingleItemDataWriterTest { lateinit var testedWriter: DataWriter<String> @Mock lateinit var mockSerializer: Serializer<String> @Mock lateinit var mockOrchestrator: FileOrchestrator @Mock lateinit var mockFileHandler: FileHandler private val stubReverseSerializerAnswer = Answer<String?> { invocation -> (invocation.getArgument<String>(0)).reversed() } private val stubFailingSerializerAnswer = Answer<String?> { null } @BeforeEach fun `set up`() { whenever(mockSerializer.serialize(any())).doAnswer(stubReverseSerializerAnswer) testedWriter = SingleItemDataWriter( mockOrchestrator, mockSerializer, mockFileHandler ) } @Test fun `𝕄 write element to file 𝕎 write(element)`( @StringForgery data: String, @Forgery file: File ) { // Given val serialized = data.reversed().toByteArray(Charsets.UTF_8) whenever(mockOrchestrator.getWritableFile(any())) doReturn file // When testedWriter.write(data) // Then verify(mockFileHandler) .writeData( file, serialized, append = false, separator = null ) } @Test fun `𝕄 write last element to file 𝕎 write(list)`( @StringForgery data: List<String>, @Forgery file: File ) { // Given val lastSerialized = data.last().reversed().toByteArray(Charsets.UTF_8) whenever(mockOrchestrator.getWritableFile(any())) doReturn file // When testedWriter.write(data) // Then verify(mockFileHandler) .writeData( file, lastSerialized, append = false, separator = null ) } @Test fun `𝕄 do nothing 𝕎 write(element) { serialization failure }`( @StringForgery data: String ) { // Given whenever(mockSerializer.serialize(data)) doAnswer stubFailingSerializerAnswer // When testedWriter.write(data) // Then verifyZeroInteractions(mockFileHandler) } }
0
null
0
1
1f5132637da21d6ae24ec8a5516d362ff4940c3c
3,960
dd-sdk-android
Apache License 2.0
vscode/src/jsMain/kotlin/vscode/IDisposable.kt
lppedd
761,812,661
false
{"Kotlin": 1844789}
@file:Suppress("WRONG_EXTERNAL_DECLARATION") package vscode /** * Represents a type which can release resources, such * as event listening or a timer. */ external fun interface IDisposable { /** * Dispose this object. */ fun dispose(): Any? }
0
Kotlin
0
2
1111ef252b1414eeb7448b944481965c65c83c40
258
kotlin-externals
MIT License
dagger/src/main/java/com/kodyuzz/daggerproject/di/component/ApplicationComponent.kt
mustafaatush
274,828,691
false
null
package com.kodyuzz.daggerproject.di.component import com.kodyuzz.daggerproject.MyApplication import com.kodyuzz.daggerproject.di.module.ApplicationModule import com.kodyuzz.daggerproject.model.DatabaseService import com.kodyuzz.daggerproject.model.NetworkService import com.kodyuzz.daggerproject.util.NetworkHelper import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [ApplicationModule::class]) interface ApplicationComponent { fun inject(application: MyApplication); fun getNetworkService(): NetworkService; fun getDatabaseService(): DatabaseService; fun getNetworkHelper(): NetworkHelper; }
0
Kotlin
0
0
a946972fe26c3ed8bb2abc69be6a72af976320c1
650
kodyuzz
Apache License 2.0
reaktor-android-koin/src/test/kotlin/at/florianschuster/reaktor/android/koin/AndroidKoinReactorTest.kt
floschu
175,684,147
false
null
package at.florianschuster.reaktor.android.koin import at.florianschuster.reaktor.android.ViewModelReactor import org.junit.Before import org.junit.Test import org.koin.core.context.startKoin import org.koin.core.get import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.AutoCloseKoinTest class AndroidKoinReactorTest : AutoCloseKoinTest() { private class TestReactor : ViewModelReactor<Unit, Unit, Unit>(Unit) private val testModule: Module = module { reactor { TestReactor() } } @Before fun before() { startKoin { modules(testModule) } } @Test fun testModuleReactorDSLExtension() { get<TestReactor>() } }
2
null
2
16
756b754bd2d9b04590fd112845c7454d0d94bd0e
722
Reaktor
Apache License 2.0
core/sharedui/src/commonMain/kotlin/dev/koga/deeplinklauncher/folder/AddFolderBottomSheet.kt
FelipeKoga
741,211,763
false
{"Kotlin": 225170, "Swift": 342}
package dev.koga.deeplinklauncher import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddFolderBottomSheet( onDismiss: () -> Unit, onAdd: (name: String, description: String) -> Unit, ) { ModalBottomSheet(onDismissRequest = onDismiss) { AddFolderBottomSheetContent(onAdd = onAdd) } } @Composable fun AddFolderBottomSheetContent( onAdd: (name: String, description: String) -> Unit, ) { val (name, setName) = rememberSaveable { mutableStateOf("") } val (description, setDescription) = rememberSaveable { mutableStateOf("") } Column( modifier = Modifier.padding(32.dp), ) { Text( text = "Add Folder", style = MaterialTheme.typography.titleSmall.copy( fontWeight = FontWeight.Bold, ), ) Spacer(modifier = Modifier.height(12.dp)) DLLTextField( value = name, onValueChange = setName, label = "Name", ) Spacer(modifier = Modifier.height(12.dp)) DLLTextField( modifier = Modifier.defaultMinSize(minHeight = 120.dp), value = description, onValueChange = setDescription, label = "Description", imeAction = ImeAction.Done, ) Spacer(modifier = Modifier.height(24.dp)) Button( onClick = { onAdd(name, description) }, enabled = name.isNotBlank(), modifier = Modifier .align(Alignment.CenterHorizontally) .fillMaxWidth(.6f), ) { Text(text = "Save") } Spacer(modifier = Modifier.height(12.dp)) } }
0
Kotlin
0
5
73199e8464acfb090107fd66a717582a8a9c3f25
2,583
deeplink-launcher
Apache License 2.0
app/src/main/java/io/github/vladimirmi/internetradioplayer/data/net/UberStationsService.kt
VladimirMi
132,266,318
false
null
package io.github.vladimirmi.internetradioplayer.data.net import io.github.vladimirmi.internetradioplayer.data.net.ubermodel.StationIdSearch import io.github.vladimirmi.internetradioplayer.data.net.ubermodel.StationsSearch import io.github.vladimirmi.internetradioplayer.data.net.ubermodel.SuggestionsSearch import io.github.vladimirmi.internetradioplayer.data.net.ubermodel.TopSongsSearch import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Query /** * Created by Vladimir Mikhalev 13.11.2018. */ interface UberStationsService { companion object { const val HOST = "api.dar.fm" const val BASE_URL = "http://$HOST" const val PRESEARCH_ENDPOINT = "presearch.php" const val STATIONS_ENDPOINT = "playlist.php" const val STATION_ENDPOINT = "darstations.php" const val TOPSONGS_ENDPOINT = "topsongs.php" const val TALK_URL_ENDPOINT = "uberurl.php" } @GET(PRESEARCH_ENDPOINT) fun getSuggestions(@Query("q") query: String): Single<SuggestionsSearch> @GET(STATIONS_ENDPOINT) fun searchStations(@Query("q") query: String, @Query("pagesize") pageSize: Int = 50): Single<StationsSearch> @GET(STATION_ENDPOINT) fun getStation(@Query("station_id") id: String): Single<StationIdSearch> @GET(TOPSONGS_ENDPOINT) fun searchTopSongs(@Query("q") query: String, @Query("pagesize") pageSize: Int = 50): Single<TopSongsSearch> }
2
Kotlin
6
11
3bca269876825dd3c20067ed4b9887fbd1589fa0
1,483
InternetRadioPlayer
MIT License
mobile/src/main/java/br/com/helpdev/velocimetroalerta/dialogs/DialogHR.kt
helpdeveloper
72,458,937
false
{"Kotlin": 103294, "Java": 14234}
package br.com.helpdev.velocimetroalerta.dialogs import android.app.AlertDialog import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.Context import android.content.DialogInterface import android.preference.DialogPreference import android.util.AttributeSet import android.view.LayoutInflater import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.BaseAdapter import android.widget.ListView import java.io.IOException import java.util.ArrayList import br.com.helpdev.velocimetroalerta.R import br.com.helpdev.velocimetroalerta.bluetooth.Bluetooth class DialogHR(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs), BluetoothAdapter.LeScanCallback { override fun onLeScan(device: BluetoothDevice, rssi: Int, scanRecord: ByteArray?) { devices.forEach({ d -> if (d.address == device.address) { return } }) devices.add(MyDevice(device)) (listView?.adapter as BaseAdapter).notifyDataSetInvalidated() } class MyDevice(private val blDevice: BluetoothDevice) { val name: String get() = blDevice.name val address: String get() = blDevice.address override fun toString(): String { return blDevice.name + "\n" + blDevice.address } } private val devices = ArrayList<MyDevice>() private var listView: ListView? = null override fun onPrepareDialogBuilder(builder: AlertDialog.Builder) { if (Bluetooth.isAdapterEnabled) { val view = LayoutInflater.from(context).inflate(R.layout.dialog_config_hr, null) builder.setView(view) builder.setNegativeButton(R.string.bt_disable_module) { _, _ -> editor.putBoolean(key, false).apply() } try { listView = view.findViewById(R.id.listView) listView!!.adapter = ArrayAdapter<MyDevice>(context, android.R.layout.simple_list_item_1, devices) listView!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, id -> editor.putBoolean(key, true).apply() editor.putString( context.getString(R.string.pref_hr_sensor_name), devices[position].name).apply() editor.putString( context.getString(R.string.pref_hr_sensor_address), devices[position].address).apply() dialog.dismiss() } Bluetooth.bluetoothAdapter.startLeScan(this) } catch (e: IOException) { e.printStackTrace() } } else { builder.setMessage(R.string.disabled_bluetooth) builder.setPositiveButton(R.string.bt_enable) { _, _ -> Bluetooth.enableAdapter() } } } override fun onDismiss(dialog: DialogInterface) { Bluetooth.bluetoothAdapter.stopLeScan(this) onPreferenceChangeListener?.onPreferenceChange(this, summary) super.onDismiss(dialog) } override fun getSummary(): CharSequence { val status = sharedPreferences.getBoolean(key, false) var valueToSummary: String? = context.getString(R.string.disable) if (status) { valueToSummary = sharedPreferences.getString(context.getString(R.string.pref_hr_sensor_name), context.getString(R.string.disable)) } return valueToSummary.toString() } }
0
Kotlin
3
1
99feeee1ff53b44c7446e1b60f685fc575479773
3,578
VelocimetroAlerta
Apache License 2.0
app/src/main/java/io/aayush/relabs/ui/screens/more/MoreScreen.kt
theimpulson
679,298,392
false
{"Kotlin": 134233}
package io.aayush.relabs.ui.screens.more import android.net.Uri import android.util.Log import androidx.browser.customtabs.CustomTabsIntent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue 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.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import io.aayush.relabs.R import io.aayush.relabs.network.data.user.Me import io.aayush.relabs.ui.components.UserHeader private const val TAG = "SettingsScreen" @OptIn(ExperimentalMaterial3Api::class) @Composable fun MoreScreen( navHostController: NavHostController, viewModel: MoreViewModel = hiltViewModel() ) { val user: Me? by viewModel.currentUser.collectAsStateWithLifecycle() Scaffold( modifier = Modifier.fillMaxSize(), topBar = { TopAppBar( title = { Text(text = stringResource(id = R.string.more)) }, actions = { if (user?.me?.view_url?.isNotBlank() == true) { val context = LocalContext.current IconButton(onClick = { try { CustomTabsIntent.Builder() .build() .launchUrl(context, Uri.parse(viewModel.currentUser.value?.me?.view_url)) } catch (exception: Exception) { Log.e(TAG, "Failed to open profile", exception) } }) { Icon( painter = painterResource(id = R.drawable.ic_open), contentDescription = "" ) } } } ) } ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(it), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { if (user?.me?.username?.isNotBlank() == true) { UserHeader(user = user?.me!!) } } } }
0
Kotlin
2
51
859502d8d7d13a8deac15d77bd0808e17f7188db
3,136
ReLabs
Apache License 2.0
src/test/kotlin/io/getunleash/UnleashContextTest.kt
Unleash
369,129,274
false
{"Kotlin": 102938}
package io.getunleash import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.util.UUID class UnleashContextTest { @Test fun `can build context with builder`() { val ctx = UnleashContext.newBuilder().appName("my-app").addProperty("somekey", "somevalue") .addProperty("someotherkey", "someothervalue") .remoteAddress("127.0.0.1") .build() assertThat(ctx.properties).containsEntry("somekey", "somevalue").containsEntry("someotherkey", "someothervalue") assertThat(ctx.remoteAddress).isEqualTo("127.0.0.1") assertThat(ctx.appName).isEqualTo("my-app") } @Test fun `can build context using normal class constructor`() { val ctx = UnleashContext(properties = mapOf("somekey" to "somevalue", "someotherkey" to "someothervalue"), remoteAddress = "127.0.0.1", appName = "my-app") assertThat(ctx.properties).containsEntry("somekey", "somevalue").containsEntry("someotherkey", "someothervalue") assertThat(ctx.remoteAddress).isEqualTo("127.0.0.1") assertThat(ctx.appName).isEqualTo("my-app") } @Test fun `Can get a builder from existing context`() { val ctx = UnleashContext(properties = mapOf("somekey" to "somevalue", "someotherkey" to "someothervalue"), remoteAddress = "127.0.0.1", appName = "my-app") val newCtx = ctx.newBuilder().addProperty("third", "3").build() assertThat(ctx.properties).doesNotContainEntry("third", "3") assertThat(newCtx.properties).containsEntry("third", "3") } @Test fun `Can set environment with builder`() { val ctx = UnleashContext(properties = mapOf("somekey" to "somevalue", "someotherkey" to "someothervalue"), remoteAddress = "127.0.0.1", appName = "my-app") val updatedCtx = ctx.newBuilder().environment("dev").build() assertThat(updatedCtx.environment).isEqualTo("dev") } @Test fun `Can set instanceId with builder`() { val ctx = UnleashContext(properties = mapOf("somekey" to "somevalue", "someotherkey" to "someothervalue"), remoteAddress = "127.0.0.1", appName = "my-app") val uuid = UUID.randomUUID().toString() val updatedCtx = ctx.newBuilder().instanceId(uuid).build() assertThat(updatedCtx.instanceId).isEqualTo(uuid) } @Test fun `Can override properties with builder method`() { val ctx = UnleashContext(properties = mapOf("somekey" to "somevalue", "someotherkey" to "someothervalue"), remoteAddress = "127.0.0.1", appName = "my-app") val updatedCtx = ctx.newBuilder().properties(mutableMapOf("third" to "3")).build() assertThat(updatedCtx.properties).hasSize(1) } }
7
Kotlin
14
7
5e96dd06cfddaabaa9fa1308cec98e577c4622be
2,736
unleash-android-proxy-sdk
Apache License 2.0
modules/meta/arrow-meta-prototype/compiler-plugin/src/main/kotlin/arrow/meta/MetaCommandLineProcessor.kt
rybalkinsd
265,091,421
true
{"Kotlin": 2664254, "CSS": 152663, "JavaScript": 67900, "HTML": 23177, "Scala": 8150, "Java": 4465, "Shell": 3043, "Ruby": 1598}
package arrow.meta import org.jetbrains.kotlin.compiler.plugin.CliOption import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor class MetaCommandLineProcessor : CommandLineProcessor { override val pluginId: String = "arrow.meta.plugin.compiler" override val pluginOptions: Collection<CliOption> = emptyList() }
0
null
0
0
92199c03b14b0c7488fd844e1845b7ca93079a18
330
arrow-meta
Apache License 2.0
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/SaveForFutureUseElement.kt
stripe
6,926,049
false
null
package com.stripe.android.ui.core.elements import androidx.annotation.RestrictTo import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map /** * This is an element that will make elements (as specified by identifier) hidden * when "save for future" use is unchecked */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class SaveForFutureUseElement( override val identifier: IdentifierSpec, override val controller: SaveForFutureUseController, val merchantName: String? ) : FormElement() { override fun getFormFieldValueFlow(): Flow<List<Pair<IdentifierSpec, FormFieldEntry>>> = controller.formFieldValue.map { listOf( identifier to it ) } }
64
Kotlin
619
935
bec4fc5f45b5401a98a310f7ebe5d383693936ea
787
stripe-android
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/LariSign.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.LariSign: ImageVector get() { if (_lariSign != null) { return _lariSign!! } _lariSign = Builder(name = "LariSign", 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(23.0f, 22.5f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) horizontalLineTo(2.5f) curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f) reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f) horizontalLineToRelative(1.96f) curveToRelative(-2.13f, -2.01f, -3.46f, -4.85f, -3.46f, -8.0f) curveTo(1.0f, 8.35f, 3.91f, 4.36f, 8.0f, 2.75f) verticalLineTo(1.5f) curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.67f, 1.5f, 1.5f) verticalLineToRelative(0.55f) curveToRelative(0.33f, -0.03f, 0.66f, -0.05f, 1.0f, -0.05f) reflectiveCurveToRelative(0.67f, 0.02f, 1.0f, 0.05f) verticalLineToRelative(-0.55f) curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.67f, 1.5f, 1.5f) verticalLineToRelative(1.25f) curveToRelative(4.09f, 1.6f, 7.0f, 5.59f, 7.0f, 10.25f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.67f, -1.5f, -1.5f) curveToRelative(0.0f, -2.95f, -1.61f, -5.54f, -4.0f, -6.93f) verticalLineToRelative(4.43f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.67f, -1.5f, -1.5f) verticalLineTo(5.06f) curveToRelative(-0.33f, -0.04f, -0.66f, -0.06f, -1.0f, -0.06f) reflectiveCurveToRelative(-0.67f, 0.02f, -1.0f, 0.06f) verticalLineToRelative(5.44f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.67f, -1.5f, -1.5f) verticalLineTo(6.07f) curveToRelative(-2.39f, 1.39f, -4.0f, 3.97f, -4.0f, 6.93f) curveToRelative(0.0f, 4.41f, 3.59f, 8.0f, 8.0f, 8.0f) horizontalLineToRelative(9.5f) curveToRelative(0.83f, 0.0f, 1.5f, 0.67f, 1.5f, 1.5f) close() } } .build() return _lariSign!! } private var _lariSign: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,470
icons
MIT License
app/src/main/java/com/animsh/appita/models/CaloricBreakdown.kt
animsh
340,045,597
false
null
package com.animsh.appita.models import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class CaloricBreakdown( @SerializedName("percentCarbs") val percentCarbs: Double?, @SerializedName("percentFat") val percentFat: Double?, @SerializedName("percentProtein") val percentProtein: Double? ) : Parcelable
0
null
0
3
ad44196d69a9b4fb8ccd4d2eb51f9a29b34b1ad8
404
Appita
Apache License 2.0
app/src/main/java/com/tugrulbo/mvvmnewsapp/ui/activity/MainActivity.kt
tugrulbo
515,014,744
false
{"Kotlin": 33958}
package com.tugrulbo.mvvmnewsapp.ui.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.tugrulbo.mvvmnewsapp.R import com.tugrulbo.mvvmnewsapp.databinding.ActivityMainBinding import com.tugrulbo.mvvmnewsapp.db.ArticleDatabase import com.tugrulbo.mvvmnewsapp.repository.NewsRepository import com.tugrulbo.mvvmnewsapp.ui.NewsViewModel import com.tugrulbo.mvvmnewsapp.ui.NewsViewModelFactory class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding lateinit var viewModel: NewsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val repository = NewsRepository(ArticleDatabase(this)) val viewModelProviderFactory = NewsViewModelFactory(application,newsRepository = repository) viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java) val navHostFragment = supportFragmentManager .findFragmentById(R.id.fragmentContainerView) as NavHostFragment val navController = navHostFragment.navController binding.bottomNav.setupWithNavController(navController) } }
0
Kotlin
0
1
26620f1c07d2d6f21a04715a62112bf098319e86
1,531
NewsApp
MIT License
app/src/main/java/com/javalon/xpensewhiz/domain/repository/DatastoreRepository.kt
ezechuka
472,029,227
false
{"Kotlin": 333980}
package com.business.money_minder.domain.repository import kotlinx.coroutines.flow.Flow interface DatastoreRepository { suspend fun writeOnboardingKeyToDataStore(completed: Boolean) suspend fun readOnboardingKeyFromDataStore(): Flow<Boolean> suspend fun writeCurrencyToDataStore(currency: String) suspend fun readCurrencyFromDataStore(): Flow<String> suspend fun writeExpenseLimitToDataStore(amount: Double) suspend fun readExpenseLimitFromDataStore(): Flow<Double> suspend fun writeLimitKeyToDataStore(enabled: Boolean) suspend fun readLimitKeyFromDataStore(): Flow<Boolean> suspend fun writeLimitDurationToDataStore(duration: Int) suspend fun readLimitDurationFromDataStore(): Flow<Int> suspend fun eraseDataStore() }
1
Kotlin
5
52
7876f00908cca4f8444ab8b4460f1e7edb4cfa1a
775
xpense-whiz
MIT License
DatePick/app/src/main/java/com/sun/toy/datepick/AdapterEvent.kt
hnhariat
95,398,020
false
null
package com.sun.toy.datepick import android.support.v7.widget.RecyclerView import android.text.format.DateFormat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.sun.toy.datepick.base.OnClickDeliverer import java.util.* import kotlin.collections.ArrayList /** * Created by 1100160 on 2017. 6. 26.. */ class AdapterEvent : RecyclerView.Adapter<AdapterEvent.ViewHolder>() { var mList = ArrayList<Event>() var mOnClickDeliver: OnClickDeliverer? = null override fun getItemCount(): Int { return mList.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { var view = LayoutInflater.from(parent?.context).inflate(R.layout.item_event, null, false) as View var viewHolder = ViewHolder(view) view.setOnClickListener(View.OnClickListener { mOnClickDeliver?.onClickDeliver(view) }) return viewHolder } override fun onBindViewHolder(holder: ViewHolder?, position: Int) { var item = mList.get(position) holder.apply { holder?.txtTitle?.apply { text = item.name } } holder.apply { holder?.txtTime?.apply { var cal = Calendar.getInstance() as Calendar cal.timeInMillis = item.time text = DateFormat.getLongDateFormat(context).format(Date(cal.timeInMillis)) } } } class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { var txtTitle: TextView? var txtTime: TextView? init { txtTitle = itemView?.findViewById(R.id.txt_title) as TextView? txtTime = itemView?.findViewById(R.id.txt_time) as TextView? } } fun setOnClickDeliverer(l: OnClickDeliverer) { mOnClickDeliver = l } fun setList(list: ArrayList<Event>) { mList.clear() mList.addAll(list) notifyDataSetChanged() } fun item(pos: Int): Event { return mList?.get(pos) } }
1
null
1
1
4389b5a10024d424c446ddbdc5ff7c5db2bc18c9
2,125
DatePick
Apache License 2.0
teacher/app/src/androidTest/java/com/instructure/teacher/ui/pages/SpeedGraderCommentsPage.kt
XinicsInc
123,872,784
true
{"Markdown": 5, "INI": 18, "Shell": 27, "Proguard": 16, "Gradle": 54, "Ignore List": 38, "Java": 1391, "XML": 1946, "Gradle Kotlin DSL": 2, "Kotlin": 965, "Ruby": 19, "Protocol Buffer": 14, "JSON": 7, "GraphQL": 1, "Text": 12, "Batchfile": 2, "Java Properties": 11, "HTML": 7, "Python": 1, "YAML": 3, "CSS": 1, "Ant Build System": 1}
/* * Copyright (C) 2017 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.instructure.teacher.ui.pages import android.support.test.espresso.Espresso import android.support.test.espresso.Espresso.onView import android.support.test.espresso.matcher.ViewMatchers import android.support.test.espresso.matcher.ViewMatchers.* import com.instructure.espresso.ViewCallOnClick.Companion.callOnClick import com.instructure.espresso.WaitForViewMatcher import com.instructure.soseedy.Attachment import com.instructure.teacher.R import com.instructure.teacher.ui.utils.* import com.instructure.teacher.ui.utils.pageAssert.PageAssert import com.instructure.teacher.ui.utils.pageAssert.SimplePageAssert import org.hamcrest.Matchers class SpeedGraderCommentsPage : BasePage(), PageAssert by SimplePageAssert() { private val commentEditText by OnViewWithId(R.id.commentEditText) private val sendCommentButton by WaitForViewWithId(R.id.sendCommentButton) fun assertDisplaysAuthorName(name: String) { onView(withText(name)).assertVisible() } fun assertDisplaysCommentText(comment: String) { WaitForViewMatcher.waitForView(Matchers.allOf(ViewMatchers.withId(R.id.commentTextView), ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE))) .assertHasText(comment) } fun assertDisplaysCommentAttachment(attachment: Attachment) { onViewWithId(R.id.attachmentNameTextView).assertHasText(attachment.displayName) } fun assertDisplaysSubmission() { onViewWithId(R.id.commentSubmissionAttachmentView).assertDisplayed() } fun assertDisplaysSubmissionFile(attachment: Attachment) { val parentMatcher = ViewMatchers.withParent(ViewMatchers.withId(R.id.commentSubmissionAttachmentView)) val match = Espresso.onView(Matchers.allOf(parentMatcher, ViewMatchers.withId(R.id.titleTextView))) match.assertHasText(attachment.displayName) } fun addComment(comment: String) { commentEditText.replaceText(comment) callOnClick(withId(R.id.sendCommentButton)) } fun assertDisplaysEmptyState() { onViewWithText(R.string.no_submission_comments).assertDisplayed() } }
0
Java
0
1
70b0cd08042e05293fc78478f90c3608a31831e1
2,789
instructure-android
Apache License 2.0
app/src/main/java/com/singularity_code/singularitycodebase/ui/activity/providerdemo/ProviderDemoViewModel.kt
SingularityIndonesia
659,777,906
false
null
package com.singularity_code.singularitycodebase.ui.activity.providerdemo import androidx.lifecycle.ViewModel import com.singularity_code.codebase.util.flow.collect import com.singularity_code.codebase.util.flow.lazyFunction import com.singularity_code.codebase.util.flow.provider import com.singularity_code.singularitycodebase.data.SampleRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first class ProviderDemoViewModel( /** * Note that im giving you example as simple as possible so it is less too you to get trough the mechanism; * There fore the architecture might not be satisfying. * But of course for the real world execution, i recommend you to use prefer architecture such Clean Architecture or such. */ private val repository: SampleRepository = SampleRepository() ) : ViewModel() { /** Creating a Provider **/ val sampleProvider by provider(repository::getSample) /** * this is the pattern that I recommended, * I called it "State Automation". * This pattern successfully reduce Code Diversity and remove Side Effects completely. **/ val sampleText: Flow<String> by lazy { // private internal flow val flow = MutableStateFlow("Idle") // updater function val updater = lazyFunction { val isLoading = sampleProvider.loading.first() if (isLoading) { flow.emit("Loading..") return@lazyFunction } val success = sampleProvider.success.first() if (success.first) { flow.emit("Success : ${success.second}") return@lazyFunction } val failed = sampleProvider.failed.first() if (failed.first) { flow.emit("Failed : ${failed.second}") return@lazyFunction } } // state relations run { collect( sampleProvider.state ) { updater.tryInvoke( signature = "sampleProvider.state ${System.currentTimeMillis()}") } } flow } }
0
Kotlin
0
3
38e73034980d0a864b910fd37d57615386e822e2
2,216
AndroidCodebase
MIT License
app/src/main/java/com/shlomikatriel/expensesmanager/preferences/components/SwitchPreference.kt
shlomikatriel
286,574,650
false
null
package com.shlomikatriel.expensesmanager.preferences.components import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.shlomikatriel.expensesmanager.R import com.shlomikatriel.expensesmanager.compose.AppTheme import com.shlomikatriel.expensesmanager.compose.tooling.ComponentPreviews @ComponentPreviews @Composable private fun SwitchPreferencePreview() = AppTheme { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp) ) { SwitchPreference( title = R.string.preferences_anonymous_crash_reports_title, description = R.string.preferences_anonymous_crash_reports_summary, value = false, onValueChanged = { } ) } } @Composable fun SwitchPreference( @StringRes title: Int, @StringRes description: Int, value: Boolean, onValueChanged: (value: Boolean) -> Unit ) = Row( modifier = Modifier .clickable { onValueChanged(!value) } .padding(8.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp) ) { Column( modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp) ) { Text( text = stringResource(title), style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Bold, textAlign = TextAlign.Start ) Text( text = stringResource(description), style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Start ) } Switch( checked = value, onCheckedChange = null ) }
3
Kotlin
0
0
011caec46214aa05d69ea79f3a8d2954296c6890
2,235
BucksBunny
Apache License 2.0
graphql-kotlin-federation/src/test/kotlin/com/expediagroup/graphql/federation/validation/integration/FederatedRequiresDirectiveIT.kt
babyfish-ct
247,506,424
false
null
/* * Copyright 2022 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.generator.federation.validation.integration import com.expediagroup.graphql.generator.TopLevelObject import com.expediagroup.graphql.generator.federation.data.integration.requires.failure._3.RequiresOnLocalTypeQuery import com.expediagroup.graphql.generator.federation.exception.InvalidFederatedSchema import com.expediagroup.graphql.generator.federation.toFederatedSchema import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertTrue class FederatedRequiresDirectiveIT { @Test fun `verifies @requires directive`() { assertDoesNotThrow { val schema = toFederatedSchema(config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.success._1")) val validatedType = schema.getObjectType("SimpleRequires") assertTrue(validatedType.hasDirective("key")) val weightField = validatedType.getFieldDefinition("weight") assertNotNull(weightField) assertNotNull(weightField.getDirective("external")) val requiresField = validatedType.getFieldDefinition("shippingCost") assertNotNull(requiresField) assertNotNull(requiresField.getDirective("requires")) } } @Test fun `@requires directive cannot reference local fields`() { val exception = assertFailsWith<InvalidFederatedSchema> { toFederatedSchema(config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.failure._1")) } val expected = """ Invalid federated schema: - @requires(fields = weight) directive on RequiresLocalField.shippingCost specifies invalid field set - extended type incorrectly references local field=weight """.trimIndent() assertEquals(expected, exception.message) } @Test fun `@requires directive should reference valid fields`() { val exception = assertFailsWith<InvalidFederatedSchema> { toFederatedSchema(config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.failure._2")) } val expected = """ Invalid federated schema: - @requires(fields = zipCode) directive on RequiresNonExistentField.shippingCost specifies invalid field set - field set specifies field that does not exist, field=zipCode """.trimIndent() assertEquals(expected, exception.message) } @Test fun `@requires directive cannot be applied on local type`() { val exception = assertFailsWith<InvalidFederatedSchema> { toFederatedSchema( config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.failure._3"), queries = listOf(TopLevelObject(RequiresOnLocalTypeQuery())) ) } val expectedMessage = """ Invalid federated schema: - base RequiresOnLocalType type has fields marked with @requires directive, validatedField=shippingCost """.trimIndent() assertEquals(expectedMessage, exception.message) } @Test fun `verifies @requires directive on list does not throw`() { assertDoesNotThrow { val schema = toFederatedSchema(config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.success._2")) val validatedType = schema.getObjectType("User") assertTrue(validatedType.hasDirective("key")) val externalField = validatedType.getFieldDefinition("email") assertNotNull(externalField) assertNotNull(externalField.getDirective("external")) val requiresField = validatedType.getFieldDefinition("reviews") assertNotNull(requiresField) assertNotNull(requiresField.getDirective("requires")) } } @Test fun `verifies @requires directive on interface does not throw`() { assertDoesNotThrow { val schema = toFederatedSchema(config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.success._3")) val validatedType = schema.getObjectType("User") assertTrue(validatedType.hasDirective("key")) val externalField = validatedType.getFieldDefinition("email") assertNotNull(externalField) assertNotNull(externalField.getDirective("external")) val requiresField = validatedType.getFieldDefinition("reviews") assertNotNull(requiresField) assertNotNull(requiresField.getDirective("requires")) } } @Test fun `verifies @requires directive on union does not throw`() { assertDoesNotThrow { val schema = toFederatedSchema(config = federatedTestConfig("com.expediagroup.graphql.generator.federation.data.integration.requires.success._4")) val validatedType = schema.getObjectType("User") assertTrue(validatedType.hasDirective("key")) val externalField = validatedType.getFieldDefinition("email") assertNotNull(externalField) assertNotNull(externalField.getDirective("external")) val requiresField = validatedType.getFieldDefinition("reviews") assertNotNull(requiresField) assertNotNull(requiresField.getDirective("requires")) } } }
24
null
273
2
270c0b147753fc5c624de3601e3c064fc8d23946
6,306
graphql-kotlin
Apache License 2.0
build-logic/convention/src/main/kotlin/rt/convention/ecosystem/ext/AndroidComposeExt.kt
queencodemonkey
840,896,614
false
{"Kotlin": 195780}
/* * MIT License * * Copyright (c) 2024 Randomly Typing * * 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 rt.convention.ecosystem.ext import com.android.build.api.dsl.CommonExtension import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies import rt.convention.ext.getPluginId import rt.convention.ext.library import rt.convention.ext.versionCatalog // // This file contains extension methods for configuring Jetpack Compose // in Android plugins. // /** * Configure Compose-specific options for a [Project] that has an * Android plugin (library, application, etc.) applied. * * Adapted from Now in Android: * https://github.com/android/nowinandroid/blob/main/build-logic/convention/src/main/kotlin/com/google/samples/apps/nowinandroid/AndroidCompose.kt */ internal fun Project.configureAndroidCompose(commonExtension: CommonExtension<*, *, *, *, *, *>) { val libs = versionCatalog() with(pluginManager) { apply(libs.getPluginId("kotlin-compose")) } commonExtension.apply { buildFeatures { compose = true } dependencies { val bom = platform(libs.library("compose-bom")) add("implementation", bom) add("implementation", libs.library("compose-ui")) add("implementation", libs.library("compose-ui-graphics")) add("implementation", libs.library("compose-ui-tooling-preview")) add("debugImplementation", bom) add("debugImplementation", libs.library("compose-ui-tooling")) add("lintChecks", libs.library("lint-compose")) } } }
0
Kotlin
0
1
1ad60898776b6bfa8a92bfaa59199ac0c3e741ff
2,657
creating-custom-compose-layouts
MIT License
app/src/main/java/website/grahamearley/placefinder/model/Category.kt
grahamearley
116,883,200
false
null
package website.grahamearley.placefinder.model import android.annotation.SuppressLint import android.os.Parcelable import kotlinx.android.parcel.Parcelize @SuppressLint("ParcelCreator") @Parcelize data class Category( val id: String? = null, val name: String? = null, val pluralName: String? = null, val shortName: String? = null, val icon: Icon? = null ): Parcelable
2
Kotlin
0
2
b59a9f8571ae6c8f2a65fa6ff5d85bd2edb5aa31
379
Place-Finder
MIT License
core/src/main/kotlin/gropius/service/user/AvatarGenerationService.kt
ccims
487,996,394
false
{"Kotlin": 1068191, "TypeScript": 458057, "MDX": 61340, "JavaScript": 27194, "HTML": 19890, "CSS": 4796, "Shell": 2363}
package gropius.service.user import org.springframework.stereotype.Service import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.pow private const val SIZE = 36 /** * Service to generate avatars for users * Based upon https://github.com/boringdesigners/boring-avatars */ @Service class AvatarGenerationService { /** * The default color palette */ private val colors = listOf("#001449","#012677","#005bc5","#00b4fc","#17f9ff") /** * Generates a random avatar for the given id * Avatar is returned as Base64 encoded SVG data url * * @param id The id of the user * @return The avatar as Base64 encoded SVG data url */ fun generateAvatar(id: String): String { val numFromName = max(abs(id.hashCode()), 0) val range = colors.size val preTranslateX = getUnit(numFromName, 10, 1) val wrapperTranslateX = if (preTranslateX < 5) preTranslateX + SIZE / 9.0 else preTranslateX.toDouble() val preTranslateY = getUnit(numFromName, 10, 2) val wrapperTranslateY = if (preTranslateY < 5) preTranslateY + SIZE / 9.0 else preTranslateY.toDouble() val wrapperColor = getRandomColor(numFromName, colors, range) val faceColor = getContrast(wrapperColor) val backgroundColor = getRandomColor(numFromName + 13, colors, range) val wrapperRotate = getUnit(numFromName, 360, 0) val wrapperScale = 1 + getUnit(numFromName, SIZE / 12, 0) / 10.0 val isMouthOpen = getBoolean(numFromName, 3) val isCircle = getBoolean(numFromName, 1) val eyeSpread = getUnit(numFromName, 5, 0) val mouthSpread = getUnit(numFromName, 3, 0) val faceRotate = getUnit(numFromName, 10, 3) val faceTranslateX = if (wrapperTranslateX > SIZE / 6.0) wrapperTranslateX / 2.0 else getUnit(numFromName, 8, 1) val faceTranslateY = if (wrapperTranslateY > SIZE / 6.0) wrapperTranslateY / 2.0 else getUnit(numFromName, 7, 2) val svg = Tag("svg") { attrs["xmlns"] = "http://www.w3.org/2000/svg" attrs["viewBox"] = "0 0 $SIZE $SIZE" tag("g") { tag("rect") { attrs["width"] = SIZE.toString() attrs["height"] = SIZE.toString() attrs["fill"] = backgroundColor } tag("rect") { attrs["x"] = "0" attrs["y"] = "0" attrs["width"] = SIZE.toString() attrs["height"] = SIZE.toString() attrs["transform"] = "translate($wrapperTranslateX $wrapperTranslateY) rotate($wrapperRotate ${SIZE / 2} ${SIZE / 2}) scale($wrapperScale)" attrs["fill"] = wrapperColor attrs["rx"] = if (isCircle) SIZE.toString() else (SIZE / 6).toString() } tag("g") { attrs["transform"] = "translate($faceTranslateX $faceTranslateY) rotate($faceRotate ${SIZE / 2} ${SIZE / 2})" if (isMouthOpen) { tag("path") { attrs["d"] = "M15 ${19 + mouthSpread} c2 1 4 1 6 0" attrs["stroke"] = faceColor attrs["fill"] = "none" attrs["stroke-linecap"] = "round" } } else { tag("path") { attrs["d"] = "M13 ${19 + mouthSpread} a1,0.75 0 0,0 10,0" attrs["fill"] = faceColor } } tag("rect") { attrs["x"] = (14 - eyeSpread).toString() attrs["y"] = "14" attrs["width"] = "1.5" attrs["height"] = "2" attrs["fill"] = faceColor attrs["rx"] = "1" attrs["stroke"] = "none" } tag("rect") { attrs["x"] = (20 + eyeSpread).toString() attrs["y"] = "14" attrs["width"] = "1.5" attrs["height"] = "2" attrs["fill"] = faceColor attrs["rx"] = "1" attrs["stroke"] = "none" } } } } val svgString = svg.toString() return "data:image/svg+xml;base64,${Base64.getEncoder().encodeToString(svgString.toByteArray())}" } /** * Gets a random color from the provided list of colors based on the number * * @param number The number to use to get the color * @param colors The list of colors to choose from * @param range The range of colors to choose from * @return The chosen color */ private fun getRandomColor(number: Int, colors: List<String>, range: Int): String { return colors[number % range] } /** * Generates a number required for rendering the image * * @param number Required for generating the number * @param range Required for generating the number * @param index Required for generating the number * @return The generated number */ private fun getUnit(number: Int, range: Int, index: Int): Int { val value = number % range return if (index != 0 && getDigit(number, index) % 2 == 0) { -value } else { value } } /** * Gets the nth digit of a number, starting from the right * * @param number The number to get the digit from * @param nth The index of the digit to get * @return The digit at the nth index */ private fun getDigit(number: Int, nth: Int): Int { return (number / 10.0.pow(nth)).toInt() % 10 } /** * Gets the contrast color for a given color * * @param color The color to get the contrast for * @return The contrast color */ private fun getContrast(color: String): String { val r = color.substring(1, 3).toInt(16) val g = color.substring(3, 5).toInt(16) val b = color.substring(5, 7).toInt(16) val yiq = (r * 299 + g * 587 + b * 114) / 1000 return if (yiq >= 128) "#000000" else "#ffffff" } /** * Gets whether the nth digit of a number is even * * @param number The number to get the digit from * @param nth The index of the digit to get * @return Whether the nth digit is even */ private fun getBoolean(number: Int, nth: Int): Boolean { return getDigit(number, nth) % 2 == 0 } } /** * Simple DSL for generating SVGs * * @param name The name of the element * @param block The block to execute, used for defining attributes and inner elements */ private class Tag(val name: String, block: Tag.() -> Unit) { /** * The attributes of the tag */ val attrs = mutableMapOf<String, String>() /** * The inner tags of the tag */ private val tags = mutableListOf<Tag>() init { block() } /** * Adds a new inner element * * @param name The name of the element * @param block The block defining the inner element */ fun tag(name: String, block: Tag.() -> Unit) { val tag = Tag(name, block) tags.add(tag) } override fun toString(): String { val attributes = attrs.map { "${it.key}=\"${it.value}\"" }.joinToString(" ") val innerTags = tags.joinToString("") return "<$name $attributes>$innerTags</$name>" } }
7
Kotlin
1
0
02d52ff1076b4d3c75e2000e1c5d0b24daf5f719
7,733
gropius-backend
MIT License
app/src/test/java/com/rstit/connector/ui/main/MainViewModelTest.kt
rstgroup
113,022,246
false
null
package com.rstit.connector.ui.main import com.rstit.connector.BaseTest import com.rstit.connector.di.base.DaggerTestAppComponent import com.rstit.connector.di.main.TestMainModule import com.rstit.connector.model.user.UserRole import com.rstit.connector.ui.base.RowViewModel import io.reactivex.Observable import org.hamcrest.CoreMatchers.* import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.mockito.Matchers import org.mockito.Mockito.`when` import org.mockito.Mockito.verify import javax.inject.Inject /** * @author <NAME> * * * @since 2017-07-24 */ class MainViewModelTest : BaseTest() { @Inject lateinit var model: MainViewModel @Before fun setUp() { DaggerTestAppComponent.builder() .build() .plus(TestMainModule()) .inject(this) } @Test fun checkInitialState() { assertThat(model.loading.get(), `is`(false)) assertThat(model.isEmpty.get(), `is`(false)) assertThat(model.isSendingMessage.get(), `is`(false)) assertThat(model.isChatAvailable.get(), `is`(false)) assertThat(model.isMessageVisible.get(), `is`(false)) assertThat(model.messageToAll.get(), nullValue()) } @Test fun hideMessage() { model.isMessageVisible.set(true) model.messageToAll.set("custom message") model.hideMessage() assertThat(model.isMessageVisible.get(), `is`(false)) assertThat(model.messageToAll.get().isNullOrEmpty(), `is`(true)) verify(model.viewAccess).closeKeyboard() } @Test fun checkChatAvailability_False() { model.checkChatAvailability() assertThat(model.isChatAvailable.get(), `is`(false)) } @Test fun checkChatAvailability_True() { `when`(model.appSettings.userStatus).thenReturn(UserRole.Admin.role) model.checkChatAvailability() assertThat(model.isChatAvailable.get(), `is`(true)) } @Test fun showMessage() { model.isMessageVisible.set(false) model.showMessage() assertThat(model.isMessageVisible.get(), `is`(true)) } @Test fun handleError_NonEmpty() { model.models.add(RowViewModel()) model.handleError() assertThat(model.isEmpty.get(), `is`(false)) } @Test fun handleError_Empty() { model.models.clear() model.handleError() assertThat(model.isEmpty.get(), `is`(true)) } @Test fun handleModels_NotClear() { model.models.add(RowViewModel()) model.handleModels(listOf(RowViewModel()), false) assertThat(model.isEmpty.get(), `is`(false)) assertThat(model.models.size, not(1)) verify(model.viewAccess).notifyDataSetChanged() } @Test fun handleModels_Clear() { model.models.add(RowViewModel()) model.handleModels(listOf(RowViewModel()), true) assertThat(model.isEmpty.get(), `is`(false)) assertThat(model.models.size, `is`(1)) verify(model.viewAccess).notifyDataSetChanged() } @Test fun sendMessageToAll() { model.messageToAll.set("custom message") `when`(model.api.sendMessageToAll(any())).thenReturn(Observable.just(response(true))) model.sendMessageToAll() verify(model.api).sendMessageToAll(any()) } @Test fun loadDate() { `when`(model.api.getInbox(Matchers.anyInt(), Matchers.anyInt())).thenReturn(Observable.just(inboxResponse)) model.loadData(0, clear = true) verify(model.api).getInbox(0) } @Test fun displaySuccess() { model.displaySuccess() verify(model.viewAccess).closeKeyboard() } }
0
Kotlin
0
0
4385ffd936f56a53aa1db9a83da4c9f3c3488fc9
3,725
rst-connector
Apache License 2.0
compiler/testData/diagnostics/tests/sealed/TreeWhenFunctional.fir.kt
JetBrains
3,432,266
false
null
sealed class Tree { object Empty: Tree() class Leaf(val x: Int): Tree() class Node(val left: Tree, val right: Tree): Tree() fun max(): Int = when(this) { is Empty -> -1 is Leaf -> this.x is Node -> this.left.max() } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
265
kotlin
Apache License 2.0