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
src/main/kotlin/no/nav/brukerdialog/ytelse/omsorgpengerutbetalingsnf/api/domene/OmsorgspengerutbetalingSnfKomplettSøknad.kt
navikt
585,578,757
false
{"Kotlin": 1442489, "Handlebars": 126943, "Dockerfile": 98}
package no.nav.brukerdialog.ytelse.omsorgpengerutbetalingsnf.api.domene import no.nav.k9.søknad.Søknad import no.nav.k9.søknad.felles.type.SøknadId import no.nav.brukerdialog.domenetjenester.innsending.KomplettInnsending import no.nav.brukerdialog.ytelse.fellesdomene.Bekreftelser import no.nav.brukerdialog.ytelse.fellesdomene.Bosted import no.nav.brukerdialog.ytelse.fellesdomene.Opphold import no.nav.brukerdialog.ytelse.fellesdomene.Utbetalingsperiode import no.nav.brukerdialog.ytelse.fellesdomene.Virksomhet import no.nav.brukerdialog.oppslag.soker.Søker import java.time.ZoneOffset import java.time.ZonedDateTime import java.util.* class OmsorgspengerutbetalingSnfKomplettSøknad( internal val søknadId: SøknadId = SøknadId(UUID.randomUUID().toString()), private val mottatt: ZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC), private val språk: String, private val søker: Søker, private val bosteder: List<Bosted>, private val opphold: List<Opphold>, private val spørsmål: List<SpørsmålOgSvar>, private val harDekketTiFørsteDagerSelv: Boolean? = null, private val harSyktBarn: Boolean? = null, private val harAleneomsorg: Boolean? = null, private val bekreftelser: Bekreftelser, private val utbetalingsperioder: List<Utbetalingsperiode>, private val erArbeidstakerOgså: Boolean, private val barn: List<Barn>, private val frilans: Frilans? = null, private val selvstendigNæringsdrivende: Virksomhet? = null, private val vedleggId: List<String> = listOf(), private val titler: List<String>, private val k9FormatSøknad: Søknad, ) : KomplettInnsending
4
Kotlin
0
0
7c29304e39924a70fdbb7270c9dd4669bb70a150
1,633
k9-brukerdialog-prosessering
MIT License
kontroller/src/main/kotlin/no/ssb/kostra/validation/rule/famvern/famvern52a/Rule038Ventetid.kt
statisticsnorway
414,216,275
false
{"Kotlin": 1524176, "TypeScript": 58079, "HTML": 694, "SCSS": 110}
package no.ssb.kostra.validation.rule.famvern.famvern52a import no.ssb.kostra.area.famvern.famvern52a.Familievern52aColumnNames.FORSTE_SAMT_A_COL_NAME import no.ssb.kostra.area.famvern.famvern52a.Familievern52aColumnNames.HENV_DATO_A_COL_NAME import no.ssb.kostra.area.famvern.famvern52a.Familievern52aColumnNames.JOURNAL_NR_A_COL_NAME import no.ssb.kostra.area.famvern.famvern52a.Familievern52aColumnNames.KONTOR_NR_A_COL_NAME import no.ssb.kostra.program.KostraRecord import no.ssb.kostra.program.extension.fieldAs import no.ssb.kostra.validation.report.Severity import no.ssb.kostra.validation.rule.AbstractNoArgsRule import java.time.LocalDate class Rule038Ventetid : AbstractNoArgsRule<List<KostraRecord>>( Familievern52aRuleId.FAMILIEVERN52A_RULE038.title, Severity.WARNING ) { override fun validate(context: List<KostraRecord>) = context .filter { it[HENV_DATO_A_COL_NAME].isNotBlank() && it[FORSTE_SAMT_A_COL_NAME].isNotBlank() } .filterNot { it.fieldAs<LocalDate?>(HENV_DATO_A_COL_NAME) != null && it.fieldAs<LocalDate?>(FORSTE_SAMT_A_COL_NAME) != null && it.fieldAs<LocalDate>(HENV_DATO_A_COL_NAME) .plusYears(1L) .plusDays(1L) .isAfter(it.fieldAs<LocalDate>(FORSTE_SAMT_A_COL_NAME)) } .map { createValidationReportEntry( messageText = "Dato for primærklientens henvendelse '${it[HENV_DATO_A_COL_NAME]}' " + "til familievernkontoret er mer enn 1 år før første behandlingssamtale " + "'${it[FORSTE_SAMT_A_COL_NAME]}'.", lineNumbers = listOf(it.lineNumber) ).copy( caseworker = it[KONTOR_NR_A_COL_NAME], journalId = it[JOURNAL_NR_A_COL_NAME] ) } .ifEmpty { null } }
2
Kotlin
0
1
7f0ff824cb1328ec5a0a3232c8e271d20c6b16ae
1,923
kostra-kontrollprogram
MIT License
app/src/main/java/com/moos/constraint/widget/ViewPagerHeader.kt
jvyun
205,815,662
true
{"Kotlin": 13753}
package com.moos.constraint.widget import android.content.Context import android.support.constraint.motion.MotionLayout import android.support.v4.view.ViewPager import android.util.AttributeSet import android.util.Log class ViewpagerHeader @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : MotionLayout(context, attrs, defStyleAttr), ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { val animateProgress = (position.toFloat() + positionOffset)/3 Log.e("LottieMotionActivity", "viewpager scroll progress is: $animateProgress") progress = animateProgress } override fun onPageSelected(position: Int) { } }
0
Kotlin
0
1
882ce00144bbdac9b1ad9047f7ddeb80a6a2b52c
842
ConstraintSample
MIT License
src/main/java/org/springframework/samples/petclinic/sfg/LaurelWordProducer.kt
adrianbadarau
179,500,879
true
{"Batchfile": 1, "Shell": 1, "Maven POM": 1, "Ignore List": 1, "Text": 3, "Markdown": 1, "Java": 61, "Kotlin": 11, "XML": 11, "Less": 4, "SVG": 2, "Java Server Pages": 19, "INI": 3, "SQL": 6, "Java Properties": 2}
package org.springframework.samples.petclinic.sfg import org.springframework.context.annotation.Primary import org.springframework.stereotype.Component @Component @Primary class LaurelWordProducer : WordProducer { override fun getWord(): String { return "Laurel" } }
0
Java
0
0
b7647c7b44152b8e7303542c62763efbea654e84
285
tb2g-testing-spring
Apache License 2.0
processor/src/main/java/com/joom/lightsaber/processor/io/FileSink.kt
joomcode
170,310,869
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.grip.io import java.io.Closeable import java.io.File interface FileSink : Closeable { fun createFile(path: String, data: ByteArray) fun createDirectory(path: String) fun flush() interface Factory { fun createFileSink(inputFile: File, outputFile: File): FileSink } }
2
null
8
9
f1eede8e14ecb399a451085fd5d13e77dd67f329
898
lightsaber
Apache License 2.0
app/src/main/java/com/assistne/kotlintodoapp/BasePresenter.kt
AssIstne
82,243,970
false
null
package com.assistne.kotlintodoapp /** * Created by assistne on 17/2/17. */ interface BasePresenter { fun start() }
0
Kotlin
0
0
75b055155d2b15dfb487c9a962c7ef15ccde914d
122
KotlinTodoApp
MIT License
src/en/vidembed/src/eu/kanade/tachiyomi/animeextension/en/vidembed/Vidembed.kt
jmir1
360,630,872
false
null
package eu.kanade.tachiyomi.animeextension.en.vidembed import android.app.Application import android.content.SharedPreferences import android.net.Uri import androidx.preference.ListPreference import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.animeextension.en.vidembed.extractors.StreamSBExtractor import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource import eu.kanade.tachiyomi.animesource.model.AnimeFilterList import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.lang.Exception class Vidembed : ConfigurableAnimeSource, ParsedAnimeHttpSource() { override val name = "Vidembed" override val baseUrl = "https://vidembed.io" override val lang = "en" override val supportsLatest = false override val client: OkHttpClient = network.cloudflareClient private val downloadLink = "https://vidembed.io/download?id=" private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override fun popularAnimeSelector(): String = ".video-block a" override fun popularAnimeRequest(page: Int): Request = GET("$baseUrl/?page=$page") override fun popularAnimeFromElement(element: Element): SAnime { val anime = SAnime.create() anime.setUrlWithoutDomain(element.attr("href")) anime.thumbnail_url = element.select("img").first().attr("src") anime.title = element.select(".name").first().text().split("Episode").first() return anime } override fun popularAnimeNextPageSelector(): String = "ul.pagination li:last-child:not(.selected)" override fun episodeListSelector() = "ul.listing.items.lists li a" override fun episodeListParse(response: Response): List<SEpisode> { val document = response.asJsoup() return document.select(episodeListSelector()).map { episodeFromElement(it) } } override fun episodeFromElement(element: Element): SEpisode { val episode = SEpisode.create() episode.setUrlWithoutDomain(baseUrl + element.attr("href")) val epName = element.selectFirst("div.name").ownText() val ep = epName.substringAfter("Episode ") val epNo = try { ep.substringBefore(" ").toFloat() } catch (e: NumberFormatException) { 0.toFloat() } episode.episode_number = epNo episode.name = if (ep == epName) epName else "Episode $ep" episode.date_upload = System.currentTimeMillis() return episode } override fun videoListRequest(episode: SEpisode): Request { val document = client.newCall(GET(baseUrl + episode.url)).execute().asJsoup() val link = document.selectFirst(".play-video iframe").attr("src") val id = Uri.parse(link).getQueryParameter("id").toString() return GET(downloadLink + id) } override fun videoListParse(response: Response): List<Video> { val document = response.asJsoup() return videosFromElement(document) } private fun videosFromElement(document: Document): List<Video> { val videoList = mutableListOf<Video>() val elements = document.select(videoListSelector()) for (element in elements) { val quality = element.text().substringAfter("Download (").replace("P - mp4)", "p") val url = element.attr("href") val location = element.ownerDocument().location() val videoHeaders = Headers.headersOf("Referer", location) when { url.contains("https://dood") -> { val newQuality = "Doodstream mirror" val video = try { Video(url, newQuality, doodUrlParse(url), null, videoHeaders) } catch (e: Exception) { null } if (video != null) videoList.add(video) } url.contains("https://sbplay") -> { val newUrl = url.replace("/d/", "/e/") val headers = headers.newBuilder() .set("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0") .set("Accept-Language", "en-US,en;q=0.5") .set("watchsb", "streamsb") .build() val videos = StreamSBExtractor(client).videosFromUrl(newUrl, headers) videoList.addAll(videos) } else -> { val parsedQuality = when (quality) { "FullHDp" -> "1080p" "HDp" -> "720p" "SDp" -> "360p" else -> quality } val video = Video(url, parsedQuality, videoUrlParse(url, location), null, videoHeaders) videoList.add(video) } } } return videoList } override fun videoListSelector() = "div.mirror_link a[download], div.mirror_link a[href*=https://dood],div.mirror_link a[href*=https://sbplay]" override fun videoFromElement(element: Element): Video = throw Exception("not used") override fun videoUrlParse(document: Document) = throw Exception("not used") private fun videoUrlParse(url: String, referer: String): String { val refererHeader = Headers.headersOf("Referer", referer) val noRedirectClient = client.newBuilder().followRedirects(false).build() val response = noRedirectClient.newCall(GET(url, refererHeader)).execute() val videoUrl = response.header("location") response.close() return videoUrl ?: url } private fun doodUrlParse(url: String): String? { val response = client.newCall(GET(url.replace("/d/", "/e/"))).execute() val content = response.body!!.string() if (!content.contains("'/pass_md5/")) return null val md5 = content.substringAfter("'/pass_md5/").substringBefore("',") val token = md5.substringAfterLast("/") val doodTld = url.substringAfter("https://dood.").substringBefore("/") val randomString = getRandomString() val expiry = System.currentTimeMillis() val videoUrlStart = client.newCall( GET( "https://dood.$doodTld/pass_md5/$md5", Headers.headersOf("referer", url) ) ).execute().body!!.string() return "$videoUrlStart$randomString?token=$token&expiry=$expiry" } private fun getRandomString(length: Int = 10): String { val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9') return (1..length) .map { allowedChars.random() } .joinToString("") } override fun List<Video>.sort(): List<Video> { val quality = preferences.getString("preferred_quality", null) if (quality != null) { val newList = mutableListOf<Video>() var preferred = 0 for (video in this) { if (video.quality.contains(quality)) { newList.add(preferred, video) preferred++ } else { newList.add(video) } } return newList } return this } override fun searchAnimeFromElement(element: Element): SAnime { val anime = SAnime.create() anime.setUrlWithoutDomain(element.attr("href")) anime.thumbnail_url = element.select("img").first().attr("src") anime.title = element.select(".name").first().text().split("Episode").first() return anime } override fun searchAnimeNextPageSelector(): String = "ul.pagination-list li:last-child:not(.selected)" override fun searchAnimeSelector(): String = ".video-block a" override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request { return when { query.isNotBlank() -> GET("$baseUrl/search.html?keyword=$query&page=$page", headers) else -> GET("$baseUrl/?page=$page") } } override fun animeDetailsParse(document: Document): SAnime { val anime = SAnime.create() anime.title = document.select(".video-details span").text() anime.description = document.select(".video-details .post-entry .content-more-js").text() return anime } override fun latestUpdatesNextPageSelector(): String = throw Exception("Not used") override fun latestUpdatesFromElement(element: Element): SAnime = throw Exception("Not used") override fun latestUpdatesRequest(page: Int): Request = throw Exception("Not used") override fun latestUpdatesSelector(): String = throw Exception("Not used") override fun setupPreferenceScreen(screen: PreferenceScreen) { val videoQualityPref = ListPreference(screen.context).apply { key = "preferred_quality" title = "Preferred quality" entries = arrayOf("1080p", "720p", "480p", "360p") entryValues = arrayOf("1080", "720", "480", "360") setDefaultValue("1080") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } screen.addPreference(videoQualityPref) } }
84
null
30
84
3c7386f566efc05b5b9a4fdb537e9a201ee4b67f
10,120
aniyomi-extensions
Apache License 2.0
model/src/main/kotlin/AdvisorCapability.kt
oss-review-toolkit
107,540,288
false
null
/* * Copyright (C) 2021 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.model /** * An enum class that defines the capabilities of a specific advisor implementation. * * There are multiple types of findings that can be retrieved by an advisor, such as security vulnerabilities or * defects. An [AdvisorResult] has different fields for the different findings types. This enum corresponds to these * fields. It allows an advisor implementation to declare, which of these fields it can populate. This information is * of interest, for instance, when generating reports for specific findings to determine, which advisor may have * contributed. */ enum class AdvisorCapability { /** Indicates that an advisor can retrieve information about defects. */ DEFECTS, /** Indicates that an advisor can retrieve information about security vulnerabilities. */ VULNERABILITIES }
304
Kotlin
309
873
0546d450d3082cff0c685897bef4c23e56a3d73a
1,598
ort
Apache License 2.0
client/src/commonMain/kotlin/com/algolia/client/model/analytics/GetStatusResponse.kt
algolia
153,273,215
false
{"Kotlin": 1427996}
/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ package com.algolia.client.model.analytics import kotlinx.serialization.* import kotlinx.serialization.json.* /** * GetStatusResponse * * @param updatedAt Date and time when the object was updated, in RFC 3339 format. */ @Serializable public data class GetStatusResponse( /** Date and time when the object was updated, in RFC 3339 format. */ @SerialName(value = "updatedAt") val updatedAt: String, )
15
Kotlin
23
59
7d994efaee2fba70a7b4396a44e3f484b7b16463
596
algoliasearch-client-kotlin
MIT License
compiler/testData/codegen/box/coroutines/suspensionInsideSafeCall.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND: JS_IR // WITH_RUNTIME // WITH_COROUTINES // COMMON_COROUTINES_TEST import helpers.* import COROUTINES_PACKAGE.* import COROUTINES_PACKAGE.intrinsics.* suspend fun suspendHere(): String = suspendCoroutineOrReturn { x -> x.resume("OK") COROUTINE_SUSPENDED } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var result = "" builder { result = suspendHere() } return result }
2
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
478
kotlin
Apache License 2.0
compiler/testData/codegen/box/coroutines/suspensionInsideSafeCall.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND: JS_IR // WITH_RUNTIME // WITH_COROUTINES // COMMON_COROUTINES_TEST import helpers.* import COROUTINES_PACKAGE.* import COROUTINES_PACKAGE.intrinsics.* suspend fun suspendHere(): String = suspendCoroutineOrReturn { x -> x.resume("OK") COROUTINE_SUSPENDED } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var result = "" builder { result = suspendHere() } return result }
2
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
478
kotlin
Apache License 2.0
libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/KDocConfig.kt
chirino
3,596,099
false
null
package org.jetbrains.kotlin.doc import java.util.* import org.jetbrains.kotlin.doc.model.KPackage /** * The configuration used with KDoc */ class KDocConfig() { /** * Returns the directory to use to output the API docs */ public var docOutputDir: String = "target/site/apidocs" /** * Returns the name of the documentation set */ public var title: String = "Documentation" /** * Returns the version name of the documentation set */ public var version: String = "SNAPSHOT" /** * Returns a map of the package prefix to the HTML URL for the root of the apidoc using javadoc/kdoc style * directory layouts so that this API doc report can link to external packages */ public val packagePrefixToUrls: MutableMap<String, String> = TreeMap<String, String>(LongestFirstStringComparator()) /** * Returns a Set of the package name prefixes to ignore from the KDoc report */ public val ignorePackages: MutableSet<String> = HashSet<String>() /** * Returns true if a warning should be generated if there are no comments * on documented function or property */ public var warnNoComments: Boolean = true /** * Returns the HTTP URL of the root directory of source code that we should link to */ public var sourceRootHref: String? = null /** * The root project directory used to deduce relative file names when linking to source code */ public var projectRootDir: String? = null /** * A map of package name to html or markdown files used to describe the package. If none is * specified we will look for a package.html or package.md file in the source tree */ public var packageDescriptionFiles: MutableMap<String,String> = HashMap<String,String>() /** * A map of package name to summary text used in the package overviews */ public var packageSummaryText: MutableMap<String,String> = HashMap<String, String>() /** * Returns true if protected functions and properties should be documented */ public var includeProtected: Boolean = true { // add some common defaults addPackageLink("http://docs.oracle.com/javase/6/docs/api/", "java", "org.w3c.dom", "org.xml.sax", "org.omg", "org.ietf.jgss") addPackageLink("http://kentbeck.github.com/junit/javadoc/latest/", "org.junit", "junit") } /** * Returns a set of all the package which have been warned that were missing an external URL */ private val mutableMissingPackageUrls: MutableSet<String> = TreeSet<String>() public val missingPackageUrls: Set<String> = mutableMissingPackageUrls /** * Adds one or more package prefixes to the given javadoc URL */ fun addPackageLink(url: String, vararg packagePrefixes: String): Unit { for (p in packagePrefixes) { packagePrefixToUrls.put(p, url) } } /** * Resolves a link to the given class name */ fun resolveLink(packageName: String, warn: Boolean = true): String { for (e in packagePrefixToUrls) { val p = e.key val url = e.value if (packageName.startsWith(p)) { return url } } if (warn && mutableMissingPackageUrls.add(packageName)) { println("Warning: could not find external link to package: $packageName") } return "" } /** * Returns true if the package should be included in the report */ fun includePackage(pkg: KPackage): Boolean { return !ignorePackages.any{ pkg.name.startsWith(it) } } } private class LongestFirstStringComparator() : Comparator<String> { public override fun compare(s1: String, s2: String): Int { return compareBy<String>(s1, s2, { length() }, { this }) } public override fun equals(obj : Any?) : Boolean { return obj is LongestFirstStringComparator } }
0
null
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
3,982
kotlin
Apache License 2.0
app/src/main/java/net/assemble/android/mywallet/activity/BaseActivity.kt
yh1224
116,141,430
false
null
package net.assemble.android.mywallet.activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.github.salomonbrys.kodein.KodeinInjected import com.github.salomonbrys.kodein.KodeinInjector import com.github.salomonbrys.kodein.android.AppCompatActivityInjector abstract class BaseActivity : AppCompatActivity() , AppCompatActivityInjector, KodeinInjected { override val injector: KodeinInjector = KodeinInjector() //override fun provideOverridingModule() = Kodein.Module { // import(activityModule(this@BaseActivity)) //} override fun onCreate(savedInstanceState: Bundle?) { initializeInjector() super.onCreate(savedInstanceState) } override fun onDestroy() { destroyInjector() super.onDestroy() } }
0
Kotlin
0
0
a170d22b92ddec2b781a495cb81f7d5678b2a3a9
814
wastlet
Apache License 2.0
liveedgedetection/src/main/java/info/hannes/liveedgedetection/ScanHint.kt
prahlad-dev
649,291,735
false
{"Java": 1201072, "Kotlin": 78358, "Shell": 935}
package info.hannes.liveedgedetection /** * Enum that defines receipt detection messages */ enum class ScanHint { MOVE_AWAY, MOVE_CLOSER, FIND_RECT, ADJUST_ANGLE, CAPTURING_IMAGE, NO_MESSAGE }
7
null
1
1
fa95f83490f8c2866d7e70ce655722b69c57f83d
199
edgeDetect
Apache License 2.0
src/main/kotlin/com/workos/webhooks/models/DirectoryGroupUserAddedEvent.kt
workos
419,780,611
false
null
package com.workos.webhooks.models import com.fasterxml.jackson.annotation.JsonCreator /** * Webhook Event for `dsync.group.user_added`. */ class DirectoryGroupUserAddedEvent @JsonCreator constructor( @JvmField override val id: String, @JvmField override val event: EventType, @JvmField override val data: DirectoryGroupUserEvent, @JvmField override val createdAt: String ) : WebhookEvent(id, event, data, createdAt)
1
Kotlin
6
9
8be0571a48e643cea2f0c783ddb4c5fa79be1ed5
440
workos-kotlin
MIT License
src/main/kotlin/eu/automateeverything/tabletsplugin/TabletPort.kt
tomaszbabiuk
669,691,372
false
{"Kotlin": 67706}
/* * Copyright (c) 2019-2023 Tomasz Babiuk * * 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 eu.automateeverything.tabletsplugin import eu.automateeverything.domain.events.EventBus import eu.automateeverything.domain.hardware.Port import eu.automateeverything.domain.hardware.PortCapabilities import eu.automateeverything.tabletsplugin.interop.DashboardItem import java.util.* import kotlinx.coroutines.* import org.eclipse.californium.core.CoapClient class TabletPort( factoryId: String, adapterId: String, portId: String, eventBus: EventBus, lastSeenTimestamp: Long, private val aeClient: AETabletClient, private var operationScope: CoroutineScope? = null ) : Port<TabletConnectorPortValue>( factoryId, adapterId, portId, eventBus, TabletConnectorPortValue::class.java, PortCapabilities(canRead = true, canWrite = false), 2 * 60 * 1000 ) { init { updateLastSeenTimeStamp(lastSeenTimestamp) } private var lastValue = TabletConnectorPortValue(TabletUIState(0, null)) private var actionsClient: CoapClient? = null override fun readInternal(): TabletConnectorPortValue { return lastValue } fun start() { operationScope = CoroutineScope(Dispatchers.IO) actionsClient = aeClient.observeDashboard { lastValue = TabletConnectorPortValue(TabletUIState(it.id, it.buttonRef)) notifyValueUpdate() updateLastSeenTimeStamp(Calendar.getInstance().timeInMillis) } operationScope?.launch { while (isActive) { delay(500) try { aeClient.releasePutQueue() } catch (ex: Exception) { println(ex) } } } } fun stop() { actionsClient?.shutdown() operationScope?.cancel() } fun updateDashboard(title: String, dashboardId: Long, content: DashboardItem) { aeClient.changeDashboard(title, dashboardId, content) } }
0
Kotlin
0
0
a5b79f17fc62c81ca14246d20139c20d6187b856
2,633
aeplugin-tablets
Apache License 2.0
src/main/kotlin/io/opengood/gradle/constant/Configurations.kt
opengoodio
314,074,661
false
null
package io.opengood.gradle.constant class Configurations { companion object { const val ANNOTATION_PROCESSOR = "annotationProcessor" const val IMPLEMENTATION = "implementation" const val TEST_ANNOTATION_PROCESSOR = "testAnnotationProcessor" const val TEST_IMPLEMENTATION = "testImplementation" } }
0
Kotlin
0
0
c99b8241f3a15554320d1c9cd56728dbf0baf477
340
config-gradle-plugin
MIT License
src/main/kotlin/com/projectcitybuild/modules/errorreporting/adapters/SentryErrorReporter.kt
projectcitybuild
42,997,941
false
null
package com.projectcitybuild.modules.errorreporting.adapters import com.projectcitybuild.modules.config.ConfigKey import com.projectcitybuild.modules.config.PlatformConfig import com.projectcitybuild.modules.errorreporting.ErrorReporter import com.projectcitybuild.modules.logger.PlatformLogger import dagger.Reusable import io.sentry.Sentry @Reusable class SentryErrorReporter( private val config: PlatformConfig, private val logger: PlatformLogger, ): ErrorReporter { override fun bootstrap() { val enabled = config.get(ConfigKey.ERROR_REPORTING_SENTRY_ENABLED) if (!enabled) return logger.info("Enabling error reporting") Sentry.init { options -> options.dsn = config.get(ConfigKey.ERROR_REPORTING_SENTRY_DSN) } } override fun report(throwable: Throwable) { Sentry.captureException(throwable) } }
8
Kotlin
0
2
670536a5832dd6c3dbde0ba2f94f74a6ec576ed3
889
PCBridge
MIT License
src/test/kotlin/com/code_intelligence/cifuzz/test/android/MultiProjectAndroidAppReleaseVariantTest.kt
CodeIntelligenceTesting
613,793,747
false
{"Kotlin": 56168}
package com.code_intelligence.cifuzz.test.android class MultiProjectAndroidAppReleaseVariantTest : MultiProjectAndroidTest() { override fun testedAndroidVariant() = listOf("release") }
0
Kotlin
0
4
4e4b1952cebe2ed63a7a2c5e1e60570b95dc7d01
192
cifuzz-gradle-plugin
Apache License 2.0
kotlin-analysers/src/test/resources/org/jetbrains/research/lupa/kotlinAnalysis/dependencies/analysis/data/gradle_projects/in_0_dataset_gradle_groovy_one_module/sample_project/src/main/kotlin/com/jetbrains/kotlin/analysis/test/project/one/OneImportClass.kt
nbirillo
353,952,951
false
null
package com.jetbrains.kotlin.analysis.test.project.one import kotlinx.coroutines.delay class OneImportClass { suspend fun importUsage(): Int { delay(1000L) return 29 } }
7
Jupyter Notebook
5
25
c4875ccd6762d779bff8b3da37690360253a74fb
198
Lupa
Apache License 2.0
kotlin-analysers/src/test/resources/org/jetbrains/research/lupa/kotlinAnalysis/dependencies/analysis/data/gradle_projects/in_0_dataset_gradle_groovy_one_module/sample_project/src/main/kotlin/com/jetbrains/kotlin/analysis/test/project/one/OneImportClass.kt
nbirillo
353,952,951
false
null
package com.jetbrains.kotlin.analysis.test.project.one import kotlinx.coroutines.delay class OneImportClass { suspend fun importUsage(): Int { delay(1000L) return 29 } }
7
Jupyter Notebook
5
25
c4875ccd6762d779bff8b3da37690360253a74fb
198
Lupa
Apache License 2.0
features/lockscreen/impl/src/main/kotlin/io/element/android/features/lockscreen/impl/settings/LockScreenSettingsFlowNode.kt
element-hq
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.lockscreen.impl.settings import android.os.Parcelable import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.lifecycleScope import com.bumble.appyx.core.lifecycle.subscribe import com.bumble.appyx.core.modality.BuildContext import com.bumble.appyx.core.node.Node import com.bumble.appyx.core.node.node import com.bumble.appyx.core.plugin.Plugin import com.bumble.appyx.navmodel.backstack.BackStack import com.bumble.appyx.navmodel.backstack.operation.newRoot import com.bumble.appyx.navmodel.backstack.operation.push import dagger.assisted.Assisted import dagger.assisted.AssistedInject import io.element.android.anvilannotations.ContributesNode import io.element.android.features.lockscreen.impl.pin.DefaultPinCodeManagerCallback import io.element.android.features.lockscreen.impl.pin.PinCodeManager import io.element.android.features.lockscreen.impl.setup.pin.SetupPinNode import io.element.android.features.lockscreen.impl.unlock.PinUnlockNode import io.element.android.libraries.architecture.BackstackView import io.element.android.libraries.architecture.BaseFlowNode import io.element.android.libraries.architecture.createNode import io.element.android.libraries.di.SessionScope import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.parcelize.Parcelize @ContributesNode(SessionScope::class) class LockScreenSettingsFlowNode @AssistedInject constructor( @Assisted buildContext: BuildContext, @Assisted plugins: List<Plugin>, private val pinCodeManager: PinCodeManager, ) : BaseFlowNode<LockScreenSettingsFlowNode.NavTarget>( backstack = BackStack( initialElement = NavTarget.Unknown, savedStateMap = buildContext.savedStateMap, ), buildContext = buildContext, plugins = plugins, ) { sealed interface NavTarget : Parcelable { @Parcelize data object Unknown : NavTarget @Parcelize data object Unlock : NavTarget @Parcelize data object SetupPin : NavTarget @Parcelize data object Settings : NavTarget } private val pinCodeManagerCallback = object : DefaultPinCodeManagerCallback() { override fun onPinCodeRemoved() { navigateUp() } override fun onPinCodeCreated() { backstack.newRoot(NavTarget.Settings) } } override fun onBuilt() { super.onBuilt() lifecycleScope.launch { val hasPinCode = pinCodeManager.hasPinCode().first() if (hasPinCode) { backstack.newRoot(NavTarget.Unlock) } else { backstack.newRoot(NavTarget.SetupPin) } } lifecycle.subscribe( onCreate = { pinCodeManager.addCallback(pinCodeManagerCallback) }, onDestroy = { pinCodeManager.removeCallback(pinCodeManagerCallback) } ) } override fun resolve(navTarget: NavTarget, buildContext: BuildContext): Node { return when (navTarget) { NavTarget.Unlock -> { val callback = object : PinUnlockNode.Callback { override fun onUnlock() { backstack.newRoot(NavTarget.Settings) } } createNode<PinUnlockNode>(buildContext, plugins = listOf(callback)) } NavTarget.SetupPin -> { createNode<SetupPinNode>(buildContext) } NavTarget.Settings -> { val callback = object : LockScreenSettingsNode.Callback { override fun onChangePinClick() { backstack.push(NavTarget.SetupPin) } } createNode<LockScreenSettingsNode>(buildContext, plugins = listOf(callback)) } NavTarget.Unknown -> node(buildContext) { } } } @Composable override fun View(modifier: Modifier) { BackstackView() } }
263
null
65
955
31d0621fa15fe153bfd36104e560c9703eabe917
4,713
element-x-android
Apache License 2.0
client-android/app/src/main/java/stasis/client_android/tracking/RecoveryTrackerView.kt
sndnv
153,169,374
false
{"Scala": 3373826, "Kotlin": 1821771, "Dart": 853650, "Python": 363474, "Shell": 70265, "CMake": 8759, "C++": 4051, "HTML": 2655, "Dockerfile": 1942, "Ruby": 1330, "C": 691, "Swift": 594, "JavaScript": 516}
package stasis.client_android.tracking import androidx.lifecycle.LiveData import stasis.client_android.lib.ops.OperationId import stasis.client_android.lib.tracking.state.RecoveryState interface RecoveryTrackerView : RecoveryTrackerManage { val state: LiveData<Map<OperationId, RecoveryState>> fun updates(operation: OperationId): LiveData<RecoveryState> }
0
Scala
4
53
d7b3002880814039b332b3d5373a16b57637eb1e
367
stasis
Apache License 2.0
app/src/main/java/ml/dvnlabs/animize/ui/recyclerview/comment/CommentMainAdapter.kt
rootdavinalfa
177,693,326
false
null
/* * Copyright (c) 2020. * Animize Devs * Copyright 2019 - 2020 * <NAME> <<EMAIL>> * This program used for watching anime without ads. * */ package ml.dvnlabs.animize.ui.recyclerview.comment import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import ml.dvnlabs.animize.model.CommentMainModel import java.util.* class CommentMainAdapter(private val commentMainModels: ArrayList<CommentMainModel>?, private val mcontext: Context, private val itemResor: Int) : RecyclerView.Adapter<CommentMainHolder>() { override fun onBindViewHolder(holder: CommentMainHolder, position: Int) { val slm = commentMainModels!![position] holder.bindComment(slm) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentMainHolder { val view = LayoutInflater.from(parent.context).inflate(itemResor, parent, false) return CommentMainHolder(mcontext, view) } override fun getItemCount(): Int { return commentMainModels?.size ?: 0 } }
1
Kotlin
1
2
c12aa046a42712794dc3f7e06dbbcee654c1e79f
1,096
animize
Apache License 2.0
android/src/main/java/drawbox/android/MainActivity.kt
MarkYav
616,161,838
false
null
package drawbox.android import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageBitmapConfig import androidx.compose.ui.unit.dp import drawbox.common.box.DrawBox import drawbox.common.controller.DrawBoxBackground import drawbox.common.controller.DrawController class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { val controller = remember { DrawController() } val bitmap by controller.getBitmapFlow(250).collectAsState(ImageBitmap(250, 250, ImageBitmapConfig.Argb8888)) controller.background = DrawBoxBackground.ColourBackground(color = Color.Blue, alpha = 0.15f) controller.canvasOpacity = 0.5f Row { DrawBox( controller = controller, modifier = Modifier .fillMaxHeight() .aspectRatio(1f) .padding(100.dp) .border(width = 1.dp, color = Color.Blue), ) Column { Text("Result:") Image( bitmap, contentDescription = "drawn bitmap", modifier = Modifier.size(250.dp).border(width = 1.dp, color = Color.Red), ) } } } } } }
0
Kotlin
0
0
79eea9f8d83f76b44d6f2767bc93417a9b7f5231
2,145
DrawBox-alpha
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/resolve/OperatorModifierChecker.kt
guiping
49,639,828
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.resolve import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.util.OperatorChecks public class OperatorModifierChecker : DeclarationChecker { override fun check( declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink, bindingContext: BindingContext ) { val functionDescriptor = descriptor as? FunctionDescriptor ?: return if (!functionDescriptor.isOperator) return val modifier = declaration.modifierList?.getModifier(KtTokens.OPERATOR_KEYWORD) ?: return if (!OperatorChecks.canBeOperator(functionDescriptor)) { diagnosticHolder.report(Errors.INAPPLICABLE_OPERATOR_MODIFIER.on(modifier)) } } }
0
null
1
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
2,268
kotlin
Apache License 2.0
year2020/day10/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day10/part1/Year2020Day10Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2014224}
/* --- Day 10: Adapter Array --- Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off! Its battery is dead. You'll need to plug it in. There's only one problem: the charging outlet near your seat produces the wrong number of jolts. Always prepared, you make a list of all of the joltage adapters in your bag. Each of your joltage adapters is rated for a specific output joltage (your puzzle input). Any given adapter can take an input 1, 2, or 3 jolts lower than its rating and still produce its rated output joltage. In addition, your device has a built-in joltage adapter rated for 3 jolts higher than the highest-rated adapter in your bag. (If your adapter list were 3, 9, and 6, your device's built-in adapter would be rated for 12 jolts.) Treat the charging outlet near your seat as having an effective joltage rating of 0. Since you have some time to kill, you might as well test all of your adapters. Wouldn't want to get to your resort and realize you can't even charge your device! If you use every adapter in your bag at once, what is the distribution of joltage differences between the charging outlet, the adapters, and your device? For example, suppose that in your bag, you have adapters with the following joltage ratings: 16 10 15 5 1 11 7 19 6 12 4 With these adapters, your device's built-in joltage adapter would be rated for 19 + 3 = 22 jolts, 3 higher than the highest-rated adapter. Because adapters can only connect to a source 1-3 jolts lower than its rating, in order to use every adapter, you'd need to choose them like this: - The charging outlet has an effective rating of 0 jolts, so the only adapters that could connect to it directly would need to have a joltage rating of 1, 2, or 3 jolts. Of these, only one you have is an adapter rated 1 jolt (difference of 1). - From your 1-jolt rated adapter, the only choice is your 4-jolt rated adapter (difference of 3). - From the 4-jolt rated adapter, the adapters rated 5, 6, or 7 are valid choices. However, in order to not skip any adapters, you have to pick the adapter rated 5 jolts (difference of 1). - Similarly, the next choices would need to be the adapter rated 6 and then the adapter rated 7 (with difference of 1 and 1). - The only adapter that works with the 7-jolt rated adapter is the one rated 10 jolts (difference of 3). - From 10, the choices are 11 or 12; choose 11 (difference of 1) and then 12 (difference of 1). - After 12, only valid adapter has a rating of 15 (difference of 3), then 16 (difference of 1), then 19 (difference of 3). - Finally, your device's built-in adapter is always 3 higher than the highest adapter, so its rating is 22 jolts (always a difference of 3). In this example, when using every adapter, there are 7 differences of 1 jolt and 5 differences of 3 jolts. Here is a larger example: 28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3 In this larger example, in a chain that uses all of the adapters, there are 22 differences of 1 jolt and 10 differences of 3 jolts. Find a chain that uses all of your adapters to connect the charging outlet to your device's built-in adapter and count the joltage differences between the charging outlet, the adapters, and your device. What is the number of 1-jolt differences multiplied by the number of 3-jolt differences? */ package com.curtislb.adventofcode.year2020.day10.part1 import com.curtislb.adventofcode.common.io.readInts import com.curtislb.adventofcode.year2020.day10.joltage.JoltageAdapters import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 10, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val file = inputPath.toFile() val adapters = JoltageAdapters(file.readInts().toSet()) val differenceCounts = adapters.countRatingDifferences() return differenceCounts[1] * (differenceCounts[3] + 1L) } fun main() { println(solve()) }
0
Kotlin
1
1
a55341d18b4a44f05efbc9b0b9583e11d9528285
4,210
AdventOfCode
MIT License
pluto/src/main/java/com/mocklets/pluto/modules/logging/ui/LogDetailsDialog.kt
mocklets
459,260,997
false
null
package com.mocklets.pluto.modules.logging.ui import android.content.Context import android.graphics.drawable.ColorDrawable import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.widget.FrameLayout import androidx.fragment.app.FragmentActivity import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.mocklets.pluto.R import com.mocklets.pluto.core.DeviceInfo import com.mocklets.pluto.core.extensions.color import com.mocklets.pluto.core.extensions.inflate import com.mocklets.pluto.core.sharing.Shareable import com.mocklets.pluto.core.sharing.lazyContentSharer import com.mocklets.pluto.core.ui.setDebounceClickListener import com.mocklets.pluto.core.ui.spannable.createSpan import com.mocklets.pluto.core.ui.spannable.setSpan import com.mocklets.pluto.databinding.PlutoLayoutLogDetailsBinding import com.mocklets.pluto.modules.exceptions.asExceptionData import com.mocklets.pluto.modules.logging.LogData import com.mocklets.pluto.modules.logging.ui.LogDetailsDialog.Companion.MAX_STACK_TRACE_LINES internal class LogDetailsDialog(context: FragmentActivity, data: LogData) : BottomSheetDialog(context, R.style.PlutoBottomSheetDialogTheme) { private val sheetView: View = context.inflate(R.layout.pluto___layout_log_details) private val binding = PlutoLayoutLogDetailsBinding.bind(sheetView) private val deviceInfo = DeviceInfo(context) private val contentSharer by context.lazyContentSharer() init { setContentView(sheetView) (sheetView.parent as View).background = ColorDrawable(context.color(R.color.pluto___transparent)) this.setOnShowListener { dialog -> val d = dialog as BottomSheetDialog val bottomSheet = d.findViewById<View>(R.id.design_bottom_sheet) as FrameLayout? val behavior = BottomSheetBehavior.from(bottomSheet!!) behavior.apply { state = BottomSheetBehavior.STATE_EXPANDED isHideable = false skipCollapsed = true peekHeight = deviceInfo.height } binding.title.setSpan { append("${context.getString(R.string.pluto___log_details)} ") append(italic(fontColor(data.level.label.uppercase(), context.color(data.level.textColor)))) } binding.cta.setDebounceClickListener { contentSharer.share(Shareable(title = "Share Log details", content = data.toShareText(context))) } binding.tag.text = data.tag binding.filename.setSpan { append(fontColor("called from\n", context.color(R.color.pluto___text_dark_40))) append(data.stackTraceElement.methodName) append(fontColor(" (", context.color(R.color.pluto___text_dark_40))) append(data.stackTraceElement.fileName) append(fontColor(", line:", context.color(R.color.pluto___text_dark_60))) append(fontColor("${data.stackTraceElement.lineNumber}", context.color(R.color.pluto___text_dark_80))) append(fontColor(")", context.color(R.color.pluto___text_dark_40))) } binding.message.text = data.message binding.stackTraceContainer.visibility = GONE data.tr?.asExceptionData()?.let { binding.stackTraceContainer.visibility = VISIBLE binding.stackTrace.setSpan { append("${it.name}: ${it.message}") it.stackTrace.take(MAX_STACK_TRACE_LINES).forEach { append("\n\t\t\t") append(fontColor(" at ", context.color(R.color.pluto___text_dark_40))) append(it) } val extraTrace = it.stackTrace.size - MAX_STACK_TRACE_LINES if (extraTrace > 0) { append( fontColor( "\n\t\t\t + $extraTrace more lines", context.color(R.color.pluto___text_dark_40) ) ) } } } if (!data.eventAttributes.isNullOrEmpty()) { binding.stackTraceContainer.visibility = VISIBLE binding.stackTraceTitle.setSpan { append(context.getString(R.string.pluto___event_attributes)) append(fontColor(" (${data.eventAttributes.size})", context.color(R.color.pluto___text_dark_40))) } binding.stackTrace.text = context.beautifyAttributes(data.eventAttributes) } } } companion object { const val MAX_STACK_TRACE_LINES = 15 } } private fun Context?.beautifyAttributes(data: Map<String, Any?>): CharSequence? { return this?.createSpan { data.forEach { append("${it.key} : ") if (it.value != null) { append(fontColor(semiBold("${it.value}"), context.color(R.color.pluto___text_dark_80))) } else { append(fontColor(light(italic("null")), context.color(R.color.pluto___text_dark_40))) } append("\n") } }?.trim() } private fun LogData.toShareText(context: Context): String { val text = StringBuilder() text.append("$tag : $message\n") tr?.asExceptionData()?.let { text.append("\n${it.name}: ${it.message}\n") it.stackTrace.take(MAX_STACK_TRACE_LINES).forEach { trace -> text.append("\t at $trace\n") } if (it.stackTrace.size - MAX_STACK_TRACE_LINES > 0) { text.append("\t + ${it.stackTrace.size - MAX_STACK_TRACE_LINES} more lines\n\n") } } if (!eventAttributes.isNullOrEmpty()) { text.append("\n${context.getString(R.string.pluto___event_attributes).lowercase()} - ") eventAttributes.entries.forEach { text.append("\n\t ${it.key} : ${it.value}") } } return text.toString() }
0
null
2
8
87dc5a27272e0fc5c38e042fa95689a143ae5446
6,160
pluto
Apache License 2.0
buildSrc/src/main/java/Packages.kt
exaV
218,529,113
true
{"Kotlin": 331887}
object Packages { const val group = "subroh0508.net.kotlinmaterialui" const val version = "0.2.3" }
0
null
0
0
88c46c4d3d2aa22df2e82b048351ad967ac50ea3
107
kotlin-material-ui
MIT License
app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginDialogPreference.kt
arkon
127,645,159
false
null
package eu.kanade.tachiyomi.widget.preference import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.annotation.StringRes import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.dd.processbutton.iml.ActionProcessButton import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.domain.base.BasePreferences import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.databinding.PrefAccountLoginBinding import eu.kanade.tachiyomi.ui.base.controller.DialogController import uy.kohesive.injekt.injectLazy abstract class LoginDialogPreference( @StringRes private val usernameLabelRes: Int? = null, bundle: Bundle? = null, ) : DialogController(bundle) { var binding: PrefAccountLoginBinding? = null private set val preferences: BasePreferences by injectLazy() override fun onCreateDialog(savedViewState: Bundle?): Dialog { binding = PrefAccountLoginBinding.inflate(LayoutInflater.from(activity!!)) onViewCreated(binding!!.root) val titleName = activity!!.getString(getTitleName()) return MaterialAlertDialogBuilder(activity!!) .setTitle(activity!!.getString(R.string.login_title, titleName)) .setView(binding!!.root) .setNegativeButton(android.R.string.cancel, null) .create() } fun onViewCreated(view: View) { if (usernameLabelRes != null) { binding!!.usernameLabel.hint = view.context.getString(usernameLabelRes) } binding!!.login.setMode(ActionProcessButton.Mode.ENDLESS) binding!!.login.setOnClickListener { checkLogin() } setCredentialsOnView(view) } override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeStarted(handler, type) if (!type.isEnter) { onDialogClosed() } } open fun onDialogClosed() { binding = null } @StringRes protected abstract fun getTitleName(): Int protected abstract fun checkLogin() protected abstract fun setCredentialsOnView(view: View) }
86
null
42
9
2f07f226b8182699884262ac67139454d5b7070d
2,240
tachiyomi
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/cloud_assembly_schema/TestOptionsDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5482239}
package com.faendir.awscdkkt.generated.cloud_assembly_schema import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.cloud_assembly_schema.TestOptions @Generated public fun buildTestOptions(initializer: @AwsCdkDsl TestOptions.Builder.() -> Unit = {}): TestOptions = TestOptions.Builder().apply(initializer).build()
1
Kotlin
0
4
f1542b808f0e2cf4fcdd0d84d025a8fbaf09e90d
388
aws-cdk-kt
Apache License 2.0
supermarket/src/test/kotlin/CatalogDataProvider.kt
santukis
558,526,758
false
null
import model.* import model.catalog.SupermarketCatalog import model.offer.* import model.product.BundleProduct import model.product.ProductUnit import model.product.SingleProduct import org.junit.jupiter.params.provider.Arguments import java.util.stream.Stream object CatalogDataProvider { fun SupermarketCatalog.addSpecialOffers() { addOffer(TwoForAmountOffer(product = getToothBrush(), price = 0.99)) addOffer(PercentDiscountOffer(product = getApples(), percentage = 20.0)) addOffer(PercentDiscountOffer(product = getRice(), percentage = 10.0)) addOffer(FiveForAmountOffer(product = getToothPaste(), price = 7.49)) addOffer(ThreeForTwoOffer(product = getCherries())) addOffer(PercentDiscountBundleOffer(product = BundleProduct(listOf(getToothBrush(), getToothPaste())), percentage = 10.0)) addOffer(PercentDiscountBundleOffer(product = BundleProduct(listOf(getOranges(), getLemons())), percentage = 15.0)) } @JvmStatic fun getShoppingCartWithoutSpecialOffers(): Stream<Arguments> = Stream.of( Arguments.of(ShoppingCart(), "/shopping_cart_empty.txt"), Arguments.of( ShoppingCart() .addItem(getToothBrush(), quantity = 1.0) .addItem(getToothPaste(), quantity = 1.0) .addItem(getApples(), quantity = 2.0) .addItem(getRice(), quantity = 1.0) .addItem(getCherries(), quantity = 1.0), "/shopping_cart_without_special_offers.txt" ), ) @JvmStatic fun getShoppingCartWithSpecialOffers(): Stream<Arguments> = Stream.of( Arguments.of( ShoppingCart().addItem(getToothBrush(), quantity = 2.0), "/shopping_cart_with_special_offer_TwoForAmount.txt" ), Arguments.of( ShoppingCart() .addItem(getToothBrush(), quantity = 4.0) .addItem(getToothBrush(), quantity = 1.0), "/shopping_cart_with_special_offer_TwoForAmountMultipleItems.txt" ), Arguments.of( ShoppingCart().addItem(getApples(), quantity = 5.0), "/shopping_cart_with_special_offer_discount_per_kilo.txt" ), Arguments.of( ShoppingCart().addItem(getRice(), quantity = 2.0), "/shopping_cart_with_special_offer_discount_per_each.txt" ), Arguments.of( ShoppingCart().addItem(getToothPaste(), quantity = 5.0), "/shopping_cart_with_special_offer_FiveForAmount.txt" ), Arguments.of( ShoppingCart().addItem(getCherries(), quantity = 3.0), "/shopping_cart_with_special_offer_ThreeForAmount.txt" ), Arguments.of( ShoppingCart() .addItem(getToothBrush(), quantity = 1.0) .addItem(getToothPaste(), quantity = 1.0) .addItem(getLemons(), quantity = 1.0), "/shopping_cart_with_special_offer_PercentDiscountBundle.txt" ), Arguments.of( ShoppingCart() .addItem(getOranges(), quantity = 1.0) .addItem(getLemons(), quantity = 3.0), "/shopping_cart_with_special_offer_PercentDiscountBundle_MultipleItems.txt" ), ) private fun getToothBrush() = SingleProduct(name = "toothbrush", unit = ProductUnit.Each, unitPrice = 0.99) private fun getToothPaste() = SingleProduct(name = "toothpaste", unit = ProductUnit.Each, unitPrice = 1.79) private fun getApples() = SingleProduct(name = "apples", unit = ProductUnit.Kilo, unitPrice = 1.99) private fun getRice() = SingleProduct(name = "rice", unit = ProductUnit.Each, unitPrice = 2.49) private fun getCherries() = SingleProduct(name = "Cherry tomatoes", unit = ProductUnit.Each, unitPrice = 0.69) private fun getOranges() = SingleProduct(name = "Oranges", unit = ProductUnit.Kilo, unitPrice = 0.79) private fun getLemons() = SingleProduct(name = "Lemons", unit = ProductUnit.Kilo, unitPrice = 1.29) private fun ShoppingCart.addItem(item: SingleProduct, quantity: Double): ShoppingCart = this.apply { addItemQuantity(item, quantity) } }
0
Kotlin
0
1
7eb9dce81e698a655312d7b41bb25e0a4935d2bb
4,217
refactoringKatas
Apache License 2.0
waltid-wallet-api/src/test/kotlin/id/walt/webwallet/utils/StreamUtilsTest.kt
walt-id
701,058,624
false
{"Kotlin": 1791725, "Vue": 327781, "TypeScript": 92214, "JavaScript": 20560, "Dockerfile": 6475, "Shell": 1651, "CSS": 404}
package id.walt.webwallet.utils import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotNull class StreamUtilsTest { private val bitString = "0123456789abcdef" @Test fun `test unit bitsize, no overflow`() { val value = StreamUtils.getBitValue(inputStream = bitString.toByteArray().inputStream(), index = 4UL, bitSize = 1) assertNotNull(value) assertEquals(expected = "4", actual = value.joinToString("")) } @Test fun `test non-unit bitsize, no overflow`() { val value = StreamUtils.getBitValue(inputStream = bitString.toByteArray().inputStream(), index = 4UL, bitSize = 2) assertNotNull(value) assertEquals(expected = "89", actual = value.joinToString("")) } @Test fun `test unit bitsize, with overflow`() { assertFailsWith<IllegalStateException> { StreamUtils.getBitValue( inputStream = bitString.toByteArray().inputStream(), index = 16UL, bitSize = 1 ) } } @Test fun `test non-unit bitsize, with overflow`() { assertFailsWith<IllegalStateException> { StreamUtils.getBitValue( inputStream = bitString.toByteArray().inputStream(), index = 1UL, bitSize = 9 ) } } }
20
Kotlin
27
79
50bae539101d2f7b98a4aa7bbcbcf510c4a405f4
1,409
waltid-identity
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/toolkit/MusicPlayer.kt
EagleRobotics7373
237,697,292
false
{"Java": 204821, "Kotlin": 2708}
package org.firstinspires.ftc.teamcode.toolkit import android.media.MediaPlayer import com.qualcomm.robotcore.hardware.HardwareMap import org.firstinspires.ftc.teamcode.R class MusicPlayer (hardwareMap: HardwareMap, option1 : Boolean) { private val mediaPlayer: MediaPlayer = if (option1) MediaPlayer.create(hardwareMap.appContext, R.raw.angrybirds) else MediaPlayer.create(hardwareMap.appContext, R.raw.badpiggies) init { mediaPlayer.isLooping = true mediaPlayer.seekTo(0) } fun play() { if (!mediaPlayer.isPlaying) mediaPlayer.start() } fun pause() { mediaPlayer.pause() } fun stop() { mediaPlayer.stop() mediaPlayer.release() } fun isPlaying() = mediaPlayer.isPlaying }
1
null
1
1
8e59dec03b89f97cc9135231e144f75cb39193c0
788
EagleRoboticsFTCRepo
MIT License
app/src/main/kotlin/no/nav/hjelpemidler/soknad/db/domain/PapirSøknadData.kt
navikt
357,158,611
false
{"Kotlin": 300642, "Dockerfile": 138}
package no.nav.hjelpemidler.soknad.db.domain import com.fasterxml.jackson.annotation.JsonAlias import no.nav.hjelpemidler.behovsmeldingsmodell.BehovsmeldingStatus import no.nav.hjelpemidler.behovsmeldingsmodell.SøknadId import no.nav.hjelpemidler.behovsmeldingsmodell.TilknyttetSøknad data class PapirSøknadData( override val søknadId: SøknadId, @JsonAlias("journalpostid") val journalpostId: String, val status: BehovsmeldingStatus, val fnrBruker: String, val navnBruker: String, ) : TilknyttetSøknad
1
Kotlin
0
0
a907af91dffea6c76e44a200f1134bcb6ca7274a
528
hm-soknadsbehandling-db
MIT License
app/src/main/kotlin/no/nav/hjelpemidler/soknad/db/domain/PapirSøknadData.kt
navikt
357,158,611
false
{"Kotlin": 300642, "Dockerfile": 138}
package no.nav.hjelpemidler.soknad.db.domain import com.fasterxml.jackson.annotation.JsonAlias import no.nav.hjelpemidler.behovsmeldingsmodell.BehovsmeldingStatus import no.nav.hjelpemidler.behovsmeldingsmodell.SøknadId import no.nav.hjelpemidler.behovsmeldingsmodell.TilknyttetSøknad data class PapirSøknadData( override val søknadId: SøknadId, @JsonAlias("journalpostid") val journalpostId: String, val status: BehovsmeldingStatus, val fnrBruker: String, val navnBruker: String, ) : TilknyttetSøknad
1
Kotlin
0
0
a907af91dffea6c76e44a200f1134bcb6ca7274a
528
hm-soknadsbehandling-db
MIT License
js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/DoWhileGuardElimination.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.inline.clean import org.jetbrains.kotlin.js.backend.ast.* /** * During inlining we can sometimes get the following representation for do..while statement: * * do { * guard: { * // some logic * break guard; * // some logic * } * } * while (condition) * * A block labeled `guard` can be eliminated with `break guard` converted to `continue`. */ internal class DoWhileGuardElimination(private val root: JsStatement) { private val guardLabels = mutableSetOf<JsName>() private var hasChanges = false private val loopGuardMap = mutableMapOf<JsDoWhile, JsLabel>() private val guardToLoopLabel = mutableMapOf<JsName, JsName?>() fun apply(): Boolean { analyze() perform() return hasChanges } private fun analyze() { object : RecursiveJsVisitor() { override fun visitLabel(x: JsLabel) { val statement = x.statement if (statement is JsDoWhile) { processDoWhile(statement, x.name) } else { super.visitLabel(x) } } override fun visitDoWhile(x: JsDoWhile) = processDoWhile(x, null) private fun processDoWhile(x: JsDoWhile, label: JsName?) { val body = x.body val guard = when (body) { is JsBlock -> { val firstStatement = body.statements.firstOrNull() if (firstStatement is JsLabel && body.statements.size == 1) { firstStatement } else { null } } is JsLabel -> body else -> null } if (guard != null) { // When do..while loop has no label and we encounter break guard from nested loop, we can't // replace this break with continue. Example: // // do { // guard: { // for (;;) { // break guard; // } // } // } // while (condition) // // In this case we get simple `continue` that goes to beginning of `for`, not `do`. // We can't specify label explicitly, since there's no label on `do`. // See `js-optimizer/do-while-guard-elimination/innerBreakInLoopWithoutLabel.original.js` // // So we don't apply optimization if `do` statement does not have label on it and there's // a nested loop which has `break guard` statement. if (label != null || !findBreakInNestedLoop(guard, guard.name)) { guardLabels += guard.name loopGuardMap[x] = guard guardToLoopLabel[guard.name] = label } } body.accept(this) } override fun visitFunction(x: JsFunction) { } }.accept(root) } private fun findBreakInNestedLoop(statement: JsStatement, name: JsName): Boolean { var result = false statement.accept(object : RecursiveJsVisitor() { private var loopLevel = 0 override fun visitBreak(x: JsBreak) { val guardLabel = x.label?.name ?: return if (guardLabel == name && isInLoop()) { result = true } } private fun isInLoop() = loopLevel > 0 override fun visitLoop(x: JsLoop) { loopLevel++ super.visitLoop(x) loopLevel-- } override fun visitFunction(x: JsFunction) { } override fun visitElement(node: JsNode) { if (!result) { super.visitElement(node) } } }) return result } private fun perform() { object : JsVisitorWithContextImpl() { override fun visit(x: JsDoWhile, ctx: JsContext<JsNode>): Boolean { loopGuardMap[x]?.let { guard -> if (guard.name in guardLabels) { x.body = accept(guard.statement) hasChanges = true return false } } return super.visit(x, ctx) } override fun visit(x: JsBreak, ctx: JsContext<JsNode>): Boolean { val name = x.label?.name if (name in guardLabels) { val target = guardToLoopLabel[name] ctx.replaceMe(JsContinue(target?.makeRef())) hasChanges = true } return false } }.accept(root) } }
34
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
5,798
kotlin
Apache License 2.0
sdk/src/main/java/live/talkshop/sdk/utils/Collector.kt
TalkShopLive
756,521,933
false
{"Kotlin": 105350}
package live.talkshop.sdk.utils import android.content.Context import android.os.Build import android.util.DisplayMetrics import android.view.WindowManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import live.talkshop.sdk.core.authentication.isDNT import live.talkshop.sdk.utils.networking.APIHandler import live.talkshop.sdk.utils.networking.HTTPMethod import live.talkshop.sdk.utils.networking.URLs.getCollectorUrl import org.json.JSONObject class Collector private constructor(context: Context) { private val deviceScreenResolution: String init { val displayMetrics = DisplayMetrics() val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager deviceScreenResolution = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val windowMetrics = windowManager.currentWindowMetrics val bounds = windowMetrics.bounds "${bounds.width()}x${bounds.height()}" } else { @Suppress("DEPRECATION") windowManager.defaultDisplay.getMetrics(displayMetrics) "${displayMetrics.widthPixels}x${displayMetrics.heightPixels}" } } private suspend fun collect( action: String, category: String, userId: String? = "NOT_SET", eventID: String? = "NOT_SET", showKey: String? = "NOT_SET", storeId: String? = "NOT_SET", videoKey: String? = "NOT_SET", showStatus: String? = "NOT_SET", duration: String? = "NOT_SET" ) { val timestamp = System.currentTimeMillis() val payload = JSONObject().apply { put("timestamp_utc", timestamp) put("user_id", userId) put("category", category) put("version", "1.0.4") put("action", action) put("application", "android") put("meta", JSONObject().apply { put("external", true) put("event_id", eventID) put("streaming_content_key", showKey) put("store_id", storeId) put("video_key", videoKey) put("video_status", showStatus) put("video_time", duration) }) put("utm", JSONObject().apply { put("source", "NOT_SET") put("campaign", "NOT_SET") put("medium", "NOT_SET") put("term", "NOT_SET") put("content", "NOT_SET") }) put("aspect", JSONObject().apply { put("browser_resolution", "NOT_SET") put("screen_resolution", deviceScreenResolution) }) } APIHandler.makeRequest( requestUrl = getCollectorUrl(), requestMethod = HTTPMethod.POST, payload = payload ) } companion object { @Volatile private var instance: Collector? = null fun initialize(context: Context) { if (instance == null) { synchronized(this) { if (instance == null) { instance = Collector(context) } } } } private fun getInstance(): Collector { return instance ?: throw IllegalStateException("Collector must be initialized in Application.onCreate()") } fun collect( action: String, category: String, userId: String? = null, eventID: String? = null, showKey: String? = null, storeId: String? = null, videoKey: String? = null, showStatus: String? = null, duration: String? = null ) { if (isDNT) { return } CoroutineScope(Dispatchers.IO).launch { getInstance().collect( action, category, userId, eventID, showKey, storeId, videoKey, showStatus, duration ) } } } }
1
Kotlin
0
0
b86f85401b2684d13933ae7e3a1a0a9735f364eb
4,293
android-sdk
Apache License 2.0
core/src/com/ascending/games/id1/edit/board/action/room/RotateAction.kt
AscendingGames
147,917,936
false
null
package com.ascending.games.id1.edit.board.action.room import com.ascending.games.id1.edit.board.BoardDomain import com.ascending.games.id1.model.board.Board import com.ascending.games.id1.model.board.Room class RotateAction : IBoardAction { override fun execute(room : Room, board : Board) { for (i in 0..3) { room.rotate() if(!board.isRoomOverlapping(room) && board.isRoomInBounds(room)) { break } } } }
11
null
1
1
7fb0ee90967c49ab1056620c68a2029f663e4e40
483
DungeonCreator
MIT License
src/main/kotlin/org/bonitasoft/example/processes/ProcessWith3AutomaticTaskAnd1UsesBDM.kt
bonitasoft-labs
300,656,896
false
null
/* * Copyright 2020 Bonitasoft S.A. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bonitasoft.example.processes import org.bonitasoft.engine.api.APIClient import org.bonitasoft.engine.bpm.bar.BarResource import org.bonitasoft.engine.bpm.bar.BusinessArchiveBuilder import org.bonitasoft.engine.bpm.bar.actorMapping.Actor import org.bonitasoft.engine.bpm.bar.actorMapping.ActorMapping import org.bonitasoft.engine.bpm.flownode.GatewayType import org.bonitasoft.engine.bpm.process.impl.ProcessDefinitionBuilder import org.bonitasoft.example.toExpression import org.bonitasoft.example.toParameter import org.bonitasoft.example.toScript import java.util.* class ProcessWith3AutomaticTaskAnd1UsesBDM : BonitaProcess() { override fun process(): ProcessDefinitionBuilder { return ProcessDefinitionBuilder().createNewInstance("ProcessWith3AutomaticTaskAnd1UsesBDM", "1.0") .apply { addActor("theActor", true) addStartEvent("start") addAutomaticTask("sub1") addAutomaticTask("sub2").apply { addBusinessData("myEmployee", "com.company.model.Employee", """ def employee = new com.company.model.Employee() employee.name = "name" return employee """.trimIndent().toScript("com.company.model.Employee")) } addAutomaticTask("sub3") addEndEvent("end") addTransition("start", "sub1") addTransition("sub1", "sub2") addTransition("sub2", "sub3") addTransition("sub3", "end") } } override fun withResources(bar: BusinessArchiveBuilder) { bar.apply { actorMapping = ActorMapping().apply { addActor(Actor("theActor").apply { addUser("walter.bates") }) } } } }
2
Kotlin
1
0
d095693b6c7942c6cf5c6a6131095d20654fc7d1
2,562
bonita-test-processes
Apache License 2.0
app/src/main/java/com/awxkee/avif/glideapp/decoder/MainActivity.kt
awxkee
692,821,483
false
{"Kotlin": 15586}
package com.awxkee.avif.glideapp.decoder import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.awxkee.avif.glideapp.decoder.databinding.ActivityMainBinding import com.awxkee.avif.glideapp.decoder.ui.theme.AvifGlideAppDecoderTheme import com.bumptech.glide.Glide class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //https://wh.aimuse.online/creatives/IMUSE_03617fe2db82a584166_27/TT_a9d21ff1061d785347935fef/68f06252.avif //https://wh.aimuse.online/preset/federico-beccari.avif // https://wh.aimuse.online/preset/avif10bit.avif Glide.with(this) .load("https://wh.aimuse.online/preset/avif10bit.avif") .skipMemoryCache(true) .into(binding.imageView) } }
0
Kotlin
0
5
273660205a62836f62009e544af9a05fa89a27f7
1,405
avif-coder-glide
Apache License 2.0
app/src/main/kotlin/app/alarmbanner/ContinueModule.kt
anirudh8860
144,851,679
false
null
package app.alarmbanner import android.view.View import app.di.PerActivity import app.login.TinderLoginView import app.login.TinderLoginViewImpl import dagger.Module import dagger.Provides @Module @PerActivity internal class ContinueModule(private val activity: AlarmBannerActivity, private val view: View) { @Provides fun view(): ContinueView = ContinueViewImpl(view) @Provides fun coordinator(view: ContinueView) = ContinueCoordinator(activity, view) }
0
null
0
1
ba8ead38f5bcefc857a6dc9cc344cd030ca5b22d
474
dinger
MIT License
core/src/main/kotlin/com/makentoshe/booruchan/core/tag/deserialize/TagDeserialize.kt
Makentoshe
147,361,920
false
null
package com.makentoshe.booruchan.core.tag.deserialize import com.makentoshe.booruchan.core.tag.Tag interface TagDeserialize<out T : Tag> { val tag: T /** An object representation in string (json, xml) */ val raw: String }
0
Kotlin
1
6
d0f40fb8011967e212df1f21beb43e4c4ec03356
236
Booruchan
Apache License 2.0
app/src/main/java/antuere/how_are_you/presentation/screens/add_day/state/AddDaySideEffect.kt
antuere
526,507,044
false
null
package antuere.how_are_you.presentation.screens.add_day.state sealed interface AddDaySideEffect { object NavigateUp : AddDaySideEffect }
1
Kotlin
1
1
dccddea7bf36f0910b87c09becd0de2d74ac26b2
142
HowAreYou
Apache License 2.0
app/src/main/java/com/ozkan/bookshelf/di/FirebaseModele.kt
ozkantuncel
547,763,851
false
{"Kotlin": 150023}
package com.ozkan.bookshelf.di import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.ozkan.bookshelf.util.FirebaseStorageConstants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object FirebaseModele { @Provides @Singleton fun provideFirebaseDatabaseInstance(): FirebaseDatabase { return FirebaseDatabase.getInstance() } @Provides @Singleton fun provideFireStoreInstance(): FirebaseFirestore { return FirebaseFirestore.getInstance() } @Provides @Singleton fun provideFirebaseAuthInstance(): FirebaseAuth { return FirebaseAuth.getInstance() } @Singleton @Provides fun provideFirebaseStroageImageofUserInstance(): StorageReference { return FirebaseStorage.getInstance().getReference(FirebaseStorageConstants.ROOT_DIRECTORY) } }
0
Kotlin
0
9
823dba50df575461f75118c53b8bb124db25259f
1,193
Bookshelf
The Unlicense
src/main/kotlin/com/terraformation/backend/search/table/SpeciesTable.kt
terraware
323,722,525
false
{"Kotlin": 3742063, "HTML": 88799, "Python": 46278, "FreeMarker": 16407, "PLpgSQL": 3305, "Makefile": 746, "Dockerfile": 674}
package com.terraformation.backend.search.table import com.terraformation.backend.auth.currentUser import com.terraformation.backend.db.accelerator.tables.references.PARTICIPANT_PROJECT_SPECIES import com.terraformation.backend.db.default_schema.SpeciesId import com.terraformation.backend.db.default_schema.tables.references.ORGANIZATIONS import com.terraformation.backend.db.default_schema.tables.references.SPECIES import com.terraformation.backend.db.default_schema.tables.references.SPECIES_ECOSYSTEM_TYPES import com.terraformation.backend.db.default_schema.tables.references.SPECIES_GROWTH_FORMS import com.terraformation.backend.db.default_schema.tables.references.SPECIES_PLANT_MATERIAL_SOURCING_METHODS import com.terraformation.backend.db.default_schema.tables.references.SPECIES_PROBLEMS import com.terraformation.backend.db.default_schema.tables.references.SPECIES_SUCCESSIONAL_GROUPS import com.terraformation.backend.db.nursery.tables.references.INVENTORIES import com.terraformation.backend.db.nursery.tables.references.SPECIES_PROJECTS import com.terraformation.backend.search.SearchTable import com.terraformation.backend.search.SublistField import com.terraformation.backend.search.field.SearchField import org.jooq.Condition import org.jooq.Record import org.jooq.TableField class SpeciesTable(tables: SearchTables) : SearchTable() { override val primaryKey: TableField<out Record, out Any?> get() = SPECIES.ID override val sublists: List<SublistField> by lazy { with(tables) { listOf( inventories.asSingleValueSublist( "inventory", SPECIES.ORGANIZATION_ID.eq(INVENTORIES.ORGANIZATION_ID) .and(SPECIES.ID.eq(INVENTORIES.SPECIES_ID)), isRequired = false), nurserySpeciesProjects.asMultiValueSublist( "nurseryProjects", SPECIES.ID.eq(SPECIES_PROJECTS.SPECIES_ID)), organizations.asSingleValueSublist( "organization", SPECIES.ORGANIZATION_ID.eq(ORGANIZATIONS.ID)), participantProjectSpecies.asMultiValueSublist( "participantProjectSpecies", SPECIES.ID.eq(PARTICIPANT_PROJECT_SPECIES.SPECIES_ID)), speciesEcosystemTypes.asMultiValueSublist( "ecosystemTypes", SPECIES.ID.eq(SPECIES_ECOSYSTEM_TYPES.SPECIES_ID)), speciesGrowthForms.asMultiValueSublist( "growthForms", SPECIES.ID.eq(SPECIES_GROWTH_FORMS.SPECIES_ID)), speciesPlantMaterialSourcingMethods.asMultiValueSublist( "plantMaterialSourcingMethods", SPECIES.ID.eq(SPECIES_PLANT_MATERIAL_SOURCING_METHODS.SPECIES_ID)), speciesProblems.asMultiValueSublist( "problems", SPECIES.ID.eq(SPECIES_PROBLEMS.SPECIES_ID)), speciesSuccessionalGroups.asMultiValueSublist( "successionalGroups", SPECIES.ID.eq(SPECIES_SUCCESSIONAL_GROUPS.SPECIES_ID)), ) } } override val fields: List<SearchField> = listOf( timestampField("checkedTime", SPECIES.CHECKED_TIME), textField("commonName", SPECIES.COMMON_NAME), enumField("conservationCategory", SPECIES.CONSERVATION_CATEGORY_ID, localize = false), timestampField("createdTime", SPECIES.CREATED_TIME), textField("familyName", SPECIES.FAMILY_NAME), idWrapperField("id", SPECIES.ID) { SpeciesId(it) }, timestampField("modifiedTime", SPECIES.MODIFIED_TIME), booleanField("rare", SPECIES.RARE), textField("scientificName", SPECIES.SCIENTIFIC_NAME), enumField("seedStorageBehavior", SPECIES.SEED_STORAGE_BEHAVIOR_ID), ) override fun conditionForVisibility(): Condition { return SPECIES.ORGANIZATION_ID.`in`(currentUser().organizationRoles.keys) .and(SPECIES.DELETED_TIME.isNull) } }
7
Kotlin
1
9
be4ce75aff529944d4f1d0fe2fecade47fe29317
3,818
terraware-server
Apache License 2.0
benchmark/src/jmh/kotlin/test/Objects.kt
Peanuuutz
444,688,345
false
{"Kotlin": 356004}
package test import kotlinx.datetime.Instant import kotlinx.datetime.serializers.InstantIso8601Serializer import kotlinx.datetime.toKotlinInstant import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import net.peanuuutz.tomlkt.NativeOffsetDateTime import net.peanuuutz.tomlkt.TomlContentPolymorphicSerializer import net.peanuuutz.tomlkt.TomlDecoder import net.peanuuutz.tomlkt.TomlElement import net.peanuuutz.tomlkt.TomlEncoder import net.peanuuutz.tomlkt.TomlOffsetDateTimeSerializer import net.peanuuutz.tomlkt.asTomlTable import org.intellij.lang.annotations.Language import java.time.ZoneOffset fun main() { val string = """ x = 0.0 y = 0.0 """.trimIndent() val value = TomlObjects.tomlkt.decodeFromString<Config>(SampleConfig) println(value) } object PlacementSerializer : TomlContentPolymorphicSerializer<Placement>(Placement::class) { override fun selectDeserializer(element: TomlElement): DeserializationStrategy<Placement> { return when { element.asTomlTable().isNotEmpty() -> Placement.Placed.serializer() else -> Placement.Unplaced.serializer() } } } @Serializable(PlacementSerializer::class) sealed class Placement { @Serializable data object Unplaced : Placement() @Serializable data class Placed(val x: Double, val y: Double) : Placement() } @Serializable data class Config( val title: String, val owner: Owner, val database: Database, // val servers: Map<String, Server> ) @Serializable data class Owner( val name: String, val birthday: @Serializable(OffsetDateTimeSerializer::class) Any ) @Serializable data class Database( val enabled: Boolean, val ports: List<Short>, val temperature: Temperature ) @Serializable data class Temperature( val cpu: Float, val case: Float ) @Serializable data class Server( val ip: String, val role: String ) @Language("toml") const val SampleConfig: String = """ # This is a TOML document title = "TOML Example" [owner] name = "Tom Preston-Werner" birthday = 1979-05-27T07:32:00-08:00 [database] enabled = true ports = [ 8000, 8001, 8002 ] temperature = { cpu = 79.5, case = 72.0 } # [servers] # [servers.alpha] # ip = "10.0.0.1" # role = "frontend" # [servers.beta] # ip = "10.0.0.2" # role = "backend" """ object OffsetDateTimeSerializer : KSerializer<Any> { override val descriptor: SerialDescriptor get() = InstantIso8601Serializer.descriptor override fun serialize(encoder: Encoder, value: Any) { if (encoder is TomlEncoder) { when (value) { is NativeOffsetDateTime -> { encoder.encodeSerializableValue(TomlOffsetDateTimeSerializer(), value) } is Instant -> { @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") val converted = value.value.atOffset(ZoneOffset.UTC) encoder.encodeSerializableValue(TomlOffsetDateTimeSerializer(), converted) } } } else { when (value) { is NativeOffsetDateTime -> { val converted = value.toInstant().toKotlinInstant() encoder.encodeSerializableValue(InstantIso8601Serializer, converted) } is Instant -> { encoder.encodeSerializableValue(InstantIso8601Serializer, value) } } } } override fun deserialize(decoder: Decoder): Any { return if (decoder is TomlDecoder) { decoder.decodeSerializableValue(TomlOffsetDateTimeSerializer()) } else { decoder.decodeSerializableValue(InstantIso8601Serializer) } } }
3
Kotlin
2
80
9689e08a57785d2fb56fee352c0b82c9bac8c593
4,053
tomlkt
Apache License 2.0
varp-serializers/varp-serializer-gson/src/main/kotlin/net/voxelpi/varp/serializer/gson/FolderPathSerializer.kt
VoxelPi
869,165,536
false
{"Kotlin": 178363, "Java": 2122}
package net.voxelpi.varp.serializer.gson import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import net.voxelpi.varp.warp.path.FolderPath import java.lang.reflect.Type public object FolderPathSerializer : JsonSerializer<FolderPath>, JsonDeserializer<FolderPath> { override fun serialize(src: FolderPath?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement? { if (src == null) { return null } return JsonPrimitive(src.toString()) } override fun deserialize(json: JsonElement?, typeOfT: Type, context: JsonDeserializationContext): FolderPath? { if (json == null || json.isJsonNull) { return null } return FolderPath.parse(json.asJsonPrimitive.asString).getOrThrow() } }
0
Kotlin
0
0
f9c616f84996d87363d37ba64eac4f89b9a32bd6
970
Varp
MIT License
chart_server/src/main/kotlin/io/madrona/njord/layers/Hulkes.kt
manimaul
213,533,249
false
{"Kotlin": 283714, "TypeScript": 70908, "Python": 11027, "PLpgSQL": 5036, "HTML": 3275, "Shell": 3043, "Dockerfile": 2008, "CSS": 1315}
package io.madrona.njord.layers import io.madrona.njord.model.* class Hulkes : Layerable() { override suspend fun preTileEncode(feature: ChartFeature) { feature.pointSymbol(Sprite.HULKES01) } override fun layers(options: LayerableOptions): Sequence<Layer> { return sequenceOf( areaLayerWithFillColor(theme = options.theme, color = Color.CHBRN), lineLayerWithColor(theme = options.theme, color = Color.CSTLN, width = 2f), pointLayerFromSymbol( symbol = Sprite.HULKES01, anchor = Anchor.CENTER, iconAllowOverlap = true, iconKeepUpright = false ), ) } }
17
Kotlin
3
8
6dfcdb85cd8a56f87d1090a7b1dafe24a7f7beee
705
njord
Apache License 2.0
API/Ponto Inteligente/src/main/kotlin/com/wendergalan/pontointeligente/services/EmpresaService.kt
WenderGalan
151,712,934
false
null
package com.wendergalan.pontointeligente.services import com.wendergalan.pontointeligente.documents.Empresa /** * Ponto Inteligente * Wender Galan LTDA * Todos os direitos reservados © ********************************************** * Nome do arquivo: EmpresaService.java * Criado por : Wender Galan * Data da criação : 05/10/2018 * Observação : ********************************************** */ interface EmpresaService { fun buscarPorCnpj(cnpj: String) : Empresa? fun persistir(empresa: Empresa): Empresa }
0
Kotlin
1
0
196f56e4701561c143922bafda219f8f24bdb908
530
ponto-inteligente
Apache License 2.0
lib_base/src/main/kotlin/com/crow/base/ui/dialog/LoadingAnimDialog.kt
CrowForKotlin
610,636,509
false
null
package com.crow.base.ui.dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.lifecycleScope import com.crow.base.R import com.crow.base.tools.extensions.animateFadeIn import com.crow.base.tools.extensions.animateFadeOut import com.crow.base.tools.extensions.doAfterDelay import com.crow.base.tools.extensions.setBackgroundTransparent import com.crow.base.tools.extensions.setMaskAmount /************************* * @Machine: RedmiBook Pro 15 * @RelativePath: cn\barry\base\dialog\LoadingAnimDialog.kt * @Path: D:\Barry\B_study\Android\Android_Project\JetpackApp\lib_base\src\main\java\cn\barry\base\dialog\LoadingAnimDialog.kt * @Author: CrowForKotlin * @Time: 2022/5/2 12:23 周一 下午 * @Description: 加载动画弹窗 * @formatter:off *************************/ class LoadingAnimDialog : DialogFragment() { fun interface LoadingAnimCallBack { fun onAnimEnd() } interface LoadingAnimConfig { fun isNoInitStyle() : Boolean fun doOnConfig(window: Window) } companion object { private val TAG: String = this::class.java.simpleName private var mShowTime = 0L private var mIsLoading = false private const val mDismissFlagTime = 1000L private const val mAnimateDuration = 200L @JvmStatic @Synchronized fun show(fragmentManager: FragmentManager,loadingAnimConfig: LoadingAnimConfig? = null) { val dialog = fragmentManager.findFragmentByTag(TAG) as? LoadingAnimDialog ?: LoadingAnimDialog() if (dialog.isAdded) return if (!dialog.isVisible) { mShowTime = System.currentTimeMillis() if (!fragmentManager.isStateSaved) { dialog.show(fragmentManager, TAG) mIsLoading = true if (loadingAnimConfig != null) { if (!loadingAnimConfig.isNoInitStyle()) dialog.lifecycleScope.launchWhenCreated { dialog.setStyle(STYLE_NO_TITLE, R.style.Base_LoadingAnim_Dark) } dialog.lifecycleScope.launchWhenStarted { loadingAnimConfig.doOnConfig(dialog.dialog?.window ?: return@launchWhenStarted) } } else { dialog.setStyle(STYLE_NO_TITLE, R.style.Base_LoadingAnim_Dark) } } } } @JvmStatic @Synchronized fun dismiss(fragmentManager: FragmentManager, animCallBack: LoadingAnimCallBack? = null) { if (!mIsLoading) return val dialog = fragmentManager.findFragmentByTag(TAG) as? LoadingAnimDialog ?: return val consumeTime = System.currentTimeMillis() - mShowTime // 判断 取消时间是否大于 显示超1S 时间 if (mDismissFlagTime > consumeTime) dialog.doAfterDelay(mDismissFlagTime - consumeTime) { dismissWithAnim(dialog, animCallBack) } else dismissWithAnim(dialog, animCallBack) } private fun dismissWithAnim(dialog: LoadingAnimDialog, animCallBack: LoadingAnimCallBack?) { dialog.requireView().animateFadeOut(mAnimateDuration).withEndAction { dialog.dismissAllowingStateLoss() animCallBack?.onAnimEnd() mIsLoading = false } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.base_dialog_loading, container, false) } override fun onStart() { super.onStart() isCancelable = false val window = dialog!!.window!! window.setBackgroundTransparent() window.setMaskAmount(0f) view?.animateFadeIn() } }
0
Kotlin
1
7
dec97a516e63af93483eb8fcde786ee894463207
3,952
CopyMangaX
Apache License 2.0
app/src/main/java/com/architectcoders/aacboard/ui/fragments/viewmodel/ListDashboardsViewModel.kt
fesave
616,599,477
false
null
package com.architectcoders.aacboard.ui.fragments.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.architectcoders.aacboard.domain.data.dashboard.Dashboard import com.architectcoders.aacboard.domain.use_case.dashboard.delete.DeleteDashboardUseCase import com.architectcoders.aacboard.domain.use_case.dashboard.get.GetAllDashboardsUseCase import com.architectcoders.aacboard.domain.use_case.dashboard.get.GetPreferredDashboardIdUseCase import com.architectcoders.aacboard.domain.use_case.dashboard.save.SetPreferredDashboardIdUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class ListDashboardsViewModel( private val getAllDashboardsUseCase: GetAllDashboardsUseCase, private val setPreferredDashboardIdUseCase: SetPreferredDashboardIdUseCase, private val getPreferredDashboardIdUseCase: GetPreferredDashboardIdUseCase, ) : ViewModel() { private val _state = MutableStateFlow(ListDashboardsUiState()) val state: StateFlow<ListDashboardsUiState> get() = _state.asStateFlow() init { viewModelScope.launch { getPreferredDashboardIdUseCase().collect(::onPreferredDashboardCollected) } viewModelScope.launch { getAllDashboardsUseCase().collect(::onAllDashboardsCollected) } } private fun onPreferredDashboardCollected(id: Int) { _state.update { state -> state.copy( dashboards = _state.value.dashboards.updatePreferred(id), preferredDashboardId = id, ) } } private fun onAllDashboardsCollected(dashboards: List<Dashboard>) { _state.update { state -> state.copy( loading = false, dashboards = dashboards.map { dashboard -> dashboard.toDashBoardUiItem(state.preferredDashboardId) }, ) } if (dashboards.size == 1) { viewModelScope.launch { setPreferredDashboardIdUseCase(dashboards.first().id) } } } fun onPreferredDashboardClicked(id: Int) { viewModelScope.launch { setPreferredDashboardIdUseCase(id) } } data class ListDashboardsUiState( val loading: Boolean = true, val dashboards: List<DashboardUiItem> = emptyList(), val preferredDashboardId: Int = -1 ) data class DashboardUiItem( val id: Int, val name: String, val image: String, val isPreferred: Boolean, ) } fun List<ListDashboardsViewModel.DashboardUiItem>.updatePreferred(preferredId: Int) = map { it.copy(isPreferred = it.id == preferredId) } fun Dashboard.toDashBoardUiItem(preferredId: Int) = ListDashboardsViewModel.DashboardUiItem(id, name, image, id == preferredId)
0
Kotlin
0
0
7fe7942bb53c23410763f73a30b5e085e45af1fb
2,997
AAC-Board
Apache License 2.0
app/src/main/java/husaynhakeem/io/unconnectifyre/worker/AlarmJob.kt
husaynhakeem
151,892,709
false
null
package husaynhakeem.io.unconnectifyre.worker data class AlarmJob( val id: Int, val delay: Long, val connectivity: Int, val shouldConnect: Boolean)
0
Kotlin
0
3
4ee13fc554b305a01d132d6e5db2fea44a633992
181
Unconnectify-Re
MIT License
app/src/main/java/de/beatbrot/screenshotassistant/util/LiveData+.kt
eric-ampire
206,854,183
true
{"Kotlin": 27915}
package de.beatbrot.screenshotassistant.util import androidx.lifecycle.MutableLiveData fun <T> liveDataOf(value: T): MutableLiveData<T> { val data = MutableLiveData<T>() data.postValue(value) return data }
0
null
0
1
e0fbfbcc62431b0bb3657b3e217eb146543ee8e7
219
ScreenshotAssistant
Apache License 2.0
rpgJavaInterpreter-core/src/main/kotlin/com/smeup/rpgparser/interpreter/movel.kt
smeup
170,714,014
false
{"RPGLE": 7087271, "Kotlin": 1761227, "ANTLR": 163198, "Java": 13658, "Ruby": 1899, "PowerShell": 861, "Dockerfile": 551, "Batchfile": 395}
package com.smeup.rpgparser.interpreter import com.smeup.rpgparser.parsing.ast.* import com.smeup.rpgparser.parsing.parsetreetoast.DateFormat import com.smeup.rpgparser.parsing.parsetreetoast.isDecimal import com.smeup.rpgparser.parsing.parsetreetoast.isInt import com.smeup.rpgparser.parsing.parsetreetoast.toDecimal import java.math.BigDecimal private fun clear(value: String, type: Type): String { return when (type) { is NumberType -> "0".repeat(type.numberOfDigits) is StringType -> { if (type.varying) { // return the actual length of the string " ".repeat(value.length) } else { " ".repeat(type.size) } } is UnlimitedStringType -> " ".repeat(value.length) else -> " ".repeat(type.size) } } fun movel( operationExtender: String?, target: AssignableExpression, value: Expression, dataAttributes: Expression?, interpreterCore: InterpreterCore ): Value { if (value !is FigurativeConstantRef) { if (value.type() is ArrayType) { throw UnsupportedOperationException("Cannot set an array as factor 2 in MOVEL/MOVEL(P) statement") } if (value.type() is DateType) { return interpreterCore.assign(target, dateToString(value, dataAttributes, interpreterCore)) } val valueToMove: String = getStringOfValue(target, interpreterCore, value) if (target.type() is ArrayType) { // for each element of array apply move val arrayValue: ConcreteArrayValue = interpreterCore.eval(target) as ConcreteArrayValue val valueToApplyMoveElementType: Type = (target.type() as ArrayType).element arrayValue.elements.forEachIndexed { index, el -> arrayValue.setElement( index + 1, stringToValue( movel( valueToMove, valueToString(el, valueToApplyMoveElementType), valueToApplyMoveElementType, operationExtender != null ), valueToApplyMoveElementType ) ) } return interpreterCore.assign(target, arrayValue) } else { val valueToApplyMove: String = valueToString(interpreterCore.eval(target), target.type()) return interpreterCore.assign( target, stringToValue( movel(valueToMove, valueToApplyMove, target.type(), operationExtender != null), target.type() ) ) } } else { return interpreterCore.assign(target, interpreterCore.eval(value)) } } fun move( operationExtender: String?, target: AssignableExpression, value: Expression, interpreterCore: InterpreterCore ): Value { if (value !is FigurativeConstantRef) { if (value.type() is ArrayType) { throw UnsupportedOperationException("Cannot set an array as factor 2 in MOVE/MOVE(P) statement") } val valueToMove: String = getStringOfValue(target, interpreterCore, value) if (target.type() is ArrayType) { // for each element of array apply move val arrayValue: ConcreteArrayValue = interpreterCore.eval(target) as ConcreteArrayValue val valueToApplyMoveElementType: Type = (target.type() as ArrayType).element arrayValue.elements.forEachIndexed { index, el -> arrayValue.setElement( index + 1, stringToValue( move( valueToMove, valueToString(el, valueToApplyMoveElementType), valueToApplyMoveElementType, operationExtender != null ), valueToApplyMoveElementType ) ) } return interpreterCore.assign(target, arrayValue) } else { val valueToApplyMove: String = valueToString(interpreterCore.eval(target), target.type()) return interpreterCore.assign( target, stringToValue( move(valueToMove, valueToApplyMove, target.type(), operationExtender != null), target.type() ) ) } } else { return interpreterCore.assign(target, interpreterCore.eval(value)) } } private fun getStringOfValue( target: AssignableExpression, interpreterCore: InterpreterCore, value: Expression ): String = when (target.type()) { is BooleanType -> { val valueInterpreted: String = (interpreterCore.eval(value)).asString().value when { (valueInterpreted.isInt() && valueInterpreted.toInt() in 0..1) -> valueInterpreted (valueInterpreted.isDecimal() && valueInterpreted.toDecimal() in 0.0..1.0) -> "0" valueInterpreted.isBlank() -> "0" else -> throw UnsupportedOperationException("MOVE/MOVEL for ${target.type()} have to be 0, 1 or blank") } } is DataStructureType -> { value.type().toDataStructureValue(interpreterCore.eval(value)).value } else -> valueToString(interpreterCore.eval(value), value.type()) } private fun movel( valueToMove: String, valueToApplyMove: String, valueToApplyMoveType: Type, withClear: Boolean = false ): String { return if (valueToApplyMoveType is UnlimitedStringType) { valueToMove } else if (valueToMove.length <= valueToApplyMove.length) { var result: String = valueToApplyMove if (withClear) { result = clear(result, valueToApplyMoveType) } // overwrite valueToMove from left to right to valueToApplyMove if (valueToApplyMoveType is BooleanType) valueToMove else valueToMove + result.substring(valueToMove.length) } else { // overwrite valueToMove to valueToApplyMove valueToMove.substring(0, valueToApplyMove.length) } } private fun move( valueToMove: String, valueToApplyMove: String, valueToApplyMoveType: Type, withClear: Boolean = false ): String { return if (valueToMove.length <= valueToApplyMove.length) { var result: String = valueToApplyMove if (withClear) { result = clear(result, valueToApplyMoveType) } // overwrite valueToMove from left to right to valueToApplyMove if (valueToApplyMoveType is BooleanType) valueToMove else result.substring(0, result.length - valueToMove.length) + valueToMove } else { // overwrite valueToMove to valueToApplyMove valueToMove.substring(valueToMove.length - valueToApplyMove.length) } } private fun dateToString(source: Expression, destinationFormat: Expression?, interpreterCore: InterpreterCore): Value { val sourceEvaluated: DateValue = interpreterCore.eval(source) as DateValue if (destinationFormat == null) { return sourceEvaluated.asString() } return when (destinationFormat) { is JulFormatExpr -> StringValue(sourceEvaluated.adapt(DateFormat.JUL)) is IsoFormatExpr -> StringValue(sourceEvaluated.adapt(DateFormat.ISO)) else -> throw UnsupportedOperationException("Unable to convert to $destinationFormat") } } private fun valueToString(value: Value, type: Type): String { var s = value.asString().value return when (type) { is StringType -> { return if (type.varying) { s } else { s + " ".repeat(type.length - s.length) } } is UnlimitedStringType -> return s is CharacterType -> return s is NumberType -> { if (value is NumberValue) { if (value.isNegative()) { throw UnsupportedOperationException("MOVEL/MOVE for negative numbers not supported") } if (value is IntValue) { val zeros = "0".repeat(type.numberOfDigits - s.length) zeros + s } else { s = s.replace(".", "") val zeros = "0".repeat(type.numberOfDigits - s.length) zeros + s } } else { throw UnsupportedOperationException("MOVE/MOVEL not supported for the type: $type") } } is BooleanType -> return s is DataStructureType -> return s else -> throw UnsupportedOperationException("MOVE/MOVEL not supported for the type: $type") } } private fun stringToValue(value: String, type: Type): Value { when (type) { is StringType -> { return if (type.varying) { StringValue(value, true) } else { var newValue = value if (value.length < type.length) { // fill with blank space newValue += " ".repeat(type.length - value.length) } StringValue(newValue, false) } } is UnlimitedStringType -> return UnlimitedStringValue(value) is CharacterType -> return StringValue(value) is NumberType -> { return if (type.integer) { // integer if (value.isBlank()) IntValue.ZERO else value.toLong().asValue() } else { // decimal val integerPart = value.substring(0, type.entireDigits) val decimalPart = value.substring(type.entireDigits, value.length) if (value.isBlank()) DecimalValue.ZERO else DecimalValue(BigDecimal("$integerPart.$decimalPart")) } } is BooleanType -> return StringValue(value) is DataStructureType -> { return DataStructValue(value) } else -> throw UnsupportedOperationException("MOVE/MOVEL not supported for the type: $type") } }
9
RPGLE
12
65
fb9f97fb57b9f9a87fdfbec3697d21f6bd251004
10,225
jariko
Apache License 2.0
_lifecycle-handler/_sample/lifecycle-handler-sample/src/main/java/io/androidalatan/lifecycle/handler/sample/SampleViewModel.kt
android-alatan
466,507,427
false
null
package io.androidalatan.lifecycle.handler.sample import android.Manifest import android.util.Log import android.widget.Toast import androidx.fragment.app.FragmentActivity import io.androidalatan.backkey.flow.handler.onBackPressedAsFlow import io.androidalatan.backkey.handler.api.BackKeyHandlerStream import io.androidalatan.bundle.collector.api.BundleCollectorStream import io.androidalatan.bundle.collector.flow.adapter.intentData import io.androidalatan.coroutine.dispatcher.api.DispatcherProvider import io.androidalatan.databinding.observables.ObservableString import io.androidalatan.lifecycle.handler.annotations.async.CreatedToDestroy import io.androidalatan.lifecycle.handler.annotations.async.ResumedToPause import io.androidalatan.lifecycle.handler.api.LifecycleListener import io.androidalatan.lifecycle.handler.api.LifecycleSource import io.androidalatan.lifecycle.handler.sample.adapter.PersonAdapter import io.androidalatan.lifecycle.handler.sample.bottomsheet.SampleBottomSheetDialogFragment import io.androidalatan.lifecycle.handler.sample.model.Person import io.androidalatan.lifecycle.handler.sample.prefs.SamplePrefs import io.androidalatan.request.permission.api.PermissionResult import io.androidalatan.request.permission.api.PermissionStream import io.androidalatan.request.permission.api.exception.PermissionGrantException import io.androidalatan.request.permission.flow.handler.requestAsFlow import io.androidalatan.result.handler.api.ResultInfo import io.androidalatan.result.handler.api.ResultStream import io.androidalatan.result.handler.flow.adapter.resultInfoAsFlow import io.androidalatan.router.api.Router import io.androidalatan.view.event.api.ViewInteractionStream import io.androidalatan.view.event.api.view.OnSizeChangeEvent import io.androidalatan.view.event.legacy.flow.asFlow import io.androidalatan.view.event.legacy.flow.view.onClickAsFlow import io.androidalatan.view.event.legacy.flow.view.onSizeChangeAsFlow import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart class SampleViewModel( lifecycleSource: LifecycleSource, private val activity: FragmentActivity, private val dispatcherProvider: DispatcherProvider, val adapter: PersonAdapter, private val samplePrefs: SamplePrefs, ) : LifecycleListener(lifecycleSource) { val text = ObservableString() val bundleText = ObservableString() val locationGrantedText = ObservableString("Try...") val countDownTextCreateToDestroy = ObservableString() val countDownTextResumeToPause = ObservableString() val countDownTextResumeToPauseFlow = ObservableString("Count : 0") val personText = ObservableString("") val personName = ObservableString("") @ResumedToPause fun updateTextView(viewInteractionStream: ViewInteractionStream): Flow<Long> { var count = 0 return viewInteractionStream.asFlow() .flatMapLatest { it.find(R.id.text) .onClickAsFlow() .onEach { text.set("${count++}") } } .onStart { text.set("Ready bro!!") } .catch { Log.d(this::class.java.simpleName, "updateTextView: ${it.localizedMessage}") } } @ResumedToPause fun updateTestViewSize(viewInteractionStream: ViewInteractionStream): Flow<OnSizeChangeEvent.ViewSize> { return viewInteractionStream.asFlow() .flatMapLatest { it.find(R.id.text) .onSizeChangeAsFlow() } .onEach { (width, height) -> Log.i(this::class.java.simpleName, "View Size [$width, $height]") } } @ResumedToPause fun observeClick(viewInteractionStream: ViewInteractionStream): Flow<Long> { return viewInteractionStream.asFlow() .flatMapLatest { it.find(R.id.button) .onClickAsFlow() .onEach { SampleBottomSheetDialogFragment().show(activity.supportFragmentManager, "SampleBottomSheetDialogFragment") } .flowOn(dispatcherProvider.main()) } } @CreatedToDestroy fun observeNamePref(): Flow<String> { return samplePrefs.getName() .onEach { personText.set(it) } } @ResumedToPause fun observeClickName(viewInteractionStream: ViewInteractionStream): Flow<Boolean> { return viewInteractionStream.asFlow() .flatMapLatest { view -> view.find(R.id.btn_pref_set_object) .onClickAsFlow() .flatMapLatest { samplePrefs.setName(personName.get()) } } } @ResumedToPause fun observeClickClear(viewInteractionStream: ViewInteractionStream): Flow<Boolean> { return viewInteractionStream.asFlow() .flatMapLatest { view -> view.find(R.id.btn_pref_clear) .onClickAsFlow() .flatMapLatest { samplePrefs.clear() } } } @CreatedToDestroy fun observeResult(resultStream: ResultStream): Flow<ResultInfo> { return resultStream.resultInfoAsFlow(REQ_CODE) .onEach { Toast.makeText(activity, "Got Result: ${it.resultCode()}", Toast.LENGTH_LONG) .show() } .flowOn(dispatcherProvider.main()) } @CreatedToDestroy fun countDownCreateToDestroy(): Flow<Int> { return (0..100) .asFlow() .flowOn(dispatcherProvider.main()) .onEach { value -> countDownTextCreateToDestroy.set("$value") delay(1000) } } @ResumedToPause fun countDownResumeToPause(): Flow<Int> { return (0..10) .asFlow() .flowOn(dispatcherProvider.default()) .map { value -> 10 - value } .flowOn(dispatcherProvider.main()) .onEach { value -> countDownTextResumeToPause.set("$value") delay(1000) } } @CreatedToDestroy fun savedInstances(bundleCollectorStream: BundleCollectorStream): Flow<Boolean> { return bundleCollectorStream.intentData() .onEach { bundleData -> val count: Int = (bundleData.getIntOrNull("count") ?: 0) + 1 bundleData.setInt("count", count) bundleText.set("$count") } .map { true } } @CreatedToDestroy fun setPersonData(): Flow<List<Person>> { return flowOf("Steve", "John", "Jonathan", "Mary", "Maria") .map { Person(it) } .let { source -> flow { val people = mutableListOf<Person>() source.collect { person -> people.add(person) } emit(people.toList()) } } .onEach { adapter.setData(it) } .flowOn(dispatcherProvider.main()) } @ResumedToPause fun observeBackey(backKeyHandlerStream: BackKeyHandlerStream, router: Router): Flow<Long> { return backKeyHandlerStream.onBackPressedAsFlow() .onEach { // do something router.end() } } @ResumedToPause fun flowBackey(backKeyHandlerStream: BackKeyHandlerStream): Flow<Long> { return backKeyHandlerStream.onBackPressedAsFlow() .onEach { // do something } } @CreatedToDestroy fun locationPermission( viewInteractionStream: ViewInteractionStream, permissionStream: PermissionStream ): Flow<PermissionResult> { return viewInteractionStream.asFlow() .flatMapLatest { it.find(R.id.invoke_permission) .onClickAsFlow() .flatMapLatest { permissionStream.requestAsFlow(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 19823) { builder -> builder.title("Permission") .message("Location...") .confirmButtonText("Confirm") .build() } .onEach { result -> val allGranted = result.result.all { it.second } if (allGranted) { locationGrantedText.set("Granted!!") } else { locationGrantedText.set("Failed to Grant") } } .catch { t -> if (t is PermissionGrantException) { locationGrantedText.set(t.message) emit(t.origin) } else { throw t } } } } } @OptIn(ExperimentalCoroutinesApi::class) @ResumedToPause fun flowCounterEvent(viewInteractionStream: ViewInteractionStream): Flow<Long> { return viewInteractionStream.asFlow() .flatMapLatest { view -> var flowCount = 0 view.find(R.id.btn_flow_count) .onClickAsFlow() .onEach { countDownTextResumeToPauseFlow.set("Count : ${++flowCount}") } } } companion object { const val REQ_CODE = 1002 } }
3
Kotlin
5
56
35b0ec7a89f8254db0af1830ac1de8a7124c6f09
10,305
LifecycleComponents
MIT License
profile/src/main/java/rdx/works/profile/domain/DeleteProfileUseCase.kt
radixdlt
513,047,280
false
{"Kotlin": 4299129, "HTML": 215350, "Ruby": 2757, "Shell": 1962}
package rdx.works.profile.domain import com.radixdlt.sargon.extensions.toJson import rdx.works.core.KeystoreManager import rdx.works.profile.data.repository.BackupProfileRepository import rdx.works.profile.data.repository.ProfileRepository import rdx.works.profile.domain.backup.BackupType import timber.log.Timber import javax.inject.Inject class DeleteProfileUseCase @Inject constructor( private val profileRepository: ProfileRepository, private val backupProfileRepository: BackupProfileRepository, private val keystoreManager: KeystoreManager ) { suspend operator fun invoke() { val profileThatWasBackedUpToCloud = backupProfileRepository.getTemporaryRestoringProfile(BackupType.Cloud) profileRepository.clearAllWalletData() keystoreManager.removeKeys().onFailure { Timber.d(it, "Failed to delete encryption keys") } if (profileThatWasBackedUpToCloud != null) { // Rescuing the copy of the cloud backup so as the user // can see it and restore it, even after deleting the profile and the keys. backupProfileRepository.saveTemporaryRestoringSnapshot( snapshotSerialised = profileThatWasBackedUpToCloud.toJson(), backupType = BackupType.Cloud ) } } suspend fun deleteProfileDataOnly() { profileRepository.clearProfileDataOnly() } }
9
Kotlin
11
6
8f9fe597c6234c2f01a6cb26708e5b88e90ab364
1,416
babylon-wallet-android
Apache License 2.0
app/src/main/java/com/amrdeveloper/linkhub/ui/link/LinkFragment.kt
AmrDeveloper
379,033,562
false
null
package com.amrdeveloper.linkhub.ui.link import android.os.Bundle import android.view.* import android.webkit.URLUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.amrdeveloper.linkhub.R import com.amrdeveloper.linkhub.data.Folder import com.amrdeveloper.linkhub.data.Link import com.amrdeveloper.linkhub.databinding.FragmentLinkBinding import com.amrdeveloper.linkhub.ui.adapter.FolderArrayAdapter import com.amrdeveloper.linkhub.ui.widget.PinnedLinksWidget import com.amrdeveloper.linkhub.util.showError import com.amrdeveloper.linkhub.util.showSnackBar import dagger.hilt.android.AndroidEntryPoint import java.text.SimpleDateFormat import java.util.Locale @AndroidEntryPoint class LinkFragment : Fragment() { private var _binding: FragmentLinkBinding? = null private val binding get() = _binding!! private val safeArguments by navArgs<LinkFragmentArgs>() private lateinit var currentLink: Link private var linkFolderID : Int = -1 private lateinit var folderMenuAdapter: FolderArrayAdapter private val linkViewModel by viewModels<LinkViewModel>() private val simpleDateFormatter = SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) safeArguments.link?.let { currentLink = it } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLinkBinding.inflate(inflater, container, false) handleIntentSharedLink() handleLinkArgument() setupObservers() setupFolderListMenu() linkViewModel.getFolderList() return binding.root } private fun handleIntentSharedLink() { val sharedLink = arguments?.getString("shared_link") ?: return if(URLUtil.isValidUrl(sharedLink).not()) { binding.linkUrlLayout.showError(R.string.error_link_url_invalid) return } binding.linkUrlEdit.setText(sharedLink) linkViewModel.generateLinkTitleAndSubTitle(sharedLink) } private fun handleLinkArgument() { if(::currentLink.isInitialized) { binding.linkTitleEdit.setText(currentLink.title) binding.linkSubtitleEdit.setText(currentLink.subtitle) binding.linkUrlEdit.setText(currentLink.url) binding.linkPinnedSwitch.isChecked = currentLink.isPinned val linkCreatedStamp = if (currentLink.createdTime == 0L) System.currentTimeMillis() else currentLink.createdTime val formattedCreationDate = simpleDateFormatter.format(linkCreatedStamp) binding.linkCreatedStatus.text ="Created at ${formattedCreationDate}" if (currentLink.isUpdated) { val linkUpdatedStamp = if (currentLink.createdTime == 0L) System.currentTimeMillis() else currentLink.createdTime val formattedUpdateDate = simpleDateFormatter.format(linkUpdatedStamp) binding.linkUpdatedStatus.text ="Last updated at ${formattedUpdateDate}" } if (currentLink.folderId != -1) linkViewModel.getFolderWithId(currentLink.folderId) } } private fun setupObservers() { linkViewModel.currentFolderLiveData.observe(viewLifecycleOwner) { binding.folderNameMenu.setText(it.name, false) linkFolderID = it.id } linkViewModel.folderLiveData.observe(viewLifecycleOwner) { folderMenuAdapter.addAll(it) } linkViewModel.linkInfoLiveData.observe(viewLifecycleOwner) { binding.linkTitleEdit.setText(it.linkTitle) binding.linkSubtitleEdit.setText(it.linkSubtitle) } linkViewModel.completeSuccessTask.observe(viewLifecycleOwner) { PinnedLinksWidget.refresh(requireContext()) findNavController().navigateUp() } linkViewModel.errorMessages.observe(viewLifecycleOwner) { messageId -> activity.showSnackBar(messageId) } } private fun setupFolderListMenu() { binding.folderNameMenu.setOnItemClickListener { _, _, position, _ -> val folder = folderMenuAdapter.getItem(position) if (folder != null) linkFolderID = folder.id } folderMenuAdapter = FolderArrayAdapter(requireContext()) folderMenuAdapter.add(Folder("None", false, id = -1)) binding.folderNameMenu.setAdapter(folderMenuAdapter) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_save, menu) inflater.inflate(R.menu.menu_delete, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.save_action -> { if(::currentLink.isInitialized) updateCurrentLink() else createNewLink() true } R.id.delete_action -> { if(::currentLink.isInitialized) deleteCurrentLink() else findNavController().navigateUp() true } else -> super.onOptionsItemSelected(item) } } private fun createNewLink() { val title = binding.linkTitleEdit.text.toString() val subtitle = binding.linkSubtitleEdit.text.toString() val url = binding.linkUrlEdit.text.toString() val isPinned = binding.linkPinnedSwitch.isChecked if(title.isEmpty()) { binding.linkTitleLayout.showError(R.string.error_link_title_empty) return } if(url.isEmpty()) { binding.linkUrlLayout.showError(R.string.error_link_url_empty) return } if(URLUtil.isValidUrl(url).not()) { binding.linkUrlLayout.showError(R.string.error_link_url_invalid) return } val link = Link(title, subtitle, url, isPinned, folderId = linkFolderID) linkViewModel.createNewLink(link) } private fun updateCurrentLink() { val title = binding.linkTitleEdit.text.toString() val subtitle = binding.linkSubtitleEdit.text.toString() val url = binding.linkUrlEdit.text.toString() val isPinned = binding.linkPinnedSwitch.isChecked if(title.isEmpty()) { binding.linkTitleLayout.showError(R.string.error_link_title_empty) return } if(url.isEmpty()) { binding.linkUrlLayout.showError(R.string.error_link_url_empty) return } if(URLUtil.isValidUrl(url).not()) { binding.linkUrlLayout.showError(R.string.error_link_url_invalid) return } currentLink.title = title currentLink.subtitle = subtitle currentLink.url = url currentLink.isPinned = isPinned currentLink.isUpdated = true currentLink.folderId = linkFolderID currentLink.lastUpdatedTime = System.currentTimeMillis() linkViewModel.updateLink(currentLink) } private fun deleteCurrentLink() { linkViewModel.deleteLink(currentLink) } override fun onDestroyView() { binding.folderNameMenu.setAdapter(null) super.onDestroyView() _binding = null } }
9
Kotlin
8
90
1a0179c15e03001898022499324b2d92d6a699c3
7,573
LinkHub
MIT License
app/src/main/java/com/flixclusive/presentation/mobile/utils/DragAndDropUtils.kt
rhenwinch
659,237,375
false
null
package com.flixclusive.presentation.mobile.utils import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.gestures.scrollBy import androidx.compose.runtime.MutableState import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.pointerInput import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch object DragAndDropUtils { fun Modifier.dragGestureHandler( scope: CoroutineScope, itemListDragAndDropState: ItemListDragAndDropState, overscrollJob: MutableState<Job?>, feedbackLongPress: () -> Unit, ): Modifier = pointerInput(Unit) { detectDragGesturesAfterLongPress( onDrag = { change, offset -> change.consume() itemListDragAndDropState.onDrag(offset) handleOverscrollJob(overscrollJob, scope, itemListDragAndDropState) }, onDragStart = { offset -> feedbackLongPress() itemListDragAndDropState.onDragStart(offset) }, onDragEnd = { itemListDragAndDropState.onDragInterrupted() }, onDragCancel = { itemListDragAndDropState.onDragInterrupted() } ) } private fun handleOverscrollJob( overscrollJob: MutableState<Job?>, scope: CoroutineScope, itemListDragAndDropState: ItemListDragAndDropState, ) { if (overscrollJob.value?.isActive == true) return val overscrollOffset = itemListDragAndDropState.checkForOverScroll() if (overscrollOffset != 0f) { overscrollJob.value = scope.launch { itemListDragAndDropState.getLazyListState().scrollBy(overscrollOffset) } } else { overscrollJob.value?.cancel() } } }
26
null
7
96
a90215b8c40ac0675cd217b38b842d2d57c90acc
1,862
Flixclusive
MIT License
app/src/main/kotlin/com/duongkhai/snakegame/presentation/screen/GameScreen.kt
duongkhaineverdie
784,021,262
false
{"Kotlin": 60320}
package com.duongkhai.snakegame.presentation.screen import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.duongkhai.snakegame.R import com.duongkhai.snakegame.domain.game.GameEngine import com.duongkhai.snakegame.domain.game.SnakeDirection import com.duongkhai.snakegame.presentation.activity.GameActivity import com.duongkhai.snakegame.presentation.component.AppBar import com.duongkhai.snakegame.presentation.component.Board import com.duongkhai.snakegame.presentation.component.Controller @Composable fun GameScreen(gameEngine: GameEngine, score: Int) { val state = gameEngine.state.collectAsState(initial = null) val activity = LocalContext.current as GameActivity AppBar( title = stringResource(id = R.string.your_score, score), onBackClicked = { activity.finish() }) { contentPadding -> Column( modifier = Modifier.padding(contentPadding), horizontalAlignment = Alignment.CenterHorizontally ) { state.value?.let { Board(it) } Controller { when (it) { SnakeDirection.Up -> gameEngine.move = Pair(0, -1) SnakeDirection.Left -> gameEngine.move = Pair(-1, 0) SnakeDirection.Right -> gameEngine.move = Pair(1, 0) SnakeDirection.Down -> gameEngine.move = Pair(0, 1) } } } } }
0
Kotlin
0
0
25aad736e4ddd449be826a93bda8d5997dc1b77b
1,719
SnakeWebview
MIT License
feature/my-playground/src/main/java/com/alxnophis/jetpack/myplayground/ui/contract/MyPlaygroundContract.kt
alex-amenos
370,444,543
false
{"Kotlin": 286102, "Ruby": 6147, "Shell": 169}
package com.alxnophis.jetpack.myplayground.ui.contract import arrow.optics.optics import com.alxnophis.jetpack.core.ui.viewmodel.UiEvent import com.alxnophis.jetpack.core.ui.viewmodel.UiState import com.alxnophis.jetpack.kotlin.constants.EMPTY internal sealed class MyPlaygroundEvent : UiEvent { data object GoBackRequested : MyPlaygroundEvent() data class TextFieldChanged(val value: String) : MyPlaygroundEvent() } @optics internal data class MyPlaygroundState( val textFieldValue: String, ) : UiState { internal companion object { val initialState = MyPlaygroundState( textFieldValue = EMPTY, ) } }
7
Kotlin
0
4
cfe4f0c809b6246f1a6ad6ac2577ea191c3fdbac
674
Jetpack
MIT License
dp-oppdrag-app/src/test/kotlin/no/nav/dagpenger/oppdrag/iverksetting/OppdragKvitteringstatusTest.kt
navikt
596,541,750
false
{"Kotlin": 165052, "Dockerfile": 255}
package no.nav.dagpenger.oppdrag.iverksetting import no.nav.dagpenger.kontrakter.oppdrag.OppdragStatus import no.nav.dagpenger.oppdrag.iverksetting.domene.status import no.trygdeetaten.skjema.oppdrag.Mmel import no.trygdeetaten.skjema.oppdrag.Oppdrag import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class OppdragKvitteringstatusTest { @Test fun `konverterer status`() { assertEquals(OppdragStatus.KVITTERT_OK, lagOppdrag("00").status) assertEquals(OppdragStatus.KVITTERT_MED_MANGLER, lagOppdrag("04").status) assertEquals(OppdragStatus.KVITTERT_FUNKSJONELL_FEIL, lagOppdrag("08").status) assertEquals(OppdragStatus.KVITTERT_TEKNISK_FEIL, lagOppdrag("12").status) assertEquals(OppdragStatus.KVITTERT_UKJENT, lagOppdrag("Ukjent").status) } private fun lagOppdrag(alvorlighetsgrad: String) = Oppdrag().apply { mmel = Mmel() mmel.alvorlighetsgrad = alvorlighetsgrad } }
12
Kotlin
0
0
fc887c218d792f94e10a04b6936e454c9ada616f
992
dp-oppdrag
MIT License
app/src/main/java/dev/patrickgold/florisboard/ime/core/InputView.kt
geanbrandao
305,498,904
false
null
/* * Copyright (C) 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.patrickgold.florisboard.ime.core import android.content.Context import android.content.res.Configuration import android.util.AttributeSet import android.util.Log import android.widget.LinearLayout import android.widget.ViewFlipper import dev.patrickgold.florisboard.BuildConfig import dev.patrickgold.florisboard.R import dev.patrickgold.florisboard.util.ViewLayoutUtils import kotlin.math.roundToInt /** * Root view of the keyboard. Notifies [FlorisBoard] when it has been attached to a window. */ class InputView : LinearLayout { private var florisboard: FlorisBoard = FlorisBoard.getInstance() private val prefs: PrefHelper = PrefHelper.getDefaultInstance(context) var desiredInputViewHeight: Int = resources.getDimension(R.dimen.inputView_baseHeight).roundToInt() private set var desiredSmartbarHeight: Int = resources.getDimension(R.dimen.smartbar_baseHeight).roundToInt() private set var desiredTextKeyboardViewHeight: Int = resources.getDimension(R.dimen.textKeyboardView_baseHeight).roundToInt() private set var desiredMediaKeyboardViewHeight: Int = resources.getDimension(R.dimen.mediaKeyboardView_baseHeight).roundToInt() private set var mainViewFlipper: ViewFlipper? = null private set var oneHandedCtrlPanelStart: LinearLayout? = null private set var oneHandedCtrlPanelEnd: LinearLayout? = null private set constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onAttachedToWindow() { if (BuildConfig.DEBUG) Log.i(this::class.simpleName, "onAttachedToWindow()") super.onAttachedToWindow() mainViewFlipper = findViewById(R.id.main_view_flipper) oneHandedCtrlPanelStart = findViewById(R.id.one_handed_ctrl_panel_start) oneHandedCtrlPanelEnd = findViewById(R.id.one_handed_ctrl_panel_end) florisboard.registerInputView(this) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val heightFactor = when (resources.configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE -> 0.85f else -> if (prefs.keyboard.oneHandedMode != "off") { 0.9f } else { 1.0f } } * when (prefs.keyboard.heightFactor) { "extra_short" -> 0.85f "short" -> 0.90f "mid_short" -> 0.95f "normal" -> 1.00f "mid_tall" -> 1.05f "tall" -> 1.10f "extra_tall" -> 1.15f else -> 1.00f } var height = (resources.getDimension(R.dimen.inputView_baseHeight) * heightFactor).roundToInt() desiredInputViewHeight = height desiredSmartbarHeight = (0.16129 * height).roundToInt() desiredTextKeyboardViewHeight = height - desiredSmartbarHeight desiredMediaKeyboardViewHeight = height // Add bottom offset for curved screens here. As the desired heights have already been set, // adding a value to the height now will result in a bottom padding (aka offset). height += ViewLayoutUtils.convertDpToPixel(florisboard.prefs.keyboard.bottomOffset.toFloat(), context).toInt() super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)) } }
0
null
0
1
671ff1d8b40f631aa68af30f47348608593fe891
4,107
florisboard
Apache License 2.0
compiler/testData/codegen/boxInline/anonymousObject/capturedLambdaInInline3.2.kt
msdgwzhy6
52,061,310
true
{"Java": 15875830, "Kotlin": 12695228, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 29983, "Lex": 16598, "ANTLR": 9689, "CSS": 9358, "Groovy": 6859, "Shell": 4704, "IDL": 4669, "Batchfile": 3703}
package test inline fun bar(crossinline y: () -> String) = { { { call(y) }() }() } public inline fun <T> call(crossinline f: () -> T): T = {{ f() }()}()
0
Java
0
1
f713adc96e9adeacb1373fc170a5ece1bf2fc1a2
158
kotlin
Apache License 2.0
app/src/main/kotlin/com/equalexperts/slack/api/rest/model/Timestamp.kt
EqualExperts
94,084,953
false
{"Kotlin": 121397, "HCL": 15381}
package com.equalexperts.slack.api.rest.model import java.time.Instant import java.time.ZoneOffset.UTC import java.time.ZonedDateTime data class Timestamp constructor(private val opaque: String) { constructor(timeBased: ZonedDateTime) : this(timeBased.toEpochSecond().toString()) override fun toString(): String = opaque fun toZonedDateTime(): ZonedDateTime { return Instant.ofEpochSecond(opaque.split(".")[0].toLong()).atZone(UTC) } }
1
Kotlin
7
17
837f229cbfa89eb66392ea8277cb24f0b0b38e5f
462
slack-gardener
Apache License 2.0
arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/continuations/Effect.kt
lukaszkalnik
427,116,886
true
{"Kotlin": 1928099, "SCSS": 99659, "JavaScript": 83153, "HTML": 25306, "Java": 7691, "Ruby": 917, "Shell": 98}
package arrow.core.continuations import arrow.core.Either import arrow.core.Ior import arrow.core.NonFatal import arrow.core.Option import arrow.core.Some import arrow.core.Validated import arrow.core.identity import arrow.core.nonFatalOrThrow import kotlin.coroutines.Continuation import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn import kotlin.coroutines.resume /** * [Effect] represents a function of `suspend () -> A`, that short-circuit with a value of [R] (and [Throwable]), * or completes with a value of [A]. * * So [Effect] is defined by `suspend fun <B> fold(f: suspend (R) -> B, g: suspend (A) -> B): B`, * to map both values of [R] and [A] to a value of `B`. * * <!--- TOC --> * * * [Writing a program with Effect<R, A>](#writing-a-program-with-effect<r-a>) * * [Handling errors](#handling-errors) * * [Structured Concurrency](#structured-concurrency) * * [Arrow Fx Coroutines](#arrow-fx-coroutines) * * [parZip](#parzip) * * [parTraverse](#partraverse) * * [raceN](#racen) * * [bracketCase / Resource](#bracketcase--resource) * * [KotlinX](#kotlinx) * * [withContext](#withcontext) * * [async](#async) * * [launch](#launch) * * [Strange edge cases](#strange-edge-cases) * * <!--- END --> * * * ## Writing a program with Effect<R, A> * * Let's write a small program to read a file from disk, and instead of having the program work exception based we want to * turn it into a polymorphic type-safe program. * * We'll start by defining a small function that accepts a [String], and does some simply validation to check that the path * is not empty. If the path is empty, we want to program to result in `EmptyPath`. So we're immediately going to see how * we can raise an error of any arbitrary type [R] by using the function `shift`. The name `shift` comes shifting (or * changing, especially unexpectedly), away from the computation and finishing the `Continuation` with [R]. * * <!--- INCLUDE * import arrow.core.continuations.Effect * import arrow.core.continuations.effect * import arrow.core.continuations.ensureNotNull * --> * ```kotlin * object EmptyPath * * fun readFile(path: String): Effect<EmptyPath, Unit> = effect { * if (path.isEmpty()) shift(EmptyPath) else Unit * } * ``` * * Here we see how we can define an `Effect<R, A>` which has `EmptyPath` for the shift type [R], and `Unit` for the success * type [A]. * * Patterns like validating a [Boolean] is very common, and the [Effect] DSL offers utility functions like [kotlin.require] * and [kotlin.requireNotNull]. They're named [EffectScope.ensure] and [ensureNotNull] to avoid conflicts with the `kotlin` namespace. * So let's rewrite the function from above to use the DSL instead. * * ```kotlin * fun readFile2(path: String?): Effect<EmptyPath, Unit> = effect { * ensureNotNull(path) { EmptyPath } * ensure(path.isEmpty()) { EmptyPath } * } * ``` * <!--- KNIT example-effect-guide-01.kt --> * * Now that we have the path, we can read from the `File` and return it as a domain model `Content`. * We also want to take a look at what exceptions reading from a file might occur `FileNotFoundException` & `SecurityError`, * so lets make some domain errors for those too. Grouping them as a sealed interface is useful since that way we can resolve *all* errors in a type safe manner. * * <!--- INCLUDE * import arrow.core.Either * import arrow.core.Ior * import arrow.core.None * import arrow.core.Validated * import arrow.core.continuations.Effect * import arrow.core.continuations.effect * import arrow.core.continuations.ensureNotNull * import io.kotest.matchers.collections.shouldNotBeEmpty * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeInstanceOf * import java.io.File * import java.io.FileNotFoundException * --> * ```kotlin * @JvmInline * value class Content(val body: List<String>) * * sealed interface FileError * @JvmInline value class SecurityError(val msg: String?) : FileError * @JvmInline value class FileNotFound(val path: String) : FileError * object EmptyPath : FileError { * override fun toString() = "EmptyPath" * } * ``` * * We can finish our function, but we need to refactor the return type from `Unit` to `Content` and the error type from `EmptyPath` to `FileError`. * * ```kotlin * fun readFile(path: String?): Effect<FileError, Content> = effect { * ensureNotNull(path) { EmptyPath } * ensure(path.isNotEmpty()) { EmptyPath } * try { * val lines = File(path).readLines() * Content(lines) * } catch (e: FileNotFoundException) { * shift(FileNotFound(path)) * } catch (e: SecurityException) { * shift(SecurityError(e.message)) * } * } * ``` * * The `readFile` function defines a `suspend fun` that will return: * * - the `Content` of a given `path` * - a `FileError` * - An unexpected fatal error (`OutOfMemoryException`) * * Since these are the properties of our `Effect` function, we can turn it into a value. * * ```kotlin * suspend fun main() { * readFile("").toEither() shouldBe Either.Left(EmptyPath) * readFile("knit.properties").toValidated() shouldBe Validated.Invalid(FileNotFound("knit.properties")) * readFile("gradle.properties").toIor() shouldBe Ior.Left(FileNotFound("gradle.properties")) * readFile("README.MD").toOption { None } shouldBe None * * readFile("build.gradle.kts").fold({ _: FileError -> null }, { it }) * .shouldBeInstanceOf<Content>() * .body.shouldNotBeEmpty() * } * ``` * <!--- KNIT example-effect-guide-02.kt --> * * The functions above are available out of the box, but it's easy to define your own extension functions in terms * of `fold`. Implementing the `toEither()` operator is as simple as: * * <!--- INCLUDE * import arrow.core.Either * import arrow.core.None * import arrow.core.Option * import arrow.core.Some * import arrow.core.continuations.Effect * import arrow.core.identity * --> * ```kotlin * suspend fun <R, A> Effect<R, A>.toEither(): Either<R, A> = * fold({ Either.Left(it) }) { Either.Right(it) } * * suspend fun <A> Effect<None, A>.toOption(): Option<A> = * fold(::identity) { Some(it) } * ``` * <!--- KNIT example-effect-guide-03.kt --> * * Adding your own syntax to `EffectScope<R>` is not advised, yet, but will be easy once "Multiple Receivers" become available. * * ``` * context(EffectScope<R>) * suspend fun <R, A> Either<R, A>.bind(): A = * when (this) { * is Either.Left -> shift(value) * is Either.Right -> value * } * * context(EffectScope<None>) * fun <A> Option<A>.bind(): A = * fold({ shift(it) }, ::identity) * ``` * * ## Handling errors * * Handling errors of type [R] is the same as handling errors for any other data type in Arrow. * `Effect<R, A>` offers `handleError`, `handleErrorWith`, `redeem`, `redeemWith` and `attempt`. * * As you can see in the examples below it is possible to resolve errors of [R] or `Throwable` in `Effect<R, A>` in a generic manner. * There is no need to run `Effect<R, A>` into `Either<R, A>` before you can access [R], * you can simply call the same functions on `Effect<R, A>` as you would on `Either<R, A>` directly. * * <!--- INCLUDE * import arrow.core.Either * import arrow.core.continuations.Effect * import arrow.core.continuations.effect * import arrow.core.identity * import io.kotest.matchers.shouldBe * --> * ```kotlin * val failed: Effect<String, Int> = * effect { shift("failed") } * * val resolved: Effect<Nothing, Int> = * failed.handleError { it.length } * * val newError: Effect<List<Char>, Int> = * failed.handleErrorWith { str -> * effect { shift(str.reversed().toList()) } * } * * val redeemed: Effect<Nothing, Int> = * failed.redeem({ str -> str.length }, ::identity) * * val captured: Effect<String, Result<Int>> = * effect<String, Int> { 1 }.attempt() * * suspend fun main() { * failed.toEither() shouldBe Either.Left("failed") * resolved.toEither() shouldBe Either.Right(6) * newError.toEither() shouldBe Either.Left(listOf('d', 'e', 'l', 'i', 'a', 'f')) * redeemed.toEither() shouldBe Either.Right(6) * captured.toEither() shouldBe Either.Right(Result.success(1)) * } * ``` * <!--- KNIT example-effect-guide-04.kt --> * * Note: * Handling errors can also be done with `try/catch` but this is **not recommended**, it uses `CancellationException` which is used to cancel `Coroutine`s and is advised not to capture in Kotlin. * The `CancellationException` from `Effect` is `ShiftCancellationException`, this a public type, thus can be distinguished from any other `CancellationException` if necessary. * * ## Structured Concurrency * * `Effect<R, A>` relies on `kotlin.cancellation.CancellationException` to `shift` error values of type [R] inside the `Continuation` since it effectively cancels/short-circuits it. * For this reason `shift` adheres to the same rules as [`Structured Concurrency`](https://kotlinlang.org/docs/coroutines-basics.html#structured-concurrency) * * Let's overview below how `shift` behaves with the different concurrency builders from Arrow Fx & KotlinX Coroutines. * In the examples below we're going to be using a utility to show how _sibling tasks_ get cancelled. * The utility function show below called `awaitExitCase` will `never` finish suspending, and completes a `Deferred` with the `ExitCase`. * `ExitCase` is a sealed class that can be a value of `Failure(Throwable)`, `Cancelled(CancellationException)`, or `Completed`. * Since `awaitExitCase` suspends forever, it can only result in `Cancelled(CancellationException)`. * * <!--- INCLUDE * import arrow.core.continuations.effect * import arrow.fx.coroutines.ExitCase * import arrow.fx.coroutines.guaranteeCase * import arrow.fx.coroutines.parZip * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeTypeOf * import kotlinx.coroutines.CompletableDeferred * import kotlinx.coroutines.awaitCancellation * --> * ```kotlin * suspend fun <A> awaitExitCase(exit: CompletableDeferred<ExitCase>): A = * guaranteeCase(::awaitCancellation) { exitCase -> exit.complete(exitCase) } * * ``` * * ### Arrow Fx Coroutines * All operators in Arrow Fx Coroutines run in place, so they have no way of leaking `shift`. * It's there always safe to compose `effect` with any Arrow Fx combinator. Let's see some small examples below. * * #### parZip * * ```kotlin * suspend fun main() { * val error = "Error" * val exit = CompletableDeferred<ExitCase>() * effect<String, Int> { * parZip({ awaitExitCase<Int>(exit) }, { shift<Int>(error) }) { a, b -> a + b } * }.fold({ it shouldBe error }, { fail("Int can never be the result") }) * exit.await().shouldBeTypeOf<ExitCase>() * } * ``` * <!--- KNIT example-effect-guide-05.kt --> * * #### parTraverse * <!--- INCLUDE * import arrow.core.continuations.effect * import arrow.fx.coroutines.ExitCase * import arrow.fx.coroutines.guaranteeCase * import arrow.fx.coroutines.parTraverse * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeTypeOf * import kotlinx.coroutines.CompletableDeferred * import kotlinx.coroutines.awaitCancellation * * suspend fun <A> awaitExitCase(exit: CompletableDeferred<ExitCase>): A = * guaranteeCase(::awaitCancellation) { exitCase -> exit.complete(exitCase) } * * suspend fun <A> CompletableDeferred<A>.getOrNull(): A? = * if (isCompleted) await() else null * --> * ```kotlin * suspend fun main() { * val error = "Error" * val exits = (0..3).map { CompletableDeferred<ExitCase>() } * effect<String, List<Unit>> { * (0..4).parTraverse { index -> * if (index == 4) shift(error) * else awaitExitCase(exits[index]) * } * }.fold({ msg -> msg shouldBe error }, { fail("Int can never be the result") }) * // It's possible not all parallel task got launched, and in those cases awaitCancellation never ran * exits.forEach { exit -> exit.getOrNull()?.shouldBeTypeOf<ExitCase.Cancelled>() } * } * ``` * <!--- KNIT example-effect-guide-06.kt --> * * `parTraverse` will launch 5 tasks, for every element in `1..5`. * The last task to get scheduled will `shift` with "error", and it will cancel the other launched tasks before returning. * * #### raceN * <!--- INCLUDE * import arrow.core.continuations.effect * import arrow.core.merge * import arrow.fx.coroutines.ExitCase * import arrow.fx.coroutines.guaranteeCase * import arrow.fx.coroutines.raceN * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeTypeOf * import kotlinx.coroutines.CompletableDeferred * import kotlinx.coroutines.awaitCancellation * * suspend fun <A> awaitExitCase(exit: CompletableDeferred<ExitCase>): A = * guaranteeCase(::awaitCancellation) { exitCase -> exit.complete(exitCase) } * * suspend fun <A> CompletableDeferred<A>.getOrNull(): A? = * if (isCompleted) await() else null * --> * ```kotlin * suspend fun main() { * val error = "Error" * val exit = CompletableDeferred<ExitCase>() * effect<String, Int> { * raceN({ awaitExitCase<Int>(exit) }) { shift<Int>(error) } * .merge() // Flatten Either<Int, Int> result from race into Int * }.fold({ msg -> msg shouldBe error }, { fail("Int can never be the result") }) * // It's possible not all parallel task got launched, and in those cases awaitCancellation never ran * exit.getOrNull()?.shouldBeTypeOf<ExitCase.Cancelled>() * } * ``` * <!--- KNIT example-effect-guide-07.kt --> * * `raceN` races `n` suspend functions in parallel, and cancels all participating functions when a winner is found. * We can consider the function that `shift`s the winner of the race, except with a shifted value instead of a successful one. * So when a function in the race `shift`s, and thus short-circuiting the race, it will cancel all the participating functions. * * #### bracketCase / Resource * <!--- INCLUDE * import arrow.core.continuations.effect * import arrow.fx.coroutines.ExitCase * import arrow.fx.coroutines.bracketCase * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeTypeOf * import kotlinx.coroutines.CompletableDeferred * import java.io.BufferedReader * import java.io.File * --> * ```kotlin * suspend fun main() { * val error = "Error" * val exit = CompletableDeferred<ExitCase>() * effect<String, Int> { * bracketCase( * acquire = { File("build.gradle.kts").bufferedReader() }, * use = { reader: BufferedReader -> shift(error) }, * release = { reader, exitCase -> * reader.close() * exit.complete(exitCase) * } * ) * }.fold({ it shouldBe error }, { fail("Int can never be the result") }) * exit.await().shouldBeTypeOf<ExitCase.Cancelled>() * } * ``` * <!--- KNIT example-effect-guide-08.kt --> * * <!--- INCLUDE * import arrow.core.continuations.effect * import arrow.fx.coroutines.ExitCase * import arrow.fx.coroutines.Resource * import arrow.fx.coroutines.fromAutoCloseable * import arrow.fx.coroutines.releaseCase * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeTypeOf * import kotlinx.coroutines.CompletableDeferred * import java.io.BufferedReader * import java.io.File * --> * ```kotlin * suspend fun main() { * val error = "Error" * val exit = CompletableDeferred<ExitCase>() * * fun bufferedReader(path: String): Resource<BufferedReader> = * Resource.fromAutoCloseable { File(path).bufferedReader() } * .releaseCase { _, exitCase -> exit.complete(exitCase) } * * effect<String, Int> { * val lineCount = bufferedReader("build.gradle.kts") * .use { reader -> shift<Int>(error) } * lineCount * }.fold({ it shouldBe error }, { fail("Int can never be the result") }) * exit.await().shouldBeTypeOf<ExitCase.Cancelled>() * } * ``` * <!--- KNIT example-effect-guide-09.kt --> * * ### KotlinX * #### withContext * It's always safe to call `shift` from `withContext` since it runs in place, so it has no way of leaking `shift`. * When `shift` is called from within `withContext` it will cancel all `Job`s running inside the `CoroutineScope` of `withContext`. * * <!--- INCLUDE * import arrow.core.continuations.Effect * import arrow.core.continuations.effect * import arrow.core.continuations.ensureNotNull * import arrow.fx.coroutines.ExitCase * import arrow.fx.coroutines.guaranteeCase * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import io.kotest.matchers.types.shouldBeInstanceOf * import kotlinx.coroutines.CompletableDeferred * import kotlinx.coroutines.Dispatchers * import kotlinx.coroutines.awaitCancellation * import kotlinx.coroutines.launch * import kotlinx.coroutines.withContext * import java.io.File * import java.io.FileNotFoundException * * @JvmInline * value class Content(val body: List<String>) * * sealed interface FileError * @JvmInline value class SecurityError(val msg: String?) : FileError * @JvmInline value class FileNotFound(val path: String) : FileError * object EmptyPath : FileError { * override fun toString() = "EmptyPath" * } * * fun readFile(path: String?): Effect<FileError, Content> = effect { * ensureNotNull(path) { EmptyPath } * ensure(path.isNotEmpty()) { EmptyPath } * try { * val lines = File(path).readLines() * Content(lines) * } catch (e: FileNotFoundException) { * shift(FileNotFound(path)) * } catch (e: SecurityException) { * shift(SecurityError(e.message)) * } * } * * suspend fun <A> awaitExitCase(exit: CompletableDeferred<ExitCase>): A = * guaranteeCase(::awaitCancellation) { exitCase -> exit.complete(exitCase) } * --> * ```kotlin * suspend fun main() { * val exit = CompletableDeferred<ExitCase>() * effect<FileError, Int> { * withContext(Dispatchers.IO) { * val job = launch { awaitExitCase(exit) } * val content = readFile("failure").bind() * job.join() * content.body.size * } * }.fold({ e -> e shouldBe FileNotFound("failure") }, { fail("Int can never be the result") }) * exit.await().shouldBeInstanceOf<ExitCase>() * } * ``` * <!--- KNIT example-effect-guide-10.kt --> * * #### async * * When calling `shift` from `async` you should **always** call `await`, otherwise `shift` can leak out of its scope. * * <!--- INCLUDE * import arrow.core.continuations.effect * import io.kotest.assertions.fail * import io.kotest.matchers.collections.shouldBeIn * import kotlinx.coroutines.async * import kotlinx.coroutines.coroutineScope * --> * ```kotlin * suspend fun main() { * val errorA = "ErrorA" * val errorB = "ErrorB" * coroutineScope { * effect<String, Int> { * val fa = async<Int> { shift(errorA) } * val fb = async<Int> { shift(errorB) } * fa.await() + fb.await() * }.fold({ error -> error shouldBeIn listOf(errorA, errorB) }, { fail("Int can never be the result") }) * } * } * ``` * <!--- KNIT example-effect-guide-11.kt --> * * #### launch * * <!--- INCLUDE * import arrow.core.continuations.effect * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * import kotlinx.coroutines.coroutineScope * import kotlinx.coroutines.launch * --> * ```kotlin * suspend fun main() { * val errorA = "ErrorA" * val errorB = "ErrorB" * val int = 45 * effect<String, Int> { * coroutineScope<Int> { * launch { shift(errorA) } * launch { shift(errorB) } * int * } * }.fold({ fail("Shift can never finish") }, { it shouldBe int }) * } * ``` * <!--- KNIT example-effect-guide-12.kt --> * * #### Strange edge cases * * **NOTE** * Capturing `shift` into a lambda, and leaking it outside of `Effect` to be invoked outside will yield unexpected results. * Below we capture `shift` from inside the DSL, and then invoke it outside its context `EffectScope<String>`. * * <!--- INCLUDE * import arrow.core.continuations.effect * import kotlinx.coroutines.Deferred * import kotlinx.coroutines.async * import kotlinx.coroutines.coroutineScope * * suspend fun main() { * --> * <!--- SUFFIX * } * --> * ```kotlin * effect<String, suspend () -> Unit> { * suspend { shift("error") } * }.fold({ }, { leakedShift -> leakedShift.invoke() }) * ``` * * The same violation is possible in all DSLs in Kotlin, including Structured Concurrency. * * ```kotlin * val leakedAsync = coroutineScope<suspend () -> Deferred<Unit>> { * suspend { * async { * println("I am never going to run, until I get called invoked from outside") * } * } * } * * leakedAsync.invoke().await() * ``` * <!--- KNIT example-effect-guide-13.kt --> */ public interface Effect<R, A> { /** * Runs the suspending computation by creating a [Continuation], and running the `fold` function * over the computation. * * When the [Effect] has shifted with [R] it will [recover] the shifted value to [B], and when it * ran the computation to completion it will [transform] the value [A] to [B]. * * ```kotlin * import arrow.core.continuations.effect * import io.kotest.matchers.shouldBe * * suspend fun main() { * val shift = effect<String, Int> { * shift("Hello, World!") * }.fold({ str: String -> str }, { int -> int.toString() }) * shift shouldBe "Hello, World!" * * val res = effect<String, Int> { * 1000 * }.fold({ str: String -> str.length }, { int -> int }) * res shouldBe 1000 * } * ``` * <!--- KNIT example-effect-01.kt --> */ public suspend fun <B> fold( recover: suspend (shifted: R) -> B, transform: suspend (value: A) -> B ): B /** * Like [fold] but also allows folding over any unexpected [Throwable] that might have occurred. * @see fold */ public suspend fun <B> fold( error: suspend (error: Throwable) -> B, recover: suspend (shifted: R) -> B, transform: suspend (value: A) -> B ): B = try { fold(recover, transform) } catch (e: Throwable) { error(e.nonFatalOrThrow()) } /** * [fold] the [Effect] into an [Either]. Where the shifted value [R] is mapped to [Either.Left], and * result value [A] is mapped to [Either.Right]. */ public suspend fun toEither(): Either<R, A> = fold({ Either.Left(it) }) { Either.Right(it) } /** * [fold] the [Effect] into an [Ior]. Where the shifted value [R] is mapped to [Ior.Left], and * result value [A] is mapped to [Ior.Right]. */ public suspend fun toIor(): Ior<R, A> = fold({ Ior.Left(it) }) { Ior.Right(it) } /** * [fold] the [Effect] into an [Validated]. Where the shifted value [R] is mapped to * [Validated.Invalid], and result value [A] is mapped to [Validated.Valid]. */ public suspend fun toValidated(): Validated<R, A> = fold({ Validated.Invalid(it) }) { Validated.Valid(it) } /** * [fold] the [Effect] into an [Option]. Where the shifted value [R] is mapped to [Option] by the * provided function [orElse], and result value [A] is mapped to [Some]. */ public suspend fun toOption(orElse: suspend (R) -> Option<A>): Option<A> = fold(orElse, ::Some) /** * [fold] the [Effect] into an [A?]. Where the shifted value [R] is mapped to * [null], and result value [A]. */ public suspend fun orNull(): A? = fold({ null }, ::identity) /** Runs the [Effect] and captures any [NonFatal] exception into [Result]. */ public fun attempt(): Effect<R, Result<A>> = effect { try { Result.success(bind()) } catch (e: Throwable) { Result.failure(e.nonFatalOrThrow()) } } public fun handleError(recover: suspend (R) -> A): Effect<Nothing, A> = effect { fold(recover, ::identity) } public fun <R2> handleErrorWith(recover: suspend (R) -> Effect<R2, A>): Effect<R2, A> = effect { fold({ recover(it).bind() }, ::identity) } public fun <B> redeem(recover: suspend (R) -> B, transform: suspend (A) -> B): Effect<Nothing, B> = effect { fold(recover, transform) } public fun <R2, B> redeemWith( recover: suspend (R) -> Effect<R2, B>, transform: suspend (A) -> Effect<R2, B> ): Effect<R2, B> = effect { fold(recover, transform).bind() } } /** * **AVOID USING THIS TYPE, it's meant for low-level cancellation code** When in need in low-level * code, you can use this type to differentiate between a foreign [CancellationException] and the * one from [Effect]. */ public sealed class ShiftCancellationException : CancellationException("Shifted Continuation") /** * Holds `R` and `suspend (R) -> B`, the exception that wins the race, will get to execute * `recover`. */ @PublishedApi internal class Suspend(val token: Token, val shifted: Any?, val recover: suspend (Any?) -> Any?) : ShiftCancellationException() { override fun toString(): String = "ShiftCancellationException($message)" } /** Class that represents a unique token by hash comparison **/ @PublishedApi internal class Token { override fun toString(): String = "Token(${hashCode().toString(16)})" } /** * Continuation that runs the `recover` function, after attempting to calculate [B]. In case we * encounter a `shift` after suspension, we will receive [Result.failure] with * [ShiftCancellationException]. In that case we still need to run `suspend (R) -> B`, which is what * we do inside the body of this `Continuation`, and we complete the [parent] [Continuation] with * the result. */ @PublishedApi internal class FoldContinuation<B>( private val token: Token, override val context: CoroutineContext, private val parent: Continuation<B> ) : Continuation<B> { override fun resumeWith(result: Result<B>) { result.fold(parent::resume) { throwable -> if (throwable is Suspend && token == throwable.token) { val f: suspend () -> B = { throwable.recover(throwable.shifted) as B } when (val res = f.startCoroutineUninterceptedOrReturn(parent)) { COROUTINE_SUSPENDED -> Unit else -> parent.resume(res as B) } } else parent.resumeWith(result) } } } /** * DSL for constructing Effect<R, A> values * * ```kotlin * import arrow.core.Either * import arrow.core.None * import arrow.core.Option * import arrow.core.Validated * import arrow.core.continuations.effect * import io.kotest.assertions.fail * import io.kotest.matchers.shouldBe * * suspend fun main() { * effect<String, Int> { * val x = Either.Right(1).bind() * val y = Validated.Valid(2).bind() * val z = Option(3).bind { "Option was empty" } * x + y + z * }.fold({ fail("Shift can never be the result") }, { it shouldBe 6 }) * * effect<String, Int> { * val x = Either.Right(1).bind() * val y = Validated.Valid(2).bind() * val z: Int = None.bind { "Option was empty" } * x + y + z * }.fold({ it shouldBe "Option was empty" }, { fail("Int can never be the result") }) * } * ``` * <!--- KNIT example-effect-02.kt --> */ public inline fun <R, A> effect(crossinline f: suspend EffectScope<R>.() -> A): Effect<R, A> = object : Effect<R, A> { // We create a `Token` for fold Continuation, so we can properly differentiate between nested // folds override suspend fun <B> fold(recover: suspend (R) -> B, transform: suspend (A) -> B): B = suspendCoroutineUninterceptedOrReturn { cont -> val token = Token() val effectScope = object : EffectScope<R> { // Shift away from this Continuation by intercepting it, and completing it with // ShiftCancellationException // This is needed because this function will never yield a result, // so it needs to be cancelled to properly support coroutine cancellation override suspend fun <B> shift(r: R): B = // Some interesting consequences of how Continuation Cancellation works in Kotlin. // We have to throw CancellationException to signal the Continuation was cancelled, and we // shifted away. // This however also means that the user can try/catch shift and recover from the // CancellationException and thus effectively recovering from the cancellation/shift. // This means try/catch is also capable of recovering from monadic errors. // See: EffectSpec - try/catch tests throw Suspend(token, r, recover as suspend (Any?) -> Any?) } try { suspend { transform(f(effectScope)) } .startCoroutineUninterceptedOrReturn(FoldContinuation(token, cont.context, cont)) } catch (e: Suspend) { if (token == e.token) { val f: suspend () -> B = { e.recover(e.shifted) as B } f.startCoroutineUninterceptedOrReturn(cont) } else throw e } } }
0
Kotlin
0
1
73fa3847df1f04e634a02bba527917389b59d7df
29,502
arrow
Apache License 2.0
src/main/kotlin/com/nowakartur/animedownloader/subsciption/entity/SubscribedAnimeDataLoader.kt
NowakArtur97
485,280,191
false
{"Kotlin": 72829}
package com.nowakartur.animedownloader.subsciption.entity import com.nowakartur.animedownloader.csv.CsvDataLoader import com.nowakartur.animedownloader.subsciption.entity.SubscribedAnimeStatus.IN_PROGRESS import com.nowakartur.animedownloader.subsciption.entity.SubscribedAnimeStatus.TO_DOWNLOAD import org.slf4j.LoggerFactory import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Component @Component class SubscribedAnimeDataLoader( private val subscribedAnimeRepository: SubscribedAnimeRepository, private val csvDataLoader: CsvDataLoader ) { private val logger = LoggerFactory.getLogger(javaClass) @EventListener(ApplicationReadyEvent::class) fun prepareDataOnStartup() { correctStatusOfAllTitlesInProgress() val animeListFromCsv = csvDataLoader.loadData() updateAfterChange(animeListFromCsv) saveNewTitles(animeListFromCsv) removeOldTitles(animeListFromCsv) logger.info("Data loading completed.") } private fun updateAfterChange(animeListFromCsv: List<SubscribedAnimeEntity>) { val toUpdate = animeListFromCsv .mapNotNull { subscribedAnimeRepository.findByTitle(it.title) } .filter { entity -> val titleFromCsv = animeListFromCsv.find { it.title == entity.title }!! entity.hasChanged(titleFromCsv) } .map { entity -> val titleFromCsv = animeListFromCsv.find { it.title == entity.title }!! entity.update(titleFromCsv) } if (toUpdate.isNotEmpty()) { subscribedAnimeRepository.saveAll(toUpdate) logger.info("Successfully updated: ${toUpdate.map { it.title }}.") } } private fun saveNewTitles(animeListFromCsv: List<SubscribedAnimeEntity>) { val notInDb = animeListFromCsv.filterNot { subscribedAnimeRepository.existsByTitle(it.title) } if (notInDb.isNotEmpty()) { subscribedAnimeRepository.saveAll(notInDb) logger.info("Successfully added new titles: ${notInDb.map { it.title }}.") } } private fun removeOldTitles(animeListFromCsv: List<SubscribedAnimeEntity>) { val oldTitles = subscribedAnimeRepository.findAll() .filter { animeListFromCsv.none { animeFromCsv -> it.title == animeFromCsv.title } } if (oldTitles.isNotEmpty()) { subscribedAnimeRepository.deleteAll(oldTitles) logger.info("Successfully removed old titles: ${oldTitles.map { it.title }}.") } } private fun correctStatusOfAllTitlesInProgress() = subscribedAnimeRepository.updateAllStatusToStatus(IN_PROGRESS, TO_DOWNLOAD) }
1
Kotlin
1
1
e2d3a27d7053fded5aed8c0d4eacde8f39db4553
2,794
Anime-Downloader
The Unlicense
app/src/main/java/com/geekymusketeers/medify/mainFragments/PatientAppointmentFragment.kt
aritra-tech
530,580,001
false
null
package com.kerberos.medico.mainFragments import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.kerberos.medico.appointment.PatientAppointment import com.kerberos.medico.adapter.PatientAppointmentAdapter import com.kerberos.medico.databinding.FragmentPatientAppointmentBinding import com.google.android.material.datepicker.MaterialDatePicker import com.google.firebase.database.* import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList class PatientAppointmentFragment : Fragment() { private var _binding: FragmentPatientAppointmentBinding? = null private val binding get() = _binding!! private lateinit var dbref : DatabaseReference private lateinit var Recyclerview : RecyclerView private lateinit var appointmentAdapter: PatientAppointmentAdapter private lateinit var appointmentList : ArrayList<PatientAppointment> private lateinit var sharedPreference : SharedPreferences @RequiresApi(Build.VERSION_CODES.O) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentPatientAppointmentBinding.inflate(inflater, container, false) sharedPreference = requireActivity().getSharedPreferences("UserData", Context.MODE_PRIVATE) // CODE appointmentList = ArrayList() appointmentAdapter = PatientAppointmentAdapter(requireActivity(), appointmentList) val isDoctor = sharedPreference.getString("isDoctor","Not found").toString() if (isDoctor == "Doctor") binding.toPatientList.visibility = View.VISIBLE binding.toPatientList.setOnClickListener { startActivity(Intent(requireActivity(), DoctorPatient::class.java)) } Recyclerview = binding.appointmentRecyclerview Recyclerview.layoutManager = LinearLayoutManager(requireActivity()) Recyclerview.setHasFixedSize(true) binding.selectDate.setOnClickListener { val datePicker = MaterialDatePicker.Builder.datePicker().build() fragmentManager?.let { datePicker.show(it, "DatePicker") } val date: StringBuilder = StringBuilder("") // Setting up the event for when ok is clicked datePicker.addOnPositiveButtonClickListener { // formatting date in dd-mm-yyyy format. val dateFormatter = SimpleDateFormat("dd-MM-yyyy") val tempDate = dateFormatter.format(Date(it)).toString().trim() date.setLength(0) date.append(tempDate) appointmentList.clear() getData(date.toString()) } // Setting up the event for when cancelled is clicked datePicker.addOnNegativeButtonClickListener { Toast.makeText(requireActivity(), "${datePicker.headerText} is cancelled", Toast.LENGTH_LONG).show() } // Setting up the event for when back button is pressed datePicker.addOnCancelListener { Toast.makeText(requireActivity(), "Date Picker Cancelled", Toast.LENGTH_LONG).show() } } // getData() return binding.root } @RequiresApi(Build.VERSION_CODES.O) private fun getData(date: String) { // val current = LocalDateTime.now() val userID = sharedPreference.getString("uid","Not found").toString() // val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") // val date = current.format(formatter) dbref = FirebaseDatabase.getInstance().getReference("Users").child(userID).child("PatientsAppointments").child(date) dbref.addValueEventListener(object : ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()){ for (appointmentSnapshot in snapshot.children){ val appointment = appointmentSnapshot.getValue(PatientAppointment::class.java) appointmentList.add(appointment!!) } Recyclerview.adapter = appointmentAdapter } } override fun onCancelled(error: DatabaseError) { Toast.makeText(requireActivity(), error.message, Toast.LENGTH_SHORT).show() } }) binding.selectDateTextToHide.visibility = View.GONE } override fun onStart() { super.onStart() val isDoctor = sharedPreference.getString("isDoctor","Not found").toString() if (isDoctor == "Doctor") binding.toPatientList.visibility = View.VISIBLE } }
0
Kotlin
4
7
d4f1c53007371dc9538ab9300bb7fe96eec14c03
5,105
Medify
MIT License
v1_29/src/main/java/de/loosetie/k8s/dsl/impls/Resourcequotastatus.kt
loosetie
283,145,621
false
null
package de.loosetie.k8s.dsl.impls import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonPropertyOrder import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasParent import de.loosetie.k8s.dsl.manifests.* @JsonPropertyOrder("hard", "used") open class Resourcequotastatus_core_v1Impl( @JsonIgnore override val parent: K8sManifest? = null, ) : Resourcequotastatus_core_v1, HasParent { override var hard: Any? = null override var used: Any? = null }
0
null
0
2
57d56ab780bc3134c43377e647e7f0336a5f17de
512
k8s-dsl
Apache License 2.0
app/src/main/java/com/ozturksahinyetisir/livedatat1/presentation/views/livedata/LivedataFragment.kt
ozturksahinyetisir
618,361,352
false
null
package com.ozturksahinyetisir.livedatat1.presentation.views.livedata import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.ozturksahinyetisir.livedatat1.databinding.FragmentLivedataBinding import com.ozturksahinyetisir.livedatat1.presentation.viewmodels.ExperienceViewModel class LivedataFragment : Fragment() { private lateinit var binding: FragmentLivedataBinding lateinit var expViewModel: ExperienceViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentLivedataBinding.inflate(layoutInflater) expViewModel = ViewModelProvider(this).get(ExperienceViewModel::class.java) activity?.let { expViewModel.currentExperience.observe(it, Observer { binding.scoreTv.text= it.toString() }) } incrementExp() return binding.root } private fun incrementExp(){ binding.plusButton.setOnClickListener{ expViewModel.currentExperience.value = ++expViewModel.experience } } }
0
Kotlin
0
0
7f32906935262090ca40ed20fc0a7133a7d98a8d
1,261
Livedata
MIT License
src/main/kotlin/me/mairwunnx/covid19/api/presets/ICoronavirusParameters.kt
MairwunNx
251,269,586
false
{"Kotlin": 82413}
package me.mairwunnx.covid19.api.presets interface ICoronavirusParameters { val genericInfectDosePerTickParam: Double val genericDisinfectDosePerTickParam: Double val infectedMobInfectDosePerTickParam: Double val infectedMobSpawnChanceParam: Double val infectedMobInfectDurationParam: Double val infectedMobInfectRangeParam: Double val infectedMobInfectEntityChanceParam: Double val infectedMobInitiallyInfectEntityChanceParam: Double val infectedEatChanceParam: Double val infectedEatInfectDoseParam: Double val healingGoldenAppleHealDoseParam: Double val healingEnchantedGoldenAppleHealDoseParam: Double val healingGoldenCarrotHealDoseParam: Double val healingPotionHealDoseParam: Double val healingStrongPotionHealDoseParam: Double val epidemicChanceParam: Double val epidemicInfectedMobSpawnChanceParam: Double val playerVirusEffectChanceParam: Double val coronavirusRebornChanceParam: Double }
1
Kotlin
0
2
7a4b92b2772e72649dedee7b8da6c3bc84e3f6eb
976
COVID-19-Mod
MIT License
app/src/main/java/com/siasg/comprasnet/ui/fragment/onboarding/OnboardingFragment.kt
rayanovelha
642,602,901
false
null
package com.siasg.comprasnet.ui.fragment.onboarding import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.siasg.comprasnet.R import com.siasg.comprasnet.databinding.FragmentOnboardingBinding import com.siasg.comprasnet.ui.adapter.OnboardingAdapter import com.siasg.comprasnet.ui.fragment.onboarding.screen.OnboardingFirstFragment import com.siasg.comprasnet.ui.fragment.onboarding.screen.OnboardingSecondFragment import com.siasg.comprasnet.ui.fragment.onboarding.screen.OnboardingThirdFragment class OnboardingFragment : Fragment() { private lateinit var binding: FragmentOnboardingBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentOnboardingBinding.inflate(inflater, container, false) binding.lifecycleOwner = viewLifecycleOwner binding.fragment = this val listaFragmentos = arrayListOf( OnboardingFirstFragment(), OnboardingSecondFragment(), OnboardingThirdFragment() ) val adaptador = OnboardingAdapter( listaFragmentos, requireActivity().supportFragmentManager, lifecycle ) binding.vpOnboarding.adapter = adaptador binding.wormDotsIndicator.attachTo(binding.vpOnboarding) return binding.root } fun start(v: View){ findNavController().navigate(R.id.action_onboardingFragment3_to_homeFragment) } }
0
Kotlin
0
2
940d5af7a82d4f12212cd5b99cf98692986e0294
1,667
Comprasnet-App
Apache License 2.0
injective-core/src/commonMain/kotlin/injective/insurance/v1beta1/tx.converter.kt
jdekim43
759,720,689
false
{"Kotlin": 8940168, "Java": 3242559}
// Transform from injective/insurance/v1beta1/tx.proto @file:GeneratorVersion(version = "0.3.1") package injective.insurance.v1beta1 import google.protobuf.Any import java.lang.IllegalStateException import kr.jadekim.protobuf.`annotation`.GeneratorVersion import kr.jadekim.protobuf.converter.ProtobufConverter import kr.jadekim.protobuf.converter.parseProtobuf public expect object MsgCreateInsuranceFundConverter : ProtobufConverter<MsgCreateInsuranceFund> public fun MsgCreateInsuranceFund.toAny(): Any = Any(MsgCreateInsuranceFund.TYPE_URL, with(MsgCreateInsuranceFundConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgCreateInsuranceFund>): MsgCreateInsuranceFund { if (typeUrl != MsgCreateInsuranceFund.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgCreateInsuranceFundResponseConverter : ProtobufConverter<MsgCreateInsuranceFundResponse> public fun MsgCreateInsuranceFundResponse.toAny(): Any = Any(MsgCreateInsuranceFundResponse.TYPE_URL, with(MsgCreateInsuranceFundResponseConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgCreateInsuranceFundResponse>): MsgCreateInsuranceFundResponse { if (typeUrl != MsgCreateInsuranceFundResponse.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgUnderwriteConverter : ProtobufConverter<MsgUnderwrite> public fun MsgUnderwrite.toAny(): Any = Any(MsgUnderwrite.TYPE_URL, with(MsgUnderwriteConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgUnderwrite>): MsgUnderwrite { if (typeUrl != MsgUnderwrite.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgUnderwriteResponseConverter : ProtobufConverter<MsgUnderwriteResponse> public fun MsgUnderwriteResponse.toAny(): Any = Any(MsgUnderwriteResponse.TYPE_URL, with(MsgUnderwriteResponseConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgUnderwriteResponse>): MsgUnderwriteResponse { if (typeUrl != MsgUnderwriteResponse.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgRequestRedemptionConverter : ProtobufConverter<MsgRequestRedemption> public fun MsgRequestRedemption.toAny(): Any = Any(MsgRequestRedemption.TYPE_URL, with(MsgRequestRedemptionConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgRequestRedemption>): MsgRequestRedemption { if (typeUrl != MsgRequestRedemption.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgRequestRedemptionResponseConverter : ProtobufConverter<MsgRequestRedemptionResponse> public fun MsgRequestRedemptionResponse.toAny(): Any = Any(MsgRequestRedemptionResponse.TYPE_URL, with(MsgRequestRedemptionResponseConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgRequestRedemptionResponse>): MsgRequestRedemptionResponse { if (typeUrl != MsgRequestRedemptionResponse.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgUpdateParamsConverter : ProtobufConverter<MsgUpdateParams> public fun MsgUpdateParams.toAny(): Any = Any(MsgUpdateParams.TYPE_URL, with(MsgUpdateParamsConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgUpdateParams>): MsgUpdateParams { if (typeUrl != MsgUpdateParams.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) } public expect object MsgUpdateParamsResponseConverter : ProtobufConverter<MsgUpdateParamsResponse> public fun MsgUpdateParamsResponse.toAny(): Any = Any(MsgUpdateParamsResponse.TYPE_URL, with(MsgUpdateParamsResponseConverter) { toByteArray() }) public fun Any.parse(converter: ProtobufConverter<MsgUpdateParamsResponse>): MsgUpdateParamsResponse { if (typeUrl != MsgUpdateParamsResponse.TYPE_URL) throw IllegalStateException("Please check the type_url") return value.parseProtobuf(converter) }
0
Kotlin
0
0
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
4,368
chameleon.proto
Apache License 2.0
MirrorTrips-main/app/src/main/java/com/ipca/budget/travelmobile/EmailSendView.kt
ademar1k82
676,015,143
false
null
package com.ipca.budget.travelmobile import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.EditText import android.widget.Toast import androidx.constraintlayout.widget.ConstraintLayout import androidx.lifecycle.lifecycleScope import com.ipca.budget.travelmobile.Utils.getEmailPostBody import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import org.json.JSONArray import org.json.JSONObject class EmailSendView : AppCompatActivity() { val client = OkHttpClient() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_email_send_view) val containerButton = findViewById<ConstraintLayout>(R.id.container_button) var emailComp = findViewById<EditText>(R.id.EmailNameEdit) var subjectComp = findViewById<EditText>(R.id.EmailSubjectEdit) var emailBodyComp = findViewById<EditText>(R.id.EmailMessageEdit) Utils.addClickEventToButtons(containerButton) { lifecycleScope.launch(Dispatchers.IO) { val mediaType = "application/json".toMediaTypeOrNull() val body = RequestBody.create(mediaType, getEmailPostBody(emailComp.text.toString(), subjectComp.text.toString(), emailBodyComp.text.toString()) ) val request = Request.Builder() .url("https://http2smtp.p.rapidapi.com/send") .post(body) .addHeader("content-type", "application/json") .addHeader("X-RapidAPI-Key", "<KEY>") .addHeader("X-RapidAPI-Host", "http2smtp.p.rapidapi.com") .build() val response = client.newCall(request).execute() if (response.isSuccessful) { lifecycleScope.launch(Dispatchers.Main) { val text = "Email sent with success" val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(applicationContext, text, duration) toast.show() } } else { val text = "It was not possible to send email" val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(applicationContext, text, duration) toast.show() } } val intent = Intent(this@EmailSendView, MainPage::class.java) startActivity(intent) } } }
0
Kotlin
0
1
cc26e834045569534705e692eafa2b0f5937e545
2,772
mirrortrips
FSF All Permissive License
src/test/kotlin/com/github/imflog/schema/registry/parser/AvroSchemaParserTest.kt
ImFlog
132,165,857
false
null
package com.github.imflog.schema.registry.parser import com.github.imflog.schema.registry.LocalReference import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient import org.assertj.core.api.Assertions import org.json.JSONObject import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.io.TempDir import java.nio.file.Path @TestInstance(TestInstance.Lifecycle.PER_CLASS) class AvroSchemaParserTest { private val schemaRegistryClient = MockSchemaRegistryClient() @TempDir lateinit var folderRule: Path companion object { private const val ADDRESS_REFERENCE_NAME = "Address" private const val USER_REFERENCE_NAME = "User" private const val ADDRESS_SCHEMA = """{ "type": "record", "name": "$ADDRESS_REFERENCE_NAME", "fields": [ {"name": "street", "type": "string" } ] }""" private const val USER_SCHEMA = """{ "type": "record", "name": "$USER_REFERENCE_NAME", "fields": [ {"name": "name", "type": "string" }, {"name": "address", "type": "$ADDRESS_REFERENCE_NAME"} ] }""" } @Test fun `Should format local references correctly`() { // Given val parser = AvroSchemaParser(schemaRegistryClient, folderRule.toFile()) val aLocalReference = givenALocalReference() // When val resolvedSchema = parser.resolveLocalReferences( USER_REFERENCE_NAME, USER_SCHEMA, listOf(aLocalReference) ) // Then localSchemaShouldBeAppended(resolvedSchema) } private fun givenALocalReference(): LocalReference { val addressLocalFile = folderRule.resolve("Address.avsc").toFile() addressLocalFile.writeText(ADDRESS_SCHEMA) return LocalReference(ADDRESS_REFERENCE_NAME, addressLocalFile.path) } private fun localSchemaShouldBeAppended(resolvedSchema: String) { Assertions .assertThat( JSONObject(resolvedSchema) .getJSONArray("fields") .getJSONObject(1) .getJSONObject("type") ) .usingRecursiveComparison() // To check the content of the JSON Objects instead of the equal method .isEqualTo(JSONObject(ADDRESS_SCHEMA)) } }
10
Kotlin
22
92
a46cc2c5904ed873f3df11512b60fc700767ca6d
2,464
schema-registry-plugin
Apache License 2.0
src/test/kotlin/com/github/imflog/schema/registry/parser/AvroSchemaParserTest.kt
ImFlog
132,165,857
false
null
package com.github.imflog.schema.registry.parser import com.github.imflog.schema.registry.LocalReference import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient import org.assertj.core.api.Assertions import org.json.JSONObject import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.io.TempDir import java.nio.file.Path @TestInstance(TestInstance.Lifecycle.PER_CLASS) class AvroSchemaParserTest { private val schemaRegistryClient = MockSchemaRegistryClient() @TempDir lateinit var folderRule: Path companion object { private const val ADDRESS_REFERENCE_NAME = "Address" private const val USER_REFERENCE_NAME = "User" private const val ADDRESS_SCHEMA = """{ "type": "record", "name": "$ADDRESS_REFERENCE_NAME", "fields": [ {"name": "street", "type": "string" } ] }""" private const val USER_SCHEMA = """{ "type": "record", "name": "$USER_REFERENCE_NAME", "fields": [ {"name": "name", "type": "string" }, {"name": "address", "type": "$ADDRESS_REFERENCE_NAME"} ] }""" } @Test fun `Should format local references correctly`() { // Given val parser = AvroSchemaParser(schemaRegistryClient, folderRule.toFile()) val aLocalReference = givenALocalReference() // When val resolvedSchema = parser.resolveLocalReferences( USER_REFERENCE_NAME, USER_SCHEMA, listOf(aLocalReference) ) // Then localSchemaShouldBeAppended(resolvedSchema) } private fun givenALocalReference(): LocalReference { val addressLocalFile = folderRule.resolve("Address.avsc").toFile() addressLocalFile.writeText(ADDRESS_SCHEMA) return LocalReference(ADDRESS_REFERENCE_NAME, addressLocalFile.path) } private fun localSchemaShouldBeAppended(resolvedSchema: String) { Assertions .assertThat( JSONObject(resolvedSchema) .getJSONArray("fields") .getJSONObject(1) .getJSONObject("type") ) .usingRecursiveComparison() // To check the content of the JSON Objects instead of the equal method .isEqualTo(JSONObject(ADDRESS_SCHEMA)) } }
10
Kotlin
22
92
a46cc2c5904ed873f3df11512b60fc700767ca6d
2,464
schema-registry-plugin
Apache License 2.0
Yum-Client/app/src/main/java/com/anbui/yum/presentation/recipe/component/TabTopBar.kt
AnBuiii
608,489,464
false
null
package com.anbui.yum.presentation.recipe.component import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun TabTopBar( leading: @Composable () -> Unit, trailing: @Composable () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { leading() trailing() } }
0
Kotlin
0
3
94a9344aeb57403214315191304b81d15d584863
685
Yum
MIT License
kotlin-asyncapi-examples/kotlin-asyncapi-spring-boot-example/src/main/resources/build.asyncapi.kts
asyncapi
509,940,588
false
{"Kotlin": 233237}
info { title("Gitter Streaming API") version("1.0.0") }
1
Kotlin
1
22
a8658f2546fdd2fdc9ad7209dd26cabbeb6d84ba
64
kotlin-asyncapi
Apache License 2.0
kotlin-asyncapi-examples/kotlin-asyncapi-spring-boot-example/src/main/resources/build.asyncapi.kts
asyncapi
509,940,588
false
{"Kotlin": 233237}
info { title("Gitter Streaming API") version("1.0.0") }
1
Kotlin
1
22
a8658f2546fdd2fdc9ad7209dd26cabbeb6d84ba
64
kotlin-asyncapi
Apache License 2.0
plugins/kotlin/idea/tests/testData/gradle/androidImportAndCheckHighlighting/hmppWithSeveralHmppDependencies/p1/src/jvmAndAndroidMain/kotlin/JvmAndAndroidMain.kt
JetBrains
2,489,216
false
null
@file:Suppress("unused") import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import io.ktor.client.* import io.ktor.utils.io.core.* import io.reactivex.rxjava3.core.Observable import kotlinx.atomicfu.AtomicInt import kotlinx.atomicfu.update import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import java.util.concurrent.locks.ReentrantLock interface <lineMarker descr="Is implemented by AndroidMain JvmMain Press Ctrl+Alt+B to navigate">JvmAndAndroidMain</lineMarker> : CommonMain { override fun <lineMarker descr="Overrides function in CommonMain Press Ctrl+U to navigate"><lineMarker descr="Is overridden in AndroidMain JvmMain Press Ctrl+Alt+B to navigate">useKtorApis</lineMarker></lineMarker>(): HttpClient { return super.useKtorApis().config { this.useDefaultTransformers = true } } override fun <lineMarker descr="Overrides function in CommonMain Press Ctrl+U to navigate"><lineMarker descr="Is overridden in AndroidMain JvmMain Press Ctrl+Alt+B to navigate">useKtorApisCloseable</lineMarker></lineMarker>(): Closeable { return Closeable { } } override fun <lineMarker descr="Overrides function in CommonMain Press Ctrl+U to navigate"><lineMarker descr="Is overridden in AndroidMain JvmMain Press Ctrl+Alt+B to navigate">useCoroutinesApis</lineMarker></lineMarker>(): Deferred<String> { return runBlocking(Dispatchers.IO) { super.useCoroutinesApis() } } override fun <lineMarker descr="Overrides function in CommonMain Press Ctrl+U to navigate"><lineMarker descr="Is overridden in JvmMain Press Ctrl+Alt+B to navigate">useAtomicFu</lineMarker></lineMarker>(): AtomicInt { return super.useAtomicFu().also { atomicInt -> atomicInt.update { it + 1 } } } override fun <lineMarker descr="Overrides function in CommonMain Press Ctrl+U to navigate"><lineMarker descr="Is overridden in JvmMain Press Ctrl+Alt+B to navigate">androidSdkIsNotVisible</lineMarker></lineMarker>(context: <error descr="[UNRESOLVED_REFERENCE] Unresolved reference: android" textAttributesKey="null">android</error>.<error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved" textAttributesKey="KOTLIN_DEBUG_INFO">content</error>.<error descr="[DEBUG] Reference is not resolved to anything, but is not marked unresolved" textAttributesKey="KOTLIN_DEBUG_INFO">Context</error>) { } fun <lineMarker descr="Is overridden in AndroidMain JvmMain Press Ctrl+Alt+B to navigate">useJdkApis</lineMarker>(): ReentrantLock { return ReentrantLock() } fun useRxJava(): Observable<String> { return Observable.fromIterable(listOf("Hello", "RX")) } fun useJackson(): ObjectMapper { return jacksonObjectMapper() .configure(JsonParser.Feature.IGNORE_UNDEFINED, true) } }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
3,028
intellij-community
Apache License 2.0
src/main/kotlin/no/nav/helse/rapids_rivers/RapidApplication.kt
navikt
245,991,465
false
null
package no.nav.helse.rapids_rivers import io.ktor.server.application.Application import io.ktor.server.cio.CIO import io.ktor.server.engine.* import io.prometheus.client.CollectorRegistry import kotlinx.coroutines.delay import org.slf4j.LoggerFactory import java.io.File import java.io.FileNotFoundException import java.net.InetAddress import java.util.* import java.util.concurrent.atomic.AtomicBoolean class RapidApplication internal constructor( private val ktor: ApplicationEngine, private val rapid: RapidsConnection, private val appName: String? = null, private val instanceId: String, private val onKtorStartup: () -> Unit = {}, private val onKtorShutdown: () -> Unit = {} ) : RapidsConnection(), RapidsConnection.MessageListener, RapidsConnection.StatusListener { init { Runtime.getRuntime().addShutdownHook(Thread(::shutdownHook)) rapid.register(this as MessageListener) rapid.register(this as StatusListener) if (appName != null) { PingPong(rapid, appName, instanceId) } else { log.info("not responding to pings; no app name set.") } } override fun onMessage(message: String, context: MessageContext) { notifyMessage(message, context) } override fun start() { ktor.start(wait = false) try { onKtorStartup() rapid.start() } finally { onKtorShutdown() val gracePeriod = 5000L val forcefulShutdownTimeout = 30000L log.info("shutting down ktor, waiting $gracePeriod ms for workers to exit. Forcing shutdown after $forcefulShutdownTimeout ms") ktor.stop(gracePeriod, forcefulShutdownTimeout) log.info("ktor shutdown complete: end of life. goodbye.") } } override fun stop() { rapid.stop() } override fun publish(message: String) { rapid.publish(message) } override fun publish(key: String, message: String) { rapid.publish(key, message) } override fun publishWithTimeout(message: String, timeoutInSec: Long) { rapid.publishWithTimeout(message, timeoutInSec) } override fun publishWithTimeout(key: String, message: String, timeoutInSec: Long) { rapid.publishWithTimeout(key, message, timeoutInSec) } override fun rapidName(): String { return rapid.rapidName() } private fun shutdownHook() { log.info("received shutdown signal, stopping app") stop() } override fun onStartup(rapidsConnection: RapidsConnection) { publishApplicationEvent(rapidsConnection, "application_up") notifyStartup() } override fun onReady(rapidsConnection: RapidsConnection) { publishApplicationEvent(rapidsConnection, "application_ready") notifyReady() } override fun onNotReady(rapidsConnection: RapidsConnection) { publishApplicationEvent(rapidsConnection, "application_not_ready") notifyNotReady() } override fun onShutdownSignal(rapidsConnection: RapidsConnection) { publishApplicationEvent(rapidsConnection, "application_stop") notifyShutdownSignal() } override fun onShutdown(rapidsConnection: RapidsConnection) { publishApplicationEvent(rapidsConnection, "application_down") notifyShutdown() } private fun publishApplicationEvent(rapidsConnection: RapidsConnection, event: String) { applicationEvent(event)?.also { log.info("publishing $event event for app_name=$appName, instance_id=$instanceId") try { rapidsConnection.publish(it) } catch (err: Exception) { log.info("failed to publish event: {}", err.message, err) } } } private fun applicationEvent(event: String): String? { if (appName == null) return null val packet = JsonMessage.newMessage(event, mapOf( "app_name" to appName, "instance_id" to instanceId )) return packet.toJson() } companion object { private val log = LoggerFactory.getLogger(RapidApplication::class.java) fun create(env: Map<String, String>, configure: (ApplicationEngine, KafkaRapid) -> Unit = {_, _ -> }) = Builder(RapidApplicationConfig.fromEnv(env)).build(configure, CIO) } class Builder(private val config: RapidApplicationConfig) { init { Thread.currentThread().setUncaughtExceptionHandler(::uncaughtExceptionHandler) } private val isKtorRunning = AtomicBoolean(false) private val rapid = KafkaRapid.create(config.kafkaConfig, config.rapidTopic, config.extraTopics) private val ktor = KtorBuilder() .log(log) .port(config.httpPort) .preStopHook(this::handlePreStopRequest) .liveness(rapid::isRunning) .readiness(rapid::isReady) .metrics(rapid.getMetrics()) fun withCollectorRegistry(registry: CollectorRegistry = CollectorRegistry.defaultRegistry) = apply { ktor.withCollectorRegistry(registry) } fun withKtorModule(module: Application.() -> Unit) = apply { ktor.module(module) } fun build(configure: (ApplicationEngine, KafkaRapid) -> Unit = { _, _ -> }): RapidsConnection { return build(configure, CIO) } fun <TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration> build(configure: (ApplicationEngine, KafkaRapid) -> Unit = { _, _ -> }, factory: ApplicationEngineFactory<TEngine, TConfiguration>): RapidsConnection { val app = ktor.build(factory) configure(app, rapid) return RapidApplication(app, rapid, config.appName, config.instanceId, this::onKtorStartup, this::onKtorShutdown) } private suspend fun handlePreStopRequest() { rapid.stop() // block the preStopHook call from returning until // ktor is ready to shutdown, which means that the KafkaRapid has shutdown while (isKtorRunning.get()) { delay(1000) } } private fun onKtorStartup() { isKtorRunning.set(true) } private fun onKtorShutdown() { isKtorRunning.set(false) } private fun uncaughtExceptionHandler(thread: Thread, err: Throwable) { log.error("Uncaught exception in thread ${thread.name}: ${err.message}", err) } } class RapidApplicationConfig( internal val appName: String?, internal val instanceId: String, internal val rapidTopic: String, internal val extraTopics: List<String> = emptyList(), internal val kafkaConfig: KafkaConfig, internal val httpPort: Int = 8080 ) { companion object { fun fromEnv(env: Map<String, String>) = generateInstanceId(env).let { instanceId -> RapidApplicationConfig( appName = env["RAPID_APP_NAME"] ?: generateAppName(env) ?: log.info("app name not configured") .let { null }, instanceId = instanceId, rapidTopic = env.getValue("KAFKA_RAPID_TOPIC"), extraTopics = env["KAFKA_EXTRA_TOPIC"]?.split(',')?.map(String::trim) ?: emptyList(), kafkaConfig = kafkaConfig(env, instanceId), httpPort = env["HTTP_PORT"]?.toInt() ?: 8080 ) } private fun kafkaConfig(env: Map<String, String>, instanceId: String): KafkaConfig { val preferOnPrem = env["KAFKA_PREFER_ON_PREM"]?.let { it.lowercase() == "true"} ?: false if (preferOnPrem || !gcpConfigAvailable(env)) return onPremConfig(env, instanceId) return gcpConfig(env, instanceId) } private fun gcpConfigAvailable(env: Map<String, String>) = env.containsKey("KAFKA_BROKERS") && env.containsKey("KAFKA_CREDSTORE_PASSWORD") private fun gcpConfig(env: Map<String, String>, instanceId: String) = KafkaConfig( bootstrapServers = env.getValue("KAFKA_BROKERS"), consumerGroupId = env.getValue("KAFKA_CONSUMER_GROUP_ID"), clientId = instanceId, username = null, password = <PASSWORD>, truststore = env["KAFKA_TRUSTSTORE_PATH"], truststorePassword = env.getValue("KAFKA_CREDSTORE_PASSWORD"), keystoreLocation = env.getValue("KAFKA_KEYSTORE_PATH"), keystorePassword = env.getValue("KAFKA_CREDSTORE_PASSWORD"), autoOffsetResetConfig = env["KAFKA_RESET_POLICY"], autoCommit = env["KAFKA_AUTO_COMMIT"]?.let { "true" == it.lowercase() }, maxIntervalMs = env["KAFKA_MAX_POLL_INTERVAL_MS"]?.toInt(), maxRecords = env["KAFKA_MAX_RECORDS"]?.toInt() ) private fun onPremConfig(env: Map<String, String>, instanceId: String) = KafkaConfig( bootstrapServers = env.getValue("KAFKA_BOOTSTRAP_SERVERS"), consumerGroupId = env.getValue("KAFKA_CONSUMER_GROUP_ID"), clientId = instanceId, username = "/var/run/secrets/nais.io/service_user/username".readFile(), password = "/var/run/secrets/nais.io/service_user/password".readFile(), truststore = env["NAV_TRUSTSTORE_PATH"], truststorePassword = env["NAV_TRUSTSTORE_PASSWORD"], keystoreLocation = null, keystorePassword = null, autoOffsetResetConfig = env["KAFKA_RESET_POLICY"], autoCommit = env["KAFKA_AUTO_COMMIT"]?.let { "true" == it.lowercase() }, maxIntervalMs = env["KAFKA_MAX_POLL_INTERVAL_MS"]?.toInt(), maxRecords = env["KAFKA_MAX_RECORDS"]?.toInt() ) private fun generateInstanceId(env: Map<String, String>): String { if (env.containsKey("NAIS_APP_NAME")) return InetAddress.getLocalHost().hostName return UUID.randomUUID().toString() } private fun generateAppName(env: Map<String, String>): String? { val appName = env["NAIS_APP_NAME"] ?: return log.info("not generating app name because NAIS_APP_NAME not set").let { null } val namespace = env["NAIS_NAMESPACE"] ?: return log.info("not generating app name because NAIS_NAMESPACE not set").let { null } val cluster = env["NAIS_CLUSTER_NAME"] ?: return log.info("not generating app name because NAIS_CLUSTER_NAME not set").let { null } return "$appName-$cluster-$namespace" } } } } private fun String.readFile() = try { File(this).readText(Charsets.UTF_8) } catch (err: FileNotFoundException) { null }
8
null
5
24
196b7068ceed24a35b541ef93e4b3a6547bcccc4
11,168
rapids-and-rivers
MIT License
library/src/main/java/cn/rubintry/gopermission/core/GoPermission.kt
RubinTry
368,127,499
false
null
package cn.rubintry.gopermission.core import android.content.pm.PackageManager import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentActivity import cn.rubintry.gopermission.utils.LogUtils import cn.rubintry.gopermission.utils.Utils import kotlinx.coroutines.* import kotlin.system.measureTimeMillis object GoPermission { private var permission: MutableList<String> = mutableListOf() @JvmStatic fun initialize() { val curActivity = ActivityMonitor.getInstance().getTopActivity() checkNotNull(curActivity) { "Top Activity is null" } if (curActivity !is FragmentActivity) { throw IllegalArgumentException("Activity must be FragmentActivity") } //用栈顶activity来创建一个可复用的fragment if (curActivity.supportFragmentManager.findFragmentByTag(PermissionFragment::class.java.name) == null) { val fragment = PermissionFragment() curActivity.supportFragmentManager.beginTransaction() .add(fragment, PermissionFragment::class.java.name).attach(fragment).commit() } } @JvmStatic fun permissions(vararg permissions: String): GoPermission { for (permission in permissions) { if (permission.isBlank()) { throw IllegalArgumentException("Permission should not be empty!!!") } } permission.clear() permission.addAll(permissions) return this } /** * 判断权限是否已经授予 * * @param permission * @return */ @JvmStatic fun isGranted(permission: String): Boolean { return ContextCompat.checkSelfPermission( Utils.getApp(), permission ) == PackageManager.PERMISSION_GRANTED } /** * 发起权限请求 * */ fun request(callback: Callback) = runBlocking { val time = measureMethodTime { requestPermission(callback) } LogUtils.debug("方法调用耗时:${time / 1000f}秒 ") } /** * 请求权限 * */ private fun requestPermission(callback: Callback) { val curActivity = ActivityMonitor.getInstance().getTopActivity() if (curActivity !is FragmentActivity) { throw IllegalArgumentException("Activity must be FragmentActivity") } //用创建好的全透明无背景的fragment进行权限请求 val existFragment = curActivity.supportFragmentManager.findFragmentByTag(PermissionFragment::class.java.name) if (existFragment != null && existFragment is PermissionFragment) { existFragment.requestNow(permission.toTypedArray(), callback) } } /** * 测量方法耗时 * * @param action */ private suspend fun measureMethodTime(action: suspend () -> Unit): Long { return measureTimeMillis { coroutineScope { launch { action() } } } } }
0
Kotlin
0
1
2a16c2eb1d2c7b01fb1d698f8fe98ffc7fbfb681
2,968
GoPermission
Apache License 2.0
plugins/kotlin/idea/tests/testData/shortenRefsFir/calls/importAlias.kt
JetBrains
2,489,216
false
null
package test import dependency.foo as bar fun usage() { <selection>dependency.foo()</selection> }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
103
intellij-community
Apache License 2.0
lib/src/test/java/com/sha/apphead/DismissViewTest.kt
ShabanKamell
220,487,015
false
null
package com.sha.apphead import org.junit.Before import org.junit.Test class DismissViewTest { private lateinit var args: DismissView.Args @Before fun setup() { args = DismissView.Args() } @Test fun layoutRes() { args.layoutRes(1, 2) assert(args.layoutRes == 1) assert(args.imageViewId == 2) } @Test fun drawableRes() { args.drawableRes(1) assert(args.drawableRes == 1) } @Test fun scaleRatio() { args.scaleRatio(1.0) assert(args.scaleRatio == 1.0) } @Test fun alpha() { args.alpha(1f) assert(args.alpha == 1f) } @Test fun onFinishInflate() { args.onFinishInflate {} assert(args.onFinishInflate != null) } }
2
Kotlin
12
68
954b6c00e69ca0311918c3ece9564122093845a6
788
AppHead
Apache License 2.0
certificatetransparency/src/main/kotlin/com/babylon/certificatetransparency/internal/logclient/LogClientFactory.kt
babylonhealth
152,060,574
false
null
/* * Copyright 2019 Babylon Partners Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.babylon.certificatetransparency.internal.logclient import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Factory to create a [LogClient] for querying a log server */ @Suppress("unused") internal object LogClientFactory { /** * Create a [LogClient] for the log server [baseUrl] * @property baseUrl Url of the log server */ fun create(baseUrl: String): LogClient { val client = OkHttpClient.Builder().build() val retrofit = Retrofit.Builder().client(client).addConverterFactory(GsonConverterFactory.create()).baseUrl(baseUrl).build() val logClientService = retrofit.create(LogClientService::class.java) return HttpLogClient(logClientService) } }
1
Kotlin
24
197
15ea45c73631cf39c0bbf206b10641f0dbfef957
1,385
certificate-transparency-android
Apache License 2.0
core/droidMain/framework/BaseActivity.kt
shibasis0801
669,270,289
false
{"Kotlin": 58270, "C++": 47981, "Objective-C++": 11829, "Ruby": 7529, "Objective-C": 6478, "CSS": 6110, "TypeScript": 4225, "JavaScript": 4148, "Swift": 2554, "CMake": 1744, "Shell": 629, "Dockerfile": 185, "C": 123}
package app.mehmaan.core.framework import android.app.Activity import androidx.activity.ComponentActivity abstract class BaseActivity: ComponentActivity() { val adapters = mutableListOf<Adapter<Activity>>() fun connect(adapterList: List<Adapter<Activity>>) { adapters.addAll(adapterList) adapterList.forEach(lifecycle::addObserver) } /** * Prefer this function to connect your adapters * onDestroy removes all adapters * You can add adapters in multiple steps * And can also do eager disconnect */ fun connect(vararg adapters: Adapter<Activity>) = connect(adapters.toList()) fun disconnect(adapterList: List<Adapter<Activity>>) { this.adapters.removeAll(adapterList) adapterList.forEach(lifecycle::removeObserver) } fun disconnect(vararg adapters: Adapter<Activity>) = disconnect(adapters.toList()) override fun onDestroy() { super.onDestroy() disconnect(adapters) } override fun onBackPressed() { super.onBackPressed() adapters.forEach { it.handle(ControllerEvent.BackPressed) } } }
0
Kotlin
0
0
2db27b7ea8bb54d39ed4d9b79e27e01c3ecfb32a
1,129
Reaktor
Apache License 2.0
app/src/test/java/io/github/msh91/arch/ui/home/chart/CryptoChartViewModelTest.kt
msh91
134,849,661
false
null
package io.github.msh91.arch.ui.home.chart import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import arrow.core.Either import io.github.msh91.arch.CoroutinesTestRule import io.github.msh91.arch.R import io.github.msh91.arch.data.model.Error import io.github.msh91.arch.data.model.crypto.ChartValue import io.github.msh91.arch.data.model.crypto.CryptoChartInfo import io.github.msh91.arch.data.repository.crypto.CryptoChartRepository import io.github.msh91.arch.util.provider.BaseResourceProvider import io.mockk.* import io.mockk.impl.annotations.MockK import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import java.util.* @ExperimentalCoroutinesApi class CryptoChartViewModelTest { @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule val testCoroutineRule = CoroutinesTestRule() @MockK lateinit var resourceProvider: BaseResourceProvider @MockK lateinit var cryptoChartRepository: CryptoChartRepository private lateinit var viewModel: CryptoChartViewModel @Before fun setup() { MockKAnnotations.init(this) viewModel = CryptoChartViewModel(cryptoChartRepository, resourceProvider) } @Test fun `getChartInfo should be called after view started`() { // GIVEN coEvery { cryptoChartRepository.getChartInfo() } returns mockk() // WHEN viewModel.onStart() // THEN coVerify { cryptoChartRepository.getChartInfo() } } @Test fun `getChartInfo should not be called after view re-started`() { // GIVEN coEvery { cryptoChartRepository.getChartInfo() } returns mockk() // WHEN viewModel.onStart() viewModel.onStart() // THEN coVerify(exactly = 1) { cryptoChartRepository.getChartInfo() } } @Test fun `chartInfo loading should be set correctly based on api call`() { // GIVEN val testObserver = mockk<Observer<Boolean>>() every { testObserver.onChanged(any()) } answers {} coEvery { cryptoChartRepository.getChartInfo() } returns mockk() viewModel.loadingLiveData.observeForever(testObserver) // WHEN viewModel.onStart() // THEN coVerifyOrder { testObserver.onChanged(true) cryptoChartRepository.getChartInfo() testObserver.onChanged(false) } } @Test fun `relevant error message should be shown when receiving chart info failed`() { // GIVEN val testObserver = mockk<Observer<String>>() val mockedError = mockk<Error>() val errorMessage = "Error message" every { testObserver.onChanged(any()) } answers {} every { resourceProvider.getErrorMessage(mockedError) } returns errorMessage coEvery { cryptoChartRepository.getChartInfo() } returns Either.left(mockedError) viewModel.errorLiveData.observeForever(testObserver) // WHEN viewModel.onStart() // THEN verify { testObserver.onChanged(errorMessage) } } @Test fun `chartInfoItem should be provided to be shown by the view`() { // GIVEN val testObserver = mockk<Observer<ChartInfoItem>>() every { testObserver.onChanged(any()) } answers {} viewModel.chartInfoLiveData.observeForever(testObserver) val mockedInfo = mockk<CryptoChartInfo>() every { mockedInfo.name } returns "name" every { mockedInfo.description } returns "description" every { mockedInfo.chartValues } returns listOf( ChartValue(Date(2021, 0, 10), 50_000f), ChartValue(Date(2021, 1, 13), 60_000f), ChartValue(Date(2021, 2, 11), 40_000f), ChartValue(Date(2021, 3, 1), 70_000f) ) every { resourceProvider.getString(R.string.holder_day_month, "Jan", 10) } returns "Jan 10" every { resourceProvider.getString(R.string.holder_day_month, "Feb", 13) } returns "Feb 13" every { resourceProvider.getString(R.string.holder_day_month, "Mar", 11) } returns "Mar 11" every { resourceProvider.getString(R.string.holder_day_month, "Apr", 1) } returns "Apr 1" coEvery { cryptoChartRepository.getChartInfo() } returns Either.right(mockedInfo) // WHEN viewModel.onStart() // THEN val item = ChartInfoItem("name", "description", listOf( ChartEntry("Jan 10", 50000f), ChartEntry("Feb 13", 60000f), ChartEntry("Mar 11", 40000f), ChartEntry("Apr 1", 70000f) )) verify { testObserver.onChanged(item) } } }
0
Kotlin
7
25
9f0bf81e3493ee733a0b64c9a64249eacd8b652b
4,747
arch
Apache License 2.0
engine/src/test/kotlin/regressionTests/config/EngineTestConfiguration.kt
Cuupa
236,094,744
false
{"JavaScript": 348091, "CSS": 195119, "Kotlin": 182293, "Java": 23235, "HTML": 11583, "Batchfile": 111}
package regressionTests.config import com.cuupa.classificator.engine.ClassificatorImplementation import com.cuupa.classificator.engine.KnowledgeManager import com.cuupa.classificator.engine.services.KnowledgeBaseExecutorService import com.cuupa.classificator.engine.services.MetadataService import com.cuupa.classificator.engine.services.SenderService import com.cuupa.classificator.engine.services.TopicService import com.cuupa.classificator.engine.services.kb.KnowledgeBase import com.cuupa.classificator.engine.services.kb.KnowledgeBaseInitiator import com.cuupa.classificator.engine.stripper.PdfAnalyser import com.cuupa.classificator.monitor.service.Monitor import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import /** * @author <NAME> (https://github.com/cuupa) */ @Configuration @Import(value = [MonitorTestConfiguration::class]) open class EngineTestConfiguration { @Autowired private var monitor: Monitor? = null @Value("\${classificator.kbfiles}") var knowledgbaseDir: String = "" @Bean open fun classificator(): ClassificatorImplementation { return ClassificatorImplementation(knowledgeManager(), analyser(), monitor!!) } @Bean open fun knowledgeManager(): KnowledgeManager { return KnowledgeManager(knowledgeBase(), knowledgeBaseExecutorService()) } @Bean open fun knowledgeBaseExecutorService(): KnowledgeBaseExecutorService { return KnowledgeBaseExecutorService(topicService(), senderService(), metadataService()) } @Bean open fun knowledgeBase(): KnowledgeBase { return knowledgeBaseInitiator().initKnowledgeBase() } @Bean open fun topicService(): TopicService { return TopicService(knowledgeBase().topicList) } @Bean open fun senderService(): SenderService { return SenderService(knowledgeBase().sendersList) } @Bean open fun metadataService(): MetadataService { return MetadataService(knowledgeBase().metadataList) } @Bean open fun knowledgeBaseInitiator(): KnowledgeBaseInitiator { return KnowledgeBaseInitiator(knowledgbaseDir) } @Bean open fun analyser(): PdfAnalyser { return PdfAnalyser() } }
94
JavaScript
0
0
ba3f2b743873a9eebd8919f5461ec53bb5cbc249
2,452
classificator
MIT License
feature_album/src/main/java/com/igorwojda/showcase/feature/album/presentation/albumdetail/AlbumDetailViewModel.kt
mortezahosseinee
263,060,635
false
null
package com.igorwojda.showcase.feature.album.presentation.albumdetail import androidx.lifecycle.viewModelScope import com.igorwojda.showcase.feature.album.domain.model.AlbumDomainModel import com.igorwojda.showcase.feature.album.domain.usecase.GetAlbumUseCase import com.igorwojda.showcase.feature.album.presentation.albumdetail.AlbumDetailViewModel.Action import com.igorwojda.showcase.feature.album.presentation.albumdetail.AlbumDetailViewModel.Action.AlbumLoadFailure import com.igorwojda.showcase.feature.album.presentation.albumdetail.AlbumDetailViewModel.Action.AlbumLoadSuccess import com.igorwojda.showcase.feature.album.presentation.albumdetail.AlbumDetailViewModel.ViewState import com.igorwojda.showcase.library.base.presentation.viewmodel.BaseAction import com.igorwojda.showcase.library.base.presentation.viewmodel.BaseViewModel import com.igorwojda.showcase.library.base.presentation.viewmodel.BaseViewState import kotlinx.coroutines.launch internal class AlbumDetailViewModel( private val getAlbumUseCase: GetAlbumUseCase, private val args: AlbumDetailFragmentArgs ) : BaseViewModel<ViewState, Action>(ViewState()) { override fun onLoadData() { getAlbum() } private fun getAlbum() { viewModelScope.launch { getAlbumUseCase.execute(args.artistName, args.albumName, args.mbId).also { when { it is GetAlbumUseCase.Result.Success -> sendAction(AlbumLoadSuccess(it.data)) it is GetAlbumUseCase.Result.Error -> sendAction(AlbumLoadFailure) } } } } override fun onReduceState(viewAction: Action) = when (viewAction) { is AlbumLoadSuccess -> state.copy( isLoading = false, isError = false, artistName = viewAction.albumDomainModel.artist, albumName = viewAction.albumDomainModel.name, coverImageUrl = viewAction.albumDomainModel.getDefaultImageUrl() ?: "" ) is AlbumLoadFailure -> state.copy( isLoading = false, isError = true, artistName = "", albumName = "", coverImageUrl = "" ) } internal data class ViewState( val isLoading: Boolean = true, val isError: Boolean = false, val albumName: String = "", val artistName: String = "", val coverImageUrl: String = "" ) : BaseViewState internal sealed class Action : BaseAction { class AlbumLoadSuccess(val albumDomainModel: AlbumDomainModel) : Action() object AlbumLoadFailure : Action() } }
1
null
0
2
71b793b37f8621ba9428c60a9acda598933876ea
2,681
NonStop
MIT License
retrofit_net/src/main/java/com/example/retrofit_net/manager/exception/ApiException.kt
youminghuo2
743,886,194
false
{"Kotlin": 73832}
package com.example.retrofit_net.manager.exception import java.io.IOException open class ApiException : Exception { var errCode: String var errSubCode: String="" var errMsg: String constructor(code: String, subCode: String, msg: String, e: Throwable? = null) : super(e) { this.errCode = code this.errSubCode = subCode this.errMsg = msg } } class NoNetworkException : IOException { var errCode: Int var errMsg: String constructor(errCode: Int, errMsg: String, e: Throwable? = null) : super(e) { this.errCode = errCode this.errMsg = errMsg } }
0
Kotlin
0
1
bf8a6fc20cedf8cf60a704af2d365995e3f93527
622
unisolution-android-sdk
Apache License 2.0
android/src/main/java/com/reactnativejwplayer/JwplayerPackage.kt
abdullahkhan70
435,819,087
false
null
package com.reactnativejwplayer import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import com.google.android.exoplayer2.ExoPlayer class JwplayerPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { val nativeModules: MutableList<NativeModule> = ArrayList(); nativeModules.add(RNJwplayerMainView()) // return emptyList() return nativeModules; } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return listOf(RNJwplayerMainView()) } }
0
null
0
0
2128f32a7b7c7037897a90891f630e1c31875e5c
743
react-native-jwplayer
MIT License
bukkit/src/main/kotlin/dev/jaims/moducore/bukkit/command/CraftCommand.kt
Jaimss
321,796,760
false
null
/* * This file is a part of ModuCore, licensed under the MIT License. * * Copyright (c) 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.jaims.moducore.bukkit.command import dev.jaims.moducore.bukkit.ModuCore import dev.jaims.moducore.bukkit.config.Modules import dev.jaims.moducore.bukkit.perm.Permissions import dev.jaims.moducore.bukkit.func.noConsoleCommand import me.mattstudios.config.properties.Property import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryType class CraftCommand(override val plugin: ModuCore) : BaseCommand { override suspend fun execute(sender: CommandSender, args: List<String>, props: CommandProperties) { if (!Permissions.CRAFT.has(sender)) return if (sender !is Player) { sender.noConsoleCommand() return } sender.openInventory(Bukkit.createInventory(null, InventoryType.WORKBENCH)) } override val module: Property<Boolean> = Modules.COMMAND_CRAFT override val usage: String = "/craft" override val description: String = "Open a crafting workbench" override val commandName: String = "craft" override val aliases: List<String> = listOf("workbench", "wb") }
8
null
2
3
75d723bafa9f53c09e1100c7828e4085ebfa3060
2,319
moducore
MIT License
ktaf/src/main/kotlin/com/github/benpollarduk/ktaf/assets/characters/Character.kt
benpollarduk
696,256,399
false
{"Kotlin": 531898, "JavaScript": 486, "HTML": 346, "CSS": 343}
package com.github.benpollarduk.ktaf.assets.characters import com.github.benpollarduk.ktaf.assets.ExaminableObject import com.github.benpollarduk.ktaf.assets.Item import com.github.benpollarduk.ktaf.assets.interaction.InteractWithItem import com.github.benpollarduk.ktaf.assets.interaction.Interaction import com.github.benpollarduk.ktaf.assets.interaction.InteractionEffect import com.github.benpollarduk.ktaf.assets.interaction.InteractionResult /** * Provides a base for all Characters. */ public abstract class Character : ExaminableObject(), InteractWithItem { /** * Specifies how this [Character] interacts with various [Item]. */ public var interaction: Interaction = { item -> InteractionResult(InteractionEffect.NO_EFFECT, item) } /** * Determines if this [Character] is alive. */ public var isAlive: Boolean = true protected set /** * This characters [Item]. */ public val items: List<Item> get() { return itemsList.toList() } private val itemsList: MutableList<Item> = mutableListOf() protected fun interactWithItem(item: Item): InteractionResult { return interaction.invoke(item) } /** * Kill this [Character]. */ public fun kill() { isAlive = false } /** * Acquire the specified [item]. */ public fun acquireItem(item: Item) { itemsList.add(item) } /** * Dequire the specified [item]. */ public fun decquireItem(item: Item) { itemsList.remove(item) } /** * Determine if this [Character] has the specified [item]. When [includeInvisibleItems] is set to true even [Item] * that have been marked as invisible to the player will be inspected. */ public fun hasItem(item: Item, includeInvisibleItems: Boolean = false): Boolean { return itemsList.contains(item) && (includeInvisibleItems || item.isPlayerVisible) } /** * Find an return an item from the specified [itemName]. When [includeInvisibleItems] is set to true even [Item] * that have been marked as invisible to the player will be inspected. If the [Character] does not have the [Item] * then null wil be returned. */ public fun findItem(itemName: String, includeInvisibleItems: Boolean = false): Item? { return itemsList.firstOrNull { it.identifier.equals(itemName) && (includeInvisibleItems || it.isPlayerVisible) } } /** * Give a specified [item] to a specified [character]. This will return true if the transaction was successful, * else false. */ public fun give(item: Item, character: Character): Boolean { if (!hasItem(item)) { return false } decquireItem(item) character.acquireItem(item) return true } }
1
Kotlin
0
9
b892bacb2a877b58a2192b7d01a7ee22aff9c5de
2,861
ktaf
MIT License
src/main/kotlin/xyz/poeschl/pixelmaze/Maze.kt
Poeschl
182,655,345
false
null
package xyz.poeschl.pixelmaze import de.amr.graph.core.api.Edge import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import mu.KotlinLogging import xyz.poeschl.kixelflut.Pixel import xyz.poeschl.kixelflut.Point import xyz.poeschl.kixelflut.createHorizontalPixels import xyz.poeschl.kixelflut.createVerticalPixels import java.awt.Color import java.util.stream.IntStream import java.util.stream.Stream import kotlin.math.max import kotlin.math.min class Maze( private val origin: Point, private val mazeSize: Pair<Int, Int>, private val pathSize: Int ) { companion object { private val VISUAL_LOGGER = KotlinLogging.logger("visualDebug") private val DEBUG = VISUAL_LOGGER.isDebugEnabled private const val BORDER_WIDTH = 1 private val WALL_COLOR = Color.WHITE } private val cellSize = pathSize + BORDER_WIDTH * 2 val widthInCells = mazeSize.first / cellSize val heightInCells = mazeSize.second / cellSize private var shadowMatrix = PixelMatrix(mazeSize.first, mazeSize.second) var mazeSet = setOf<Pixel>() fun updateMaze(edges: Stream<Edge>) { createGrid() edges.parallel().forEach { createEdges(it) } mazeSet = shadowMatrix.getPixelSet().map { Pixel(it.point.plus(origin), it.color) }.toSet() shadowMatrix = PixelMatrix(mazeSize.first, mazeSize.second) } fun clear() { mazeSet = setOf() } private fun createGrid() { runBlocking { launch { IntStream.rangeClosed(0, widthInCells) .mapToObj { x -> createVerticalPixels( Point(x * cellSize, 0), heightInCells * cellSize, WALL_COLOR ) } .flatMap { it.parallelStream() } .forEach { shadowMatrix.insert(it) } } launch { IntStream.rangeClosed(0, heightInCells) .mapToObj { y -> createHorizontalPixels( Point(0, y * cellSize), widthInCells * cellSize, WALL_COLOR ) } .flatMap { it.parallelStream() } .forEach { shadowMatrix.insert(it) } } } } private fun createEdges(edge: Edge) { val from = getOriginPointOfCell(min(edge.either(), edge.other())) val to = getOriginPointOfCell(max(edge.either(), edge.other())) when { from.x == to.x && from.y != to.y -> removeHorizontalBorderToRightOf(from) from.y == to.y && from.x != to.x -> removeVerticalBorderToBottomOf(from) } } private fun removeVerticalBorderToBottomOf(from: Point) { for (yOffset in 0..pathSize) { val wallPoint = from.plus(Point(cellSize, BORDER_WIDTH + yOffset)) shadowMatrix.remove(wallPoint) if (DEBUG) { shadowMatrix.insert(Pixel(wallPoint, Color.RED)) } } } private fun removeHorizontalBorderToRightOf(from: Point) { for (xOffset in 0..pathSize) { val wallPoint = from.plus(Point(BORDER_WIDTH + xOffset, cellSize)) shadowMatrix.remove(wallPoint) if (DEBUG) { shadowMatrix.insert(Pixel(wallPoint, Color.RED)) } } } private fun getOriginPointOfCell(index: Int): Point { val y = (index / heightInCells) * cellSize val x = (index % widthInCells) * cellSize return Point(x, y) } }
10
Kotlin
0
0
3d65bedce3dd4a8d58ea9bf70d5e18823dac8d5d
3,740
PixelMaze
Apache License 2.0
foundation/domain-model/main/ru/pixnews/domain/model/game/Game.kt
illarionov
305,333,284
false
{"Kotlin": 1170461, "Java": 7303, "FreeMarker": 2734, "Shell": 668, "Fluent": 72}
/* * Copyright (c) 2023, the Pixnews project authors and contributors. Please see the AUTHORS file for details. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package ru.pixnews.domain.model.game import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.ImmutableSet import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentSetOf import ru.pixnews.domain.model.company.Company import ru.pixnews.domain.model.datasource.DataSource import ru.pixnews.domain.model.datetime.Date import ru.pixnews.domain.model.id.GameId import ru.pixnews.domain.model.locale.Localized import ru.pixnews.domain.model.rating.AgeRating import ru.pixnews.domain.model.url.ExternalLink import ru.pixnews.domain.model.url.ImageUrl import ru.pixnews.domain.model.url.VideoUrl import ru.pixnews.domain.model.util.HasId import ru.pixnews.domain.model.util.Ref import ru.pixnews.domain.model.util.RichText import ru.pixnews.library.kotlin.utils.isNotWhitespaceOnly public data class Game( override val id: GameId, val name: Localized<String> = Localized.EMPTY_STRING, val summary: Localized<RichText> = Localized.EMPTY_RICH_TEXT, val description: Localized<RichText> = Localized.EMPTY_RICH_TEXT, val videoUrls: ImmutableList<VideoUrl> = persistentListOf(), val screenshots: ImmutableList<ImageUrl> = persistentListOf(), val developer: Company? = null, val publisher: Company? = null, val releaseDate: Date = Date.Unknown(), val releaseStatus: GameReleaseStatus? = null, val genres: ImmutableSet<GameGenre> = persistentSetOf(), val tags: ImmutableSet<GameTag> = persistentSetOf(), val ratings: RatingsSummary? = null, val links: ImmutableList<ExternalLink> = persistentListOf(), val category: GameReleaseCategory? = null, val parentGame: Ref<Game>? = null, val series: Ref<GameSeriesSummary>? = null, val platforms: ImmutableSet<Ref<GamePlatform>> = persistentSetOf(), val ageRanking: AgeRating? = null, val localizations: GameLocalizations? = null, val gameMode: ImmutableSet<Ref<GameMode>> = persistentSetOf(), val playerPerspectives: ImmutableSet<Ref<PlayerPerspective>> = persistentSetOf(), val systemRequirements: GameSystemRequirements? = null, val dataSources: ImmutableList<DataSource> = persistentListOf(), ) : HasId<GameId> { init { require(name.value.isNotWhitespaceOnly()) require(description.value.raw.isNotWhitespaceOnly()) } }
4
Kotlin
0
2
bbd35f589b8e361058218b1125896df638c14a5c
2,578
Pixnews
Apache License 2.0
app/app/src/main/java/xyz/mirage/app/business/domain/core/DataState.kt
sentrionic
378,704,735
false
null
package xyz.mirage.app.business.domain.core data class DataState<out T>( val data: T? = null, val stateMessage: StateMessage? = null, val isLoading: Boolean = false, ) { companion object { fun <T> error( response: Response, ): DataState<T> { return DataState( stateMessage = StateMessage( response ), data = null, ) } fun <T> data( response: Response?, data: T? = null, ): DataState<T> { return DataState( stateMessage = response?.let { StateMessage( it ) }, data = data, ) } fun <T> loading(): DataState<T> = DataState(isLoading = true) } }
0
Kotlin
2
1
8f50fc8244f16b43b8e054e79bcd50e98765a0e1
886
Mirage
MIT License
draggable_scaffold/src/main/java/tgo1014/draggablescaffold/DraggableScaffoldState.kt
Tgo1014
375,026,009
false
null
package tgo1014.draggablescaffold import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.animate import androidx.compose.animation.core.tween import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.unit.dp /** * Create and [remember] the [DraggableScaffoldState] taking into account default state and * SnapOffset * * @param defaultExpandState initial state of the DraggableScaffold, * @param snapOffset specifies the offset of when Snap happens when drag ends * @param allowFullWidthSwipe specifies if content can be dragged all the way to the side * @param fullWidthSwipeOffset specifies the offset of when snap happens during full width swipe */ @Composable fun rememberDraggableScaffoldState( defaultExpandState: ExpandState = ExpandState.Collapsed, snapOffset: Float = 0.5f, fullWidthSwipeOffset: Float = 0.5f, allowFullWidthSwipe: Boolean = false, key: String? = null, vararg inputs: Any, ): DraggableScaffoldState { return rememberSaveable(saver = Saver, inputs = inputs, key = key) { DraggableScaffoldState( defaultExpandState = defaultExpandState, snapOffset = SnapOffset(snapOffset), allowFullWidthSwipe = allowFullWidthSwipe, fullWidthSwipeOffset = SnapOffset(fullWidthSwipeOffset), ) } } class DraggableScaffoldState( internal val allowFullWidthSwipe: Boolean, internal val defaultExpandState: ExpandState = ExpandState.Collapsed, internal val snapOffset: SnapOffset = SnapOffset(0.5f), internal val fullWidthSwipeOffset: SnapOffset = SnapOffset(0.5f), offsetX: Float = 0f, ) { /** * represents the current dragging left offset between 0 and 1 */ val leftContentOffset: Float get() { if (contentUnderLeftWidth == 0f) return 0f return offsetX / ExpandState.ExpandedLeft.offset() } /** * represents the current dragging right offset between 0 and 1 */ val rightContentOffset: Float get() { if (contentUnderRightWidth == 0f) return 0f return offsetX / ExpandState.ExpandedRight.offset() } /** * Represents current right offset in context of full width swipe * Value between 0 and 1 */ val rightFullOffset: Float get() { val offset = ExpandState.ExpandedFullRight.offset() if (offset == 0f) return 0f return offsetX / offset } /** * Represents current left offset in context of full width swipe * Value between 0 and 1 */ val leftFullOffset: Float get() { val offset = ExpandState.ExpandedFullLeft.offset() if (offset == 0f) return 0f return offsetX / offset } /** * represents the current State of the Draggable scaffold based on current offset */ val currentState: ExpandState get() { if (contentWidth == 0f) return ExpandState.Collapsed return when { offsetX == ExpandState.ExpandedLeft.offset() && contentUnderLeftWidth != 0f -> ExpandState.ExpandedLeft offsetX == ExpandState.ExpandedRight.offset() && contentUnderRightWidth != 0f -> ExpandState.ExpandedRight offsetX == ExpandState.ExpandedFullRight.offset() && contentUnderRightWidth != 0f -> ExpandState.ExpandedFullRight offsetX == ExpandState.ExpandedFullLeft.offset() && contentUnderLeftWidth != 0f -> ExpandState.ExpandedFullLeft else -> ExpandState.Collapsed } } /** * Represents the next that will be assigned once the drag event ends */ val targetState: State<ExpandState> get() = derivedStateOf { calculateTargetStateForOffset() } /** * The width of the layout under which defines how much the top view can be dragged */ private var contentUnderLeftWidth by mutableStateOf(0.dp.value) /** * The width of the layout under which defines how much the top view can be dragged */ private var contentUnderRightWidth by mutableStateOf(0.dp.value) private var contentWidth by mutableStateOf(0.dp.value) /** * Current X offset of content on top */ internal var offsetX by mutableStateOf(offsetX) /** * Animates to the new [ExpandState] using the [AnimationSpec] * @param newState - the new state to animate to * @param spec - [AnimationSpec] that will be used for the animation */ suspend fun animateToState(newState: ExpandState, spec: AnimationSpec<Float> = tween(300)) { animate(offsetX, newState.offset(), animationSpec = spec) { currentValue, _ -> offsetX = currentValue } } /** * Sets new [ExpandState] */ fun setExpandState(state: ExpandState) { if (state != currentState) { offsetX = state.offset() } } /** * Set the content on the left width so it's not dragged further than [contentUnderLeftWidth]'s size */ internal fun onLeftContentMeasured(width: Int) { if (contentUnderLeftWidth != width.dp.value) { contentUnderLeftWidth = width.dp.value setExpandState(defaultExpandState) } } /** * Set the content on the right width so it's not dragged further than [contentUnderRightWidth]'s size */ internal fun onRightContentMeasured(width: Int) { if (contentUnderRightWidth != width.dp.value) { contentUnderRightWidth = width.dp.value setExpandState(defaultExpandState) } } internal fun onContentMeasured(width: Float) { contentWidth = width } internal suspend fun onHandleDragEnd(spec: AnimationSpec<Float>) { val nextState = calculateTargetStateForOffset() animateToState(nextState, spec) } private fun calculateTargetStateForOffset(): ExpandState { val leftOffset = leftContentOffset val rightOffset = rightContentOffset return when { leftFullOffset > fullWidthSwipeOffset -> ExpandState.ExpandedFullLeft rightFullOffset > fullWidthSwipeOffset -> ExpandState.ExpandedFullRight leftOffset > snapOffset -> ExpandState.ExpandedLeft rightOffset > snapOffset -> ExpandState.ExpandedRight else -> ExpandState.Collapsed } } internal fun onHandleDrag(dragAmount: Float, resistance: DragResistance) { offsetX = (offsetX + dragAmount * resistance.value).coerceIn( if (allowFullWidthSwipe) ExpandState.ExpandedFullRight.offset() else ExpandState.ExpandedRight.offset(), if (allowFullWidthSwipe) ExpandState.ExpandedFullLeft.offset() else ExpandState.ExpandedLeft.offset() ) } private fun ExpandState.offset(): Float { return when (this) { ExpandState.ExpandedRight -> contentUnderRightWidth * -1 ExpandState.ExpandedLeft -> contentUnderLeftWidth ExpandState.ExpandedFullRight -> (contentWidth * -1).takeIf { contentUnderRightWidth != 0f } ?: 0f ExpandState.ExpandedFullLeft -> contentWidth.takeIf { contentUnderLeftWidth != 0f } ?: 0f else -> 0f } } }
0
Kotlin
3
59
7f12eb2df7a63c4a29e658916b6ba0f01f1fa453
7,368
DraggableScaffold
Apache License 2.0
app/src/main/java/com/mezhendosina/sgo/data/emoji/DefaultEmoji.kt
mezhendosina
448,087,094
false
{"Kotlin": 593653, "Java": 1357}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mezhendosina.sgo.data.emoji import com.mezhendosina.sgo.app.R import com.mezhendosina.sgo.app.uiEntities.LessonNameUiEntity object DefaultLessons { val list = listOf( LessonNameUiEntity("русский", R.drawable.lesson_russia, "Русский язык"), LessonNameUiEntity("математик", R.drawable.lesson_math, "Математика"), LessonNameUiEntity("информатик", R.drawable.lesson_inf, "Информатика"), LessonNameUiEntity("литератур", R.drawable.lesson_lit, "Литература"), LessonNameUiEntity("английск", R.drawable.lesson_eng, "Английский язык"), LessonNameUiEntity("иностранн", R.drawable.lesson_languages, "Иностранный язык"), LessonNameUiEntity("немецк", R.drawable.lesson_german, "Немецкий"), LessonNameUiEntity("алгебр", R.drawable.lesson_math, "Алгебра"), LessonNameUiEntity("геометр", R.drawable.lesson_geometry, "Геометрия"), LessonNameUiEntity( "основы безопасности жизнедеятельности", R.drawable.lesson_obz, "Основы безопасности жизнедеятельности", ), LessonNameUiEntity("география", R.drawable.lesson_geo, "География"), LessonNameUiEntity("обществознание", R.drawable.lesson_social, "Обществознание"), LessonNameUiEntity("история", R.drawable.lesson_history, "История"), LessonNameUiEntity( "изо", R.drawable.lesson_paint, "Изобразительное искусство", ), LessonNameUiEntity("физическая культура", R.drawable.lesson_run, "Физическая культура"), LessonNameUiEntity("музыка", R.drawable.lesson_music, "Музыка"), LessonNameUiEntity("химия", R.drawable.lesson_chemistry, "Химия"), LessonNameUiEntity("физика", R.drawable.lesson_phys, "Физика"), LessonNameUiEntity("астрономия", R.drawable.lesson_astronomy, "Астрономия"), LessonNameUiEntity("биология", R.drawable.lesson_bio, "Биология"), LessonNameUiEntity("технология", R.drawable.lesson_tech, "Технология"), LessonNameUiEntity( "окружающий мир", R.drawable.lesson_natural_science, "Окружающий мир", ), LessonNameUiEntity("проект", R.drawable.lesson_project, null), ) }
0
Kotlin
0
11
d6727bca32c5daaaaa0ed4c21a671f754b59ffdb
2,998
che-zadali-app
Apache License 2.0
misskey/src/commonMain/kotlin/work/socialhub/planetlink/misskey/model/MisskeyComment.kt
uakihir0
733,128,300
false
{"Kotlin": 526097, "Shell": 1521, "Makefile": 345}
package work.socialhub.planetlink.misskey.model import work.socialhub.planetlink.micro.MicroBlogComment import work.socialhub.planetlink.misskey.define.MisskeyVisibility import work.socialhub.planetlink.model.Comment import work.socialhub.planetlink.model.Poll import work.socialhub.planetlink.model.Reaction import work.socialhub.planetlink.model.Service import work.socialhub.planetlink.model.common.AttributedString import work.socialhub.planetlink.model.request.CommentForm /** * Misskey Comment Model * Misskey のコメントモデル */ class MisskeyComment( service: Service ) : MicroBlogComment(service) { /** Requester host */ var requesterHost: String? = null /** ID for Paging */ var pagingId: String? = null /** Warning text */ var spoilerText: AttributedString? = null /** Visibility */ var visibility: MisskeyVisibility? = null /** User replied this comment */ var replyCount: Int? = null /** Poll */ var poll: Poll? = null /** Reactions */ override var reactions: List<Reaction> = listOf() get() { return field.toMutableList() .also { list -> Reaction().also { it.count = replyCount it.name = "reply" list.add(it) } Reaction().also { it.reacting = shared it.count = shareCount it.name = "share" list.add(it) } } } override val webUrl: String get() = ("https://" + requesterHost + "/notes/" + id<String>().toString()) override val displayComment: Comment get() { // Misskey の場合コメントが必ず入るので空文字か確認 return sharedComment?.let { val text = (text?.displayText ?: "") if (text.isEmpty()) it else this } ?: this } override val quoteForm: CommentForm get() { val form = CommentForm() form.isMessage(false) form.quoteId(id) return form } val idForPaging: String get() = pagingId ?: id<String>() override fun equals(other: Any?): Boolean { return if (other is MisskeyComment) { return id<String>() == other.id<String>() } else false } }
1
Kotlin
0
1
9cbf1cba723ec6d985f558312991e91beb92d8a9
2,478
planetlink
MIT License
app/src/main/java/com/verifone/mobile/dataobjects/klarna/KlarnaFinalValidationResponse.kt
verifoneone
488,284,384
false
{"Kotlin": 337130}
package com.verifone.mobile.dataobjects.klarna import com.google.gson.annotations.SerializedName class KlarnaFinalValidationResponse { @SerializedName("id") var id = "" @SerializedName("instore_reference") var inStoreReference = "" @SerializedName("amount") var amount = 0 @SerializedName("created_at") var createdAt = "" @SerializedName("merchant_reference") var merchantReference = "" @SerializedName("processor") var processor = "" @SerializedName("payment_product") var paymentProduct = "" @SerializedName("payment_product_type") var paymentProductType = "" @SerializedName("status") var status = "" @SerializedName("shopper_interaction") var shopperInteraction = "" @SerializedName("country_code") var countryCode = "SE" }
0
Kotlin
0
5
af847b68098ed977504d142f10d3e9bccec9822a
773
verifone-ecom-android-sdk
MIT License