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/test/kotlin/canon/parser/xml/strategy/MultipleChoiceStrategyTest.kt
leftshiftone
205,671,409
false
null
package canon.parser.xml.strategy import canon.extension.toNode import canon.parser.xml.CanonXmlParser import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class MultipleChoiceStrategyTest { @Test fun `ordinary parsing`() { val xml = "<multipleChoice id='testId' class='testClass' name='testName' sieve='true'>" + "<choice id='testId2' class='testClass' text='testText' selected='true'></choice>" + "<choice id='testId3' class='testClass' text='testText' selected='false'></choice>" + "</multipleChoice>" val parsed = MultipleChoiceStrategy().parse(xml.toNode(), CanonXmlParser()::toRenderables) assertThat(parsed).isNotNull assertThat(parsed.id).isEqualTo("testId") assertThat(parsed.`class`).isEqualTo("testClass") assertThat(parsed.name).isEqualTo("testName") assertThat(parsed.sieve).isEqualTo(true) assertThat(parsed.renderables).hasSize(2) } @Test fun `ordinary parsing with default value for sieve is true`() { val xml = "<multipleChoice id='testId' class='testClass' name='testName'>" + "<choice id='testId2' class='testClass' text='testText' selected='true'></choice>" + "<choice id='testId3' class='testClass' text='testText' selected='false'></choice>" + "</multipleChoice>" val parsed = MultipleChoiceStrategy().parse(xml.toNode(), CanonXmlParser()::toRenderables) assertThat(parsed).isNotNull assertThat(parsed.id).isEqualTo("testId") assertThat(parsed.`class`).isEqualTo("testClass") assertThat(parsed.name).isEqualTo("testName") assertThat(parsed.sieve).isEqualTo(true) assertThat(parsed.renderables).hasSize(2) } }
0
Kotlin
1
0
5babc577eeca5655cf92e64dd2693c591c72eb50
1,816
canon
MIT License
material-icon/src/main/kotlin/team/duckie/quackquack/material/icon/quackicon/outlined/Home.kt
duckie-team
523,387,054
false
{"Kotlin": 901061, "MDX": 51559, "JavaScript": 6871, "CSS": 1060}
/* * Designed and developed by Duckie Team 2023. * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/quack-quack-android/blob/main/LICENSE */ package team.duckie.quackquack.material.icon.quackicon.outlined import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import team.duckie.quackquack.material.icon.quackicon.OutlinedGroup public val OutlinedGroup.Home: ImageVector get() { if (_home != null) { return _home!! } _home = Builder( name = "Home", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF222222)), strokeLineWidth = 1.5f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(19.9791f, 8.108f) lineTo(13.8791f, 3.133f) curveTo(13.3437f, 2.7429f, 12.6981f, 2.5333f, 12.0356f, 2.5343f) curveTo(11.3732f, 2.5354f, 10.7282f, 2.7472f, 10.1941f, 3.139f) lineTo(4.0111f, 8.201f) curveTo(3.6263f, 8.4834f, 3.3133f, 8.8523f, 3.0972f, 9.2778f) curveTo(2.8812f, 9.7034f, 2.7681f, 10.1737f, 2.7671f, 10.651f) verticalLineTo(18.375f) curveTo(2.7696f, 18.7785f, 2.8515f, 19.1776f, 3.0083f, 19.5494f) curveTo(3.165f, 19.9212f, 3.3935f, 20.2585f, 3.6806f, 20.542f) curveTo(3.9678f, 20.8256f, 4.3079f, 21.0497f, 4.6817f, 21.2017f) curveTo(5.0555f, 21.3538f, 5.4556f, 21.4306f, 5.8591f, 21.428f) horizontalLineTo(7.5101f) curveTo(7.9197f, 21.4283f, 8.3126f, 21.2659f, 8.6025f, 20.9765f) curveTo(8.8924f, 20.6872f, 9.0556f, 20.2946f, 9.0561f, 19.885f) verticalLineTo(16.271f) curveTo(9.0561f, 15.774f, 9.2535f, 15.2973f, 9.605f, 14.9459f) curveTo(9.9564f, 14.5944f, 10.4331f, 14.397f, 10.9301f, 14.397f) horizontalLineTo(13.0711f) curveTo(13.3171f, 14.3971f, 13.5606f, 14.4457f, 13.7878f, 14.54f) curveTo(14.015f, 14.6342f, 14.2214f, 14.7723f, 14.3952f, 14.9463f) curveTo(14.569f, 15.1203f, 14.7069f, 15.3269f, 14.8009f, 15.5542f) curveTo(14.8949f, 15.7815f, 14.9432f, 16.025f, 14.9431f, 16.271f) verticalLineTo(19.885f) curveTo(14.943f, 20.0881f, 14.9829f, 20.2892f, 15.0605f, 20.4768f) curveTo(15.1382f, 20.6644f, 15.252f, 20.8349f, 15.3956f, 20.9785f) curveTo(15.5392f, 21.1221f, 15.7097f, 21.2359f, 15.8973f, 21.3136f) curveTo(16.0849f, 21.3912f, 16.286f, 21.4311f, 16.4891f, 21.431f) horizontalLineTo(18.1421f) curveTo(18.9569f, 21.4361f, 19.7404f, 21.1173f, 20.3203f, 20.5447f) curveTo(20.9001f, 19.9722f, 21.2288f, 19.1928f, 21.2341f, 18.378f) verticalLineTo(10.563f) curveTo(21.2329f, 10.0839f, 21.1187f, 9.6118f, 20.9006f, 9.1852f) curveTo(20.6825f, 8.7586f, 20.3668f, 8.3895f, 19.9791f, 8.108f) close() } } .build() return _home!! } private var _home: ImageVector? = null
45
Kotlin
8
99
24d44663cf5bea29fc73595b5f60be03b08e162b
3,555
quack-quack-android
MIT License
iris-mock-compiler/src/main/kotlin/dev/arildo/iris/processor/IrisMockProcessorProvider.kt
arildojr7
634,544,161
false
null
package dev.arildo.iris.processor import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.processing.SymbolProcessorProvider class IrisMockProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return IrisMockProcessor(environment.logger, environment.codeGenerator) } }
1
Kotlin
1
2
9bff3b96da90cd91c74d446c139f6e4bbb67135d
462
iris-mock
Apache License 2.0
app/src/main/java/ru/popov/bodya/howmoney/presentation/ui/account/activities/AccountActivity.kt
popovbodya
141,707,159
false
null
package ru.popov.bodya.howmoney.presentation.ui.account.activities import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.widget.Toast import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import ru.popov.bodya.core.mvp.AppActivity import ru.popov.bodya.howmoney.R import ru.popov.bodya.howmoney.domain.wallet.models.Wallet import ru.popov.bodya.howmoney.presentation.mvp.account.AccountPresenter import ru.popov.bodya.howmoney.presentation.mvp.account.AccountView import ru.popov.bodya.howmoney.presentation.ui.about.fragments.AboutFragment import ru.popov.bodya.howmoney.presentation.ui.budget.fragments.BudgetFragment import ru.popov.bodya.howmoney.presentation.ui.common.Screens.ABOUT_SCREEN import ru.popov.bodya.howmoney.presentation.ui.common.Screens.BUDGET_SCREEN import ru.popov.bodya.howmoney.presentation.ui.common.Screens.ENROLLMENT_SCREEN import ru.popov.bodya.howmoney.presentation.ui.common.Screens.EXPENSE_SCREEN import ru.popov.bodya.howmoney.presentation.ui.common.Screens.REPLENISHMENT_SCREEN import ru.popov.bodya.howmoney.presentation.ui.common.Screens.SETTINGS_SCREEN import ru.popov.bodya.howmoney.presentation.ui.common.Screens.WRITE_EMAIL_SCREEN import ru.popov.bodya.howmoney.presentation.ui.enrollment.EnrollmentFragment import ru.popov.bodya.howmoney.presentation.ui.expense.ExpenseFragment import ru.popov.bodya.howmoney.presentation.ui.replenishment.fragments.ReplenishmentFragment import ru.popov.bodya.howmoney.presentation.ui.settings.fragments.SettingsFragment import ru.terrakok.cicerone.NavigatorHolder import ru.terrakok.cicerone.android.SupportAppNavigator import javax.inject.Inject /** * @author popovbodya */ class AccountActivity : AppActivity(), AccountView, HasSupportFragmentInjector { @Inject @InjectPresenter lateinit var accountPresenter: AccountPresenter @Inject lateinit var navigationHolder: NavigatorHolder @Inject lateinit var injector: DispatchingAndroidInjector<Fragment> @ProvidePresenter fun provideOverviewPresenter(): AccountPresenter = accountPresenter override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.launch_activity_layout) } override fun onResume() { super.onResume() navigationHolder.setNavigator(navigator) } override fun onPause() { navigationHolder.removeNavigator() super.onPause() } override fun onBackPressed() { accountPresenter.onBackPressed() } override fun supportFragmentInjector(): AndroidInjector<Fragment> = injector private val navigator = object : SupportAppNavigator(this, supportFragmentManager, R.id.main_container) { override fun createActivityIntent(context: Context, screenKey: String, data: Any?): Intent? { return when (screenKey) { WRITE_EMAIL_SCREEN -> composeEmail(data as? String ?: getString(R.string.email), getString(R.string.about_email_subject)) else -> null } } override fun createFragment(screenKey: String, data: Any?): Fragment? { return when (screenKey) { BUDGET_SCREEN -> BudgetFragment() ENROLLMENT_SCREEN -> EnrollmentFragment.newInstance(data as Wallet) EXPENSE_SCREEN -> ExpenseFragment.newInstance(data as Wallet) REPLENISHMENT_SCREEN -> ReplenishmentFragment.newInstance(data as Wallet) SETTINGS_SCREEN -> SettingsFragment() ABOUT_SCREEN -> AboutFragment() else -> null } } override fun showSystemMessage(message: String) { Toast.makeText(this@AccountActivity, message, Toast.LENGTH_SHORT).show() } override fun exit() { finish() } } private fun composeEmail(address: String, subject: String): Intent { val intent = Intent(Intent.ACTION_SENDTO) intent.data = Uri.parse("mailto:") // only email apps should handle this intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(address)) intent.putExtra(Intent.EXTRA_SUBJECT, subject) return intent } }
0
Kotlin
1
0
dcf1146ad4ca51ffbebf8dd6c931fbbdf5602a2c
4,598
HowMoney
MIT License
flow/src/main/java/pro/progr/flow/composable/EditYear.kt
anastas-makar
643,590,978
false
null
package pro.progr.flow.composable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.TextField import androidx.compose.material.TextFieldDefaults import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Done import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import pro.progr.flow.R import pro.progr.flow.calendarViewModel @Composable fun EditYear(editYear: MutableState<Boolean>) { val newYear = rememberSaveable { mutableStateOf(calendarViewModel.calendarPage.value.yearName) } TextField( value = newYear.value, onValueChange = { v -> newYear.value = v }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), textStyle = TextStyle(textAlign = TextAlign.Center), modifier = Modifier .width(80.dp) .padding(bottom = 10.dp), colors = TextFieldDefaults.textFieldColors( // Изменяем цвета TextField backgroundColor = Color.Transparent ), singleLine = true, // Запрещаем перенос строк, чтобы текст был в одну строку maxLines = 1 // Устанавливаем максимальное количество строк равным 1 ) IconButton( onClick = { calendarViewModel.updateYear(newYear.value) editYear.value = !editYear.value } ) { Icon( imageVector = Icons.Outlined.Done, contentDescription = stringResource(id = R.string.left) ) } }
0
Kotlin
0
0
5e9562f98129215dc0e113bd7e2683892f3bfb94
2,122
Flow
MIT License
flow/src/main/java/pro/progr/flow/composable/EditYear.kt
anastas-makar
643,590,978
false
null
package pro.progr.flow.composable import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.TextField import androidx.compose.material.TextFieldDefaults import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Done import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import pro.progr.flow.R import pro.progr.flow.calendarViewModel @Composable fun EditYear(editYear: MutableState<Boolean>) { val newYear = rememberSaveable { mutableStateOf(calendarViewModel.calendarPage.value.yearName) } TextField( value = newYear.value, onValueChange = { v -> newYear.value = v }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), textStyle = TextStyle(textAlign = TextAlign.Center), modifier = Modifier .width(80.dp) .padding(bottom = 10.dp), colors = TextFieldDefaults.textFieldColors( // Изменяем цвета TextField backgroundColor = Color.Transparent ), singleLine = true, // Запрещаем перенос строк, чтобы текст был в одну строку maxLines = 1 // Устанавливаем максимальное количество строк равным 1 ) IconButton( onClick = { calendarViewModel.updateYear(newYear.value) editYear.value = !editYear.value } ) { Icon( imageVector = Icons.Outlined.Done, contentDescription = stringResource(id = R.string.left) ) } }
0
Kotlin
0
0
5e9562f98129215dc0e113bd7e2683892f3bfb94
2,122
Flow
MIT License
basic-example/product/src/main/kotlin/com/pintailconsultingllc/product/controllers/dto/CategoryDTO.kt
cebartling
347,271,498
false
null
package com.pintailconsultingllc.product.controllers.dto import com.pintailconsultingllc.product.jpa.entities.Category import java.time.LocalDateTime import java.util.UUID data class CategoryDTO( val id: UUID, val version: Int, var name: String, val deleted: Boolean, val createdAt: LocalDateTime, val updatedAt: LocalDateTime, val createdBy: String, val updatedBy: String, ) { constructor(entity: Category) : this( id = entity.id, version = entity.version, name = entity.name, deleted = entity.deleted, createdAt = entity.createdAt, updatedAt = entity.updatedAt, createdBy = entity.createdBy, updatedBy = entity.updatedBy ) }
0
Kotlin
0
0
2687b751e3eb3d2482c9548791dc14df75330a70
733
saga-pattern-examples
MIT License
src/main/kotlin/entities/EntityRenderer.kt
MJARuijs
238,959,670
false
null
package com.blazeit.game.entities import com.blazeit.game.graphics.Camera import com.blazeit.game.graphics.lights.AmbientLight import com.blazeit.game.graphics.lights.DirectionalLight import com.blazeit.game.graphics.rendertargets.RenderTarget import com.blazeit.game.graphics.rendertargets.attachments.AttachmentType import com.blazeit.game.graphics.samplers.Sampler import com.blazeit.game.graphics.shaders.ShaderProgram import com.blazeit.game.graphics.shadows.ShadowData import com.blazeit.game.math.vectors.Vector2 import com.blazeit.game.math.vectors.Vector4 object EntityRenderer { private val shaderProgram = ShaderProgram.load("shaders/entity.vert", "shaders/entity.frag") private val renderTarget = RenderTarget(960, 540, AttachmentType.COLOR_TEXTURE, AttachmentType.DEPTH_TEXTURE) fun render(camera: Camera, entities: List<Entity>, ambient: AmbientLight, directional: DirectionalLight, shadows: List<ShadowData> = ArrayList(), waterPlane: Vector4 = Vector4()): RenderTarget { renderTarget.start() renderTarget.clear() shaderProgram.start() if (shadows.isNotEmpty()) { val shadowData = shadows[0] val shadowSampler = Sampler(0) shadowSampler.bind(shadowData.shadowMap) shaderProgram.set("shadowPosition", shadowData.shadowDistance) shaderProgram.set("shadowMatrix", shadowData.getShadowMatrix()) shaderProgram.set("shadowMapSize", Vector2( shadowData.shadowMap.getWidth(), shadowData.shadowMap.getHeight() )) shaderProgram.set("shadowMap", shadowSampler.index) } shaderProgram.set("projection", camera.projectionMatrix) shaderProgram.set("view", camera.viewMatrix) shaderProgram.set("ambient.color", ambient.color) shaderProgram.set("sun.color", directional.color) shaderProgram.set("sun.direction", directional.direction) shaderProgram.set("waterPlane", waterPlane) shaderProgram.set("cameraPosition", camera.position) for (entity in entities) { val model = entity.model val transformation = entity.transformation shaderProgram.set("model", transformation) for (shape in model.shapes) { shaderProgram.set("material.diffuseColor", shape.material.diffuse) shaderProgram.set("material.specularColor", shape.material.specular) shaderProgram.set("material.shininess", shape.material.shininess) shape.mesh.draw() } } shaderProgram.stop() renderTarget.stop() return renderTarget } fun destroy() { shaderProgram.destroy() } }
0
Kotlin
0
0
ba34391da0b523907d84d71e47b70f4ad3c12173
2,776
Morgan
MIT License
app/src/main/java/com/roughlyunderscore/cubinghub/data/export/TwistyTimerAnalyzer.kt
RoughlyUnderscore
764,166,604
false
{"Kotlin": 140508}
package com.roughlyunderscore.cubinghub.data.export import com.roughlyunderscore.cubinghub.data.export.type.Punishment import com.roughlyunderscore.cubinghub.data.export.type.Solve import com.roughlyunderscore.cubinghub.util.safeSubList import com.roughlyunderscore.cubinghub.util.twistyTimeStringToTimestamp class TwistyTimerAnalyzer : Analyzer { override fun fromLine(content: String): Solve? { if (content.startsWith("Puzzle,")) return null if (content.count { it == ';' } < 4) { // session export val split = content.replace("\"", "").split(";") val initialTime = split.getOrNull(0)?.toDoubleOrNull() ?: return null val scramble = split.getOrNull(1) ?: return null val timestamp = split.getOrNull(2)?.twistyTimeStringToTimestamp() ?: return null val punishment = if (split.getOrNull(3) != null) Punishment.DNF else Punishment.NONE return Solve(initialTime, punishment, timestamp, scramble, "") } // full export // twisty timer for some reason does these in different formats val split = content.replace("\"", "").split(";") val time = (split.getOrNull(2)?.toDoubleOrNull() ?: return null) / 1000 val timestamp = split.getOrNull(3)?.toLong() ?: return null val scramble = split.getOrNull(4) ?: return null val punishment = when (split.getOrNull(5)) { "1" -> Punishment.PLUS_TWO "2" -> Punishment.DNF else -> Punishment.NONE } // everything else is comment val comment = split.safeSubList(6, split.size).joinToString(";") return Solve(time, punishment, timestamp, scramble, comment) } }
0
Kotlin
0
0
a130514d6b4077dda9065c64a68520aed6d49672
1,634
CubingHub
Apache License 2.0
kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/data/blocking/forAll10.kt
kotest
47,071,082
false
{"Kotlin": 4736924, "CSS": 352, "Java": 145}
package io.kotest.data.blocking import io.kotest.data.Row10 import io.kotest.data.forAll import io.kotest.data.forNone import io.kotest.data.headers import io.kotest.data.table import io.kotest.mpp.reflection fun <A, B, C, D, E, F, G, H, I, J> forAll( vararg rows: Row10<A, B, C, D, E, F, G, H, I, J>, testfn: (A, B, C, D, E, F, G, H, I, J) -> Unit ) { val params = reflection.paramNames(testfn) ?: emptyList<String>() val paramA = params.getOrElse(0) { "a" } val paramB = params.getOrElse(1) { "b" } val paramC = params.getOrElse(2) { "c" } val paramD = params.getOrElse(3) { "d" } val paramE = params.getOrElse(4) { "e" } val paramF = params.getOrElse(5) { "f" } val paramG = params.getOrElse(6) { "g" } val paramH = params.getOrElse(7) { "h" } val paramI = params.getOrElse(8) { "i" } val paramJ = params.getOrElse(9) { "j" } table(headers(paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, paramI, paramJ), *rows).forAll(testfn) } fun <A, B, C, D, E, F, G, H, I, J> forNone( vararg rows: Row10<A, B, C, D, E, F, G, H, I, J>, testfn: (A, B, C, D, E, F, G, H, I, J) -> Unit ) { val params = reflection.paramNames(testfn) ?: emptyList<String>() val paramA = params.getOrElse(0) { "a" } val paramB = params.getOrElse(1) { "b" } val paramC = params.getOrElse(2) { "c" } val paramD = params.getOrElse(3) { "d" } val paramE = params.getOrElse(4) { "e" } val paramF = params.getOrElse(5) { "f" } val paramG = params.getOrElse(6) { "g" } val paramH = params.getOrElse(7) { "h" } val paramI = params.getOrElse(8) { "i" } val paramJ = params.getOrElse(9) { "j" } table(headers(paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, paramI, paramJ), *rows).forNone(testfn) }
141
Kotlin
648
4,435
2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f
1,776
kotest
Apache License 2.0
src/test/kotlin/com/github/epadronu/balin/core/BrowserSpec.kt
nielsfalk
87,980,374
true
{"Kotlin": 46165}
/****************************************************************************** * Copyright 2016 Edinson E. Padrón Urdaneta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* ***************************************************************************/ package com.github.epadronu.balin.core /* ***************************************************************************/ /* ***************************************************************************/ import com.gargoylesoftware.htmlunit.BrowserVersion import com.gargoylesoftware.htmlunit.ScriptException import com.github.epadronu.balin.extensions.`$` import com.github.epadronu.balin.libs.delegatesTo import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.openqa.selenium.By import org.openqa.selenium.TimeoutException import org.openqa.selenium.htmlunit.HtmlUnitDriver import org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated import kotlin.test.assertEquals /* ***************************************************************************/ /* ***************************************************************************/ class BrowserSpec : Spek({ given("the Kotlin's website index page URL") { val indexPageUrl = "http://kotlinlang.org/" on("visiting such URL") { var currentBrowserUrl: String? = null var currentPageTitle: String? = null Browser.drive(driver = HtmlUnitDriver(BrowserVersion.FIREFOX_45)) { currentBrowserUrl = to(indexPageUrl) currentPageTitle = title } it("should change the browser's URL to the given one") { assertEquals(indexPageUrl, currentBrowserUrl) } it("should get the title of the Kotlin's website index page") { assertEquals("Kotlin Programming Language", currentPageTitle) } } } given("the Kotlin's website index page URL and a couple of CSS selectors") { val indexPageUrl = "http://kotlinlang.org/" val bonusFeaturesSelector = "li.kotlin-feature > h3:nth-child(2)" val coolestFeaturesSelector = "li.kotlin-feature > h3:nth-child(2)" val navItemsSelector = "a.nav-item" val tryItBtnSelector = ".get-kotlin-button" on("visiting such URL and getting the elements for said selectors") { var bonusFeatures: List<String>? = null var coolestFeatures: List<String>? = null var navItems: List<String>? = null var tryItBtn: String? = null Browser.drive(driver = HtmlUnitDriver(BrowserVersion.FIREFOX_45)) { to(indexPageUrl) bonusFeatures = `$`(bonusFeaturesSelector, 4, 3).map { it.text } coolestFeatures = `$`(coolestFeaturesSelector, 0..2).map { it.text } navItems = `$`(navItemsSelector).map { it.text } tryItBtn = `$`(tryItBtnSelector, 0).text } it("should get the navigation items") { assertEquals(listOf("Learn", "Community", "Try Online"), navItems) } it("should get the try-it button") { assertEquals("Try Kotlin", tryItBtn) } it("should get the coolest features") { assertEquals(listOf("Concise", "Safe", "Versatile"), coolestFeatures) } it("should get the bonus features") { assertEquals(listOf("Tooling", "Interoperable"), bonusFeatures) } } } given("the Kotlin's website index page with content elements and no URL") { class IndexPage : Page() { override val url = null override val at = delegatesTo<Browser, Boolean> { title == "Kotlin Programming Language" } val navItems by lazy { `$`("a.nav-item").map { it.text } } val tryItBtn by lazy { `$`(".get-kotlin-button", 0).text } val coolestFeatures by lazy { `$`("li.kotlin-feature").`$`("h3:nth-child(2)", 0..2).map { it.text } } val bonusFeatures by lazy { `$`("li.kotlin-feature").`$`("h3:nth-child(2)", 4, 3).map { it.text } } } on("visiting the index page URL and setting the browser's page with `at`") { var page: IndexPage? = null Browser.drive(driver = HtmlUnitDriver(BrowserVersion.FIREFOX_45)) { to("http://kotlinlang.org/") page = at(::IndexPage).apply { // In order to execute the lazy evaluation and cache the results bonusFeatures; coolestFeatures; navItems; tryItBtn } } it("should change the browser's page to the given one") { assertEquals(true, page is IndexPage) } it("should get the navigation items") { assertEquals( listOf("Learn", "Community", "Try Online"), page?.navItems ) } it("should get the try-it button") { assertEquals("Try Kotlin", page?.tryItBtn) } it("should get the coolest features") { assertEquals( listOf("Concise", "Safe", "Versatile"), page?.coolestFeatures ) } it("should get the bonus features") { assertEquals(listOf("Tooling", "Interoperable"), page?.bonusFeatures) } } } given("the selector of an element that must be present") { val selector = ".global-header-logo" on("waiting for the element located by such selector to be present") { var itSucceed = true try { Browser.drive(driver = HtmlUnitDriver(BrowserVersion.FIREFOX_45)) { to("http://kotlinlang.org/") waitFor { presenceOfElementLocated(By.cssSelector(selector)) } } } catch (ignore: TimeoutException) { itSucceed = false } it("should success") { assertEquals(true, itSucceed) } } } given("the selector of an element that shouldn't be present") { val selector = "#wrong.selector" on("waiting for the element located by such selector to be present") { var itFailed = false try { Browser.drive(driver = HtmlUnitDriver(BrowserVersion.FIREFOX_45)) { to("http://kotlinlang.org/") waitFor { presenceOfElementLocated(By.cssSelector(selector)) } } } catch (ignore: TimeoutException) { itFailed = true } it("should fail") { assertEquals(true, itFailed) } } } given("an HtmlUnitDriver with JavaScript enabled") { val driver = HtmlUnitDriver(BrowserVersion.FIREFOX_45).apply { setJavascriptEnabled(true) } on("executing a simple `console.log`") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") var itSucceed = true try { js.call { "console.log(\"Hello, world!\")" } } catch (ignore: ScriptException) { itSucceed = false } it("should success") { assertEquals(true, itSucceed) } } on("executing an invalid JavaScript code") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") var itFailed = false try { js.call { "an obvious bad JavaScript code" } } catch (ignore: ScriptException) { itFailed = true } it("should fail") { assertEquals(true, itFailed) } } } on("executing JavaScript code with arguments with `call`") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") val arguments = js.call(1, 2) { "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];" } it("should return the arguments as is") { assertEquals("Arguments: 1, 2", arguments) } } } on("executing JavaScript code with arguments with `execute`") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") val arguments = js.execute(true, false) { "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];" } it("should return the arguments as is") { assertEquals("Arguments: true, false", arguments) } } } on("executing JavaScript code with arguments with `run`") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") val arguments = js.run("a", "b") { "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];" } it("should return the arguments as is") { assertEquals("Arguments: a, b", arguments) } } } on("setting a global variable") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") js["myGlobal"] = "global variable" val globalVariableValue = js.execute { "return window.myGlobal;" } it("should return the variable's value as is") { assertEquals("global variable", globalVariableValue) } } } on("setting a global variable") { Browser.drive(driver = driver) { to("http://kotlinlang.org/") js["myGlobal"] = "super global variable" val globalVariableValue = js["myGlobal"] it("should get the variable's value as is") { assertEquals("super global variable", globalVariableValue) } } } } } }) /* ***************************************************************************/
0
Kotlin
0
0
607387ce173eb5c8bbf2f758e85118d71c04cda1
11,641
balin
Apache License 2.0
app/src/main/java/com/oceanbrasil/ocean_jornada_android_maio_2023/model/source/local/hint/HintDao.kt
DevNicolasLacerda
653,788,623
false
null
package com.oceanbrasil.ocean_jornada_android_maio_2023.model.source.local.hint import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface HintDao { @Insert fun insert(hint: HintEntity) @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertAll(hints: List<HintEntity>) @Query("SELECT * FROM hints") fun findAll(): List<HintEntity> }
0
Kotlin
0
1
9949a844148dba8fcb3bc5f14b9315287344dab2
441
jornada_android_ocean
MIT License
components/wall/src/main/java/top/sunhy/talking/wall/WallViewModel.kt
RDSunhy
421,280,382
false
null
package top.sunhy.talking.wall import top.sunhy.common.vm.CommonViewModel class WallViewModel: CommonViewModel() { }
0
Kotlin
0
0
ff8d615fceeb21169caba21df32e120e2ac783f6
118
android-component
Apache License 2.0
Chapter07/Exercise7.01/app/src/main/java/com/example/movieapp/model/MoviesResponse.kt
PacktPublishing
449,952,238
false
{"Kotlin": 66206}
package com.example.movieapp.model data class MoviesResponse( val page: Int, val results: List<Movie> )
0
Kotlin
3
20
00fbde0ecec8dccb8bf838504d9b40f9b1187574
112
Simplifying-Android-Development-with-Coroutines-and-Flows
MIT License
kvision-modules/kvision-material/src/jsMain/kotlin/io/kvision/material/chips/ChipEvents.kt
rjaros
120,835,750
false
{"Kotlin": 3524783, "CSS": 25183, "JavaScript": 16390, "HTML": 2425}
/* * Copyright (c) 2017-present Robert Jaros * Copyright (c) 2024 Maanrifa Bacar Ali <dev.manrif@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.kvision.material.chips import io.kvision.material.ExperimentalMaterialApi import io.kvision.utils.SnOn import io.kvision.utils.event import org.w3c.dom.events.Event /** * Dispatched when `disabled` is toggled. * [Event.bubbles] */ @ExperimentalMaterialApi fun SnOn<out MdChip>.updateFocus(action: (Event) -> Unit) { event("update-focus", action) } /** * Dispatched when the remove button is clicked. */ @ExperimentalMaterialApi fun <T> SnOn<T>.remove(action: (Event) -> Unit) where T: MdChip, T: RemovableChip { event("remove", action) }
17
Kotlin
65
1,235
7daa34594be70c037bfbaeefbfd1e3d7629e1e0b
1,754
kvision
MIT License
app/src/test/java/com/ahmed3elshaer/geosquar/utils/Extensions.kt
ahmed3elshaer
217,612,454
false
null
/* * * * * Created by <NAME> on 10/28/19 7:24 AM * * Copyright (c) 2019 . All rights reserved. * * Last modified 10/28/19 7:24 AM * */ package com.ahmed3elshaer.geosquar.utils import org.mockito.Mockito private fun <T> any(): T { Mockito.any<T>() return uninitialized() } private fun <T> uninitialized(): T = null as T
0
Kotlin
7
25
0ba53aeb717182a4c3bbde83a6b46a3ad4635246
340
GeoSquar
MIT License
app/src/main/java/com/futag/futag/presentation/adapter/PostRecyclerAdapter.kt
FUTAG-Software
365,867,008
false
{"Kotlin": 158142}
package com.futag.futag.presentation.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.futag.futag.R import com.futag.futag.databinding.PostRecyclerRowBinding import com.futag.futag.model.post.PostModelItem import com.futag.futag.util.fetchImagesWithUrl import com.futag.futag.util.listener.PostAdapterClickListener import com.futag.futag.util.placeholderProgressBar class PostRecyclerAdapter( private val context: Context, private val clickListener: PostAdapterClickListener, ) : RecyclerView.Adapter<PostRecyclerAdapter.PostViewHolder>() { private val diffUtil = object : DiffUtil.ItemCallback<PostModelItem>() { override fun areItemsTheSame(oldItem: PostModelItem, newItem: PostModelItem): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: PostModelItem, newItem: PostModelItem): Boolean { return oldItem == newItem } } private val recyclerDiffUtil = AsyncListDiffer(this, diffUtil) var postList: List<PostModelItem> get() = recyclerDiffUtil.currentList set(value) = recyclerDiffUtil.submitList(value) inner class PostViewHolder(val itemBinding: PostRecyclerRowBinding) : RecyclerView.ViewHolder(itemBinding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder { val binding = PostRecyclerRowBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PostViewHolder(binding) } override fun onBindViewHolder(holder: PostViewHolder, position: Int) { val currentData = postList[position] if (currentData.featuredImage != null) { holder.itemBinding.imageViewPost.fetchImagesWithUrl(currentData.featuredImage.large, placeholderProgressBar(context)) } else { holder.itemBinding.imageViewPost.setImageDrawable( ContextCompat.getDrawable(context, R.drawable.error) ) } holder.itemBinding.apply { textViewTitle.text = currentData.title cardView.setOnClickListener { clickListener.clickListener(currentData) } } } override fun getItemCount(): Int = postList.size }
0
Kotlin
1
9
61e221679ae4385fff7f0667f9e4e0e28195c127
2,528
FUTAG-Android
MIT License
data/src/main/kotlin/team/applemango/runnerbe/data/user/repository/UserRepositoryImpl.kt
ricky-buzzni
485,390,072
false
{"Kotlin": 615137}
/* * RunnerBe © 2022 Team AppleMango. all rights reserved. * RunnerBe license is under the MIT. * * [UserRepositoryImpl.kt] created by Ji Sungbin on 22. 2. 28. 오후 11:38 * * Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE. */ package team.applemango.runnerbe.data.user.repository import team.applemango.runnerbe.data.common.isSuccessNonNull import team.applemango.runnerbe.data.common.toBaseResult import team.applemango.runnerbe.data.common.toJobChangeResult import team.applemango.runnerbe.data.common.toNicknameChangeResult import team.applemango.runnerbe.data.runningitem.constant.NotYetVerifyCode import team.applemango.runnerbe.data.runningitem.constant.SuccessCode import team.applemango.runnerbe.data.user.mapper.toDomain import team.applemango.runnerbe.data.util.extension.requireSuccessfulBody import team.applemango.runnerbe.data.util.userApi import team.applemango.runnerbe.domain.runningitem.common.BaseResult import team.applemango.runnerbe.domain.runningitem.model.runningitem.RunningItem import team.applemango.runnerbe.domain.user.model.MyPageInformation import team.applemango.runnerbe.domain.user.model.wrapper.JobWrapper import team.applemango.runnerbe.domain.user.model.wrapper.NicknameWrapper import team.applemango.runnerbe.domain.user.model.wrapper.ProfileImageUrlWrapper import team.applemango.runnerbe.domain.user.repository.UserRepository class UserRepositoryImpl : UserRepository { override suspend fun setNickname( jwt: String, userId: Int, nickName: NicknameWrapper, ): BaseResult { val request = userApi.setNickname( jwt = jwt, userId = userId, nickname = nickName ) return request.requireSuccessfulBody( requestName = "userApi.setNickname", resultVerifyBuilder = { body -> body.code in listOf(SuccessCode, NotYetVerifyCode, 3004, 3005) } ).toNicknameChangeResult() } override suspend fun updateBookmarkItem( jwt: String, postId: Int, userId: Int, whetherAdd: String, ): BaseResult { val request = userApi.updateBookmarkItem( jwt = jwt, postId = postId, userId = userId, whetherAdd = whetherAdd ) return request.requireSuccessfulBody( requestName = "userApi.updateBookmarkItem", resultVerifyBuilder = { body -> body.code in listOf(SuccessCode, NotYetVerifyCode) } ).toBaseResult() } override suspend fun loadBookmarkItems( jwt: String, userId: Int, ): List<RunningItem> { val request = userApi.loadBookmarkItems( jwt = jwt, userId = userId, ) return request.requireSuccessfulBody( requestName = "userApi.loadBookmarkItems", resultVerifyBuilder = { body -> body.code in listOf(SuccessCode, NotYetVerifyCode) } ).toDomain() } override suspend fun updateProfileImage( jwt: String, userId: Int, profileImageUrl: ProfileImageUrlWrapper, ): BaseResult { val request = userApi.updateProfileImage( jwt = jwt, userId = userId, profileImageUrl = profileImageUrl ) return request.requireSuccessfulBody( requestName = "userApi.updateProfileImage", resultVerifyBuilder = { body -> body.code in listOf(SuccessCode, NotYetVerifyCode) } ).toBaseResult() } override suspend fun changeJob( jwt: String, userId: Int, jobCode: JobWrapper, ): BaseResult { val request = userApi.changeJob( jwt = jwt, userId = userId, jobCode = jobCode ) return request.requireSuccessfulBody( requestName = "userApi.changeJob", resultVerifyBuilder = { body -> body.code in listOf(SuccessCode, NotYetVerifyCode, 2078) } ).toJobChangeResult() } override suspend fun loadMyPage( jwt: String, userId: Int, ): MyPageInformation { val request = userApi.loadMyPage( jwt = jwt, userId = userId, ) return request.requireSuccessfulBody( requestName = "userApi.loadMyPage", resultVerifyBuilder = { body -> body.code == SuccessCode } ).toDomain() } override suspend fun attendanceCheck( jwt: String, postId: Int, userId: Int, ): Boolean { val request = userApi.attendanceCheck( jwt = jwt, postId = postId, userId = userId, ) return request.requireSuccessfulBody( requestName = "userApi.attendanceCheck", resultVerifyBuilder = { body -> body.code == SuccessCode } ).isSuccessNonNull } }
0
null
0
0
f48fb298c07732a9c32afcff0bddb16f9fe2e37a
5,091
RunnerBe-Android
MIT License
0450.Delete Node in a BST.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ internal class Solution { fun deleteNode(root: TreeNode?, key: Int): TreeNode? { var root: TreeNode = root ?: return null if (root.`val` > key) { root.left = deleteNode(root.left, key) return root } if (root.`val` < key) { root.right = deleteNode(root.right, key) return root } if (root.left == null) { return root.right } if (root.right == null) { return root.left } var node: TreeNode = root.right while (node.left != null) { node = node.left } node.left = root.left root = root.right return root } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
916
kotlin-leetcode
MIT License
app/src/main/java/com/steleot/sample/ui/Constants.kt
Vivecstel
321,435,519
false
null
package com.steleot.sample.ui const val SCAN_RESULT = "scan-result" const val IS_SAVED = "is_saved"
0
Kotlin
0
2
d379c43d99c524161d57c59eddd430b8e8323e1b
101
ble-kotlin
Apache License 2.0
plot-builder-portable/src/commonMain/kotlin/jetbrains/datalore/plot/builder/defaultTheme/DefaultTooltipsTheme.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2022. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.plot.builder.defaultTheme import jetbrains.datalore.base.values.FontFace import jetbrains.datalore.plot.builder.defaultTheme.values.ThemeOption.Elem import jetbrains.datalore.plot.builder.defaultTheme.values.ThemeOption.RECT import jetbrains.datalore.plot.builder.defaultTheme.values.ThemeOption.TEXT import jetbrains.datalore.plot.builder.defaultTheme.values.ThemeOption.TOOLTIP_RECT import jetbrains.datalore.plot.builder.defaultTheme.values.ThemeOption.TOOLTIP_TEXT import jetbrains.datalore.plot.builder.defaultTheme.values.ThemeOption.TOOLTIP_TITLE_TEXT import jetbrains.datalore.plot.builder.theme.TooltipsTheme import jetbrains.datalore.vis.TextStyle internal class DefaultTooltipsTheme( options: Map<String, Any> ) : ThemeValuesAccess(options), TooltipsTheme { internal val tooltipKey = listOf(TOOLTIP_RECT, RECT) internal val textKey = listOf(TOOLTIP_TEXT, TEXT) internal val titleTextKey = listOf(TOOLTIP_TITLE_TEXT, TOOLTIP_TEXT, TEXT) override fun tooltipColor() = getColor(getElemValue(tooltipKey), Elem.COLOR) override fun tooltipFill() = getColor(getElemValue(tooltipKey), Elem.FILL) override fun tooltipStrokeWidth() = getNumber(getElemValue(tooltipKey), Elem.SIZE) override fun textStyle(): TextStyle = getTextStyle(getElemValue(textKey)) override fun titleStyle(): TextStyle { val titleStyle = getTextStyle(getElemValue(titleTextKey)) val textFontFace = getFontFace(getElemValue(textKey)) return titleStyle.copy(face = titleStyle.face + textFontFace) } override fun labelStyle(): TextStyle { return with (textStyle()) { TextStyle(family, FontFace.BOLD + face, size, color) } } }
67
Kotlin
37
771
ffa5728a09b348fae441a96aba27e5812a22c18c
1,878
lets-plot
MIT License
feature_workbrowse/src/main/java/com/andtv/flicknplay/workbrowse/data/repository/GenreRepository.kt
procoder1128
553,094,605
false
null
/* * Copyright (C) 2021 Flicknplay * * 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.andtv.flicknplay.workbrowse.data.repository import com.andtv.flicknplay.workbrowse.data.remote.datasource.GenreRemoteDataSource import com.andtv.flicknplay.workbrowse.data.remote.mapper.toDomainModel import javax.inject.Inject /** * Copyright (C) Flicknplay 20-10-2019. */ class GenreRepository @Inject constructor( private val genreRemoteDataSource: GenreRemoteDataSource ) { fun getMovieGenres() = genreRemoteDataSource.getMovieGenres() .map { it.genres?.map { genre -> genre.toDomainModel() } } fun getTvShowGenres() = genreRemoteDataSource.getTvShowGenres() .map { it.genres?.map { genre -> genre.toDomainModel() } } }
0
Kotlin
1
4
45d661d6b872c13b6a1235bbb9a44c91740d3f9d
1,330
blockchain
Apache License 2.0
app/src/main/java/io/flaterlab/kyrgyzdaamy/service/response/StreetResponse.kt
chorobaev
355,274,946
false
{"Kotlin": 168085}
package io.flaterlab.kyrgyzdaamy.service.response import com.google.gson.annotations.SerializedName data class StreetResponse( @SerializedName("cityName")val cityName: String, @SerializedName("id") val id: Int, @SerializedName("name") val name: String ){ override fun toString(): String { return name } }
0
Kotlin
0
1
a1c17e42cefdf0536f4e1b9c235e0f434b9a1e58
363
kyrgyz-daamy
MIT License
app/src/main/java/com/hakmar/employeelivetracking/features/profile/di/ProfileDataModule.kt
enginemre
584,733,724
false
null
package com.hakmar.employeelivetracking.features.profile.di import com.hakmar.employeelivetracking.common.domain.repository.DataStoreRepository import com.hakmar.employeelivetracking.features.profile.data.remote.ProfileApi import com.hakmar.employeelivetracking.features.profile.data.repository.ProfileRepositoryImpl import com.hakmar.employeelivetracking.features.profile.domain.repository.ProfileRepository import com.hakmar.employeelivetracking.util.AppConstants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object ProfileDataModule { @Provides @Singleton fun provideProfileRepository( api: ProfileApi, dataStoreRepository: DataStoreRepository ): ProfileRepository { return ProfileRepositoryImpl( api, dataStoreRepository ) } @Provides @Singleton fun provideProfileApi( client: OkHttpClient ): ProfileApi { return Retrofit.Builder() .baseUrl(AppConstants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() .create() } }
0
Kotlin
0
0
5e348e0a5aac89b4e60607a14a4ef9bbd68545a5
1,420
employee_live_tracking
The Unlicense
app/src/main/kotlin/dev/sanmer/pi/ui/theme/Shape.kt
SanmerApps
720,492,308
false
{"Kotlin": 190008, "Java": 9998, "AIDL": 2361}
package dev.sanmer.pi.ui.theme import androidx.compose.material3.Shapes val Shapes = Shapes()
0
Kotlin
2
99
2239a6bb7920b97cfa4f75ade1df2b68f634997d
95
PI
MIT License
src/test/kotlin/com/github/sukhinin/krabatron/proxy/ProxyTest.kt
sukhinin
336,881,876
false
null
package com.github.sukhinin.krabatron.proxy import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe internal class ProxyTest : ShouldSpec({ should("parse host and port") { val proxy = Proxy(Proxy.Type.HTTP, "127.0.0.1:8080") proxy.host shouldBe "127.0.0.1" proxy.port shouldBe 8080 } should("throw on invalid format") { shouldThrow<IllegalArgumentException> { Proxy(Proxy.Type.HTTP, "127.0.0.1") } shouldThrow<IllegalArgumentException> { Proxy(Proxy.Type.HTTP, "127.0.0.1:8080:8081") } shouldThrow<IllegalArgumentException> { Proxy(Proxy.Type.HTTP, "127.0.0.1:abcd") } } })
0
Kotlin
0
0
972aa714174a3cdeb724f443b7464b772cd52c5f
715
krabatron
MIT License
utils/src/main/kotlin/com/ing/zkflow/util/Collections.kt
ing-bank
550,239,957
false
{"Kotlin": 1610321, "Shell": 1609}
package com.ing.zkflow.util fun <T> List<T>.extendTo(newSize: Int, default: T): List<T> { require(size <= newSize) { "List size ($size) is larger than requested size ($newSize)." } return this + List(newSize - size) { default } } fun <T> List<T>.shrinkTo(newSize: Int): List<T> { require(newSize <= size) { "Requested size ($newSize) is larger than actual size ($size)." } return this.subList(0, newSize) }
0
Kotlin
4
9
f6e2524af124c1bdb2480f03bf907f6a44fa3c6c
461
zkflow
MIT License
spring-restdocs-dsl-processor/src/main/kotlin/com/github/jntakpe/restdocs/dsl/processor/ProcessingEnvExtensions.kt
jntakpe
163,886,345
false
null
package com.github.jntakpe.restdocs.dsl.processor import com.github.jntakpe.restdocs.dsl.processor.ApiDocumentedProcessor.Companion.KAPT_KOTLIN_GENERATED_OPTION_NAME import java.io.File import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.Element import javax.tools.Diagnostic.Kind.ERROR fun ProcessingEnvironment.generatedDir(): String { return options[KAPT_KOTLIN_GENERATED_OPTION_NAME] ?: error("Target directory for generated Dsl not found") } fun ProcessingEnvironment.makeFile() = File(generatedDir()).apply { mkdir() } fun ProcessingEnvironment.error(msg: String): Nothing { messager.printMessage(ERROR, msg) throw IllegalStateException(msg) } inline fun <reified T : Annotation> RoundEnvironment.findClassesAnnotatedBy(): Set<Element> = getElementsAnnotatedWith(T::class.java)
10
Kotlin
0
2
96c8a5d63990c7bfd7235add51fd769ccb8c19d5
889
spring-restdocs-dsl
Apache License 2.0
app/src/main/java/com/stocksexchange/android/model/PerformedCurrencyMarketActions.kt
nscoincommunity
277,168,471
true
{"Kotlin": 2814235}
package com.stocksexchange.android.model import android.os.Parcelable import com.stocksexchange.api.model.rest.CurrencyMarket import kotlinx.android.parcel.Parcelize @Parcelize data class PerformedCurrencyMarketActions( val updatedCurrencyMarketsMap: MutableMap<Int, CurrencyMarket> = mutableMapOf(), val favoriteCurrencyMarketsMap: MutableMap<Int, CurrencyMarket> = mutableMapOf(), val unfavoriteCurrencyMarketsMap: MutableMap<Int, CurrencyMarket> = mutableMapOf() ) : Parcelable { fun addUpdatedCurrencyMarket(currencyMarket: CurrencyMarket): PerformedCurrencyMarketActions { updatedCurrencyMarketsMap[currencyMarket.pairId] = currencyMarket return this } fun removeUpdatedCurrencyMarket(currencyMarket: CurrencyMarket): PerformedCurrencyMarketActions { updatedCurrencyMarketsMap.remove(currencyMarket.pairId) return this } fun removeAllUpdatedCurrencyMarkets() { updatedCurrencyMarketsMap.clear() } fun hasUpdatedCurrencyMarkets(): Boolean { return updatedCurrencyMarketsMap.isNotEmpty() } fun addFavoriteCurrencyMarket(currencyMarket: CurrencyMarket): PerformedCurrencyMarketActions { favoriteCurrencyMarketsMap[currencyMarket.pairId] = currencyMarket return this } fun removeFavoriteCurrencyMarket(currencyMarket: CurrencyMarket): PerformedCurrencyMarketActions { favoriteCurrencyMarketsMap.remove(currencyMarket.pairId) return this } fun removeAllFavoriteCurrencyMarkets() { favoriteCurrencyMarketsMap.clear() } fun hasFavoriteCurrencyMarkets(): Boolean { return favoriteCurrencyMarketsMap.isNotEmpty() } fun addUnfavoriteCurrencyMarket(currencyMarket: CurrencyMarket): PerformedCurrencyMarketActions { unfavoriteCurrencyMarketsMap[currencyMarket.pairId] = currencyMarket return this } fun removeUnfavoriteCurrencyMarket(currencyMarket: CurrencyMarket): PerformedCurrencyMarketActions { unfavoriteCurrencyMarketsMap.remove(currencyMarket.pairId) return this } fun removeAllUnfavoriteCurrencyMarkets() { unfavoriteCurrencyMarketsMap.clear() } fun hasUnfavoriteCurrencyMarkets(): Boolean { return unfavoriteCurrencyMarketsMap.isNotEmpty() } fun merge(actions: PerformedCurrencyMarketActions): PerformedCurrencyMarketActions { updatedCurrencyMarketsMap.putAll(actions.updatedCurrencyMarketsMap) favoriteCurrencyMarketsMap.putAll(actions.favoriteCurrencyMarketsMap) unfavoriteCurrencyMarketsMap.putAll(actions.unfavoriteCurrencyMarketsMap) return this } fun clear() { if(isEmpty()) { return } if(hasUpdatedCurrencyMarkets()) { removeAllUpdatedCurrencyMarkets() } if(hasFavoriteCurrencyMarkets()) { removeAllFavoriteCurrencyMarkets() } if(hasUnfavoriteCurrencyMarkets()) { removeAllUnfavoriteCurrencyMarkets() } } fun isEmpty(): Boolean { return ( !hasUpdatedCurrencyMarkets() && !hasFavoriteCurrencyMarkets() && !hasUnfavoriteCurrencyMarkets() ) } }
0
null
0
0
52766afab4f96506a2d9ed34bf3564b6de7af8c3
3,261
Android-app
MIT License
wasi-emscripten-fs/src/linuxMain/kotlin/linux/LinuxStat.kt
illarionov
769,429,996
false
{"Kotlin": 1838071}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.host.filesystem.linux import arrow.core.Either import platform.posix.EACCES import platform.posix.EBADF import platform.posix.EINVAL import platform.posix.ELOOP import platform.posix.ENAMETOOLONG import platform.posix.ENOENT import platform.posix.ENOMEM import platform.posix.ENOTDIR import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.AccessDenied import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.BadFileDescriptor import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.InvalidArgument import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.IoError import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.NameTooLong import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.NoEntry import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.NotDirectory import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.StatError import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.error.TooManySymbolicLinks import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.internal.delegatefs.FileSystemOperationHandler import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.linux.ext.toDirFd import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.op.stat.Stat import ru.pixnews.wasm.sqlite.open.helper.host.filesystem.op.stat.StructStat import ru.pixnews.wasm.sqlite.open.helper.host.platform.linux.AT_SYMLINK_NOFOLLOW internal expect fun platformFstatat( dirfd: Int, path: String, statFlags: Int, ): Either<Int, StructStat> internal object LinuxStat : FileSystemOperationHandler<Stat, StatError, StructStat> { override fun invoke(input: Stat): Either<StatError, StructStat> { return platformFstatat( input.baseDirectory.toDirFd(), input.path, input.getStatFlags(), ).mapLeft { it.errnoToStatError(input) } } private fun Stat.getStatFlags(): Int = if (this.followSymlinks) { 0 } else { AT_SYMLINK_NOFOLLOW } private fun Int.errnoToStatError(request: Stat): StatError = when (this) { EACCES -> AccessDenied("Access denied for `$request`") EBADF -> BadFileDescriptor("Bad file descriptor ${request.baseDirectory}") EINVAL -> InvalidArgument("Invalid argument in `$request`") ELOOP -> TooManySymbolicLinks("Too many symlinks while resolving `$request`") ENAMETOOLONG -> NameTooLong("Name too long while resolving `$request`") ENOENT -> NoEntry("Component of `${request.path}` does not exist") ENOMEM -> IoError("No memory") ENOTDIR -> NotDirectory("Error while resolving `${request.path}`: not a directory") else -> InvalidArgument("Error `$this`") } }
0
Kotlin
1
3
5f513e2413987ce681f12ea8e14a2aff2c56a7fd
3,042
wasm-sqlite-open-helper
Apache License 2.0
src/main/kotlin/com/github/insanusmokrassar/AutoPostSmartTimerTrigger/SmartTimerConfigTimeItem.kt
InsanusMokrassar
143,629,437
false
null
package com.github.insanusmokrassar.AutoPostSmartTimerTrigger import com.github.insanusmokrassar.AutoPostSmartTimerTrigger.utils.* import kotlinx.serialization.* import kotlinx.serialization.internal.ArrayListSerializer import org.joda.time.DateTime @Serializable class SmartTimerConfigTimeItem ( @Optional val from: String = timeFormat.print(zeroHour), @Optional val to: String = timeFormat.print(nextDayZeroHour), @Optional val period: String = timeFormat.print(3600) ) { @Transient private val fromDateTime: DateTime by lazy { timeFormat.parseDateTime(from) } @Transient private val toDateTime: DateTime by lazy { timeFormat.parseDateTime(to).let { if (fromDateTime.isAfter(it) || fromDateTime.isEqual(it)) { it.plusDays(1) } else { it } } } @Transient private val periodMillis: Long by lazy { timeFormat.withZoneUTC().parseDateTime(period).millis } @Transient val triggerTimes: List<DateTime> by lazy { (fromDateTime.millis until toDateTime.millis step periodMillis).map { DateTime(it).withDayOfYear(1) }.sorted() } override fun toString(): String { val stringBuilder = StringBuilder() stringBuilder.append("Times:\n") stringBuilder.append( triggerTimes.joinToString("\n") ) return stringBuilder.toString() } } object SmartTimerConfigTimeItemsSerializer : KSerializer<List<SmartTimerConfigTimeItem>> by ArrayListSerializer( SmartTimerConfigTimeItem.serializer() )
0
Kotlin
0
0
21c65c8f1285ed1a03a887749759ff68ad2832ba
1,638
AutoPostSmartTimerTrigger
Apache License 2.0
app/src/main/java/com/chjaeggi/boardgametracker/users/UsersFragment.kt
chjaeggi
162,888,339
false
null
package com.chjaeggi.boardgametracker.users import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.chjaeggi.boardgametracker.R import com.chjaeggi.boardgametracker.databinding.FragmentUsersBinding import org.koin.android.viewmodel.ext.android.viewModel class UsersFragment : androidx.fragment.app.Fragment() { private val viewModel by viewModel<UsersViewModel>() private lateinit var binding: FragmentUsersBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_users, container, false) binding.lifecycleOwner = this return binding.root } }
0
Kotlin
0
1
63397107c03404ad4ec9e130f5f1a38ec3a0ae15
848
boardgametracker
Apache License 2.0
app/src/main/kotlin/com/ending0421/multirepo/DemoApp.kt
ending0421
877,172,260
false
{"Kotlin": 26609}
package com.ending0421.multirepo import android.app.Application import com.ending0421.multirepo.di.appModule import com.ending0421.multirepo.di.networkModule import com.ending0421.multirepo.di.repositoryModule import com.ending0421.multirepo.di.useCaseModule import com.ending0421.multirepo.di.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class DemoApp : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@DemoApp) modules( listOf( appModule, networkModule, repositoryModule, useCaseModule, viewModelModule ) ) } } }
0
Kotlin
0
0
09cc88524dc5a60c1963dc21a3a8e67828ee4c66
816
ComposeArchitecture
Apache License 2.0
app/src/main/java/com/fanstaticapps/randomticker/ui/BaseActivity.kt
carvaq
300,246,718
false
null
package com.fanstaticapps.randomticker.ui import android.widget.Toast import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity /** * Created by carvaq * Date: 20/09/2017 * Project: RandomTicker */ abstract class BaseActivity : AppCompatActivity() { protected fun toast(@StringRes resId: Int) { Toast.makeText(this, resId, Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
1
e17cdec6f94112ab0446712f44cec38147a886b4
406
random-ticker
Apache License 2.0
z2-kotlin-plugin/src/hu/simplexion/z2/kotlin/adaptive/ir/arm2ir/ArmCallBuilder.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1615216, "CSS": 166528, "Java": 13957, "HTML": 1560, "JavaScript": 975}
package hu.simplexion.z2.kotlin.adaptive.ir.arm2ir import hu.simplexion.z2.kotlin.adaptive.FqNames import hu.simplexion.z2.kotlin.adaptive.Indices import hu.simplexion.z2.kotlin.adaptive.Strings import hu.simplexion.z2.kotlin.adaptive.ir.arm.ArmCall import hu.simplexion.z2.kotlin.adaptive.ir.arm.ArmSupportFunctionArgument import hu.simplexion.z2.kotlin.adaptive.ir.arm.ArmSupportStateVariable import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.IrBlockImpl import org.jetbrains.kotlin.ir.expressions.impl.IrBranchImpl import org.jetbrains.kotlin.ir.transformStatement import org.jetbrains.kotlin.ir.types.defaultType import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET import org.jetbrains.kotlin.ir.util.getPropertyGetter import org.jetbrains.kotlin.ir.util.statements class ArmCallBuilder( parent: ClassBoundIrBuilder, val armCall: ArmCall ) : ClassBoundIrBuilder(parent), BranchBuilder { override fun genBuildConstructorCall(buildFun: IrSimpleFunction): IrExpression = if (armCall.isDirect) { irConstructorCallFromBuild(buildFun, armCall.target) } else { irConstructorCallFromBuild( buildFun, FqNames.ADAPTIVE_ANONYMOUS, argumentCount = Indices.ADAPTIVE_ANONYMOUS_FRAGMENT_ARGUMENT_COUNT ).apply { putValueArgument(Indices.ADAPTIVE_FRAGMENT_STATE_SIZE, irConst(armCall.arguments.count())) putValueArgument(Indices.ADAPTIVE_FRAGMENT_FACTORY, irGetFragmentFactory(buildFun)) } } fun irGetFragmentFactory(buildFun: IrSimpleFunction): IrExpression { val valueParameter = (armCall.irCall.dispatchReceiver as IrGetValue).symbol.owner as IrValueParameterImpl val argumentIndex = valueParameter.index val getState = irCall( irClass.getPropertyGetter(Strings.STATE)!!, dispatchReceiver = irGet(buildFun.dispatchReceiverParameter!!) ) val getStateVariable = irCall( pluginContext.arrayGet, dispatchReceiver = getState, args = arrayOf(irConst(argumentIndex)) ) return irImplicitAs( pluginContext.adaptiveFragmentFactoryClass.defaultType, getStateVariable ) } override fun genPatchDescendantBranch(patchFun: IrSimpleFunction, closureMask: IrVariable): IrBlock { val fragmentParameter = patchFun.valueParameters.first() return IrBlockImpl(SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, pluginContext.irContext.irBuiltIns.unitType) .also { block -> armCall.arguments.forEach { block.statements += it.toPatchExpression( this, patchFun, armCall.closure, fragmentParameter, closureMask ) } } } override fun genInvokeBranches( invokeFun: IrSimpleFunction, supportFunctionIndex: IrVariable, callingFragment: IrVariable, arguments: IrVariable ): List<IrBranch> = armCall.arguments .filterIsInstance<ArmSupportFunctionArgument>() .map { genInvokeBranch(invokeFun, supportFunctionIndex, callingFragment, arguments, it) } private fun genInvokeBranch( invokeFun: IrSimpleFunction, supportFunctionIndex: IrVariable, callingFragment: IrVariable, arguments: IrVariable, armSupportFunctionArgument: ArmSupportFunctionArgument ): IrBranch = IrBranchImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, irEqual( irGet(supportFunctionIndex), irConst(armSupportFunctionArgument.supportFunctionIndex) ), genInvokeBranchBody(invokeFun, callingFragment, arguments, armSupportFunctionArgument) ) private fun genInvokeBranchBody( invokeFun: IrSimpleFunction, callingFragment: IrVariable, arguments: IrVariable, armSupportFunctionArgument: ArmSupportFunctionArgument ): IrExpression { val functionToTransform = (armSupportFunctionArgument.irExpression as IrFunctionExpression).function val originalClosure = armSupportFunctionArgument.supportFunctionClosure val transformClosure = originalClosure + functionToTransform.valueParameters.mapIndexed { indexInState, parameter -> ArmSupportStateVariable( armCall.armClass, indexInState, originalClosure.size + indexInState, parameter ) } return IrBlockImpl( functionToTransform.startOffset, functionToTransform.endOffset, functionToTransform.returnType ).apply { val transform = SupportFunctionTransform(this@ArmCallBuilder, transformClosure, callingFragment, arguments) functionToTransform.body!!.statements.forEach { statements += it.transformStatement(transform) } } } }
5
Kotlin
0
1
b883ad66b061c9a2707db94944f679e9c5929567
5,387
z2
Apache License 2.0
app/src/main/java/com/example/android/marsphotos/BindingAdapters.kt
aadarshsing
667,079,650
false
null
package com.example.android.marsphotos import android.view.View import android.widget.ImageView import androidx.core.net.toUri import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import coil.load import com.example.android.marsphotos.network.MarsPhoto import com.example.android.marsphotos.overview.MarsApiStatus import com.example.android.marsphotos.overview.MarsApiStatus.* import com.example.android.marsphotos.overview.PhotoGridAdapter @BindingAdapter("imageUrl") fun bindImage(imgView: ImageView, imgUrl: String?) { imgUrl?.let { val imgUri=imgUrl.toUri().buildUpon().scheme("https").build() imgView.load(imgUri){ placeholder(R.drawable.loading_animation) error(R.drawable.ic_broken_image) } } } @BindingAdapter("listData") fun bindRecycleView(recyclerView: RecyclerView,data: List<MarsPhoto>?){ val adapter= recyclerView.adapter as PhotoGridAdapter adapter.submitList(data) } @BindingAdapter("marsApiStatus") fun bindStatus(imageView: ImageView,status: MarsApiStatus?){ when(status){ LOADING->{ imageView.visibility=View.VISIBLE imageView.setImageResource(R.drawable.loading_animation) } ERROR->{ imageView.visibility=View.VISIBLE imageView.setImageResource(R.drawable.ic_connection_error) } DONE -> { imageView.visibility = View.GONE } else -> { imageView.visibility=View.VISIBLE imageView.setImageResource(R.drawable.loading_animation) } } }
0
Kotlin
0
0
0c7d15d7f537af0fcc4efadd941db178b502ca6e
1,616
MarsphotoApp
Apache License 2.0
databinding-observables-rx/src/test/java/io/androidalatan/databinding/observables/rx/ObservableDoubleRxAdapterTest.kt
android-alatan
464,567,867
false
null
package io.androidalatan.databinding.observables.rx import androidx.databinding.ObservableDouble import org.junit.jupiter.api.Test class ObservableDoubleRxAdapterTest { @Test fun toObservable() { val observableBoolean = ObservableDouble(1.0) val testObserver = observableBoolean .toObservable() .test() .assertValueCount(1) .assertValue(1.0) .assertNoErrors() .assertNotComplete() observableBoolean.set(2.0) testObserver.assertValueCount(2) .assertValueAt(1, 2.0) .assertNoErrors() .assertNotComplete() .dispose() } @Test fun toSingle() { ObservableDouble(1.0) .toSingle() .test() .assertValueCount(1) .assertValue(1.0) .assertNoErrors() .assertComplete() .dispose() ObservableDouble() .toSingle() .test() .assertValueCount(1) .assertValue(0.0) .assertNoErrors() .assertComplete() .dispose() } @Test fun toMaybe() { ObservableDouble(1.0) .toMaybe() .test() .assertValueCount(1) .assertValue(1.0) .assertNoErrors() .assertComplete() .dispose() ObservableDouble() .toMaybe() .test() .assertValueCount(1) .assertValue(0.0) .assertNoErrors() .assertComplete() .dispose() } @Test fun toFlowable() { val observableBoolean = ObservableDouble(1.0) val testObserver = observableBoolean .toFlowable() .test() .assertValueCount(1) .assertValue(1.0) .assertNoErrors() .assertNotComplete() observableBoolean.set(2.0) testObserver.assertValueCount(2) .assertValueAt(1, 2.0) .assertNoErrors() .assertNotComplete() .cancel() } }
0
Kotlin
1
2
4be87a61a89ff1e8010ec2b8227a1fa307bfda8d
2,143
Databinding
MIT License
kotlin-lecture/src/main/kotlin/inflearn/lec19/JumpAndLabel.kt
highright96
499,829,960
false
{"Kotlin": 114073, "Java": 941}
package inflearn.lec19 fun main() { val arr = listOf(1, 2, 3) run { arr.forEach { number -> if (number == 2) { return@run } } } arr.forEach { number -> if (number == 2) { return@forEach } } loop@ for (i in 1..100) { for (j in 1..100) { if (j == 2) { break@loop } println(j) } } }
0
Kotlin
0
2
c3cd06deba34ac5b1e60650c638af65034d6ac42
463
kotlin-sandbox
MIT License
app/src/main/java/com/example/ch8n/search/MovieSearchActivity.kt
ch8n
311,709,766
false
null
package com.example.ch8n.search import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.Toast import com.example.ch8n.search.adapter.MovieSearchAdapter import com.example.ch8n.R import com.example.ch8n.detail.MovieDetailActivity import com.example.ch8n.search.adapter.SearchListItem import dagger.android.AndroidInjection import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.activity_movie_search.* import timber.log.Timber import javax.inject.Inject class MovieSearchActivity : AppCompatActivity() { private lateinit var movieSearchAdapter : MovieSearchAdapter private val compositeDisposable : CompositeDisposable = CompositeDisposable() @Inject lateinit var viewModel: MovieSearchViewModel override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_movie_search) // val viewModel = Injector.searchViewModel(this) Timber.plant(Timber.DebugTree()) val onSearchItemClick = {position : Int -> val searchItem = movieSearchAdapter.getItemAt(position) if (searchItem != null){ startActivity(Intent(this@MovieSearchActivity, MovieDetailActivity::class.java).also { it.putExtra(MovieDetailActivity.MOVIE_ID, searchItem.movieId) }) }else{ Toast.makeText(this@MovieSearchActivity, MovieDetailActivity.MOVIE_ID_ERROR, Toast.LENGTH_SHORT).show() } } list_movie.adapter = MovieSearchAdapter.newInstance(onSearchItemClick) .also { movieSearchAdapter = it } edit_movie_query.addTextChangedListener(object : TextWatcher{ override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(editable: Editable?) { val query = editable.toString() progress.visibility = View.VISIBLE viewModel.searchMovie(query) .subscribe({ onSearchResult(it) progress.visibility = View.GONE }, { onErrorResult(it) progress.visibility = View.GONE }) .addDisposer(compositeDisposable) } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } }) image_back.setOnClickListener { finish() } } fun onSearchResult(items : List<SearchListItem>){ if (items.isEmpty()){ text_error.visibility = View.VISIBLE progress.visibility = View.GONE return } text_error.visibility = View.GONE movieSearchAdapter.submitList(items) } fun onErrorResult(error : Throwable){ Timber.e(error) text_error.visibility = View.VISIBLE } override fun onDestroy() { super.onDestroy() compositeDisposable.dispose() } } fun Disposable.addDisposer(compositeDisposable: CompositeDisposable) { compositeDisposable.add(this) }
0
Kotlin
0
0
43368c4b734973a5be740de1ada2ee9059cbf753
3,527
Mvvm-movie-list-sample
Apache License 2.0
android/app/src/main/kotlin/com/example/menu_pos/MainActivity.kt
emrbli
438,076,432
false
null
package com.example.menu_pos import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
null
0
0
9b33764a5dd955c4c9fb02a1bd0fa1b57346384d
125
menu_pos
MIT License
src/main/kotlin/com/baulsupp/okurl/services/weekdone/model/weekdone.kt
yschimke
48,341,449
false
{"Kotlin": 515385, "Shell": 843, "Smarty": 777}
package com.baulsupp.okurl.services.weekdone.model
16
Kotlin
15
126
32ad9f89d17500399ac16b735f1398ad6ca32f41
51
okurl
Apache License 2.0
app/src/main/java/dev/jahidhasanco/firebasemvvm/viewmodel/AuthViewModel.kt
JahidHasanCO
524,866,956
false
null
package dev.jahidhasanco.firebasemvvm.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dev.jahidhasanco.firebasemvvm.data.model.User import dev.jahidhasanco.firebasemvvm.repository.AuthRepository import dev.jahidhasanco.firebasemvvm.utils.Resource import dev.jahidhasanco.firebasemvvm.utils.networkState.AuthState import dev.jahidhasanco.firebasemvvm.utils.networkState.UserState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.inject.Inject @HiltViewModel class AuthViewModel @Inject constructor( private var authRepository: AuthRepository, ) : ViewModel() { private val _user = MutableStateFlow(AuthState()) val user: StateFlow<AuthState> = _user private val _userData = MutableStateFlow(UserState()) val userData: StateFlow<UserState> = _userData fun login(email: String, password: String) { authRepository.login(email, password).onEach { when (it) { is Resource.Loading -> { _user.value = AuthState(isLoading = true) } is Resource.Error -> { _user.value = AuthState(error = it.message ?: "") } is Resource.Success -> { _user.value = AuthState(data = it.data) } } }.launchIn(viewModelScope) } fun register(email: String, password: String, user: User) { authRepository.register(email, password, user).onEach { when (it) { is Resource.Loading -> { _user.value = AuthState(isLoading = true) } is Resource.Error -> { _user.value = AuthState(error = it.message ?: "") } is Resource.Success -> { _user.value = AuthState(data = it.data) } } }.launchIn(viewModelScope) } fun loggedUser() { authRepository.getLoggedUser().onEach { when (it) { is Resource.Loading -> { _user.value = AuthState(isLoading = true) } is Resource.Error -> { _user.value = AuthState(error = it.message ?: "") } is Resource.Success -> { _user.value = AuthState(data = it.data) } } }.launchIn(viewModelScope) } fun getUserData() { authRepository.getUserData().onEach { when (it) { is Resource.Loading -> { _userData.value = UserState(isLoading = true) } is Resource.Error -> { _userData.value = UserState(error = it.message ?: "") } is Resource.Success -> { _userData.value = UserState(data = it.data) } } }.launchIn(viewModelScope) } }
0
Kotlin
4
6
6dafbd735a5fd0c15654c75589a6bb984f87c0a5
3,179
Android-MVVM-Architecture-Firebase-Dagger-Hilt-Coroutines-Flow
MIT License
core/src/commonMain/kotlin/com/erolc/mrouter/backstack/entry/PageEntry.kt
ErolC
786,106,502
false
{"Kotlin": 283488, "Swift": 1008}
package com.erolc.mrouter.backstack.entry import androidx.compose.animation.core.ExperimentalTransitionApi import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.rememberTransition import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.ui.Modifier import androidx.core.bundle.Bundle import androidx.core.bundle.bundleOf import androidx.lifecycle.Lifecycle import com.erolc.mrouter.MRouter import com.erolc.mrouter.lifecycle.LifecycleOwnerDelegate import com.erolc.mrouter.lifecycle.LocalOwnersProvider import com.erolc.mrouter.lifecycle.addEventObserver import com.erolc.mrouter.model.Address import com.erolc.mrouter.platform.loge import com.erolc.mrouter.route.ExitImpl import com.erolc.mrouter.route.NormalFlag import com.erolc.mrouter.route.ResultCallBack import com.erolc.mrouter.route.RouteFlag import com.erolc.mrouter.route.RouteResult import com.erolc.mrouter.route.SysBackPressed import com.erolc.mrouter.route.router.PageRouter import com.erolc.mrouter.route.router.PanelRouter import com.erolc.mrouter.route.router.WindowRouter import com.erolc.mrouter.route.shareelement.ShareElementController import com.erolc.mrouter.route.transform.* import com.erolc.mrouter.scope.PageScope import com.erolc.mrouter.utils.PageCache import com.erolc.mrouter.utils.rememberPrivateInPage /** * 页面载体,代表一个页面。 */ class PageEntry internal constructor( val scope: PageScope, override val address: Address, internal val lifecycleOwnerDelegate: LifecycleOwnerDelegate ) : StackEntry { private val pageCache = PageCache() internal var callBack: ResultCallBack? = null private lateinit var original:Transform init { scope.initLifeCycle(lifecycleOwnerDelegate.lifecycle) scope.pageCache = pageCache scope.args.value = lifecycleOwnerDelegate.arguments ?: bundleOf() scope.callBack = ResultCallBack(lifecycleOwnerDelegate) } internal constructor(entry: PageEntry, argument: Bundle) : this( entry.scope, entry.address, LifecycleOwnerDelegate(entry.lifecycleOwnerDelegate, argument) ) { callBack = entry.callBack isUpdateTransform = entry.isUpdateTransform transform.value = entry.transform.value flag = entry.flag } val id get() = lifecycleOwnerDelegate.id //是否已冻结,冻结的entry的lifecycle是不会发生变化的 internal var isFrozen = false //transform中的prev在下一个页面打开的时候才会被赋值 internal val transform = mutableStateOf(Transform.None) //是否已更新transform,避免二次更新 private var isUpdateTransform = false //路由到当前界面的flag,需要在路由完成时(当前界面完全展示时)执行相应的操作 internal var flag: RouteFlag = NormalFlag // transform的状态 internal val transformState get() = scope.transformState //是否销毁 private val isDestroy = mutableStateOf(false) //是否需要退出 internal val isExit = mutableStateOf(false) //是否拦截 private val isIntercept get() = scope.isIntercept // 管理当前页面的路由器 private val pageRouter: PageRouter get() = scope.router.parentRouter internal fun setTransform(transform: Transform){ original = transform this.transform.value = original } @Composable override fun Content(modifier: Modifier) { scope.windowId = LocalWindowScope.current.id val saveableStateHolder = rememberSaveableStateHolder() lifecycleOwnerDelegate.LocalOwnersProvider(saveableStateHolder, scope) { SysBackPressed { scope.backPressed() } Page(modifier) DisposableEffect(this) { onDispose { scope.transformTransition = null if (isDestroy.value) { MRouter.clear(id) ShareElementController.afterShare(this@PageEntry) } } } } } private val wrapScope = TransformWrapScope() @OptIn(ExperimentalTransitionApi::class) @Composable private fun Page(modifier: Modifier) { val state = rememberPrivateInPage("page_state") { MutableTransitionState(transformState.value) } var isExit by rememberPrivateInPage("page_exit") { isExit } val isIntercept by rememberPrivateInPage("page_intercept") { isIntercept } val transition = rememberTransition(state) val newState by remember { derivedStateOf { transition.apply { if (enterStart) transformState.value = ResumeState if (exitFinished && !pageRouter.backStack.pop()) if (pageRouter.parentRouter is WindowRouter) isExit = true else pageRouter.parentRouter.backPressed() if (resume) onResume() } } } //这里必须如此 if (scope.transformTransition.toString() == "null") scope.transformTransition = newState val transform by rememberPrivateInPage("page_transform", transform) { transform } Box(newState.createModifier(transform, modifier, "Built-in")) { transform.wrap.run { setContent(address.content) val pageModifier = gestureModifier.getModifier().fillMaxSize() CompositionLocalProvider(LocalTransformWrapScope provides wrapScope) { wrapScope.progress = { transformState.value = when (it) { 0f -> { ShareElementController.reset() ResumeState } 1f -> ExitState else -> { ShareElementController.sharing(1 - it) ExitingState(1 - it) } } } wrapScope.wrap = this Wrap(pageModifier) } check(isUseContent) { "必须在Wrap方法中使用PageContent,请检查 $this 的Wrap方法" } } } state.targetState = transformState.value if (isExit && !isIntercept) { ExitImpl() isExit = false } } private fun onResume() { pageRouter.backStack.execute(flag) flag = NormalFlag isUpdateTransform = false } /** * 和上一个页面共享同一个变换过程 */ @Composable internal fun shareTransform(entry: PageEntry?) { val state by remember(transformState) { transformState } updateState(this, state) // LocalHostScope.current.panelState?.pageState?.value = state entry?.also { val transformState = when (state) { EnterState -> ResumeState ExitState -> { transform.value.wrap.releasePauseModifier() ResumeState } ResumeState -> updatePrevTransform(entry) StopState -> StopState else -> StoppingState(1 - state.progress) } if (transformState == StopState) updateState(entry, transformState) entry.transformState.value = transformState } } @Composable private fun updateState(entry: PageEntry, state: TransformState) { DisposableEffect(state) { when (state) { EnterState -> entry.updateMaxState(Lifecycle.State.STARTED) ResumeState -> entry.updateMaxState(Lifecycle.State.RESUMED) StopState -> entry.updateMaxState(Lifecycle.State.CREATED) else -> {} } onDispose {} } } /** * 更新上一个页面的transform */ private fun updatePrevTransform(prev: PageEntry): TransformState { if (prev.isUpdateTransform) return StopState transform.value = original prev.transform.value = prev.transform.value.copy(exit = transform.value.exit) prev.transform.value.wrap.updatePauseModifier(transform.value.wrap.pauseModifierPost) prev.isUpdateTransform = true return StopState } private fun updateMaxState(state: Lifecycle.State) { if (!isFrozen) lifecycleOwnerDelegate.maxLifecycle = state } internal fun create() = updateMaxState(Lifecycle.State.CREATED) override fun destroy() { isDestroy.value = true callBack?.setResult(scope.result) updateMaxState(Lifecycle.State.DESTROYED) } internal fun handleHostLifecycleEvent(event: Lifecycle.Event) { if (!isFrozen) lifecycleOwnerDelegate.handleLifecycleEvent(event) } }
0
Kotlin
0
3
6948878733c1866218ead13b6bb5b8e18dfaa0bf
8,950
MRouter
Apache License 2.0
app/src/main/java/com/alex/cooksample/ui/recipes/detail/RecipeDetailFragment.kt
oleksandr-riabykh
452,447,704
false
null
package com.alex.cooksample.ui.recipes.detail import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.alex.cooksample.R import com.alex.cooksample.databinding.FragmentRecipeDetailBinding import com.alex.cooksample.extensions.dateFormat import com.alex.cooksample.ui.models.RecipeUIModel import com.alex.cooksample.utils.DATE_SERVER_INPUT_FORMAT import com.squareup.picasso.Picasso import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class RecipeDetailFragment : Fragment() { private val detailViewModel: RecipeDetailViewModel by viewModels() private var _binding: FragmentRecipeDetailBinding? = null private val binding get() = _binding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentRecipeDetailBinding.inflate(inflater, container, false) val root: View? = binding?.root binding?.stepsRecycler?.isNestedScrollingEnabled = false setupListeners() return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loadData() } private fun setupListeners() { detailViewModel.state.observe(viewLifecycleOwner) { state -> when (state) { is RecipeDetailState.OnLoadCompleted -> updateViews(state.data) is RecipeDetailState.OnError -> Toast.makeText( requireContext(), state.error.message, Toast.LENGTH_SHORT ).show() } } detailViewModel.showLoadingIndicator.observe(viewLifecycleOwner) { showIndicator -> binding?.swipeRefreshLayout?.isRefreshing = showIndicator } binding?.swipeRefreshLayout?.setOnRefreshListener { loadData() } } private fun loadData() { arguments?.getInt(ARG_RECIPE_ID) ?.let { detailViewModel.loadRecipe(it) } } private fun updateViews(data: RecipeUIModel) { if (data.imageUrl.isNotEmpty()) { Picasso.get().load(data.imageUrl) .into(binding?.posterImageView) } else { binding?.posterImageView?.scaleType = ImageView.ScaleType.CENTER_CROP binding?.posterImageView?.setImageResource(R.drawable.ic_menu_place_holder) } binding?.titleTextView?.text = data.title binding?.ingridientsTextView?.text = data.ingredients?.joinToString( prefix = "***\n* ", postfix = "\n***", separator = "\n* " ) binding?.descriptionTextView?.text = data.story binding?.dateTextView?.text = data.publishedAt.dateFormat( DATE_SERVER_INPUT_FORMAT, getString(R.string.date_recipe_details) ) binding?.stepsRecycler?.adapter = StepsAdapter(data.steps ?: listOf()) data.user?.photo?.let { if (it.isNotEmpty()) { Picasso.get().load(it) .placeholder(R.drawable.ic_hello) .into(binding?.userAvatarImage) } } } override fun onDestroyView() { super.onDestroyView() _binding = null } companion object { const val ARG_RECIPE_ID = "recipe.id" } }
0
Kotlin
0
0
5c80926fbac618ab7929e67bce1361d07d947dfa
3,592
cookapp
MIT License
app/src/main/java/id/rllyhz/dailyus/presentation/ui/post/PostFragment.kt
rllyhz
563,114,184
false
{"Kotlin": 132812}
package id.rllyhz.dailyus.presentation.ui.post import android.Manifest import android.annotation.SuppressLint import android.app.Activity.RESULT_OK import android.content.Context.INPUT_METHOD_SERVICE import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Bundle import android.provider.Settings import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import dagger.hilt.android.AndroidEntryPoint import id.rllyhz.dailyus.R import id.rllyhz.dailyus.databinding.FragmentPostBinding import id.rllyhz.dailyus.presentation.ui.main.MainActivity import id.rllyhz.dailyus.presentation.ui.main.MainViewModel import id.rllyhz.dailyus.presentation.ui.post.CameraActivity.Companion.CAMERA_X_RESULT_CODE import id.rllyhz.dailyus.presentation.ui.post.CameraActivity.Companion.IMAGE_FILE_EXTRA import id.rllyhz.dailyus.presentation.ui.post.CameraActivity.Companion.IS_BACK_CAMERA_MODE_EXTRA import id.rllyhz.dailyus.utils.* import id.rllyhz.dailyus.vo.Resource import id.rllyhz.dailyus.vo.UIState import java.io.File @AndroidEntryPoint class PostFragment : Fragment() { private var binding: FragmentPostBinding? = null private val viewModel: MainViewModel by viewModels() private var isPhotoFromCamera = false private var photoResult: Bitmap? = null private var file: File? = null private var fusedLocationClient: FusedLocationProviderClient? = null private fun isCameraPermissionGranted() = ALL_REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( requireContext(), it ) == PackageManager.PERMISSION_GRANTED } private fun isLocationPermissionGranted() = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED private val cameraRequestPermission = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { granted -> if (!granted) { updateUI(UIState.Error, getString(R.string.upload_camera_permission_rejected_message)) } } private val launcherIntentForCameraX = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { if (it.resultCode == CAMERA_X_RESULT_CODE) { val resultFile = it.data?.getSerializableExtra(IMAGE_FILE_EXTRA) as File val isBackCamera = it.data?.getBooleanExtra(IS_BACK_CAMERA_MODE_EXTRA, true) as Boolean file = resultFile file?.let { _file -> photoResult = _file.getBitmap(isBackCamera) isPhotoFromCamera = true } binding?.run { postProgressbar.hide() postIvPreviewImage.setImageBitmap(photoResult) postIvPreviewImage.show() postBtnUpload.clickable() } } } private val launcherIntentForPickingFromGallery = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { if (it.resultCode == RESULT_OK) { val resourceUri = it.data?.data as Uri file = resourceUri.toFile(requireContext()) isPhotoFromCamera = false binding?.run { postProgressbar.hide() postIvPreviewImage.setImageURI(resourceUri) postIvPreviewImage.show() postBtnUpload.clickable() } } } private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> when { permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false -> { getLastKnownLocationOfUser() } else -> { binding?.let { it.postSwitchShareLocation.isChecked = false viewModel.lastKnownLocation = null showPostSnackBar( requireContext(), it.root, it.postBtnUpload, getString(R.string.post_location_permission_denied_message), getString(R.string.post_location_permission_denied_action_label) ) { // When user not grant permission, user need to activate the permission manually // Direct user to the application detail setting Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).also { intent -> val uri = Uri.fromParts( "package", (requireActivity() as MainActivity).packageName, null ) intent.data = uri intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } } } } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentPostBinding.inflate(inflater) return binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext()) if (!isCameraPermissionGranted()) { cameraRequestPermission.launch(ALL_REQUIRED_PERMISSIONS[0]) } viewModel.uploadStoryResponse.observe(viewLifecycleOwner) { resource -> when (resource) { is Resource.Loading -> updateUI(UIState.Loading, null) is Resource.Error -> updateUI( UIState.Error, if (viewModel.shouldHandleUploadStoryEvent()) getString(R.string.upload_failed_message) else null ) is Resource.Success -> { val shouldHandleUploadStoryEvent = viewModel.shouldHandleUploadStoryEvent() updateUI( UIState.HasData, if (shouldHandleUploadStoryEvent) getString(R.string.upload_success_message) else null, (requireActivity() as MainActivity).getBottomNav() ) // navigate back to the home if (shouldHandleUploadStoryEvent) findNavController().navigate(R.id.homeFragment) } else -> updateUI(UIState.Error) } } binding?.run { postProgressbar.hide() postBtnTakePicture.setOnClickListener { takePicture() } postBtnPickFromGallery.setOnClickListener { pickPhotoFromGallery() } postSwitchShareLocation.isChecked = viewModel.lastKnownLocation != null postSwitchShareLocation.setOnCheckedChangeListener { _, isChecked -> if (isChecked && viewModel.lastKnownLocation == null) getLastKnownLocationOfUser() else viewModel.lastKnownLocation = null } postBtnUpload.setOnClickListener { postEtDescription.clearFocus() (requireActivity().getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).also { it.hideSoftInputFromWindow(view.windowToken, 0) } val description = postEtDescription.text.toString() if ((isPhotoFromCamera && photoResult == null) || file == null) { showPostSnackBar( requireContext(), root, postBtnUpload, getString(R.string.photo_empty_message) ) } else if (description.isEmpty()) { showPostSnackBar( requireContext(), root, postBtnUpload, getString(R.string.description_empty_message) ) } else { uploadNewStory(description) } } updateUI(UIState.HasData) } } private fun uploadNewStory(description: String) = file?.let { viewModel.getToken().observe(viewLifecycleOwner) { token -> if (token.isNotBlank() && token.isNotEmpty()) viewModel.uploadStory(token, it, it.name, description) { size -> updateUI( UIState.Error, getString(R.string.upload_image_size_too_large_message) + " ($size mb)" ) } } } private fun pickPhotoFromGallery() { val intent = Intent().apply { type = "image/*" action = Intent.ACTION_GET_CONTENT } val chooser = Intent.createChooser(intent, getString(R.string.title_pick_from_gallery)) launcherIntentForPickingFromGallery.launch(chooser) } private fun takePicture() { if (!isCameraPermissionGranted()) { cameraRequestPermission.launch(ALL_REQUIRED_PERMISSIONS[0]) return } Intent(requireActivity(), CameraActivity::class.java).also { launcherIntentForCameraX.launch(it) } } private fun updateUI( uiState: UIState, messageToShow: String? = null, anchorView: View? = null ) { binding?.run { when (uiState) { UIState.Loading -> { postBtnUpload.notClickable() postProgressbar.show() postBtnTakePicture.notClickable() postBtnPickFromGallery.notClickable() postBtnUpload.text = "" } UIState.Error -> { postBtnUpload.clickable() postProgressbar.hide() postBtnTakePicture.clickable() postBtnPickFromGallery.clickable() postBtnUpload.text = getString(R.string.button_upload) } UIState.HasData -> { postBtnUpload.clickable() postProgressbar.hide() postBtnTakePicture.clickable() postBtnPickFromGallery.clickable() postEtDescription.text.clear() postIvPreviewImage.setImageResource(0) postIvPreviewImage.background = ColorDrawable( ContextCompat.getColor(requireContext(), R.color.my_grey_200) ) photoResult = null file = null postBtnUpload.text = getString(R.string.button_upload) } } messageToShow?.let { showPostSnackBar( requireContext(), root, anchorView ?: postBtnUpload, it ) postBtnUpload.clickable() } } } @SuppressLint("MissingPermission") private fun getLastKnownLocationOfUser() { if (isLocationPermissionGranted()) { // Location permission granted fusedLocationClient?.let { locationClient -> locationClient.lastLocation.addOnSuccessListener { location -> if (location != null) viewModel.lastKnownLocation = location else binding?.run { showPostSnackBar( requireContext(), root, postBtnUpload, getString(R.string.post_activate_location_message) ) postSwitchShareLocation.isChecked = false viewModel.lastKnownLocation = null } } } } else { // Location permission denied requestPermissionLauncher.launch( arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION ) ) } } override fun onDestroyView() { super.onDestroyView() binding = null photoResult = null file = null fusedLocationClient = null } companion object { val ALL_REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA) } }
0
Kotlin
0
0
29510cf4ae67e83ca2e57825f3d70fb5a3798f70
13,478
DailyUs
MIT License
app/src/main/java/com/example/wellcome/MainActivity.kt
WellcomeSolution
407,485,016
false
{"Kotlin": 189938, "Java": 72597}
package com.example.wellcome import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.google.android.material.bottomsheet.BottomSheetBehavior import androidx.fragment.app.Fragment import android.content.Intent import android.util.Log import android.view.Window import androidx.activity.viewModels import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.ViewModelProvider import com.example.wellcome.data.* import com.example.wellcome.utils.CitiesHelper import com.example.wellcome.utils.City import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback import kotlinx.android.synthetic.main.fragment_trip.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sharedTripViewModel: SharedTripViewModel by viewModels() val userViewModel: UserViewModel by viewModels() val createTripViewModel: CreateTripViewModel by viewModels() val favoritesHostViewModel: FavoritesHostViewModel by viewModels() setContentView(R.layout.activity_main) } }
0
Kotlin
0
3
6e01f6922c3c8ce86df15286f94ced6ea8b5e185
1,383
Wellcome
MIT License
nfclib/src/main/java/com/zhengsr/nfclib/NfcType.kt
LillteZheng
287,002,688
false
null
package com.zhengsr.nfclib /** * @author by zhengshaorui 2020/8/27 11:35 * describe: */ enum class NfcType { EDEF, UNKOWN }
0
Kotlin
0
3
a3e1e6afc6346c5855d3028ceeda13a43d2d5170
135
NfcDemo
Apache License 2.0
packages/expo-dev-menu-interface/android/src/main/java/expo/interfaces/devmenu/DevMenuDelegateInterface.kt
expo
65,750,241
false
{"Gemfile.lock": 1, "YAML": 79, "Git Config": 1, "JSON with Comments": 175, "Ignore List": 236, "JSON": 713, "Markdown": 291, "JavaScript": 1979, "Text": 62, "Git Attributes": 7, "Shell": 66, "Ruby": 99, "TSX": 976, "Gradle": 106, "Java Properties": 5, "Batchfile": 4, "INI": 8, "Proguard": 10, "XML": 273, "Kotlin": 1210, "Dotenv": 7, "OpenStep Property List": 30, "Objective-C": 586, "Objective-C++": 49, "Jest Snapshot": 52, "CODEOWNERS": 1, "SVG": 57, "Java": 282, "Swift": 733, "CMake": 5, "C++": 109, "C": 7, "Gradle Kotlin DSL": 3, "JSON5": 1, "HTML": 5, "MATLAB": 1, "Checksums": 6, "Diff": 46, "MDX": 748, "robots.txt": 1, "CSS": 4, "Cloud Firestore Security Rules": 1, "GraphQL": 17, "TOML": 1}
package expo.interfaces.devmenu import android.os.Bundle interface DevMenuDelegateInterface { /** * Returns a `Bundle` with the most important information about the current app. */ fun appInfo(): Bundle? /** * Returns a [ReactHostWrapper] ot the currently shown app. It is a context of what the dev menu displays. */ fun reactHost(): ReactHostWrapper fun supportsDevelopment(): Boolean { return true } }
668
TypeScript
5226
32,824
e62f80228dece98d5afaa4f5c5e4fb195f3daa15
436
expo
Apache License 2.0
src/main/kotlin/com/frontleaves/greenchaincarbonledger/config/startup/StartupConfiguration.kt
carbon-ledger
766,586,691
false
{"JSON": 3, "Maven POM": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "INI": 1, "Kotlin": 50, "YAML": 24, "HTML": 6, "Java": 132, "XML": 1}
package com.frontleaves.greenchaincarbonledger.config.startup import com.frontleaves.greenchaincarbonledger.annotations.KotlinSlf4j.Companion.log import org.springframework.boot.CommandLineRunner import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.annotation.Order import org.springframework.jdbc.core.JdbcTemplate import java.io.File @Configuration open class StartupConfiguration( jdbcTemplate: JdbcTemplate, ) { private val prepareData = PrepareData(jdbcTemplate) @Bean @Order(1) open fun startUpPreparation(): CommandLineRunner { return CommandLineRunner { log.info("============================================================") log.info("[Preparation] 系统进行准备检查") } } @Bean @Order(2) open fun sqlDataPreparation(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] SQL数据进行准备检查") log.debug("\t> 检查角色数据库是否完整") // 检查角色数据库是否完整 val getRoleList = prepareData.sqlGetRoleList() prepareData.prepareUploadSqlWithRole(getRoleList) log.debug("\t> 检查权限数据库是否完整") // 检查权限数据库是否完整 val getPermissionList = prepareData.sqlGetPermissionList() prepareData.prepareUploadSqlWithPermission(getPermissionList) } } @Bean @Order(3) open fun checkRoleHasPermission(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] 检查角色是否拥有权限") val getRoleList = prepareData.sqlGetRoleList() prepareData.prepareCheckRoleHasPermission(getRoleList) } } @Bean @Order(4) open fun checkDefaultUser(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] 检查默认超级管理用户是否存在") prepareData.prepareCheckDefaultUser() } } @Bean @Order(5) open fun checkFolderExist(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] 检查文件夹是否存在") if (!File("upload").exists()) { log.debug("\t> 创建文件夹: upload") File("upload").mkdirs() } // 分别检查文件夹内部内容是否存在 if (!File("upload/license").exists()) { log.debug("\t> 创建文件夹: upload/license") File("upload/license").mkdirs() } if (!File("upload/legal_id_card").exists()) { log.debug("\t> 创建文件夹: upload/legal_id_card") File("upload/legal_id_card").mkdirs() } if (!File("upload/avatar").exists()) { log.debug("\t> 创建文件夹: upload/avatar") File("upload/avatar").mkdirs() } if (!File("upload/files").exists()) { log.debug("\t> 创建文件夹: upload/files") File("upload/files").mkdirs() } if (!File("workLoad").exists()) { log.debug("\t> 创建文件夹: workLoad") File("workLoad").mkdirs() } } } @Bean @Order(6) open fun checkCarbonAccountingRelatedData(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] 检查碳核算相关数据表信息是否完整") // 准备碳排放类型表 prepareData.sqlCarbonItemType() // 准备过程因子 prepareData.sqlProcessFactor() // 准备其他因子 prepareData.sqlOtherFactor() prepareData.sqlDesulfurizationFactor() } } @Bean @Order(7) open fun checkCarbonTypeData(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] 检查碳排放采用生产类型是否完整") // 准备碳排放类型数据 prepareData.sqlCarbonType() } } @Bean @Order(1000) open fun endPreparation(): CommandLineRunner { return CommandLineRunner { log.info("[Preparation] 系统准备完成") log.info("============================================================") } } }
0
Java
0
0
e150719a39a181c0d641b11e2e35d0e78c6ad075
4,105
GreenChainCarbonLedger
MIT License
md-mathjax/src/desktopMain/kotlin/com/wakaztahir/markdowncompose/mathjax/MathJax.kt
Qawaz
485,501,273
false
null
package com.wakaztahir.markdowncompose.mathjax import androidx.compose.foundation.Image import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.toComposeImageBitmap import org.scilab.forge.jlatexmath.TeXConstants import org.scilab.forge.jlatexmath.TeXFormula import org.scilab.forge.jlatexmath.TeXIcon import java.awt.AlphaComposite import java.awt.Color import java.awt.Graphics2D import java.awt.image.BufferedImage import javax.swing.Icon @Composable actual fun MathJax(modifier: Modifier, latex: String, color: androidx.compose.ui.graphics.Color) { var latexImage by remember { mutableStateOf<ImageBitmap?>(null) } LaunchedEffect(latex, color) { kotlin.runCatching { val tf = TeXFormula(latex) tf.setColor(color.toAwtColor()) val ti: TeXIcon = tf.createTeXIcon(TeXConstants.STYLE_DISPLAY, 48F) latexImage = createBitmap(ti).toComposeImageBitmap() }.onFailure { it.printStackTrace() } } latexImage?.let { Image( modifier = Modifier.fillMaxWidth(), bitmap = it, contentDescription = null ) } } fun createBitmap(icon: Icon): BufferedImage { val bi = BufferedImage(icon.iconWidth, icon.iconHeight, BufferedImage.TYPE_4BYTE_ABGR) val g: Graphics2D = bi.createGraphics() g.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER) icon.paintIcon(null, g, 0, 0) g.dispose() return bi } internal fun androidx.compose.ui.graphics.Color.toAwtColor(): Color { return Color(this.red, this.green, this.blue) }
0
Kotlin
0
0
5293904088ab9ace4d4b1e7e7788437cadd513d6
1,750
markdown-compose
MIT License
src/commonMain/kotlin/com/dxc/ssi/agent/didcomm/model/issue/data/CredentialOffer.kt
dxc-technology
259,322,339
false
{"Kotlin": 598967, "Objective-C": 537589, "Objective-C++": 442889, "C": 238203, "Ruby": 12614, "Shell": 7187, "Swift": 1114}
package com.dxc.ssi.agent.didcomm.model.issue.data import kotlinx.serialization.Serializable //Marker interface interface CredentialOffer
3
Kotlin
6
5
9bede83e0358b16d6dc9459ccc2fd85541027b6c
139
ssi-mobile-sdk
Apache License 2.0
compiler/src/main/java/cn/jailedbird/arouter/ksp/compiler/InterceptorSymbolProcessorProvider.kt
JailedBird
611,236,215
false
{"Kotlin": 62632, "Java": 10223}
package cn.jailedbird.arouter.ksp.compiler import cn.jailedbird.arouter.ksp.compiler.utils.* import cn.jailedbird.arouter.ksp.compiler.utils.findAnnotationWithType import cn.jailedbird.arouter.ksp.compiler.utils.findModuleName import com.alibaba.android.arouter.facade.annotation.Interceptor import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFile import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.ksp.KotlinPoetKspPreview import com.squareup.kotlinpoet.ksp.toClassName import com.squareup.kotlinpoet.ksp.writeTo import java.util.* @KotlinPoetKspPreview class InterceptorSymbolProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return InterceptorSymbolProcessor( KSPLoggerWrapper(environment.logger), environment.codeGenerator, environment.options ) } class InterceptorSymbolProcessor( private val logger: KSPLoggerWrapper, private val codeGenerator: CodeGenerator, options: Map<String, String> ) : SymbolProcessor { @Suppress("SpellCheckingInspection") companion object { val INTERCEPTOR_CLASS_NAME = Interceptor::class.qualifiedName!! private val IINTERCEPTOR_GROUP_CLASSNAME = Consts.IINTERCEPTOR_GROUP.quantifyNameToClassName() } private val moduleName = options.findModuleName(logger) override fun process(resolver: Resolver): List<KSAnnotated> { val symbol = resolver.getSymbolsWithAnnotation(INTERCEPTOR_CLASS_NAME) val elements = symbol .filterIsInstance<KSClassDeclaration>() .toList() if (elements.isNotEmpty()) { logger.info(">>> InterceptorSymbolProcessor init. <<<") try { parseInterceptor(elements) } catch (e: Exception) { logger.exception(e) } } return emptyList() } private fun parseInterceptor(elements: List<KSClassDeclaration>) { logger.info(">>> Found interceptors, size is " + elements.size + " <<<") val interceptors: TreeMap<Int, KSClassDeclaration> = TreeMap() for (element in elements) { if (verify(element)) { // Check the interceptor meta logger.info("A interceptor verify over, its ${element.qualifiedName?.asString()}") val interceptor = element.findAnnotationWithType<Interceptor>()!! // Avoid has same priority @Interceptor interceptors[interceptor.priority]?.let { throw IllegalArgumentException( String.format( Locale.getDefault(), "More than one interceptors use same priority [%d], They are [%s] and [%s].", interceptor.priority, it.simpleName.asString(), element.simpleName.asString() ) ) } interceptors[interceptor.priority] = element } else { logger.error("A interceptor verify failed, its " + element.qualifiedName?.asString()) } } generateInterceptorFile(interceptors) } private fun generateInterceptorFile(interceptors: TreeMap<Int, KSClassDeclaration>) { val parameterName = "interceptor" /** interceptor: MutableMap<Int, Class<out IInterceptor>>? */ val parameterSpec = ParameterSpec.builder( parameterName, MUTABLE_MAP.parameterizedBy( INT, Class::class.asClassName().parameterizedBy( WildcardTypeName.producerOf( Consts.IINTERCEPTOR.quantifyNameToClassName() ) ) ).copy(nullable = true) ).build() /** override fun loadInto(providers: MutableMap<String, RouteMeta>?) */ val loadInfoFunSpecBuilder: FunSpec.Builder = FunSpec .builder(Consts.METHOD_LOAD_INTO) .addModifiers(KModifier.OVERRIDE) .addParameter(parameterSpec) /** if (interceptor == null) { return } **/ loadInfoFunSpecBuilder.addStatement("if($parameterName == null) { return }") val dependencies = mutableSetOf<KSFile>() for (entry in interceptors) { val priority: Int = entry.key val interceptor: KSClassDeclaration = entry.value interceptor.containingFile?.let { dependencies.add(it) } /** interceptor.put(priority, XxxInterceptor::class.java) */ loadInfoFunSpecBuilder.addStatement( "$parameterName.put(%L, %T::class.java)", priority, interceptor.toClassName() ) } val interceptorClassName = Consts.NAME_OF_INTERCEPTOR + Consts.SEPARATOR + moduleName val file = FileSpec.builder(Consts.PACKAGE_OF_GENERATE_FILE, interceptorClassName) .addType( TypeSpec.classBuilder( ClassName(Consts.PACKAGE_OF_GENERATE_FILE, interceptorClassName) ) .addKdoc(Consts.WARNING_TIPS) .addSuperinterface(IINTERCEPTOR_GROUP_CLASSNAME) .addFunction(loadInfoFunSpecBuilder.build()) .build() ) .build() file.writeTo(codeGenerator, true, dependencies) logger.info(">>> Interceptor group write over. <<<") } private fun verify(element: KSClassDeclaration): Boolean { // It must be implement the interface IInterceptor and marked with annotation Interceptor. return element.findAnnotationWithType<Interceptor>() != null && element.isSubclassOf(Consts.IINTERCEPTOR) } } }
0
Kotlin
6
50
900ac09731c0326f6a0d5cebdc43844462ca9ef8
6,606
ArouterKspCompiler
Apache License 2.0
src/main/kotlin/kuery/operators/LogicalOperators.kt
hofiisek
416,094,974
false
{"Kotlin": 21891}
package kuery.operators import kuery.ParameterizedSqlizable import kuery.functions.Condition import kuery.functions.MultiParamCondition import kuery.functions.NoParamCondition import kuery.functions.SingleParamCondition sealed class LogicalOperator : ParameterizedSqlizable() { abstract val parent: LogicalOperator? protected val conditions: MutableList<LogicalOperator> = mutableListOf() fun and(block: AndOperator.() -> Unit) = AndOperator(parent = this).apply(block).also { conditions.add(it) params.addAll(it.params) } fun or(block: OrOperator.() -> Unit) = OrOperator(parent = this).apply(block).also { conditions.add(it) params.addAll(it.params) } fun xor(block: XorOperator.() -> Unit) = XorOperator(parent = this).apply(block).also { conditions.add(it) params.addAll(it.params) } fun not(operator: OperatorType = OperatorType.AND, block: LogicalOperator.() -> Unit) = NotOperator(parent = this) .apply { when (operator) { OperatorType.AND -> and(block) OperatorType.OR -> or(block) OperatorType.XOR -> xor(block) OperatorType.NOT -> throw IllegalArgumentException("NOT operator not supported as root operator") } }.also { conditions.add(it) params.addAll(it.params) } operator fun Condition.unaryPlus() { conditions.add(SimpleOperator(this)) when (this) { is SingleParamCondition -> params.add(param) is MultiParamCondition -> this@LogicalOperator.params.addAll(params) is NoParamCondition -> Unit } } override fun toSqlOneliner(): String { val separator = when (this) { is AndOperator -> " AND " is OrOperator -> " OR " is XorOperator -> " XOR " is SimpleOperator, is NotOperator -> throw IllegalArgumentException( "Own implementation must be provided for SimpleOperator and NotOperator" ) } return conditions.joinToString( separator = separator, prefix = "(".takeIf { parent != null }.orEmpty(), postfix = ")".takeIf { parent != null }.orEmpty() ) { it.toSqlOneliner() } } } data class SimpleOperator(private val condition: Condition) : LogicalOperator() { override val parent: LogicalOperator? = null override fun toSqlOneliner() = condition.condition } data class AndOperator(override val parent: LogicalOperator? = null) : LogicalOperator() data class OrOperator(override val parent: LogicalOperator? = null) : LogicalOperator() data class XorOperator(override val parent: LogicalOperator? = null) : LogicalOperator() data class NotOperator(override val parent: LogicalOperator? = null) : LogicalOperator() { override fun toSqlOneliner() = if (conditions.size == 1) conditions.joinToString(separator = " AND ", prefix = "NOT ") { it.toSqlOneliner() } else conditions.joinToString(separator = " AND ", prefix = "NOT (", postfix = ")") { it.toSqlOneliner() } } enum class OperatorType { AND, OR, XOR, NOT }
0
Kotlin
0
0
bce795f2b51db59c4b35221852259abfa27486e3
3,208
KueryDSL
MIT License
app/src/main/java/br/com/chicorialabs/passhash/ui/main/MainFragment.kt
chicorasia
385,574,545
false
null
package br.com.chicorialabs.passhash.ui.main import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import br.com.chicorialabs.passhash.databinding.AddPasswordDialogBinding import br.com.chicorialabs.passhash.databinding.MainFragmentBinding import br.com.chicorialabs.passhash.extension.asString import org.koin.androidx.viewmodel.ext.android.viewModel class MainFragment : Fragment() { private val mMainViewModel: MainViewModel by viewModel() private var _binding: MainFragmentBinding? = null private val binding get() = _binding!! companion object { fun newInstance() = MainFragment() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = MainFragmentBinding.inflate(inflater, container, false) val root: View = binding.root initPasswordList() initAlgorithmBtns() return root } private fun initAlgorithmBtns() { binding.md5btn.setOnClickListener { mMainViewModel.setMd5() } binding.sha1btn.setOnClickListener { mMainViewModel.setSha1() } binding.sha256btn.setOnClickListener { mMainViewModel.setSha256() } } private fun initPasswordList() { mMainViewModel.passwordDtoList.observe(viewLifecycleOwner) { binding.passwordListTv.text = it.asString() } // TODO 008: Inicializar os buttons de algoritmo } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initFab() } private fun initFab() { binding.floatingActionButton.setOnClickListener { createSaveNewPasswordDialog() } } private fun createSaveNewPasswordDialog() { val dialogBinding = AddPasswordDialogBinding.inflate(layoutInflater) AlertDialog.Builder(activity) .setView(dialogBinding.root) .setCancelable(true) .setTitle("Add new password") .setNegativeButton("Cancel", null) .setPositiveButton("OK", DialogInterface.OnClickListener { _, _ -> mMainViewModel.save(dialogBinding.addDialogEdt.text.toString()) }) .create() .show() } }
0
Kotlin
0
1
f7e8b05f01dc98d245c531b3cdf3c05fa56d04b4
2,534
passhash
MIT License
server/src/main/kotlin/io/provenance/invoice/calculator/InvoiceCalculator.kt
hyperschwartz
446,950,410
false
{"Kotlin": 270514, "Shell": 2246, "Dockerfile": 263}
package io.provenance.invoice.calculator import io.provenance.invoice.domain.dto.InvoiceDto import io.provenance.invoice.domain.dto.PaymentDto import io.provenance.invoice.util.enums.InvoiceStatus import io.provenance.invoice.util.enums.PaymentStatus import io.provenance.invoice.util.extension.daysBetweenI import io.provenance.invoice.util.extension.elvisI import io.provenance.invoice.util.extension.isBeforeInclusiveI import io.provenance.invoice.util.extension.toLocalDateI import mu.KLogging import java.math.BigDecimal import java.time.LocalDate import java.time.OffsetDateTime /** * Simple tool that calculates various totals owed on an invoice based on payments made and the calculation time. */ class InvoiceCalculator( val calcTime: OffsetDateTime, val invoiceDto: InvoiceDto, val payments: List<PaymentDto> ) { private companion object : KLogging() val calc: InvoiceCalc by lazy { genCalc() } private val dueDate: LocalDate = invoiceDto.invoice.invoiceDueDate.toLocalDateI() private fun genCalc(): InvoiceCalc { val applicablePayments = payments.filter { it.effectiveTime.isBeforeInclusiveI(calcTime) }.sortedBy { it.effectiveTime } var payoffTime: OffsetDateTime? = null var currentOwed = invoiceDto.totalOwed val paymentCalcs = applicablePayments.map { paymentDto -> genPaymentCalc(currentOwed = currentOwed, payment = paymentDto).also { calc -> currentOwed = calc.owedAfterPayment if (currentOwed <= BigDecimal.ZERO) { // Only set payoff time if it hasn't yet been set. Payments after payoff should not affect this time payoffTime = payoffTime ?: paymentDto.effectiveTime if (currentOwed < BigDecimal.ZERO) { logger.error("Payment [${paymentDto.uuid}] overpaid the invoice down to [${calc.owedAfterPayment}]") } } } } return InvoiceCalc( uuid = invoiceDto.uuid, calcTime = calcTime, invoiceStatus = invoiceDto.status, paymentStatus = calcPaymentStatus(payoffTime, currentOwed), ownerAddress = invoiceDto.invoice.fromAddress, payerAddress = invoiceDto.invoice.toAddress, createdDate = invoiceDto.invoice.invoiceCreatedDate.toLocalDateI(), dueDate = invoiceDto.invoice.invoiceDueDate.toLocalDateI(), description = invoiceDto.invoice.description, lineItems = invoiceDto.invoice.lineItemsList.map(LineItemCalc::fromProto), payments = paymentCalcs, paymentSum = paymentCalcs.sumOf { it.paymentAmount }, paymentDenom = invoiceDto.invoice.paymentDenom, originalOwed = invoiceDto.totalOwed, remainingOwed = currentOwed, // Only calculate delinquency up to the payoff time - never continue incrementing if the invoice is paid paymentDelinquentDays = dueDate.daysBetweenI(payoffTime.elvisI { calcTime }.toLocalDate()).coerceAtLeast(0), payoffTime = payoffTime, ) } private fun genPaymentCalc(currentOwed: BigDecimal, payment: PaymentDto): PaymentCalc = PaymentCalc( uuid = payment.uuid, invoiceUuid = payment.invoiceUuid, effectiveTime = payment.effectiveTime, paymentAmount = payment.paymentAmount, paymentDenom = invoiceDto.invoice.paymentDenom, fromAddress = payment.fromAddress, owedBeforePayment = currentOwed, owedAfterPayment = currentOwed - payment.paymentAmount, ) private fun calcPaymentStatus( payoffTime: OffsetDateTime?, currentOwed: BigDecimal ): PaymentStatus { // Payments should not be allowed when the invoice has not yet been approved by the oracle if (invoiceDto.status != InvoiceStatus.APPROVED) { return PaymentStatus.RESTRICTED } // If the invoice still has an amount owed, it should return some form of repayment status if (currentOwed > BigDecimal.ZERO) { return if (calcTime.toLocalDate().isBeforeInclusiveI(dueDate)) { PaymentStatus.REPAY_PERIOD } else { PaymentStatus.DELINQUENT } } // Otherwise, the invoice has been paid off and it's based on the payoff time value return if (payoffTime?.toLocalDate()?.isBeforeInclusiveI(dueDate) == true) { PaymentStatus.PAID_ON_TIME } else { PaymentStatus.PAID_LATE } } }
0
Kotlin
0
0
d69c623e3c0ae51a2bbb2dde73bcdc860a0b2a39
4,618
service-invoice
Apache License 2.0
ksdtoolkit-core/src/main/kotlin/hr.unipu.ksdtoolkit/models/ModelInheritedCompoundInterest.kt
unipu-ict
327,935,092
false
null
package hr.unipu.ksdtoolkit.models import hr.unipu.ksdtoolkit.integration.RungeKuttaIntegration /** * Inheritance of Simple Compound Interest Model. * * @author [<NAME>](mailto:<EMAIL>) */ class ModelInheritedCompoundInterest : ModelSimpleCompoundInterest() { // Static properties: companion object { const val INTEREST_RATE_KEY = "INTEREST_RATE" const val INITIAL_CAPITAL_KEY = "INITIAL_CAPITAL" const val INTEREST_KEY = "interest" const val CAPITAL_KEY = "Capital" const val INTEREST_RATE_VALUE = -0.1 / 12 const val INITIAL_CAPITAL_VALUE = 200.0 const val INITIAL_TIME_VALUE = 0.0 const val FINAL_TIME_VALUE = 240.0 const val TIME_STEP_VALUE = 0.25 } // 1. Create the model (with the parameters) val modelInherited = this // inheritance: ModelSimpleCompoundInterest() //val modelInherited = object : ModelSimpleCompoundInterest() {} init { // overriding default model properties: modelInherited.initialTime = INITIAL_TIME_VALUE modelInherited.finalTime = FINAL_TIME_VALUE modelInherited.timeStep = TIME_STEP_VALUE modelInherited.integrationType = RungeKuttaIntegration() modelInherited.name = "Inherited Compound Interest Model" // changing inherited model constants modelInherited.entities[INITIAL_CAPITAL_KEY]?.equation = { INITIAL_CAPITAL_VALUE } modelInherited.entities[INTEREST_RATE_KEY]?.equation = { INTEREST_RATE_VALUE } modelInherited.INITIAL_CAPITAL.equation = { 200.0 } modelInherited.INTEREST_RATE.equation = { -0.1 / 12 } } val ModuleSimpleCompound1 = modelInherited.createModule( "ModuleSimpleCompound1", "hr.unipu.ksdtoolkit.models.ModelSimpleCompoundInterest" ) as ModelSimpleCompoundInterest val ModuleSimpleCompound2 = object : ModelSimpleCompoundInterest() {} init { modelInherited.modules["ModuleSimpleCompound1"]?.entities!!["INITIAl_CAPITAL"]?.equation = { 1000.0 } modelInherited.ModuleSimpleCompound1.INITIAL_CAPITAL.equation = { 1000.0 } modelInherited.ModuleSimpleCompound2.INITIAL_CAPITAL.equation = { 1000.0 } } val some_converter_in_parent = modelInherited.converter("some_converter_in_parent") init { some_converter_in_parent.equation = { modelInherited.ModuleSimpleCompound1.INITIAL_CAPITAL } } }
0
Kotlin
0
2
add686d7d83c918b917df70b787b164970dec272
2,429
ksdtoolkit
Apache License 2.0
rxhive-core/src/main/kotlin/com/sksamuel/rxhive/evolution/StrictSchemaEvolver.kt
sksamuel
13,625,531
false
null
package com.sksamuel.rxhive.evolution import com.sksamuel.rxhive.DatabaseName import com.sksamuel.rxhive.Struct import com.sksamuel.rxhive.StructType import com.sksamuel.rxhive.TableName import org.apache.hadoop.hive.metastore.IMetaStoreClient /** * An implementation of [SchemaEvolver] that requires the schema in the incoming * struct to be equal to the schema in the hive metastore. * * Equality is defined as the same number of fields, with the same names and * same types. Order is not important. * * Any missing fields or extra fields will throw an exception. * * This is a good choice if you must ensure that incoming data matches * the metastore schema exactly. * * This implementation will never make any changes to the metastore. */ object StrictSchemaEvolver : SchemaEvolver { override fun evolve(dbName: DatabaseName, tableName: TableName, metastoreSchema: StructType, struct: Struct, client: IMetaStoreClient): StructType { val a = metastoreSchema.fields.map { it.name to it.type }.toSet() val b = struct.schema.fields.map { it.name to it.type }.toSet() if (a != b) { throw RuntimeException("Metastore schema and struct schema are not equal $a != $b") } return metastoreSchema } }
0
Kotlin
46
318
a604ef62ae6bcbd148594b51ed52c4cee910c099
1,330
akka-patterns
Apache License 2.0
app/src/main/java/mr/lalic/playground/MainActivity.kt
lalicmarko
342,654,472
false
null
package mr.lalic.playground import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import mr.lalic.playground.ui.theme.PlaygroundTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PlaygroundTheme { // A surface container using the 'background' color from the theme Surface(color = MaterialTheme.colors.background) { Row { Column() { Greeting(name = "Playground") } Column() { Greeting(name = "Test") } } } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } @Preview(showBackground = true) @Composable fun DefaultPreview() { PlaygroundTheme { Greeting("Android") } }
1
Kotlin
0
0
71d7db8486c21be278759f14df1fe73d1b8ede5d
1,389
playground
Apache License 2.0
feature/edit-note/api/src/main/java/ru/maksonic/beresta/feature/edit_note/api/EditNoteApi.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta.feature.edit_note.api import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier /** * @Author maksonic on 23.02.2023 */ interface EditNoteApi { interface Ui { @Composable fun Widget(isNotesScrollUp: () -> Boolean, modifier: Modifier) } }
0
Kotlin
0
0
5704d413cd57a8eabe27b02a185a999fce2ca1e4
315
Beresta
MIT License
src/main/kotlin/com/github/rushyverse/api/entity/PlayerNPCEntity.kt
Rushyverse
578,345,187
false
null
package com.github.rushyverse.api.entity import com.github.rushyverse.api.position.IAreaLocatable import net.kyori.adventure.text.Component import net.minestom.server.entity.EntityType import net.minestom.server.entity.GameMode import net.minestom.server.entity.Player import net.minestom.server.network.packet.server.play.PlayerInfoPacket import net.minestom.server.network.packet.server.play.PlayerInfoPacket.AddPlayer import net.minestom.server.network.packet.server.play.PlayerInfoPacket.RemovePlayer import java.util.* /** * A non-player character that looks like a player. * @property name Name of the NPC. * @property properties Properties of the NPC. * @property playerRemovePacket Remove player packet. */ public open class PlayerNPCEntity( public val name: String, public val properties: List<AddPlayer.Property> = emptyList(), areaTrigger: IAreaLocatable<Player>? = null, uuid: UUID = UUID.randomUUID(), public val inTabList: Boolean = false, ) : NPCEntity(EntityType.PLAYER, areaTrigger, uuid) { private val playerRemovePacket = PlayerInfoPacket( PlayerInfoPacket.Action.REMOVE_PLAYER, listOf(RemovePlayer(uuid)) ) override fun updateNewViewer(player: Player) { val connection = player.playerConnection connection.sendPacket(createPlayerAddPacket()) if (!inTabList) { scheduleNextTick { connection.sendPacket(playerRemovePacket) } } super.updateNewViewer(player) } /** * Create a packet to add the NPC in the player view. * @return A new packet. */ private fun createPlayerAddPacket() = PlayerInfoPacket( PlayerInfoPacket.Action.ADD_PLAYER, listOf( AddPlayer( uuid, name, properties, GameMode.CREATIVE, 0, customName ?: Component.text(name), null ) ) ) }
0
Kotlin
0
2
bf3a94b26e277c7515af45089ad906f8a949c81d
1,969
api
MIT License
examples/function/update/updateAFunction/main.kt
GWT-M3O-TEST
485,009,715
false
null
package examples.function.update import com.m3o.m3okotlin.M3O import com.m3o.m3okotlin.services.function suspend fun main() { M3O.initialize(System.getenv("M3O_API_TOKEN")) val req = FunctionUpdateRequest(Name = "helloworld",) try { val response = FunctionServ.update(req) println(response) } catch (e: Exception) { println(e) } }
1
Kotlin
1
0
54158b584ba47bd7323a484804dcd78c55ef7f69
366
m3o-kotlin
Apache License 2.0
app/src/main/java/com/rejowan/pdfreaderpro/database/DBHelper.kt
ahmmedrejowan
696,907,897
false
{"Kotlin": 179727, "Java": 163713}
package com.rejowan.pdfreaderpro.database import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper open class DBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { companion object { const val DATABASE_VERSION = 4 const val DATABASE_NAME = "PDFReaderAndrovine.db" } override fun onCreate(db: SQLiteDatabase) { // Empty implementation for now } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // Empty implementation for now } override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { onUpgrade(db, oldVersion, newVersion) } }
1
Kotlin
0
3
c89445b7039bf02dd7ea9d169df8686058e50e1a
769
PdfReaderPro
Apache License 2.0
app/src/main/java/com/biachacon/todolist/database/AppDatabase.kt
BiaChacon
220,573,047
false
null
package com.biachacon.todolist.database import androidx.room.Database import androidx.room.RoomDatabase import com.biachacon.todolist.dao.TaskDao import com.biachacon.todolist.dao.ToDoListDao import com.biachacon.todolist.model.Task import com.biachacon.todolist.model.ToDoList @Database( entities = [Task::class,ToDoList::class], version = 1 ) abstract class AppDatabase : RoomDatabase(){ abstract fun taskDao(): TaskDao abstract fun toDoListDao(): ToDoListDao }
0
Kotlin
1
1
817297beb5c24ebf80431345f69ee8d3f65bbd4e
481
ToDoList
MIT License
app/src/main/java/com/example/simplepay/SimplePayApp.kt
naveenfunk
831,210,966
false
{"Kotlin": 50354}
package com.example.simplepay import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class SimplePayApp : Application()
0
Kotlin
0
0
372577b2b58dfc0e3e80e57f486fa0df2aa65373
156
SimplePay
MIT License
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRule.kt
pinterest
64,293,719
false
null
package com.pinterest.ktlint.ruleset.standard.rules import com.pinterest.ktlint.rule.engine.core.api.ElementType import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATED_EXPRESSION import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION import com.pinterest.ktlint.rule.engine.core.api.ElementType.ANNOTATION_ENTRY import com.pinterest.ktlint.rule.engine.core.api.ElementType.FILE_ANNOTATION_LIST import com.pinterest.ktlint.rule.engine.core.api.ElementType.MODIFIER_LIST import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_ARGUMENT_LIST import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PROJECTION import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_ARGUMENT_LIST import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE import com.pinterest.ktlint.rule.engine.core.api.IndentConfig import com.pinterest.ktlint.rule.engine.core.api.RuleId import com.pinterest.ktlint.rule.engine.core.api.children import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_SIZE_PROPERTY import com.pinterest.ktlint.rule.engine.core.api.editorconfig.INDENT_STYLE_PROPERTY import com.pinterest.ktlint.rule.engine.core.api.firstChildLeafOrSelf import com.pinterest.ktlint.rule.engine.core.api.isCodeLeaf import com.pinterest.ktlint.rule.engine.core.api.isPartOf import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpace import com.pinterest.ktlint.rule.engine.core.api.isWhiteSpaceWithNewline import com.pinterest.ktlint.rule.engine.core.api.lastChildLeafOrSelf import com.pinterest.ktlint.rule.engine.core.api.nextCodeLeaf import com.pinterest.ktlint.rule.engine.core.api.nextLeaf import com.pinterest.ktlint.rule.engine.core.api.prevLeaf import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe import com.pinterest.ktlint.rule.engine.core.util.safeAs import com.pinterest.ktlint.ruleset.standard.StandardRule import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.psiUtil.leaves import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.utils.addToStdlib.applyIf /** * Ensures that annotation are wrapped to separate lines. * * https://kotlinlang.org/docs/reference/coding-conventions.html#annotation-formatting * * 1) Place annotations on separate lines before the declaration to which they are attached, and with the same indentation: * * ``` * @Target(AnnotationTarget.PROPERTY) * annotation class JsonExclude * ``` * * 2) Annotations without arguments may be placed on the same line: * * ``` * @JsonExclude @JvmField * var x: String * ``` * * 3) A single annotation without arguments may be placed on the same line as the corresponding declaration: * * ``` * @Test fun foo() { /*...*/ } * ``` * * 4) File annotations are placed after the file comment (if any), before the package statement, and are separated from package with a blank * line (to emphasize the fact that they target the file and not the package). * * @see [AnnotationSpacingRule] for white space rules. */ public class AnnotationRule : StandardRule( id = "annotation", usesEditorConfigProperties = setOf( INDENT_SIZE_PROPERTY, INDENT_STYLE_PROPERTY, ), ) { private var indentConfig = IndentConfig.DEFAULT_INDENT_CONFIG override fun beforeFirstNode(editorConfig: EditorConfig) { indentConfig = IndentConfig( indentStyle = editorConfig[INDENT_STYLE_PROPERTY], tabWidth = editorConfig[INDENT_SIZE_PROPERTY], ) Unit } override fun beforeVisitChildNodes( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { when (node.elementType) { FILE_ANNOTATION_LIST -> { visitFileAnnotationList(node, emit, autoCorrect) } ANNOTATION -> { // Annotation array // @[...] visitAnnotation(node, emit, autoCorrect) } ANNOTATION_ENTRY -> { visitAnnotationEntry(node, emit, autoCorrect) } } } private fun visitAnnotationEntry( node: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, autoCorrect: Boolean, ) { require(node.elementType == ANNOTATION_ENTRY) if (node.isAnnotationEntryWithValueArgumentList() && node.treeParent.treeParent.elementType != VALUE_PARAMETER && // fun fn(@Ann("blah") a: String) node.treeParent.treeParent.elementType != VALUE_ARGUMENT && // fn(@Ann("blah") "42") !node.isPartOf(TYPE_ARGUMENT_LIST) && // val property: Map<@Ann("blah") String, Int> node.isNotReceiverTargetAnnotation() ) { checkForAnnotationWithParameterToBePlacedOnSeparateLine(node, emit, autoCorrect) } if (node.isOnSameLineAsAnnotatedConstruct()) { if (node.isPrecededByAnnotationOnAnotherLine()) { // Code below is disallowed // @Foo1 // @Foo2 fun foo() {} emit( node.startOffset, "Annotation must be placed on a separate line when it is preceded by another annotation on a separate line", true, ) if (autoCorrect) { node .lastChildLeafOrSelf() .nextLeaf() ?.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent)) } } if (node.treeParent.elementType != ANNOTATION && node.isPrecededByOtherAnnotationEntryOnTheSameLine() && node.isLastAnnotationEntry() ) { // Code below is disallowed // @Foo1 @Foo2 fun foo() {} // But following is allowed: // @[Foo1 Foo2] fun foo() {} emit( node.findAnnotatedConstruct().startOffset, "Multiple annotations should not be placed on the same line as the annotated construct", true, ) if (autoCorrect) { node .lastChildLeafOrSelf() .nextCodeLeaf() ?.upsertWhitespaceBeforeMe( getNewlineWithIndent(node.treeParent) .applyIf(node.typeProjectionOrNull() != null) { plus(indentConfig.indent) }, ) } } node .typeProjectionOrNull() ?.let { typeProjection -> // Code below is disallowed // var foo: List<@Foo1 @Foo2 String> // But following is allowed: // var foo: List<@[Foo1 Foo2] String> if (node.isFollowedByOtherAnnotationEntryOnTheSameLine() && node.isFirstAnnotationEntry() ) { emit( typeProjection.startOffset, "Annotations on a type reference should be placed on a separate line", true, ) if (autoCorrect) { typeProjection .upsertWhitespaceBeforeMe( getNewlineWithIndent(node.treeParent).plus(indentConfig.indent), ) } } if (node.isPrecededByOtherAnnotationEntryOnTheSameLine() && node.isLastAnnotationEntry() ) { val annotatedConstruct = node.findAnnotatedConstruct() emit( annotatedConstruct.startOffset, "Annotations on a type reference should be placed on a separate line", true, ) if (autoCorrect) { annotatedConstruct .nextLeaf { it.isCodeLeaf() && it.elementType != ElementType.COMMA }!! .firstChildLeafOrSelf() .upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent)) } } } } if (node.isPrecededByOtherAnnotationEntryOnTheSameLine() && node.isPrecededByAnnotationOnAnotherLine()) { // Code below is disallowed // @Foo1 // @Foo2 @Foo3 // fun foo() {} emit( node.startOffset, "All annotations should either be on a single line or all annotations should be on a separate line", true, ) if (autoCorrect) { node .firstChildLeafOrSelf() .upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent)) } } } private fun ASTNode.typeProjectionOrNull() = takeIf { elementType == ANNOTATION_ENTRY } ?.takeIf { it.treeParent.elementType == MODIFIER_LIST } ?.treeParent ?.takeIf { it.treeParent.elementType == TYPE_REFERENCE } ?.treeParent ?.takeIf { it.treeParent.elementType == TYPE_PROJECTION } ?.treeParent private fun ASTNode.isPrecededByAnnotationOnAnotherLine(): Boolean { val firstAnnotation = treeParent.findChildByType(ANNOTATION_ENTRY) return siblings(forward = false) .takeWhile { it != firstAnnotation } .any { it.isWhiteSpaceWithNewline() } } private fun checkForAnnotationWithParameterToBePlacedOnSeparateLine( node: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, autoCorrect: Boolean, ) { if (node.isPrecededByOtherAnnotationEntry() && node.isOnSameLineAsPreviousAnnotationEntry()) { emit( node.startOffset, "Annotation with parameter(s) should be placed on a separate line prior to the annotated construct", true, ) if (autoCorrect) { node .firstChildLeafOrSelf() .upsertWhitespaceBeforeMe(" ") } } if (node.isOnSameLineAsNextAnnotationEntryOrAnnotatedConstruct()) { emit( node.startOffset, "Annotation with parameter(s) should be placed on a separate line prior to the annotated construct", // Annotated expressions for which the annotation contains a parameter can be hard to correct // automatically. See examples below. For now, let them be fixed manually. // fun foo1() = @Suppress("DEPRECATION") bar() // if (@Suppress("DEPRECATION") bar()) { .. } node.treeParent.elementType != ANNOTATED_EXPRESSION, ) if (autoCorrect) { node .lastChildLeafOrSelf() .nextLeaf() .safeAs<LeafPsiElement>() ?.let { if (it.elementType == WHITE_SPACE) { it.replaceWithText(getNewlineWithIndent(node.treeParent)) } else { it.rawInsertBeforeMe( PsiWhiteSpaceImpl(getNewlineWithIndent(node.treeParent)), ) } } } } } private fun ASTNode.isNotReceiverTargetAnnotation() = getAnnotationUseSiteTarget() != AnnotationUseSiteTarget.RECEIVER private fun ASTNode.getAnnotationUseSiteTarget() = psi .safeAs<KtAnnotationEntry>() ?.useSiteTarget ?.getAnnotationUseSiteTarget() private fun ASTNode.isAnnotationEntryWithValueArgumentList() = getAnnotationEntryValueArgumentList() != null private fun ASTNode.getAnnotationEntryValueArgumentList() = takeIf { it.elementType == ANNOTATION_ENTRY } ?.findChildByType(VALUE_ARGUMENT_LIST) private fun ASTNode.isFirstAnnotationEntry() = this == treeParent .children() .firstOrNull { it.elementType == ANNOTATION_ENTRY } private fun ASTNode.isLastAnnotationEntry() = this == treeParent .children() .lastOrNull { it.elementType == ANNOTATION_ENTRY } private fun ASTNode.isPrecededByOtherAnnotationEntryOnTheSameLine() = siblings(forward = false) .takeWhile { !it.isWhiteSpaceWithNewline() } .any { it.elementType == ANNOTATION_ENTRY } private fun ASTNode.isFollowedByOtherAnnotationEntryOnTheSameLine() = siblings() .takeWhile { !it.isWhiteSpaceWithNewline() } .any { it.elementType == ANNOTATION_ENTRY } private fun ASTNode.isPrecededByOtherAnnotationEntry() = siblings(forward = false) .any { it.elementType == ANNOTATION_ENTRY } private fun ASTNode.isOnSameLineAsPreviousAnnotationEntry() = siblings(forward = false) .takeWhile { it.elementType != ANNOTATION_ENTRY } .none { it.isWhiteSpaceWithNewline() } private fun ASTNode.isFollowedByOtherAnnotationEntry() = siblings(forward = true).any { it.elementType == ANNOTATION_ENTRY } private fun ASTNode.isOnSameLineAsNextAnnotationEntry() = siblings(forward = true) .takeWhile { it.elementType != ANNOTATION_ENTRY } .none { it.isWhiteSpaceWithNewline() } private fun ASTNode.isOnSameLineAsAnnotatedConstruct(): Boolean { val annotatedConstruct = findAnnotatedConstruct() return lastChildLeafOrSelf() .leaves(forward = true) .takeWhile { it != annotatedConstruct } .none { it.isWhiteSpaceWithNewline() } } private fun ASTNode.findAnnotatedConstruct(): ASTNode { val astNode = if (treeParent.elementType == MODIFIER_LIST) { treeParent } else { this } return checkNotNull( astNode.lastChildLeafOrSelf().nextCodeLeaf(), ) } private fun ASTNode.isOnSameLineAsNextAnnotationEntryOrAnnotatedConstruct() = if (isFollowedByOtherAnnotationEntry()) { isOnSameLineAsNextAnnotationEntry() } else { isOnSameLineAsAnnotatedConstruct() } private fun visitFileAnnotationList( node: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, autoCorrect: Boolean, ) { node .lastChildLeafOrSelf() .nextCodeLeaf() ?.let { codeLeaf -> val whitespaceBefore = codeLeaf.prevLeaf { it.isWhiteSpace() } if (whitespaceBefore == null || whitespaceBefore.text != "\n\n") { emit( codeLeaf.startOffset, "File annotations should be separated from file contents with a blank line", true, ) if (autoCorrect) { codeLeaf.upsertWhitespaceBeforeMe("\n\n") } } } } private fun visitAnnotation( node: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, autoCorrect: Boolean, ) { require(node.elementType == ANNOTATION) if ((node.isFollowedByOtherAnnotationEntry() && node.isOnSameLineAsNextAnnotationEntry()) || (node.isPrecededByOtherAnnotationEntry() && node.isOnSameLineAsPreviousAnnotationEntry()) ) { emit( node.startOffset, "@[...] style annotations should be on a separate line from other annotations.", true, ) if (autoCorrect) { if (node.isFollowedByOtherAnnotationEntry()) { node.upsertWhitespaceAfterMe(getNewlineWithIndent(node.treeParent)) } else if (node.isPrecededByOtherAnnotationEntry()) { node.upsertWhitespaceBeforeMe(getNewlineWithIndent(node.treeParent)) } } } } private fun getNewlineWithIndent(modifierListRoot: ASTNode): String { val nodeBeforeAnnotations = modifierListRoot.treeParent.treePrev as? PsiWhiteSpace // If there is no whitespace before the annotation, the annotation is the first // text in the file val newLineWithIndent = nodeBeforeAnnotations?.text ?: "\n" return if (newLineWithIndent.contains('\n')) { // Make sure we only insert a single newline newLineWithIndent.substring(newLineWithIndent.lastIndexOf('\n')) } else { newLineWithIndent } } } public val ANNOTATION_RULE_ID: RuleId = AnnotationRule().ruleId
32
Kotlin
463
5,475
c8f7d6c7b62977189c5cfa0fcacf917520abe153
18,411
ktlint
MIT License
product/appkit/src/main/kotlin/com/reown/appkit/ui/routes/account/what_is_network/WhatIsNetworkRoute.kt
reown-com
851,466,242
false
{"Kotlin": 2055654, "Java": 4294, "Shell": 1676}
package com.reown.appkit.ui.routes.account.what_is_network import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.unit.dp import com.reown.appkit.R import com.reown.appkit.ui.components.internal.commons.ExternalIcon import com.reown.appkit.ui.components.internal.commons.HelpSection import com.reown.appkit.ui.components.internal.commons.VerticalSpacer import com.reown.appkit.ui.components.internal.commons.button.ButtonSize import com.reown.appkit.ui.components.internal.commons.button.ButtonStyle import com.reown.appkit.ui.components.internal.commons.button.ImageButton import com.reown.appkit.ui.previews.UiModePreview import com.reown.appkit.ui.previews.AppKitPreview import com.reown.appkit.ui.theme.AppKitTheme @Composable internal fun WhatIsNetworkRoute() { val uriHandler = LocalUriHandler.current WhatIsNetwork { uriHandler.openUri("https://ethereum.org/en/developers/docs/networks/") } } @Composable private fun WhatIsNetwork( onLearnMoreClick: () -> Unit ) { Column( modifier = Modifier .padding(horizontal = 20.dp) .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { VerticalSpacer(20.dp) HelpSection( title = "The system's nuts and bolts", body = "A network is what brings the blockchain to life, as this technical infrastructure allows apps to access the ledger and smart contract services.", assets = listOf(R.drawable.network, R.drawable.layers, R.drawable.system) ) VerticalSpacer(24.dp) HelpSection( title = "Designed for different uses", body = "Each network is designed differently, and may therefore suit certain apps and experiences.", assets = listOf(R.drawable.noun, R.drawable.defi_alt, R.drawable.dao) ) VerticalSpacer(height = 20.dp) ImageButton( text = "Learn more", image = { ExternalIcon(AppKitTheme.colors.inverse100) }, style = ButtonStyle.MAIN, size = ButtonSize.S, paddingValues = PaddingValues(start = 8.dp, top = 6.dp, end = 12.dp, 6.dp), onClick = { onLearnMoreClick() } ) Spacer(modifier = Modifier.height(30.dp)) } } @UiModePreview @Composable private fun WhatIsNetworkPreview() { AppKitPreview { WhatIsNetworkRoute() } }
6
Kotlin
1
8
893084b3df91b47daa77f8f964e37f84a02843b1
2,913
reown-kotlin
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/linear/Wifi.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.linear import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.LinearGroup public val LinearGroup.Wifi: ImageVector get() { if (_wifi != null) { return _wifi!! } _wifi = Builder(name = "Wifi", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.91f, 11.84f) curveTo(9.21f, 8.52f, 14.8f, 8.52f, 19.1f, 11.84f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(2.0f, 8.36f) curveTo(8.06f, 3.68f, 15.94f, 3.68f, 22.0f, 8.36f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.79f, 15.49f) curveTo(9.94f, 13.05f, 14.05f, 13.05f, 17.2f, 15.49f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.4f, 19.15f) curveTo(10.98f, 17.93f, 13.03f, 17.93f, 14.61f, 19.15f) } } .build() return _wifi!! } private var _wifi: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
2,634
VuesaxIcons
MIT License
app/src/main/java/com/example/myapplication/main/adapters/BlogPostAdapter.kt
ahmedfadul123
524,736,305
false
{"Kotlin": 24993}
package com.example.myapplication.main.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.myapplication.R import com.example.myapplication.api.interfaces.ItemClickListener import com.example.myapplication.models.Post class BlogPostAdapter( private val context :Context, private val posts :List<Post>, private val itemClickListener: ItemClickListener ):RecyclerView.Adapter<BlogPostAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_blog_post,parent,false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(posts[position]) } override fun getItemCount() = posts.size inner class ViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){ private val tvId = itemView.findViewById<TextView>(R.id.tvId) private val tvTitle = itemView.findViewById<TextView>(R.id.tvTitle) private val tvBody = itemView.findViewById<TextView>(R.id.tvBlogBody) fun bind(post :Post){ tvId.text = "Post #${post.id}" tvTitle.text = post.title tvBody.text = post.body itemView.setOnClickListener { itemClickListener.onItemClick(post) } } } }
0
Kotlin
0
3
8d61aa902a416d07995f415dafe11fb271e624b8
1,554
Learning-Retrofit
Apache License 2.0
libkit/src/main/java/com/merxury/libkit/utils/ServiceHelper.kt
lihenggui
115,417,337
false
null
package com.merxury.libkit.utils import com.elvishew.xlog.XLog import com.merxury.libkit.RootCommand import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class ServiceHelper(private val packageName: String) { private val logger = XLog.tag("ServiceHelper").build() private var serviceInfo: String = "" private val serviceList: MutableList<String> = mutableListOf() suspend fun isServiceRunning(serviceName: String): Boolean { return withContext(Dispatchers.Default) { val shortName = if (serviceName.startsWith(packageName)) { serviceName.removePrefix(packageName) } else { serviceName } val fullRegex = SERVICE_REGEX.format(packageName, serviceName).toRegex() val shortRegex = SERVICE_REGEX.format(packageName, shortName).toRegex() serviceList.forEach { if (it.contains(fullRegex) || it.contains(shortRegex)) { if (it.contains("app=ProcessRecord{")) { return@withContext true } } } return@withContext false } } suspend fun refresh() { withContext(Dispatchers.IO) { serviceList.clear() serviceInfo = try { if (PermissionUtils.isRootAvailable) { RootCommand.runBlockingCommand("dumpsys activity services -p $packageName") } else { "" } } catch (e: Exception) { logger.e("Cannot get running service list:", e) "" } parseServiceInfo() } } private suspend fun parseServiceInfo(dispatcher: CoroutineDispatcher = Dispatchers.Default) { withContext(dispatcher) { if (serviceInfo.contains("(nothing)")) { return@withContext } val list = serviceInfo.split("\n[\n]+".toRegex()).toMutableList() if (list.lastOrNull()?.contains("Connection bindings to services") == true) { list.removeAt(list.size - 1) } serviceList.addAll(list) } } companion object { private const val SERVICE_REGEX = """ServiceRecord\{(.*?) %s\/%s\}""" } }
14
Kotlin
37
323
bf2979d5b94c60ab3a172cfec0fff38420e10519
2,396
blocker
Apache License 2.0
app/src/main/java/com/uxstate/instantscore/data/remote/json/FixtureDetailsJsonParser.kt
Tonnie-Dev
578,703,528
false
{"Kotlin": 256289, "Java": 130256}
package com.uxstate.instantscore.data.remote.json import com.uxstate.instantscore.domain.models.fixture_details.* import javax.inject.Inject import javax.inject.Singleton import org.json.JSONObject // force single instance of FixtureDetailsJsonParser for the entire app process @Singleton /* Use @Inject so that Hilt knows how to create CountryRepositoryImpl object noting we will be injecting the interface and not the impl */ // always favor/depend on abstractions instead of concrete classes class FixtureDetailsJsonParser @Inject constructor() : JsonStringParser<FixtureDetails> { override suspend fun parseJsonString(jsonString: String): FixtureDetails { val jsonMainFixturesObject = JSONObject(jsonString) val responseJsonArray = jsonMainFixturesObject.getJSONArray("response") val responseJsonObject = responseJsonArray.getJSONObject(0) val fixtureJsonObject = responseJsonObject.getJSONObject("fixture") // variable - id val fixtureId = fixtureJsonObject.optInt("id", -1) // variable - timestamp val timeStamp = fixtureJsonObject.optLong("timestamp", 0L) // variable - referee val referee = fixtureJsonObject.optString("referee", "") val venueJsonObject = fixtureJsonObject.getJSONObject("venue") // variable - venue val venue = venueJsonObject.optString("name", "") val statusJsonObject = fixtureJsonObject.getJSONObject("status") // variable - short val status = statusJsonObject.optString("short", "") // variable - time elapsed val timeElapsed = statusJsonObject.optInt("elapsed", -1) val goalJsonObject = responseJsonObject.getJSONObject("goals") // variable - home goal val homeGoals = goalJsonObject.optInt("home", -1) // variable - away goal val awayGoals = goalJsonObject.optInt("away", -1) val leagueJsonObject = responseJsonObject.getJSONObject("league") // variable - league name val leagueName = leagueJsonObject.optString("name", "") val teamJsonObject = responseJsonObject.getJSONObject("teams") val homeTeamJSONObject = teamJsonObject.getJSONObject("home") val awayTeamJSONObject = teamJsonObject.getJSONObject("away") // variables val homeTeam = Team( name = homeTeamJSONObject.optString("name", ""), logo = homeTeamJSONObject.optString("logo", ""), isWinner = homeTeamJSONObject.optBoolean("winner", false) ) val awayTeam = Team( name = awayTeamJSONObject.optString("name", ""), logo = awayTeamJSONObject.optString("logo", ""), isWinner = awayTeamJSONObject.optBoolean("winner", false) ) // variable teams Pair val teamPair = Pair( first = homeTeam, second = awayTeam ) val eventsJsonArray = responseJsonObject.getJSONArray("events") val events = mutableListOf<Event>() (0 until eventsJsonArray.length()).forEach { i -> val innerEventObj = eventsJsonArray.getJSONObject(i) var event: Event? = null innerEventObj.keys() .forEach { _ -> val timeJsonObj = innerEventObj.getJSONObject("time") val teamJsonObj = innerEventObj.getJSONObject("team") val playerJsonObj = innerEventObj.getJSONObject("player") val assistJsonObj = innerEventObj.getJSONObject("assist") event = Event( timeElapsed = timeJsonObj.optInt("elapsed", -1), inExtra = timeJsonObj.optInt("extra", -1), player = playerJsonObj.optString("name", ""), side = teamJsonObj.optString("name", ""), assist = assistJsonObj.optString("name", "GXX"), eventType = innerEventObj.optString("type"), eventDetail = innerEventObj.optString("detail") ) } event?.let { events.add(it) } } val statsJsonArray = responseJsonObject.getJSONArray("statistics") // variable - Stats List val stats = mutableListOf<Stats>() for (i in 0 until statsJsonArray.length()) { val innerStatsObj = statsJsonArray.getJSONObject(i) val statsArray = innerStatsObj.getJSONArray("statistics") for (j in 0 until statsArray.length()) { val innerStatObj = statsArray.getJSONObject(j) // variable val type = innerStatObj.optString("type", "") val statValue = if (type == "Ball Possession") { innerStatObj.getString("value") .substringBefore("%").toInt() } else { innerStatObj.optInt("value", 0) } // val statValue = innerStatObj.optInt("value", 0) val stat = Stats(type, statValue) stats.add(stat) } } val lineUpsJsonArray = responseJsonObject.getJSONArray("lineups") // variable val teamLineUps = mutableListOf<LineUp>() for (i in 0 until lineUpsJsonArray.length()) { // cleanup list with each iteration to construct a fresh line-up object val startingElevenLineUp = mutableListOf<Player>() val substitutesLineUp = mutableListOf<Player>() val innerLineUpsObj = lineUpsJsonArray.getJSONObject(i) val teamJsonObj = innerLineUpsObj.getJSONObject("team") val colorsJsonObj = teamJsonObj.getJSONObject("colors") val playerColorJsonObj = colorsJsonObj.getJSONObject("player") // variables val teamName = teamJsonObj.optString("name", "") val teamLogo = teamJsonObj.optString("logo", "") val primaryPlayerColor = playerColorJsonObj.optString("primary", "D3D3D3") val coachJsonObj = innerLineUpsObj.getJSONObject("coach") // variable val coachName = coachJsonObj.optString("name", "") val coachPhoto = coachJsonObj.optString("photo", "") val startingElevenArray = innerLineUpsObj.getJSONArray("startXI") for (j in 0 until startingElevenArray.length()) { val innerStartingElevenObj = startingElevenArray.getJSONObject(j) val startingPlayerJsonObj = innerStartingElevenObj.getJSONObject("player") // variables val playerId = startingPlayerJsonObj.optInt("id", -1) val playerName = startingPlayerJsonObj.optString("name", "") val playerNumber = startingPlayerJsonObj.optInt("number", -1) val playerPosition = startingPlayerJsonObj.optString("pos", "") val startingPlayer = Player( playerId = playerId, playerName = playerName, playerNumber = playerNumber, playerPosition = playerPosition ) startingElevenLineUp.add(startingPlayer) } val subsJsonArray = innerLineUpsObj.getJSONArray("substitutes") for (k in 0 until subsJsonArray.length()) { val subsInnerJsonObj = subsJsonArray.getJSONObject(k) val subPlayerJsonObj = subsInnerJsonObj.getJSONObject("player") // variables val playerId = subPlayerJsonObj.optInt("id", -1) val playerName = subPlayerJsonObj.optString("name", "") val playerNumber = subPlayerJsonObj.optInt("number", -1) val playerPosition = subPlayerJsonObj.optString("pos", "") val subPlayer = Player( playerId = playerId, playerName = playerName, playerNumber = playerNumber, playerPosition = playerPosition ) substitutesLineUp.add(subPlayer) } val lineup = LineUp( coach = Coach( name = coachName, photo = coachPhoto ), startingXI = startingElevenLineUp, substitutes = substitutesLineUp, team = Team( name = teamName, logo = teamLogo, isWinner = false ), teamColor = primaryPlayerColor ) teamLineUps.add(lineup) } val scoreJsonObject = responseJsonObject.getJSONObject("score") val fullTimeJsonObj = scoreJsonObject.getJSONObject("fulltime") val extraTimeJsonObj = scoreJsonObject.getJSONObject("extratime") val penaltiesJsonObj = scoreJsonObject.getJSONObject("penalty") // variables val fullTimeHomeScore = fullTimeJsonObj.optInt("home", -1) val fullTimeAwayScore = fullTimeJsonObj.optInt("away", -1) val extraTimeHomeScore = extraTimeJsonObj.optInt("home", -1) val extraTimeAwayScore = extraTimeJsonObj.optInt("away", -1) val penaltiesHomeScore = penaltiesJsonObj.optInt("home", -1) val penaltiesAwayScore = penaltiesJsonObj.optInt("away", -1) return FixtureDetails( fixtureId = fixtureId, timeStamp = timeStamp, referee = referee, venue = venue, status = status, timeElapsed = timeElapsed, homeGoals = homeGoals, awayGoals = awayGoals, leagueName = leagueName, teams = teamPair, events = events, lineUps = teamLineUps, score = Score( extraTimeScore = ExtraTime( extraTimeAwayScore = extraTimeAwayScore, extraTimeHomeScore = extraTimeHomeScore ), fullTimeScore = FullTime( fullTimeAwayScore = fullTimeAwayScore, fullTimeHomeScore = fullTimeHomeScore ), penaltyShootOutScore = PenaltyShootOut( penaltiesScoredAway = penaltiesAwayScore, penaltiesScoredHome = penaltiesHomeScore ) ), stats = stats ) } }
0
Kotlin
2
0
5061dc42b599751afb7f6cbf5bff7122afe7a70d
10,541
InstantScore
The Unlicense
app/src/main/java/com/hha/heinhtetaung/mm_kunyi/event/FirebaseEvent.kt
zack1191
142,954,194
false
null
package com.hha.heinhtetaung.mm_kunyi.event import com.hha.heinhtetaung.mm_kunyi.data.vo.JobsVO /** * Created by E5 on 8/2/2018. */ class FirebaseEvent { companion object class JobsLoadedEvent { private lateinit var job: List<JobsVO> fun JobsLoaded(jobs: List<JobsVO>) { this.job = jobs } fun GetJobs(): List<JobsVO> { return job } } }
0
Kotlin
0
0
fa1c70a37218215b2b7938d90d2b94f62932ea6f
420
PADC-5-HHA-MM-KuNyi
Apache License 2.0
ion-schema/src/test/kotlin/com/amazon/ionschema/writer/internal/constraints/ValidValuesWriterTest.kt
amazon-ion
148,685,964
false
{"Kotlin": 804755, "Inno Setup": 15625, "Java": 795, "Shell": 631}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazon.ionschema.writer.internal.constraints import com.amazon.ionschema.model.ConsistentDecimal import com.amazon.ionschema.model.ConsistentTimestamp import com.amazon.ionschema.model.Constraint.ValidValues import com.amazon.ionschema.model.ContinuousRange.Limit.Closed import com.amazon.ionschema.model.ContinuousRange.Limit.Open import com.amazon.ionschema.model.ContinuousRange.Limit.Unbounded import com.amazon.ionschema.model.ExperimentalIonSchemaModel import com.amazon.ionschema.model.ValidValue.NumberRange import com.amazon.ionschema.model.ValidValue.TimestampRange import com.amazon.ionschema.model.ValidValue.Value import java.math.BigDecimal @OptIn(ExperimentalIonSchemaModel::class) class ValidValuesWriterTest : ConstraintTestBase( writer = ValidValuesWriter, expectedConstraints = setOf(ValidValues::class), writeTestCases = listOf( ValidValues(emptySet()) to "valid_values: []", ValidValues(Value(ion("a"))) to "valid_values: [a]", ValidValues(Value(ion("a")), Value(ion("b"))) to "valid_values: [a, b]", // Number ranges ValidValues(NumberRange(ConsistentDecimal(BigDecimal.ZERO))) to "valid_values: [range::[0., 0.]]", ValidValues(NumberRange(Open(ConsistentDecimal.valueOf(1L)), Closed(ConsistentDecimal.valueOf(3L)))) to "valid_values: [range::[exclusive::1., 3.]]", ValidValues(NumberRange(Closed(ConsistentDecimal.valueOf(1.0)), Unbounded)) to "valid_values: [range::[1.0, max]]", ValidValues(NumberRange(Unbounded, Closed(ConsistentDecimal.valueOf(3L)))) to "valid_values: [range::[min, 3.]]", // Timestamp ranges ValidValues( TimestampRange( ConsistentTimestamp.valueOf("2023-01-01T00:00:00Z") ) ) to "valid_values: [range::[2023-01-01T00:00:00Z, 2023-01-01T00:00:00Z]]", ValidValues( TimestampRange( Open(ConsistentTimestamp.valueOf("2023-01-02T00:00:00Z")), Closed(ConsistentTimestamp.valueOf("2023-01-04T00:00:00Z")), ) ) to "valid_values: [range::[exclusive::2023-01-02T00:00:00Z, 2023-01-04T00:00:00Z]]", ValidValues( TimestampRange( Closed(ConsistentTimestamp.valueOf("2023-01-05T00:00:00Z")), Unbounded ) ) to "valid_values: [range::[2023-01-05T00:00:00Z, max]]", ValidValues( TimestampRange( Unbounded, Closed(ConsistentTimestamp.valueOf("2023-01-06T00:00:00Z")) ) ) to "valid_values: [range::[min, 2023-01-06T00:00:00Z]]", ) )
40
Kotlin
14
27
7a9ee6d06e9cfdaa530310f5d9be9f5a52680d3b
2,745
ion-schema-kotlin
Apache License 2.0
src/test/kotlin/com/randomlychosenbytes/kotlintest/DummyTest.kt
wmentzel
295,164,360
false
null
package com.randomlychosenbytes.kotlintest import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance.Lifecycle @TestInstance(Lifecycle.PER_CLASS) class DummyTest { @Test fun `test the truth`() { assertTrue(true) } }
0
Kotlin
0
0
850a00918b6585d9fcc8c2b1eb864f0c2c587b9a
349
github-actions-test
MIT License
src/main/kotlin/ChatTheSpire/console/TreasureChestOpenConsoleCommand.kt
FylmTM
246,153,979
false
null
package ChatTheSpire.console import ChatTheSpire.command.TreasureChestOpenCommand import basemod.DevConsole import basemod.devcommands.ConsoleCommand class TreasureChestOpenConsoleCommand : ConsoleCommand() { init { minExtraTokens = 0 maxExtraTokens = 0 } override fun execute(tokens: Array<String>, depth: Int) { if (!TreasureChestOpenCommand.perform(listOf())) { DevConsole.log("Failed to open treasure chest") } } override fun errorMsg() { DevConsole.couldNotParse() } }
0
Kotlin
0
0
898f415a1d9f2a20d8d91bd89ff7b3f1bf7cf53d
555
ChatTheSpire
MIT License
app/src/main/java/com/dr1009/app/gr/ui/retrofit/RetrofitViewModel.kt
koji-1009
283,180,624
false
null
package com.dr1009.app.gr.ui.retrofit import androidx.hilt.Assisted import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.* import com.dr1009.app.gr.entity.RepositoryFragment import com.dr1009.app.gr.repository.RetrofitRepository import kotlinx.coroutines.launch class RetrofitViewModel @ViewModelInject constructor( private val repository: RetrofitRepository, @Assisted private val savedStateHandle: SavedStateHandle ) : ViewModel() { private val list = MutableLiveData<List<RepositoryFragment>>(emptyList()) init { viewModelScope.launch { val response = repository.repositories() list.value = response } } private val _text = MutableLiveData<String>().apply { value = "This is Retrofit Fragment" } val text: LiveData<String> = _text }
0
Kotlin
0
0
bf43cb3748483408bb2644efddbf8c257fef0607
840
GraphQL-Retrofit
MIT License
aws/src/test/java/com/nimbusframework/nimbusaws/annotation/services/functions/DocumentStoreFunctionResourceCreatorTest.kt
zmyer
232,053,429
true
{"Kotlin": 535208, "Java": 75469, "JavaScript": 12405, "CSS": 297, "Dockerfile": 148}
package com.nimbusframework.nimbusaws.annotation.services.functions import com.nimbusframework.nimbusaws.CompileStateService import com.nimbusframework.nimbusaws.annotation.processor.FunctionInformation import com.nimbusframework.nimbusaws.annotation.services.FunctionEnvironmentService import com.nimbusframework.nimbusaws.annotation.services.ResourceFinder import com.nimbusframework.nimbusaws.cloudformation.CloudFormationFiles import com.nimbusframework.nimbusaws.cloudformation.resource.dynamo.DynamoResource import com.nimbusframework.nimbuscore.persisted.NimbusState import com.nimbusframework.nimbuscore.wrappers.DynamoConfiguration import io.kotlintest.shouldBe import io.kotlintest.shouldNotBe import io.kotlintest.specs.AnnotationSpec import io.mockk.every import io.mockk.mockk import javax.annotation.processing.RoundEnvironment class DocumentStoreFunctionResourceCreatorTest : AnnotationSpec() { private lateinit var documentStoreFunctionResourceCreator: DocumentStoreFunctionResourceCreator private lateinit var roundEnvironment: RoundEnvironment private lateinit var cfDocuments: MutableMap<String, CloudFormationFiles> private lateinit var nimbusState: NimbusState private lateinit var functionEnvironmentService: FunctionEnvironmentService private lateinit var resourceFinder: ResourceFinder private lateinit var compileState: CompileStateService @BeforeEach fun setup() { nimbusState = NimbusState() cfDocuments = mutableMapOf() roundEnvironment = mockk() resourceFinder = mockk() compileState = CompileStateService("handlers/DocumentStoreHandlers.java") functionEnvironmentService = FunctionEnvironmentService(cfDocuments, nimbusState) } @Test fun correctlyProcessesDocumentStoreFunctionAnnotation() { compileState.compileObjects {processingEnvironment -> documentStoreFunctionResourceCreator = DocumentStoreFunctionResourceCreator(cfDocuments, nimbusState, processingEnvironment, mockk(relaxed = true), resourceFinder) every { resourceFinder.getDocumentStoreResource(any(), any(), any()) } returns DynamoResource(DynamoConfiguration("table"), nimbusState, "dev") val results: MutableList<FunctionInformation> = mutableListOf() val classElem = processingEnvironment.elementUtils.getTypeElement("handlers.DocumentStoreHandlers") val funcElem = classElem.enclosedElements[1] documentStoreFunctionResourceCreator.handleElement(funcElem, functionEnvironmentService, results) cfDocuments["dev"] shouldNotBe null val resources = cfDocuments["dev"]!!.updateTemplate.resources resources.size() shouldBe 5 results.size shouldBe 1 } } }
0
null
0
0
77aa887df9e8613c40cf355e97acc1f91d4b67e0
2,793
nimbus-core
MIT License
pig-runtime/src/org/partiql/pig/runtime/IntermediateRecord.kt
alancai98
312,336,136
true
{"Kotlin": 752870, "FreeMarker": 20128}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.partiql.pig.runtime import com.amazon.ionelement.api.AnyElement import com.amazon.ionelement.api.IonElement import com.amazon.ionelement.api.IonLocation import com.amazon.ionelement.api.SexpElement import com.amazon.ionelement.api.location import com.amazon.ionelement.api.head import com.amazon.ionelement.api.tail /** * Contains an "intermediate" representation of a Pig record. * * This is a helper function that helps reduce the complexity of the template and the size of * the generated code. * * Single use only. Discard after extracting all field values with [processRequiredField] or [processOptionalField]. */ class IntermediateRecord( /** The tag of the record. Used for error reporting purposes only. */ private val recordTagName: String, /** The location of the record within the data being transformer. */ private val location: IonLocation?, /** The fields and their values. */ fields: Map<String, AnyElement> ) { private val fieldMap = fields.toMutableMap() /** * If a field of named [fieldName] exists in [fieldMap], removes it from [fieldMap] and passes its value to * [deserFunc] to perform deserialization. Returns `null` if the field does not exist in [fieldMap]. */ fun <T> processOptionalField(fieldName: String, deserFunc: (AnyElement) -> T): T? = fieldMap.remove(fieldName)?.let { deserFunc(it) } /** * Same as [processOptionalField] but throws [MalformedDomainDataException] if the field does not exist * in [fieldMap].] */ fun <T> processRequiredField(fieldName: String, deserFunc: (AnyElement) -> T): T = processOptionalField(fieldName, deserFunc) ?: errMalformed(location, "Required field '${fieldName}' was not found within '$recordTagName' record") /** * After all required an optional fields in a record have been processed by the transformer, this * function should be invoked to throw a [MalformedDomainDataException] if any unprocessed fields remain in * [fieldMap]. This would indicate that a mis-named field was present. */ fun malformedIfAnyUnprocessedFieldsRemain() { if(fieldMap.isNotEmpty()) { errUnexpectedField(location, fieldMap.keys.first()) } } } /** * Does part of the work of deserializing records. * * Converts the receiver [AnyElement], which must be an expression in the form of: * * ``` * '(' <recordTagName> [ '(' <fieldName> <fieldValue> ')' ]... ')' * ``` * * To an instance of [IntermediateRecord]. */ fun SexpElement.transformToIntermediateRecord(): IntermediateRecord { val recordTagName = this.head.symbolValue val recordFields = this.tail val fieldMap = recordFields.map { field: AnyElement -> val fieldSexp = field.asSexp() fieldSexp.requireArityOrMalformed(1) fieldSexp.head.symbolValue to fieldSexp.tail.head }.toMap() return IntermediateRecord(recordTagName, this.metas.location, fieldMap) }
0
Kotlin
0
0
105495c4afc4d81890c3949088d0b5e0a45f3257
3,591
partiql-ir-generator
Apache License 2.0
onebusaway-sdk-java-core/src/main/kotlin/com/open_transit/api/services/blocking/StopService.kt
OneBusAway
864,202,238
false
{"Kotlin": 1841904, "Shell": 3662, "Dockerfile": 399}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.open_transit.api.services.blocking import com.open_transit.api.core.RequestOptions import com.open_transit.api.models.StopRetrieveParams import com.open_transit.api.models.StopRetrieveResponse interface StopService { /** Get details of a specific stop */ @JvmOverloads fun retrieve( params: StopRetrieveParams, requestOptions: RequestOptions = RequestOptions.none() ): StopRetrieveResponse }
0
Kotlin
0
0
4139f96c4d90517f472a1b2561df813ad231f904
586
java-sdk
Apache License 2.0
app/src/main/java/qwqeqrqwqeqr/android/room/database/dao/BookDao.kt
qwqeqrqwqeqr
775,294,342
false
{"Kotlin": 30769}
package qwqeqrqwqeqr.android.room.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import kotlinx.coroutines.flow.Flow import qwqeqrqwqeqr.android.room.database.entity.BookEntity import qwqeqrqwqeqr.android.room.database.relation.BookWithUsers @Dao interface BookDao { @Insert suspend fun insertBook(vararg bookEntity: BookEntity) @Insert suspend fun insertBook(bookEntity: BookEntity) @Update(entity = BookEntity::class, onConflict = OnConflictStrategy.REPLACE) suspend fun updateBook(bookEntity: BookEntity): Int @Update(entity = BookEntity::class, onConflict = OnConflictStrategy.REPLACE) suspend fun updateBook(vararg bookEntity: BookEntity): Int @Delete(entity = BookEntity::class) suspend fun deleteBook(bookEntity: BookEntity): Int @Delete(entity = BookEntity::class) suspend fun deleteBook(vararg bookEntity: BookEntity): Int @Query("DELETE FROM book") suspend fun deleteAllBooks() @Query("SELECT * FROM book") fun getAllBooks(): Flow<List<BookEntity>> @Transaction @Query("SELECT * FROM book where book.book_id=:bookId") fun getUserAndBookByBookId(bookId: Long): Flow<List<BookWithUsers>> }
0
Kotlin
0
0
f27e718eb35c05e431630f3e37608e321bf97356
1,362
android-room-sample
Apache License 2.0
app/src/main/java/vn/sunasterisk/travelapp/data/DataManager.kt
duccnv-1684
177,320,613
false
null
package vn.sunasterisk.travelapp.data interface DataManager
0
Kotlin
0
0
06f5e2a790a37bb65aa6c60a744372aa3257282f
61
travel_app
Apache License 2.0
app/src/main/java/tr/com/gndg/self/ui/product/stateScreens/HistoryStateScreen.kt
Cr3bain
840,332,370
false
{"Kotlin": 567278}
package tr.com.gndg.self.ui.product.stateScreens import androidx.compose.foundation.background import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import org.joda.time.DateTime import tr.com.gndg.self.R import tr.com.gndg.self.core.util.TransactionType import tr.com.gndg.self.core.util.returnTypeString import tr.com.gndg.self.domain.join.ProductTransaction import tr.com.gndg.self.domain.model.transactions.TransactionState import tr.com.gndg.self.domain.model.transactions.toTransactionDataDetail import tr.com.gndg.self.domain.model.transactions.toTransactionDetail import tr.com.gndg.self.ui.dialogs.ArrivalProductDialog import tr.com.gndg.self.ui.scopes.WarehouseNameText @Preview @Composable fun HistoryStatePreview(){ HistoryStateScreen(modifier = Modifier .fillMaxSize() .background(Color.White), productTransactionList = emptyList() ) } @Composable fun HistoryStateScreen( modifier: Modifier, productTransactionList: List<ProductTransaction> ) { BoxWithConstraints( modifier = modifier ) { if (productTransactionList.isEmpty()) { Text( modifier = Modifier .height(this.maxHeight) .fillMaxWidth(), text = stringResource(R.string.noHistory), textAlign = TextAlign.Center, style = MaterialTheme.typography.titleLarge ) } else { LazyColumn(modifier= Modifier .height(this.maxHeight) .fillMaxSize() ) { items(productTransactionList.sortedByDescending { it.transaction?.date }) { ProductTransactionListItem(it) } } } } } @Composable fun ProductTransactionListItem(productTransaction: ProductTransaction) { ArrivalListItem(productTransaction) } @Composable fun ArrivalListItem(productTransaction: ProductTransaction) { var showInfo by remember { mutableStateOf(false) } val context = LocalContext.current val sourceTargetUUID = when(productTransaction.transaction?.transactionType) { TransactionType.Arrival-> { productTransaction.transaction.targetUUID //supplier } TransactionType.Outgoing-> { productTransaction.transaction.sourceUUID // customer } TransactionType.Transfer-> { productTransaction.transaction.sourceUUID // other warehouse } else -> { null } } ListItem( leadingContent = { Text(text = productTransaction.transactionData?.piece.toString(), style = MaterialTheme.typography.titleLarge) }, overlineContent = { Row { Text(modifier = Modifier.padding(end = 10.dp), text = returnTypeString(context, productTransaction.transaction?.transactionType) ) Text(text = DateTime(productTransaction.transaction?.date).toString("dd.MM.yyyy")) } }, headlineContent = { WarehouseNameText( modifier = Modifier, warehouseUUID = sourceTargetUUID, style = MaterialTheme.typography.bodyMedium, textAlign = null) }, trailingContent = { IconButton(onClick = { showInfo = true }) { Icon(imageVector = Icons.Filled.Info, contentDescription = "Arrival Info") } } ) when { showInfo -> { if (productTransaction.transactionData != null && productTransaction.transaction != null) { ArrivalProductDialog( info = true, transactionState = TransactionState( uuid = productTransaction.transaction.uuid, transactionDetail = productTransaction.transaction.toTransactionDetail(), dataList = mutableListOf(productTransaction.transactionData.toTransactionDataDetail()) ), onDismissRequest = { showInfo = false }, transactionDataChange = {}, transactionDetailChange = {}, datePickerDialog = { }, toSupplierScreen = { }, saveArrival = {} ) } } } }
0
Kotlin
0
0
12e58c3753a642bfd922d9cca44486eef3453e88
5,644
self
Apache License 2.0
app/src/main/java/com/tcc/alif/data/util/StringExtension.kt
Limatucano
343,949,865
false
null
package com.tcc.alif.data.util import android.text.Editable import android.text.Html fun String?.emptyIfNull() : String = if(this == "null" || this == null) "" else this fun String.fromHtml() = Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT) fun Editable?.size(): Int{ if(this == null){ return 0 } return this.length }
0
Kotlin
0
4
a5774ef6e248f94d9e886bda5fcb972af6056c23
343
alif
MIT License
app/src/main/java/com/artf/chatapp/App.kt
CoderEslam
567,322,476
false
null
package com.artf.chatapp import android.app.Application import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import androidx.lifecycle.ProcessLifecycleOwner import com.google.firebase.database.FirebaseDatabase import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App : Application(), LifecycleObserver { /* * MD5: 52:E8:A1:D6:D2:42:41:E2:8B:DB:D7:AF:0E:57:BF:CE * SHA1: F3:67:56:60:18:49:2B:50:A0:DE:36:0A:9E:90:3E:F2:CC:EF:19:E9 * SHA-256: CB:58:70:BD:4E:65:3E:CB:95:AE:41:8D:62:F6:37:F1:E7:4C:9B:58:DC:99:17:1C:32:F3:00:A5:B8:81:AF:DB * */ companion object { var tempReceiverId: String? = null var receiverId: String? = null } override fun onCreate() { super.onCreate() ProcessLifecycleOwner.get().lifecycle.addObserver(this) FirebaseDatabase.getInstance().setPersistenceEnabled(true) } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onMoveToForeground() { receiverId = tempReceiverId } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun onMoveToBackground() { tempReceiverId = receiverId receiverId = null } }
0
Kotlin
0
0
e83e946c7fb843453764e9aaaeb481a458b5eecf
1,223
ChatApp-2-master
Apache License 2.0
properties/src/main/kotlin/net/aquadc/properties/executor/adapter.kt
Miha-x64
102,399,925
false
null
package net.aquadc.properties.executor import net.aquadc.properties.ChangeListener import net.aquadc.properties.diff.DiffChangeListener import net.aquadc.properties.internal.Unset import net.aquadc.properties.internal.unset import java.lang.UnsupportedOperationException import java.util.concurrent.Executor import java.util.concurrent.atomic.AtomicInteger internal class MapWhenChanged<in T, U, F : Any>( private val mapOn: Worker<F>, private val map: (T) -> U, private val consumer: (U) -> Unit ) : ChangeListener<T> { // we don't need atomic.getAndSet here because listeners are called strictly sequentially. // I'm even not sure whether volatile useful here @Volatile internal var running: F? = null override fun invoke(old: T, new: T) { running?.let(mapOn::cancel) running = mapOn.map(new, map, consumer) } fun cancel() { running?.let { mapOn.cancel(it) running = null } } } internal class ConsumeOn<in T>( private val consumeOn: Executor, private val consumer: (T) -> Unit ) : (T) -> Unit, Runnable { @Volatile private var value: T = unset() override fun invoke(value: T) { check(value !== Unset) this.value = value consumeOn.execute(this) } override fun run() { val value = value check(value !== this) consumer(value) } } /** * When invoked, calls [actual] on [executor]. */ internal class ConfinedChangeListener<in T, in D>( private val executor: Executor, @JvmField internal val actual: ChangeListener<T>?, @JvmField internal val actualDiff: DiffChangeListener<T, D>? ) : AtomicInteger(0), ChangeListener<T>, DiffChangeListener<T, D> { @Volatile @JvmField internal var canceled = false init { check(actual !is ConfinedChangeListener<*, *>) check(actualDiff !is ConfinedChangeListener<*, *>) } @Suppress("UNCHECKED_CAST") // it's safe because `actualDiff` listener is null in this case override fun invoke(old: T, new: T) { invoke(old, new, null as D) } override fun invoke(old: T, new: T, diff: D) { if (PlatformExecutors.getCurrent() === executor && get() == 0) { // call listener in-place, copying single-threaded properties' behaviour and creating less overhead // AtomicInteger keeps track of pending notifications. Can notify in-place only if there are 0 of them // TODO: write a test on this behaviour if (actual !== null) actual.invoke(old, new) else actualDiff!!.invoke(old, new, diff) } else { incrementAndGet() executor.execute { decrementAndGet() if (!canceled) { if (actual !== null) actual.invoke(old, new) else actualDiff!!.invoke(old, new, diff) } } } } // https://youtrack.jetbrains.com/issue/KT-16087 override fun toByte(): Byte = throw UnsupportedOperationException() override fun toChar(): Char = throw UnsupportedOperationException() override fun toShort(): Short = throw UnsupportedOperationException() } /** * Executes given command in-place. */ object UnconfinedExecutor : Executor { override fun execute(command: Runnable): Unit = command.run() }
11
Kotlin
10
118
d0a804271d0aaaa6368a2addce3ef7f081f5f560
3,465
Lychee
Apache License 2.0
app/src/main/java/com/example/android/politicalpreparedness/MyApplication.kt
tudang88
615,278,817
false
null
package com.example.android.politicalpreparedness import android.app.Application import androidx.lifecycle.SavedStateHandle import com.example.android.politicalpreparedness.database.ElectionDatabase import com.example.android.politicalpreparedness.election.ElectionsViewModel import com.example.android.politicalpreparedness.election.VoterInfoViewModel import com.example.android.politicalpreparedness.repository.ElectionsRepository import com.example.android.politicalpreparedness.representative.RepresentativeViewModel import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.dsl.module import timber.log.Timber class MyApplication : Application() { override fun onCreate() { super.onCreate() /** * use Koin for Dependency Injection */ val myModule = module { viewModel { ElectionsViewModel(get()) } viewModel { VoterInfoViewModel(get()) } viewModel { (handle:SavedStateHandle) -> RepresentativeViewModel(handle, get()) } // repository instance single { ElectionsRepository(get()) } // database instance single { ElectionDatabase.getInstance(this@MyApplication) } } startKoin { androidContext(this@MyApplication) modules(listOf(myModule)) } Timber.plant(Timber.DebugTree()) } }
0
Kotlin
0
0
284cda7122972dbffb95b9d4d06ae38c2315a3fb
1,578
PoliticalPreparedness
Apache License 2.0
gherkinatorbdd/src/main/java/com/codefirst/bdd/gherkinatorbdd/v2/GherkinatorEngine.kt
MichBogus
112,871,825
false
null
package com.codefirst.bdd.gherkinatorbdd.v2 import android.content.Context import com.codefirst.bdd.gherkinatorbdd.GherkinatorRobot import com.codefirst.bdd.gherkinatorbdd.v2.helper.FeatureFilePathHelper import com.codefirst.bdd.gherkinatorbdd.v2.scenarioprovider.FileReader import com.codefirst.bdd.gherkinatorbdd.v2.scenarioprovider.ScenarioProvider abstract class GherkinatorEngine(val context: Context) { private val featureFilePathHelper = FeatureFilePathHelper() private val featureFileReader = FileReader() private val scenarioProvider = ScenarioProvider() abstract var robots: MutableList<GherkinatorRobot>? abstract fun featureFileLocation(): String init { featureFilePathHelper.checkIfEmpty(this.featureFileLocation()) scenarioProvider.readScenarios(context, featureFilePathHelper.addFeatureFolderPrefixIfNotPresent(this.featureFileLocation())) } }
0
Kotlin
0
0
9ef9b85583f67662d91ed71ae4160500c35b5e0e
908
Gherkinator
Apache License 2.0
domain/src/main/kotlin/team/duckie/app/android/domain/recommendation/usecase/FetchRecommendationsUseCase.kt
duckie-team
503,869,663
false
{"Kotlin": 1819917}
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ package team.duckie.app.android.domain.recommendation.usecase import androidx.compose.runtime.Immutable import team.duckie.app.android.domain.recommendation.repository.RecommendationRepository import javax.inject.Inject @Immutable class FetchJumbotronsUseCase @Inject constructor( private val repository: RecommendationRepository, ) { suspend operator fun invoke() = runCatching { repository.fetchJumbotrons() } }
32
Kotlin
1
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
616
duckie-android
MIT License
testing/src/main/java/com/whiskersapps/sniffer/Testing.kt
Whiskers-Apps
841,668,228
false
{"Kotlin": 8502}
package com.whiskersapps.sniffer class Testing { }
0
Kotlin
0
1
e3d9c295d152924f6ce9eaf1bfb793d06ba940b9
51
sniffer-kt
MIT License
cryptoclient/src/main/java/com/sombrero/cryptoclient/CryptoService.kt
tonihuotari
145,533,443
false
null
package com.sombrero.cryptoclient import com.sombrero.cryptoclient.apimodels.ApiCoinListing import com.sombrero.cryptoclient.apimodels.ApiTickerListing import com.sombrero.cryptoclient.apimodels.ApiTickerSpecific import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Path interface CryptoService { @GET("v2/listings") fun getCoinListings(): Observable<ApiCoinListing> @GET("v2/ticker/?limit=10") fun getTicker10(): Observable<ApiTickerListing> @GET("v2/ticker/{id}") fun getTickerSpecific(@Path("id") id: Long): Observable<ApiTickerSpecific> }
0
Kotlin
0
0
87a64568167f481abb100447a901af433eea9ca3
597
crypto-cap
Apache License 2.0
app/src/main/java/com/tverona/scpanywhere/downloader/StateData.kt
tverona1
325,158,334
false
null
package com.tverona.scpanywhere.downloader /** * Object representing state of async downloading & other IO operations */ data class StateData<out T>(val status: Status, val data: T?, val error: Throwable?) { enum class Status { SUCCESS, ERROR, UPDATE } companion object { fun <T> success(data: T?): StateData<T> { return StateData(Status.SUCCESS, data, null) } fun <T> error(data: T?, err: Throwable?): StateData<T> { return StateData(Status.ERROR, data, err) } fun <T> update(data: T?): StateData<T> { return StateData(Status.UPDATE, data, null) } } }
1
Kotlin
0
6
6e8246b683ad46c2803fe69fc6890f915b280881
683
SCPAnywhere
MIT License
app/src/test/java/com/example/bookshelfapp/fake/FakeBookShelfRepository.kt
CyroPCJr
856,417,973
false
{"Kotlin": 23843}
package com.example.bookshelfapp.fake import com.example.bookshelfapp.data.BookShelfRepository import com.example.bookshelfapp.network.BookItem class FakeBookShelfRepository : BookShelfRepository { override suspend fun getVolumeBooks(query: String): List<BookItem> { return FakeDataSource.bookResponse.items } }
0
Kotlin
0
0
648deca515843bac409b6c95a9cd257f79aca587
330
BookShelfApp
MIT License
app/src/main/java/com/rumeysaozer/seyahatharitasi/model/Travel.kt
rumeysaozer0
505,480,200
false
null
package com.rumeysaozer.seyahatharitasi.model import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity class Travel ( var name : String, var explanation : String, var latittude: Double, var longtitude : Double ) : Serializable { @PrimaryKey(autoGenerate = true) var id = 0 }
0
Kotlin
0
0
0e93a7279502c6b81118e1e24b5d473ed45783f7
348
GoogleMaps
MIT License
app/src/main/java/org/ahivs/composeplayground/ui/row/SimpleRow.kt
laaptu
645,137,012
false
null
package org.ahivs.composeplayground.ui.row import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.layoutId import androidx.compose.ui.tooling.preview.Preview import java.util.Collections.min @Preview @Composable fun RowWithText() { val titleId = remember { "title" } val timeId = remember { "time" } Layout( content = { Text( text = "Title text is also growing now ", modifier = Modifier.layoutId(titleId) ) Text( text = "Time text is growing large and will it overlap", modifier = Modifier.layoutId(timeId) ) } ) { measurables, constraints -> val titleTextMeasurable: Measurable? = measurables.find { it.layoutId == titleId } val timeTextMeasurable: Measurable? = measurables.find { it.layoutId == timeId } var titleTextPlaceable: Placeable? = null var timeTextPlaceable: Placeable? = null val titleTextWidth = titleTextMeasurable?.measure(constraints.copy(maxWidth = Int.MAX_VALUE))?.also { titleTextPlaceable = it }?.width ?: 0 val timeTextWidth = timeTextMeasurable?.measure(constraints.copy(maxWidth = Int.MAX_VALUE))?.also { timeTextPlaceable = it }?.width ?: 0 val parentWidth = constraints.maxWidth val titleTextMaxWidth = (parentWidth * 0.6).toInt() val timeTextMaxWidth = (parentWidth * 0.4).toInt() val availableWidth = parentWidth - timeTextWidth val updatedTitleTextWidth = min(listOf(titleTextWidth, titleTextMaxWidth, availableWidth)) val updatedTimeTextWidth = min(listOf(timeTextWidth, timeTextMaxWidth, parentWidth - updatedTitleTextWidth)) layout(constraints.maxWidth, constraints.maxHeight) { titleTextPlaceable?.place(0, 0) timeTextPlaceable?.place(constraints.maxWidth - updatedTimeTextWidth, 0) } } }
0
Kotlin
0
0
b3e4e08082c61c11e98bf45ad43ab75030006cbb
2,225
learn-jetpack-compose
MIT License
rx/src/main/kotlin/com/github/fsbarata/functional/data/rx/SingleF.kt
fsbarata
277,280,202
false
{"Kotlin": 309214}
package com.github.fsbarata.functional.data.rx import com.github.fsbarata.functional.Context import com.github.fsbarata.functional.control.* import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.SingleObserver class SingleF<A: Any>(private val wrapped: Single<A>): Single<A>(), MonadZip<SingleContext, A> { override val scope get() = SingleF override fun subscribeActual(observer: SingleObserver<in A>) { wrapped.subscribe(observer) } override fun <B> map(f: (A) -> B) = wrapped.map { f(it)!! }.f() override fun <B, R> lift2(fb: Context<SingleContext, B>, f: (A, B) -> R): SingleF<R & Any> { return zipWith(fb, f) } override fun <B> ap(ff: Context<SingleContext, (A) -> B>): SingleF<B & Any> { return apFromLift2(SingleF, this, ff).asSingle } override infix fun <B> bind(f: (A) -> Context<SingleContext, B>): SingleF<B & Any> = flatMap { f(it) as Single<B & Any> } fun <B: Any> flatMap(f: (A) -> Single<B>): SingleF<B> = SingleF(wrapped.flatMap(f)) override fun <B, R> zipWith(other: Context<SingleContext, B>, f: (A, B) -> R): SingleF<R & Any> { return SingleF(wrapped.zipWith(other as Single<B & Any>) { a, b -> f(a, b)!! }) } companion object: MonadZip.Scope<SingleContext> { override fun <A> just(a: A): SingleF<A & Any> = SingleF(Single.just(a!!)) } } internal typealias SingleContext = Single<*> fun <A: Any> Single<A>.f() = SingleF(this) val <A> Context<SingleContext, A>.asSingle get() = this as SingleF<A & Any> operator fun <A: Any, B: Any, R: Any> Lift2<A, B, R>.invoke( single1: SingleF<A>, single2: SingleF<B>, ): SingleF<R> = app(single1, single2).asSingle operator fun <A: Any, B: Any, C: Any, R: Any> Lift3<A, B, C, R>.invoke( single1: SingleF<A>, single2: SingleF<B>, single3: SingleF<C>, ): SingleF<R> = app(single1, single2, single3).asSingle operator fun <A: Any, B: Any, C: Any, D: Any, R: Any> Lift4<A, B, C, D, R>.invoke( single1: SingleF<A>, single2: SingleF<B>, single3: SingleF<C>, single4: SingleF<D>, ): SingleF<R> = app(single1, single2, single3, single4).asSingle
0
Kotlin
2
0
9f3601b8c0fc26caf1b9303030313983a52cf2d9
2,068
kotlin-functional
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/AdjustmentsShare.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.AdjustmentsShare: ImageVector get() { if (_adjustmentsShare != null) { return _adjustmentsShare!! } _adjustmentsShare = Builder(name = "AdjustmentsShare", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 10.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, -4.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.0f, 4.0f) verticalLineToRelative(4.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(6.0f, 12.0f) verticalLineToRelative(8.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.387f, 14.56f) arcToRelative(2.0f, 2.0f, 0.0f, true, false, -0.798f, 3.352f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 4.0f) verticalLineToRelative(10.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 18.0f) verticalLineToRelative(2.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 7.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, -4.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 4.0f) verticalLineToRelative(1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 22.0f) lineToRelative(5.0f, -5.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 21.5f) verticalLineToRelative(-4.5f) horizontalLineToRelative(-4.5f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 9.0f) verticalLineToRelative(4.0f) } } .build() return _adjustmentsShare!! } private var _adjustmentsShare: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
5,544
compose-icon-collections
MIT License
discussions/discussions-adapter-input-rest-spring-mvc/src/main/kotlin/org/orkg/discussions/adapter/input/rest/representations.kt
TIBHannover
197,416,205
false
{"Kotlin": 2686425, "Cypher": 216726, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package org.orkg.discussions.adapter.input.rest import com.fasterxml.jackson.annotation.JsonProperty import java.time.OffsetDateTime import org.orkg.common.ContributorId import org.orkg.discussions.domain.DiscussionCommentId data class DiscussionCommentRepresentation( val id: DiscussionCommentId, val message: String, @JsonProperty("created_by") val createdBy: ContributorId, @JsonProperty("created_at") val createdAt: OffsetDateTime )
0
Kotlin
2
5
0df68801d82d8c36f6d3778d1971694b1b88b062
463
orkg-backend
MIT License
src/main/kotlin/com/example/domain/models/BaseResponse.kt
ToanBarcelona1998
858,525,458
false
{"Kotlin": 35566, "HTML": 73}
package com.example.domain.models import kotlinx.serialization.Serializable @Serializable data class BaseResponseSuccessful<T>(val message: String,val data: T , val code: Int = 200) @Serializable data class BaseResponseError<T>(val code : Int , val message: String , val data: T)
0
Kotlin
0
1
429ba08bbe2014211f50e39fd78cbed53192639a
281
fast-ai
MIT License
src/jsMain/kotlin/matt/file/file.kt
mgroth0
513,680,528
false
{"Kotlin": 96456}
package matt.file import matt.lang.model.file.FsFile actual fun FsFile.toIoFile(): IoFile = TODO()
0
Kotlin
0
0
6368a86e214f5aa032ef622f6ed27a9929e0788a
103
file
MIT License
app/src/main/java/com/engineerfred/kotlin/ktor/ui/navigation/AdminHomeNavGraph.kt
EngFred
763,078,300
false
{"Kotlin": 375304}
package com.engineerfred.kotlin.ktor.ui.navigation import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.engineerfred.kotlin.ktor.ui.screens.admin.admins.AdminsScreen import com.engineerfred.kotlin.ktor.ui.screens.admin.dashbord.AdminDashboardScreen import com.engineerfred.kotlin.ktor.ui.screens.student.students.AllStudentsScreen import com.engineerfred.kotlin.ktor.ui.viewModel.SharedViewModel @Composable fun AdminHomeNavigationGraph( modifier: Modifier = Modifier, sharedViewModel : SharedViewModel, navController: NavHostController ) { NavHost( navController = navController, route = Graph.ADMIN_HOME, startDestination = Routes.AdminDashBoardScreen.destination ) { composable( route = Routes.AdminDashBoardScreen.destination ) { AdminDashboardScreen( onMathCardClicked = { navController.navigate( "${Routes.QuestionsScreen.destination}/$it" ) { launchSingleTop = true } }, onEnglishCardClicked = { navController.navigate( "${Routes.QuestionsScreen.destination}/$it" ) { launchSingleTop = true } } ) } composable( route = Routes.AdminsScreen.destination ) { AdminsScreen(modifier) } composable( route = Routes.StudentsScreen.destination ) { AllStudentsScreen(modifier) } adminDetailNavGraph( navController ) } }
0
Kotlin
0
0
bf9031db3581709d5de44181361e1246850b6092
1,798
quiz-quest
MIT License
src/main/kotlin/co/anbora/labs/firebase/lang/core/psi/resolve/ref/Namespace.kt
anboralabs
302,825,861
false
null
package co.anbora.labs.firebase.lang.core.psi.resolve.ref sealed class Visibility { object Public : Visibility() object Internal : Visibility() } enum class Namespace { NAME, TYPE, SPEC_ITEM, SCHEMA, SCHEMA_FIELD, MODULE, STRUCT_FIELD, DOT_ACCESSED_FIELD; }
1
Kotlin
6
26
aca37769ce7578ff8f2e08a5d05890a18bf918fe
300
intellij-firebase-highlighter
MIT License