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
purchases/src/test/java/com/revenuecat/purchases/common/caching/InMemoryCachedObjectTest.kt
RevenueCat
127,346,826
false
null
package com.revenuecat.purchases.common.caching import com.revenuecat.purchases.Offerings import com.revenuecat.purchases.common.DateProvider import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.util.Date class InMemoryCachedObjectTest { // region clearCacheTimestamp @Test fun `cache timestamp is cleared correctly`() { val inMemoryCachedObject = InMemoryCachedObject<Offerings>() val date = Date() inMemoryCachedObject.updateCacheTimestamp(date) assertThat(inMemoryCachedObject.lastUpdatedAt).isEqualTo(date) inMemoryCachedObject.clearCacheTimestamp() assertThat(inMemoryCachedObject.lastUpdatedAt).isNull() } // endregion // region clearCache @Test fun `cache is cleared correctly`() { val inMemoryCachedObject = InMemoryCachedObject<Offerings>() assertThat(inMemoryCachedObject.cachedInstance).isNull() inMemoryCachedObject.cacheInstance(mockk()) inMemoryCachedObject.clearCache() assertThat(inMemoryCachedObject.cachedInstance).isNull() } // endregion // region cacheInstance @Test fun `instance is cached correctly`() { val inMemoryCachedObject = InMemoryCachedObject<Offerings>() assertThat(inMemoryCachedObject.cachedInstance).isNull() inMemoryCachedObject.cacheInstance(mockk()) assertThat(inMemoryCachedObject.cachedInstance).isNotNull } @Test fun `timestamp is set correctly when setting instance`() { val now = Date() val inMemoryCachedObject = InMemoryCachedObject<Offerings>(dateProvider = object : DateProvider { override val now: Date get() { return now } }) assertThat(inMemoryCachedObject.lastUpdatedAt).isNull() inMemoryCachedObject.cacheInstance(mockk()) assertThat(inMemoryCachedObject.lastUpdatedAt).isEqualTo(now) } // endregion // region updateCacheTimestamp @Test fun `timestamp is set correctly`() { val inMemoryCachedObject = InMemoryCachedObject<Offerings>() val date = Date() inMemoryCachedObject.updateCacheTimestamp(date) assertThat(inMemoryCachedObject.lastUpdatedAt).isEqualTo(date) } // endregion }
30
null
52
253
dad31133777389a224e9a570daec17f5c4c795ca
2,356
purchases-android
MIT License
18.ShareViewModel/app/src/main/java/com/jdc/share/model/StudentModel.kt
minlwin
233,192,363
false
null
package com.jdc.share.model import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import java.util.* class StudentModel:ViewModel() { val name = MutableLiveData<String>("Min Lwin") val entranceDate = MutableLiveData<Date>().also { it.value = Date() } val subject = MutableLiveData<String>("Android") val subjects = arrayOf("Java SE", "Java EE", "Spring", "Android") }
0
Kotlin
0
4
6971afb1b7a8602f7ea8dd207f346a803b941a63
423
acl3-data-binding
MIT License
Desenvolvimento Android/Cap 1 - O Mundo das Pequenas telas/08 - estruturas condicionais e de repetição/if-else.kt
fslaurafs
333,881,500
false
{"Jupyter Notebook": 59401, "JavaScript": 55135, "HTML": 48497, "Python": 19788, "Kotlin": 18635, "CSS": 10344, "C++": 785, "PHP": 559}
fun main(args: Array<String>) { // if - else - else if var number = 11 if (number % 2 == 0) { println("Ele é par") } else { println("Ele é ímpar") } var temperature = 18 var climate = "" if (temperature < 0 ) { climate = "Muito frio" } else if (temperature < 14) { climate = "Frio" } else if (temperature < 21) { climate = "Clima agradável" } else if (temperature < 30) { climate = "Um pouco quente" } else { climate = "Muito quente" } println("Temperatua: $temperature °C \tStatus: $climate") }
0
Jupyter Notebook
0
0
718458136eac36b5317ca2859e9f92be1524f60e
622
NanoCourses-FiapOn
MIT License
src/main/kotlin/dev/interfiber/karpet/server/player/PlayerBackpack.kt
KarpetPowered
490,243,114
false
{"Kotlin": 68475, "Shell": 362}
package dev.interfiber.karpet.server.player import net.minestom.server.coordinate.Pos import net.minestom.server.entity.ItemEntity import net.minestom.server.entity.Player import net.minestom.server.event.item.PickupItemEvent import net.minestom.server.instance.InstanceContainer import net.minestom.server.instance.block.Block import net.minestom.server.item.ItemStack import net.minestom.server.item.Material /** * Controls the players inventory, or backpack * @author Interfiber */ class PlayerBackpack { /** * Spawn a stack of items * @author Interfiber */ fun spawnItemStack(Type: Material?, Position: Pos, Container: InstanceContainer?) { val item = ItemEntity(ItemStack.of(Type!!)) item.setInstance(Container!!, Position) } /** * Called when a player picks up an item * @author Interfiber */ fun pickupItemCallback(PickupEvent: PickupItemEvent) { val targetPlayer: Player = PickupEvent.entity as Player val itemType = PickupEvent.itemStack.material() targetPlayer.inventory.addItemStack(ItemStack.of(itemType, 1)) } /** * Check if a player can mine a block * @author Interfiber */ fun canMineBlock(blockType: Block, player: Player): Boolean { val itemInHand = player.itemInMainHand return !(blockType == Block.IRON_ORE && itemInHand == ItemStack.of(Material.WOODEN_PICKAXE)) } }
0
Kotlin
1
8
1d0c1c2df4ad65d043150ebbb80b033c6ca86679
1,430
Karpet
MIT License
features/recipes/stepDetail/src/main/java/com/example/eziketobenna/bakingapp/stepdetail/presentation/mvi/StepDetailViewAction.kt
Ezike
270,478,922
false
null
package com.example.eziketobenna.bakingapp.stepdetail.presentation import com.example.eziketobenna.bakingapp.domain.model.Step import com.example.eziketobenna.bakingapp.presentation.mvi.ViewAction sealed class StepDetailViewAction : ViewAction { object Idle : StepDetailViewAction() data class LoadInitialViewAction(val index: Int, val steps: List<Step>, val step: Step) : StepDetailViewAction() data class GoToNextStepViewAction(val steps: List<Step>) : StepDetailViewAction() data class GoToPreviousStepViewAction(val steps: List<Step>) : StepDetailViewAction() }
1
null
79
432
ba1ee513d08f9d02141f914e3e58abde1abe4c14
593
Baking-App-Kotlin
Apache License 2.0
app/src/main/java/xyz/hetula/dragonair/city/CityManager.kt
hetula
185,856,171
false
null
package xyz.hetula.dragonair.city import android.content.Context import com.google.gson.Gson import xyz.hetula.dragonair.R import xyz.hetula.dragonair.util.GsonHelper import java.io.BufferedReader import java.io.InputStreamReader class CityManager { private val mCities = HashMap<Long, City>() fun loadCitiesSync(context: Context) { mCities.clear() BufferedReader(InputStreamReader(context.resources.openRawResource(R.raw.city_list))).use { GsonHelper.readCities(Gson(), it).forEach { city -> mCities[city.id] = city } } } fun getCity(id: Long) = mCities[id] }
0
Kotlin
0
0
7ce1fba3fcb73621efbbc0d2794e151e83f1da2a
645
wforweather
Apache License 2.0
app/src/main/java/com/rektapps/assaulttimer/notifications/ClickedNotificationEntity.kt
N3-M3-S1S
199,498,741
false
null
package com.rektapps.assaulttimer.notifications import com.rektapps.assaulttimer.model.enums.AssaultType import com.rektapps.assaulttimer.model.enums.Region data class ClickedNotificationEntity(val region: Region, val assaultType: AssaultType)
0
Kotlin
0
0
54c188e671558de43b63ea75993ec28591d8601d
245
assault_timer
MIT License
src/test/kotlin/org/springframework/data/mapping/model/PreferredConstructorDiscovererUnitTests.kt
spring-projects
1,072,614
false
null
/* * Copyright 2017-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.mapping.model import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.data.annotation.PersistenceConstructor import org.springframework.data.mapping.model.AbstractPersistentPropertyUnitTests.SamplePersistentProperty /** * Unit tests for [PreferredConstructorDiscoverer]. * * @author <NAME> */ class PreferredConstructorDiscovererUnitTests { @Test // DATACMNS-1126 fun `should discover simple constructor`() { val constructor = PreferredConstructorDiscoverer.discover<Simple, SamplePersistentProperty>(Simple::class.java) assertThat(constructor!!.parameters.size).isEqualTo(1) } @Test // DATACMNS-1126 fun `should reject two constructors`() { val constructor = PreferredConstructorDiscoverer.discover<TwoConstructors, SamplePersistentProperty>(TwoConstructors::class.java) assertThat(constructor!!.parameters.size).isEqualTo(1) } @Test // DATACMNS-1170 fun `should fall back to no-args constructor if no primary constructor available`() { val constructor = PreferredConstructorDiscoverer.discover<TwoConstructorsWithoutDefault, SamplePersistentProperty>( TwoConstructorsWithoutDefault::class.java ) assertThat(constructor!!.parameters).isEmpty() } @Test // DATACMNS-1126 fun `should discover annotated constructor`() { val constructor = PreferredConstructorDiscoverer.discover<AnnotatedConstructors, SamplePersistentProperty>( AnnotatedConstructors::class.java ) assertThat(constructor!!.parameters.size).isEqualTo(2) } @Test // DATACMNS-1126 fun `should discover default constructor`() { val constructor = PreferredConstructorDiscoverer.discover<DefaultConstructor, SamplePersistentProperty>(DefaultConstructor::class.java) assertThat(constructor!!.parameters.size).isEqualTo(1) } @Test // DATACMNS-1126 fun `should discover default annotated constructor`() { val constructor = PreferredConstructorDiscoverer.discover<TwoDefaultConstructorsAnnotated, SamplePersistentProperty>( TwoDefaultConstructorsAnnotated::class.java ) assertThat(constructor!!.parameters.size).isEqualTo(3) } @Test // DATACMNS-1171 @Suppress("UNCHECKED_CAST") fun `should not resolve constructor for synthetic Kotlin class`() { val c = Class.forName("org.springframework.data.mapping.model.TypeCreatingSyntheticClassKt") as Class<Any> val constructor = PreferredConstructorDiscoverer.discover<Any, SamplePersistentProperty>(c) assertThat(constructor).isNull() } @Test // DATACMNS-1800, GH-2215 @ExperimentalUnsignedTypes fun `should discover constructor for class using unsigned types`() { val constructor = PreferredConstructorDiscoverer.discover<UnsignedTypesEntity, SamplePersistentProperty>( UnsignedTypesEntity::class.java ) assertThat(constructor).isNotNull() } data class Simple(val firstname: String) class TwoConstructorsWithoutDefault { var firstname: String? = null constructor() {} constructor(firstname: String?) { this.firstname = firstname } } class TwoConstructors(val firstname: String) { constructor(firstname: String, lastname: String) : this(firstname) } class AnnotatedConstructors(val firstname: String) { @PersistenceConstructor constructor(firstname: String, lastname: String) : this(firstname) } class DefaultConstructor(val firstname: String = "foo") class TwoDefaultConstructorsAnnotated( val firstname: String = "foo", val lastname: String = "bar" ) { @PersistenceConstructor constructor(firstname: String = "foo", lastname: String = "bar", age: Int) : this( firstname, lastname ) } @ExperimentalUnsignedTypes data class UnsignedTypesEntity( val id: String, val a: UInt = 5u, val b: Int = 5, val c: Double = 1.5 ) }
195
null
674
775
07a5c58903e5bd5741b80f6119fce167ee0e110d
4,431
spring-data-commons
Apache License 2.0
src/test/kotlin/de/bringmeister/spring/aws/kinesis/metrics/MetricsInboundHandlerTest.kt
bringmeister
125,221,797
false
null
package de.bringmeister.spring.aws.kinesis.metrics import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import de.bringmeister.spring.aws.kinesis.KinesisInboundHandler import de.bringmeister.spring.aws.kinesis.Record import de.bringmeister.spring.aws.kinesis.TestKinesisInboundHandler import io.micrometer.core.instrument.Tags import io.micrometer.core.instrument.simple.SimpleMeterRegistry import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.Test class MetricsInboundHandlerTest { private val registry = SimpleMeterRegistry() private val mockDelegate = mock<KinesisInboundHandler<Any, Any>> { on { stream } doReturn "test" } private val mockTagsProvider = mock<KinesisTagsProvider> { } private val handler = MetricsInboundHandler(mockDelegate, registry, mockTagsProvider) private val record = Record(Any(), Any()) private val context = TestKinesisInboundHandler.TestExecutionContext() @Test fun `should time calls to delegate`() { val tags = Tags.of("test", "should time calls to delegate") whenever(mockTagsProvider.inboundTags("test", record, context, null)).thenReturn(tags) handler.handleRecord(record, context) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.inbound" && tags == Tags.of(it.tags) } } @Test fun `should count successful calls to delegate`() { val tags = Tags.of("test", "should count successful calls to delegate") whenever(mockTagsProvider.inboundTags("test", record, context, null)).thenReturn(tags) handler.handleRecord(record, context) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.inbound" && tags == Tags.of(it.tags) } } @Test fun `should count failed calls to delegate and bubble exception`() { val tags = Tags.of("test", "should count failed calls to delegate and bubble exception") whenever(mockTagsProvider.inboundTags("test", record, context, MyException)).thenReturn(tags) whenever(mockDelegate.handleRecord(record, context)).doThrow(MyException) assertThatCode { handler.handleRecord(record, context) } .isSameAs(MyException) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.inbound" && tags == Tags.of(it.tags) } } @Test fun `should count deserialization failures, call delegate and bubble exceptions`() { val tags = Tags.of("test", "should count deserialization failures, call delegate and bubble exceptions") val delegateException = RuntimeException("expected") whenever(mockTagsProvider.inboundTags("test", null, context, MyException)).thenReturn(tags) whenever(mockDelegate.handleDeserializationError(MyException, context)).doThrow(delegateException) assertThatCode { handler.handleDeserializationError(MyException, context) } .isSameAs(delegateException) assertThat(registry.meters.map { it.id }) .anyMatch { it.name == "aws.kinesis.starter.inbound" && tags == Tags.of(it.tags) } } @Test fun `should invoke delegate`() { handler.handleRecord(record, context) verify(mockDelegate).handleRecord(record, context) } private object MyException : RuntimeException() }
4
null
6
24
bb706ff599811f333363530bec9a9c3ec475ea37
3,608
aws-kinesis-spring-boot-starter
MIT License
kotlin-history/src/main/generated/history/HashHistory.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! package history /** * A hash history stores the current location in the fragment identifier portion * of the URL in a web browser environment. * * This is ideal for apps that do not control the server for some reason * (because the fragment identifier is never sent to the server), including some * shared hosting environments that do not provide fine-grained controls over * which pages are served at which URLs. * * @see https://github.com/ReactTraining/history/tree/master/docs/api-reference.md#hashhistory */ external interface HashHistory : History
11
null
135
916
a1c5ba66f49ba16a50f7ce42acc82eefb8a32604
610
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/example/gallery/ui/SettingsActivity.kt
Lmh170
482,977,075
false
{"Kotlin": 135906}
package org.kenvyra.gallery.ui import android.os.Bundle import android.provider.SearchRecentSuggestions import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import org.kenvyra.gallery.MySuggestionProvider import org.kenvyra.gallery.R class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_activity) if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .replace(R.id.settings, SettingsFragment()) .commit() } supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.root_preferences, rootKey) val btnClearHistory: Preference? = findPreference("clear_search_history") btnClearHistory?.setOnPreferenceClickListener { SearchRecentSuggestions( context, MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE ) .clearHistory() return@setOnPreferenceClickListener true } } } }
5
Kotlin
4
12
411c5be3c5f80ad8d7240e1b1397e59767187a16
1,764
Android-Gallery-App
MIT License
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/DuplicateCaseInWhenSpec.kt
winterDroid
101,381,574
true
{"Kotlin": 238835, "Java": 163}
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.rules.CommonSpec import org.jetbrains.spek.subject.SubjectSpek import org.jetbrains.spek.subject.itBehavesLike /** * @author <NAME> */ class DuplicateCaseInWhenSpec : SubjectSpek<DuplicateCaseInWhenExpression>({ subject { DuplicateCaseInWhenExpression(Config.empty) } itBehavesLike(CommonSpec()) })
0
Kotlin
2
0
95857d9d64888a42d8bf6ade0e5eb5adcc28a32c
433
detekt-old
Apache License 2.0
app/src/main/java/io/dwak/hoverlauncher/app/LauncherMenuService.kt
burntcookie90
130,277,693
false
null
package io.dwak.hoverlauncher.app import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.arch.lifecycle.GenericLifecycleObserver import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.ServiceLifecycleDispatcher import android.content.Intent import android.os.Build import android.os.IBinder import android.support.v4.app.NotificationCompat import dagger.android.AndroidInjection import io.mattcarroll.hover.HoverView import io.mattcarroll.hover.window.HoverMenuService import timber.log.Timber import javax.inject.Inject class LauncherMenuService : HoverMenuService(), LifecycleOwner { private val lifecycleDispatcher = ServiceLifecycleDispatcher(this) @Inject lateinit var launcherViewModel: LauncherViewModel override fun onCreate() { lifecycleDispatcher.onServicePreSuperOnCreate() super.onCreate() AndroidInjection.inject(this) lifecycleDispatcher.lifecycle.addObserver(GenericLifecycleObserver { _, event -> Timber.d("event: $event") }) } override fun onHoverMenuLaunched(intent: Intent, hoverView: HoverView) { val menu = LauncherMenu(launcherViewModel, this, this, { hoverView.collapse() }) hoverView.setMenu(menu) hoverView.collapse() } override fun onBind(intent: Intent?): IBinder? { lifecycleDispatcher.onServicePreSuperOnBind() return super.onBind(intent) } override fun onStart(intent: Intent?, startId: Int) { lifecycleDispatcher.onServicePreSuperOnStart() super.onStart(intent, startId) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { lifecycleDispatcher.onServicePreSuperOnDestroy() super.onDestroy() } override fun getForegroundNotification(): Notification? { val builder = NotificationCompat.Builder(this, "launcher-foreground") .setContentText("Hover Launcher is running") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel("launcher-foreground", "Launcher Foreground Notification", NotificationManager.IMPORTANCE_MIN) builder.setChannelId(channel.id) getSystemService(NotificationManager::class.java).createNotificationChannel(channel) } return builder.build() } override fun getLifecycle(): Lifecycle = lifecycleDispatcher.lifecycle }
0
Kotlin
0
3
169319f72869cf847c74cb7eb1a1ff9de2252ce2
2,512
floating-launcher
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/BarberShop.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.BarberShop: ImageVector get() { if (_barberShop != null) { return _barberShop!! } _barberShop = Builder(name = "BarberShop", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(20.0f, 8.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(2.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 0.0f, 3.0f) horizontalLineToRelative(-2.5f) verticalLineToRelative(2.0f) horizontalLineToRelative(2.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 0.0f, 3.0f) horizontalLineToRelative(-2.5f) verticalLineToRelative(4.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, -3.0f, 0.0f) verticalLineToRelative(-18.0f) arcToRelative(4.505f, 4.505f, 0.0f, false, true, 4.5f, -4.5f) horizontalLineToRelative(1.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 0.0f, 3.0f) horizontalLineToRelative(-1.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, -1.5f, 1.5f) verticalLineToRelative(0.5f) horizontalLineToRelative(2.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 0.0f, 3.0f) close() moveTo(16.0f, 19.25f) arcToRelative(4.736f, 4.736f, 0.0f, false, true, -8.0f, 3.45f) arcToRelative(4.739f, 4.739f, 0.0f, true, true, -5.8f, -7.442f) curveToRelative(1.154f, -1.4f, 2.712f, -3.5f, 4.013f, -5.474f) curveToRelative(-1.723f, -2.838f, -3.213f, -5.955f, -3.213f, -8.284f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 3.0f, 0.0f) curveToRelative(0.0f, 1.308f, 0.827f, 3.268f, 2.0f, 5.365f) curveToRelative(1.173f, -2.1f, 2.0f, -4.058f, 2.0f, -5.365f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 3.0f, 0.0f) curveToRelative(0.0f, 2.329f, -1.491f, 5.447f, -3.217f, 8.281f) curveToRelative(1.3f, 1.975f, 2.858f, 4.077f, 4.013f, 5.473f) arcToRelative(4.739f, 4.739f, 0.0f, false, true, 2.204f, 3.996f) close() moveTo(6.5f, 19.25f) arcToRelative(1.75f, 1.75f, 0.0f, true, false, -1.75f, 1.75f) arcToRelative(1.752f, 1.752f, 0.0f, false, false, 1.75f, -1.75f) close() moveTo(8.0f, 15.8f) arcToRelative(4.753f, 4.753f, 0.0f, false, true, 1.649f, -1.0f) curveToRelative(-0.5f, -0.658f, -1.063f, -1.438f, -1.649f, -2.284f) curveToRelative(-0.586f, 0.846f, -1.152f, 1.626f, -1.649f, 2.284f) arcToRelative(4.753f, 4.753f, 0.0f, false, true, 1.649f, 1.0f) close() moveTo(13.0f, 19.246f) arcToRelative(1.75f, 1.75f, 0.0f, true, false, -1.75f, 1.754f) arcToRelative(1.752f, 1.752f, 0.0f, false, false, 1.75f, -1.75f) close() } } .build() return _barberShop!! } private var _barberShop: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,117
icons
MIT License
settings-presentation/src/main/java/com/infinitepower/newquiz/settings_presentation/SettingsScreenUiEvent.kt
joaomanaia
443,198,327
false
null
package com.infinitepower.newquiz.settings_presentation sealed interface SettingsScreenUiEvent { object DownloadTranslationModel : SettingsScreenUiEvent object DeleteTranslationModel : SettingsScreenUiEvent object SignOut : SettingsScreenUiEvent object ClearWordleCalendarItems : SettingsScreenUiEvent data class EnableLoggingAnalytics( val enabled: Boolean ) : SettingsScreenUiEvent }
2
Kotlin
8
62
0dfff8721f37d61e8328f620ec3dd5a4d2f2c151
423
newquiz
Apache License 2.0
core/ui/src/main/java/org/expenny/core/ui/base/ExpennyDrawerManager.kt
expenny-application
712,607,222
false
{"Kotlin": 1159082}
package org.expenny.core.ui.base import androidx.compose.animation.core.TweenSpec import androidx.compose.material3.DrawerState import androidx.compose.material3.DrawerValue import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.res.painterResource import androidx.navigation.NavController import androidx.navigation.compose.currentBackStackEntryAsState import com.ramcosta.composedestinations.spec.NavGraphSpec import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.expenny.core.resources.R class ExpennyDrawerManager( val drawer: DrawerState, private val tabs: List<NavGraphSpec>, private val navController: NavController, private val coroutineScope: CoroutineScope ) { val isDrawerTab: Boolean get() { return navController.currentBackStackEntry?.destination?.route in tabs.map { it.startRoute.route } } val isDrawerTabAsState: Boolean @Composable get() { return tabs .map { it.startRoute.route } .contains(navController.currentBackStackEntryAsState().value?.destination?.route) } @Composable fun NavigationDrawerIcon() { IconButton( onClick = { animateTo(DrawerValue.Open) } ) { Icon( painter = painterResource(R.drawable.ic_menu), tint = MaterialTheme.colorScheme.onSurface, contentDescription = null ) } } fun animateTo(value: DrawerValue, onFinish: () -> Unit = {}) { coroutineScope.launch { drawer.animateTo(value, TweenSpec(200)) }.invokeOnCompletion { onFinish() } } }
0
Kotlin
3
42
0eb0f1fa9a4376c3ad2222d16ec704754f7f0786
1,856
expenny-android
Apache License 2.0
examples/testapp/src/main/java/saas/test/app/utils/Resource.kt
digime
198,619,583
false
{"Kotlin": 198719}
package me.digi.saas.utils /** * Utility class that helps us handle UI components */ sealed class Resource<out T>(val data: T? = null, val message: String? = null) { class Idle<out T> : Resource<T>() class Loading<out T> : Resource<T>() class Success<out T>(data: T) : Resource<T>(data) class Failure<out T>(message: String?, data: T? = null) : Resource<T>(data, message) }
0
Kotlin
3
1
dd0b82f0c991547c220d09408b63996b758a4c0d
392
digime-sdk-android
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-idea-proto/src/test/kotlin/org/jetbrains/kotlin/gradle/idea/proto/kpm/FragmentTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.idea.proto.kpm import org.jetbrains.kotlin.gradle.idea.kpm.* import org.jetbrains.kotlin.gradle.idea.proto.AbstractSerializationTest import org.jetbrains.kotlin.gradle.idea.testFixtures.kpm.TestIdeaKpmInstances import kotlin.test.Test import kotlin.test.assertEquals class FragmentTest : AbstractSerializationTest<IdeaKpmFragment>() { override fun serialize(value: IdeaKpmFragment) = value.toByteArray(this) override fun deserialize(data: ByteArray) = IdeaKpmFragment(data) @Test fun `serialize - deserialize - sample 0`() { testDeserializedEquals(TestIdeaKpmInstances.simpleFragment) } @Test fun `serialize - deserialize - sample 1`() { testDeserializedEquals(TestIdeaKpmInstances.fragmentWithExtras) } private fun testDeserializedEquals(value: IdeaKpmFragmentImpl) { val deserialized = IdeaKpmFragment(value.toByteArray(this)) val normalized = value.copy( dependencies = value.dependencies.map { if (it !is IdeaKpmResolvedBinaryDependency) return@map it IdeaKpmResolvedBinaryDependencyImpl( coordinates = it.coordinates, binaryType = it.binaryType, binaryFile = it.binaryFile.absoluteFile, extras = it.extras ) }, languageSettings = (value.languageSettings as IdeaKpmLanguageSettingsImpl).copy( compilerPluginClasspath = value.languageSettings.compilerPluginClasspath.map { it.absoluteFile } ), contentRoots = value.contentRoots .map { it as IdeaKpmContentRootImpl } .map { it.copy(file = it.file.absoluteFile) } ) assertEquals(normalized, deserialized) } }
157
null
5608
45,423
2db8f31966862388df4eba2702b2f92487e1d401
2,036
kotlin
Apache License 2.0
json-model-generator/src/main/kotlin/eft/weapons/builds/BuildModelsAnnotationProcessor.kt
neonailol
207,225,209
false
{"Kotlin": 55401}
package eft.weapons.builds import com.google.auto.service.AutoService import java.io.File import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Processor import javax.annotation.processing.RoundEnvironment import javax.annotation.processing.SupportedAnnotationTypes import javax.annotation.processing.SupportedOptions import javax.annotation.processing.SupportedSourceVersion import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import javax.tools.Diagnostic @Target(AnnotationTarget.FUNCTION) annotation class BuildModels @AutoService(Processor::class) @SupportedSourceVersion(SourceVersion.RELEASE_11) @SupportedAnnotationTypes("eft.weapons.builds.BuildModels") @SupportedOptions(BuildModelsAnnotationProcessor.KAPT_KOTLIN_GENERATED_OPTION_NAME) class BuildModelsAnnotationProcessor : AbstractProcessor() { companion object { const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated" } override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { val annotatedElements = roundEnv.getElementsAnnotatedWith(BuildModels::class.java) if (annotatedElements.isEmpty()) return false val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] ?: run { processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, "Can't find the target directory for generated Kotlin files.") return false } parseBytes(File(kaptKotlinGeneratedDir)) return true } }
0
Kotlin
1
0
1254d1157a7478360480d2a4a84aad590a95e201
1,587
eft-codex
MIT License
afterpay/src/main/kotlin/com/afterpay/android/internal/AfterpayInstalment.kt
afterpay
279,474,371
false
null
package com.afterpay.android.internal import java.math.BigDecimal import java.math.RoundingMode import java.text.DecimalFormat import java.text.NumberFormat import java.util.Currency internal sealed class AfterpayInstalment { data class Available( val instalmentAmount: String ) : AfterpayInstalment() data class NotAvailable( val minimumAmount: String?, val maximumAmount: String ) : AfterpayInstalment() object NoConfiguration : AfterpayInstalment() companion object { fun of(totalCost: BigDecimal, configuration: Configuration?): AfterpayInstalment { if (configuration == null) { return NoConfiguration } val currencyLocale = Locales.validSet.first { Currency.getInstance(it) == configuration.currency } val currencySymbol = configuration.currency.getSymbol(currencyLocale) val usCurrencySymbol = Currency.getInstance(Locales.US).getSymbol(Locales.US) val localCurrency = Currency.getInstance(configuration.locale) val currencyFormatter = (NumberFormat.getCurrencyInstance(currencyLocale) as DecimalFormat).apply { this.currency = configuration.currency } if (configuration.locale == Locales.US) { currencyFormatter.apply { decimalFormatSymbols = decimalFormatSymbols.apply { this.currencySymbol = when (configuration.currency) { Currency.getInstance(Locales.AUSTRALIA) -> "A$" Currency.getInstance(Locales.NEW_ZEALAND) -> "NZ$" Currency.getInstance(Locales.CANADA) -> "CA$" else -> currencySymbol } } } } else if (currencySymbol == usCurrencySymbol && configuration.currency != localCurrency) { currencyFormatter.apply { this.applyPattern("¤#,##0.00 ¤¤") } } val minimumAmount = configuration.minimumAmount ?: BigDecimal.ZERO if (totalCost < minimumAmount || totalCost > configuration.maximumAmount) { return NotAvailable( minimumAmount = configuration.minimumAmount?.let(currencyFormatter::format), maximumAmount = currencyFormatter.format(configuration.maximumAmount) ) } val instalment = (totalCost / 4.toBigDecimal()).setScale(2, RoundingMode.HALF_EVEN) return Available(instalmentAmount = currencyFormatter.format(instalment)) } } }
0
Kotlin
1
4
14236a9eb95ec8d3a0c886f18a376a15fe572fd6
2,700
sdk-android
Apache License 2.0
recursion/src/main/java/com/github/ch8n/recursion/extension.kt
ch8n
557,463,156
false
null
package com.github.ch8n.recursion inline fun Int.ifZero(action: () -> Unit) { if (this == 0) { action.invoke() } }
0
Kotlin
0
1
b0cf5d46ee1321509931cfab80f4229d181f16fc
131
DataStructureKT
Adobe Glyph List License
platform/util/ui/src/com/intellij/util/ui/StartupUiUtil.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package com.intellij.util.ui import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfoRt import com.intellij.ui.JreHiDpiUtil import com.intellij.ui.scale.JBUIScale import com.intellij.ui.scale.ScaleContext import com.intellij.ui.scale.ScaleType import com.intellij.ui.scale.isHiDPIEnabledAndApplicable import com.intellij.util.JBHiDPIScaledImage import org.jetbrains.annotations.ApiStatus.Internal import java.awt.* import java.awt.event.AWTEventListener import java.awt.event.InputEvent import java.awt.event.KeyEvent import java.awt.geom.AffineTransform import java.awt.image.BufferedImage import java.awt.image.BufferedImageOp import java.awt.image.ImageObserver import java.util.* import javax.swing.InputMap import javax.swing.KeyStroke import javax.swing.UIDefaults import javax.swing.UIManager import javax.swing.plaf.FontUIResource import javax.swing.text.DefaultEditorKit import javax.swing.text.StyleContext import kotlin.math.abs import kotlin.math.max import kotlin.math.pow import kotlin.math.roundToInt object StartupUiUtil { @Internal @JvmField val patchableFontResources: Array<String> = arrayOf("Button.font", "ToggleButton.font", "RadioButton.font", "CheckBox.font", "ColorChooser.font", "ComboBox.font", "Label.font", "List.font", "MenuBar.font", "MenuItem.font", "MenuItem.acceleratorFont", "RadioButtonMenuItem.font", "CheckBoxMenuItem.font", "Menu.font", "PopupMenu.font", "OptionPane.font", "Panel.font", "ProgressBar.font", "ScrollPane.font", "Viewport.font", "TabbedPane.font", "Table.font", "TableHeader.font", "TextField.font", "FormattedTextField.font", "Spinner.font", "PasswordField.font", "TextArea.font", "TextPane.font", "EditorPane.font", "TitledBorder.font", "ToolBar.font", "ToolTip.font", "Tree.font") @JvmStatic val isUnderDarcula: Boolean get() = UIManager.getLookAndFeel().name.contains("Darcula") @Internal @JvmStatic fun doGetLcdContrastValueForSplash(isUnderDarcula: Boolean): Int { if (SystemInfoRt.isMac) { return if (isUnderDarcula) 140 else 230 } @Suppress("SpellCheckingInspection") val lcdContrastValue = (Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints") as? Map<*, *>) ?.get(RenderingHints.KEY_TEXT_LCD_CONTRAST) as Int? ?: return 140 return normalizeLcdContrastValue(lcdContrastValue) } @JvmStatic fun normalizeLcdContrastValue(lcdContrastValue: Int): Int { return if (lcdContrastValue < 100 || lcdContrastValue > 250) 140 else lcdContrastValue } /** * Returns whether the JRE-managed HiDPI mode is enabled and the default monitor device is HiDPI. * (Analogue of [UIUtil.isRetina] on macOS) */ @JvmStatic val isJreHiDPI: Boolean get() = isHiDPIEnabledAndApplicable(JBUIScale.sysScale()) /** * Returns whether the JRE-managed HiDPI mode is enabled and the provided component is tied to a HiDPI device. */ @JvmStatic fun isJreHiDPI(component: Component?): Boolean = JreHiDpiUtil.isJreHiDPI(component?.graphicsConfiguration) /** * Returns whether the JRE-managed HiDPI mode is enabled and the provided system scale context is HiDPI. */ @JvmStatic fun isJreHiDPI(scaleContext: ScaleContext?): Boolean { return isHiDPIEnabledAndApplicable(scaleContext?.getScale(ScaleType.SYS_SCALE)?.toFloat() ?: JBUIScale.sysScale()) } @JvmStatic fun getCenterPoint(container: Dimension, child: Dimension): Point { return getCenterPoint(Rectangle(container), child) } @JvmStatic fun getCenterPoint(container: Rectangle, child: Dimension): Point { return Point(container.x + (container.width - child.width) / 2, container.y + (container.height - child.height) / 2) } /** * A hidpi-aware wrapper over [Graphics.drawImage]. * * @see .drawImage */ @JvmStatic fun drawImage(g: Graphics, image: Image, x: Int, y: Int, observer: ImageObserver?) { drawImage(g = g, image = image, x = x, y = y, sourceBounds = null, op = null, observer = observer) } @JvmStatic fun drawImage(g: Graphics, image: Image, x: Int, y: Int, width: Int, height: Int, op: BufferedImageOp?) { val srcBounds = if (width >= 0 && height >= 0) Rectangle(x, y, width, height) else null drawImage(g = g, image = image, x = x, y = y, dw = width, dh = height, sourceBounds = srcBounds, op = op, observer = null) } @JvmStatic fun drawImage(g: Graphics, image: Image) { drawImage(g = g, image = image, x = 0, y = 0, width = -1, height = -1, op = null) } /** * A hidpi-aware wrapper over [Graphics.drawImage]. * * @see .drawImage */ @JvmStatic fun drawImage(g: Graphics, image: Image, dstBounds: Rectangle?, observer: ImageObserver?) { drawImage(g = g, image = image, destinationBounds = dstBounds, sourceBounds = null, op = null, observer = observer) } /** * @see .drawImage */ @JvmStatic fun drawImage(g: Graphics, image: Image, dstBounds: Rectangle?, srcBounds: Rectangle?, observer: ImageObserver?) { drawImage(g = g, image = image, destinationBounds = dstBounds, sourceBounds = srcBounds, op = null, observer = observer) } /** * @see .drawImage */ @JvmStatic fun drawImage(g: Graphics, image: BufferedImage, op: BufferedImageOp?, x: Int, y: Int) { drawImage(g = g, image = image, x = x, y = y, dw = -1, dh = -1, sourceBounds = null, op = op, observer = null) } @JvmStatic val labelFont: Font get() = UIManager.getFont("Label.font") @JvmStatic fun isDialogFont(font: Font): Boolean = Font.DIALOG == font.getFamily(Locale.US) @JvmStatic fun initInputMapDefaults(defaults: UIDefaults) { // Make ENTER work in JTrees val treeInputMap = defaults.get("Tree.focusInputMap") as InputMap? treeInputMap?.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "toggle") // Cut/Copy/Paste in JTextAreas val textAreaInputMap = defaults.get("TextArea.focusInputMap") as InputMap? if (textAreaInputMap != null) { // It really can be null, for example, when LAF isn't properly initialized (an Alloy license problem) installCutCopyPasteShortcuts(textAreaInputMap, false) } // Cut/Copy/Paste in JTextFields val textFieldInputMap = defaults.get("TextField.focusInputMap") as InputMap? if (textFieldInputMap != null) { // It really can be null, for example, when LAF isn't properly initialized (an Alloy license problem) installCutCopyPasteShortcuts(textFieldInputMap, false) } // Cut/Copy/Paste in JPasswordField val passwordFieldInputMap = defaults.get("PasswordField.focusInputMap") as InputMap? if (passwordFieldInputMap != null) { // It really can be null, for example, when LAF isn't properly initialized (an Alloy license problem) installCutCopyPasteShortcuts(passwordFieldInputMap, false) } // Cut/Copy/Paste in JTables val tableInputMap = defaults.get("Table.ancestorInputMap") as InputMap? if (tableInputMap != null) { // It really can be null, for example, when LAF isn't properly initialized (an Alloy license problem) installCutCopyPasteShortcuts(tableInputMap, true) } } private fun installCutCopyPasteShortcuts(inputMap: InputMap, useSimpleActionKeys: Boolean) { val copyActionKey = if (useSimpleActionKeys) "copy" else DefaultEditorKit.copyAction val pasteActionKey = if (useSimpleActionKeys) "paste" else DefaultEditorKit.pasteAction val cutActionKey = if (useSimpleActionKeys) "cut" else DefaultEditorKit.cutAction // Ctrl+Ins, Shift+Ins, Shift+Del inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, InputEvent.CTRL_DOWN_MASK), copyActionKey) inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, InputEvent.SHIFT_DOWN_MASK), pasteActionKey) inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.SHIFT_DOWN_MASK), cutActionKey) // Ctrl+C, Ctrl+V, Ctrl+X inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK), copyActionKey) inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_DOWN_MASK), pasteActionKey) inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_DOWN_MASK), DefaultEditorKit.cutAction) } @JvmStatic fun initFontDefaults(defaults: UIDefaults, uiFont: FontUIResource) { defaults["Tree.ancestorInputMap"] = null val textFont = FontUIResource(uiFont) val monoFont = FontUIResource("Monospaced", Font.PLAIN, uiFont.size) for (fontResource in patchableFontResources) { defaults[fontResource] = uiFont } if (!SystemInfoRt.isMac) { defaults["PasswordField.font"] = monoFont } defaults["TextArea.font"] = monoFont defaults["TextPane.font"] = textFont defaults["EditorPane.font"] = textFont } @JvmStatic fun getFontWithFallback(familyName: String?, @Suppress("DEPRECATION") @org.intellij.lang.annotations.JdkConstants.FontStyle style: Int, size: Float): FontUIResource { // On macOS font fallback is implemented in JDK by default // (except for explicitly registered fonts, e.g. the fonts we bundle with IDE, for them, we don't have a solution now) // in headless mode just use fallback in order to avoid font loading val fontWithFallback = if (SystemInfoRt.isMac || GraphicsEnvironment.isHeadless()) Font(familyName, style, size.toInt()).deriveFont( size) else StyleContext().getFont(familyName, style, size.toInt()).deriveFont(size) return if (fontWithFallback is FontUIResource) fontWithFallback else FontUIResource(fontWithFallback) } @JvmStatic fun addAwtListener(listener: AWTEventListener, mask: Long, parent: Disposable) { Toolkit.getDefaultToolkit().addAWTEventListener(listener, mask) Disposer.register(parent) { Toolkit.getDefaultToolkit().removeAWTEventListener(listener) } } } @Internal fun drawImage(g: Graphics, image: Image, destinationBounds: Rectangle?, sourceBounds: Rectangle?, op: BufferedImageOp?, observer: ImageObserver?) { if (destinationBounds == null) { drawImage(g = g, image = image, sourceBounds = sourceBounds, op = op, observer = observer) } else { drawImage(g = g, image = image, x = destinationBounds.x, y = destinationBounds.y, dw = destinationBounds.width, dh = destinationBounds.height, sourceBounds = sourceBounds, op = op, observer = observer) } } private val useAccuracyDelta = System.getProperty("ide.icon.scale.useAccuracyDelta", "true").toBoolean() /** * A hidpi-aware wrapper over [Graphics.drawImage]. * * The `dstBounds` and `srcBounds` are in the user space (just like the width/height of the image). * If `dstBounds` is null or if its width/height is set to (-1) the image bounds or the image width/height is used. * If `srcBounds` is null or if its width/height is set to (-1) the image bounds or the image right/bottom area to the provided x/y is used. */ @Internal fun drawImage(g: Graphics, image: Image, x: Int = 0, y: Int = 0, dw: Int = -1, dh: Int = -1, sourceBounds: Rectangle? = null, op: BufferedImageOp? = null, observer: ImageObserver? = null) { val hasDestinationSize = dw >= 0 && dh >= 0 if (image is JBHiDPIScaledImage) { doDrawHiDpi(userWidth = image.getUserWidth(), userHeight = image.getUserHeight(), g = g, scale = image.scale, dx = x, dy = y, dw = dw, dh = dh, hasDestinationSize = hasDestinationSize, op = op, image = image.delegate ?: image, srcBounds = sourceBounds, observer = observer) } else { doDraw(op = op, image = image, invG = null, hasDestinationSize = hasDestinationSize, dw = dw, dh = dh, sourceBounds = sourceBounds, userWidth = image.getWidth(null), userHeight = image.getHeight(null), g = g, dx = x, dy = y, observer = observer, scale = 1.0) } } @Suppress("NAME_SHADOWING") private fun doDrawHiDpi(userWidth: Int, userHeight: Int, g: Graphics, scale: Double, dx: Int, dy: Int, dw: Int, dh: Int, hasDestinationSize: Boolean, op: BufferedImageOp?, image: Image, srcBounds: Rectangle?, observer: ImageObserver?) { var g1 = g var scale1 = scale var dx1 = dx var dy1 = dy var delta = 0.0 if (useAccuracyDelta) { // Calculate the delta based on the image size. The bigger the size - the smaller the delta. val maxSize = max(userWidth, userHeight) if (maxSize < Int.MAX_VALUE / 2) { var dotAccuracy = 1 var pow: Double while (maxSize > 10.0.pow(dotAccuracy.toDouble()).also { pow = it }) { dotAccuracy++ } delta = 1 / pow } } val tx = (g1 as Graphics2D).transform var invG: Graphics2D? = null if ((tx.type and AffineTransform.TYPE_MASK_ROTATION) == 0 && abs(scale1 - tx.scaleX) <= delta) { scale1 = tx.scaleX // The image has the same original scale as the graphics scale. However, the real image // scale - userSize/realSize - can suffer from inaccuracy due to the image user size // rounding to int (userSize = (int)realSize/originalImageScale). This may case quality // loss if the image is drawn via Graphics.drawImage(image, <srcRect>, <dstRect>) // due to scaling in Graphics. To avoid that, the image should be drawn directly via // Graphics.drawImage(image, 0, 0) on the unscaled Graphics. val gScaleX = tx.scaleX val gScaleY = tx.scaleY tx.scale(1 / gScaleX, 1 / gScaleY) tx.translate(dx1 * gScaleX, dy1 * gScaleY) dy1 = 0 dx1 = 0 invG = g1.create() as Graphics2D g1 = invG invG.transform = tx } try { var dw = dw var dh = dh if (invG != null && hasDestinationSize) { dw = scaleSize(dw, scale1) dh = scaleSize(dh, scale1) } doDraw(op = op, image = image, invG = invG, hasDestinationSize = hasDestinationSize, dw = dw, dh = dh, sourceBounds = srcBounds, userWidth = userWidth, userHeight = userHeight, g = g1, dx = dx1, dy = dy1, observer = observer, scale = scale1) } finally { invG?.dispose() } } private fun scaleSize(size: Int, scale: Double) = (size * scale).roundToInt() @Suppress("NAME_SHADOWING") private fun doDraw(op: BufferedImageOp?, image: Image, invG: Graphics2D?, hasDestinationSize: Boolean, dw: Int, dh: Int, sourceBounds: Rectangle?, userWidth: Int, userHeight: Int, g: Graphics, dx: Int, dy: Int, observer: ImageObserver?, scale: Double) { var image = image if (op != null && image is BufferedImage) { image = op.filter(image, null) } when { sourceBounds != null -> { fun size(size: Int) = scaleSize(size, scale) val sx = size(sourceBounds.x) val sy = size(sourceBounds.y) val sw = if (sourceBounds.width >= 0) size(sourceBounds.width) else size(userWidth) - sx val sh = if (sourceBounds.height >= 0) size(sourceBounds.height) else size(userHeight) - sy var dw = dw var dh = dh if (!hasDestinationSize) { dw = size(userWidth) dh = size(userHeight) } g.drawImage(/* img = */ image, /* dx1 = */ dx, /* dy1 = */ dy, /* dx2 = */ dx + dw, /* dy2 = */ dy + dh, /* sx1 = */ sx, /* sy1 = */ sy, /* sx2 = */ sx + sw, /* sy2 = */ sy + sh, /* observer = */ observer) } hasDestinationSize -> { g.drawImage(image, dx, dy, dw, dh, observer) } invG == null -> { g.drawImage(image, dx, dy, userWidth, userHeight, observer) } else -> { g.drawImage(image, dx, dy, observer) } } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
17,336
intellij-community
Apache License 2.0
service/src/test/kotlin/no/nav/su/se/bakover/service/søknadsbehandling/SøknadsbehandlingServiceOppdaterStønadsperiodeTest.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.service.søknadsbehandling import arrow.core.left import arrow.core.right import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import no.nav.su.se.bakover.common.juni import no.nav.su.se.bakover.common.mars import no.nav.su.se.bakover.common.periode.Periode import no.nav.su.se.bakover.domain.søknadsbehandling.Stønadsperiode import no.nav.su.se.bakover.service.argThat import no.nav.su.se.bakover.service.sak.FantIkkeSak import no.nav.su.se.bakover.test.TestSessionFactory import no.nav.su.se.bakover.test.getOrFail import no.nav.su.se.bakover.test.stønadsperiode2021 import no.nav.su.se.bakover.test.søknadsbehandlingVilkårsvurdertInnvilget import no.nav.su.se.bakover.test.søknadsbehandlingVilkårsvurdertUavklart import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doNothing import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.util.UUID internal class SøknadsbehandlingServiceOppdaterStønadsperiodeTest { @Test fun `svarer med feil hvis man ikke finner sak`() { val (sak, behandling) = søknadsbehandlingVilkårsvurdertUavklart() SøknadsbehandlingServiceAndMocks( sakService = mock { on { hentSak(any<UUID>()) } doReturn FantIkkeSak.left() }, ).let { it.søknadsbehandlingService.oppdaterStønadsperiode( SøknadsbehandlingService.OppdaterStønadsperiodeRequest( behandlingId = behandling.id, stønadsperiode = stønadsperiode2021, sakId = sak.id, ), ) shouldBe SøknadsbehandlingService.KunneIkkeOppdatereStønadsperiode.FantIkkeSak.left() verify(it.sakService).hentSak(sak.id) it.verifyNoMoreInteractions() } } @Test fun `oppdaterer stønadsperiode for behandling, grunnlagsdata og vilkårsvurderinger`() { val (sak, vilkårsvurdert) = søknadsbehandlingVilkårsvurdertInnvilget() val nyStønadsperiode = Stønadsperiode.create( periode = Periode.create(1.juni(2021), 31.mars(2022)), begrunnelse = "begg", ) SøknadsbehandlingServiceAndMocks( sakService = mock { on { hentSak(any<UUID>()) } doReturn sak.right() }, søknadsbehandlingRepo = mock { on { defaultTransactionContext() } doReturn TestSessionFactory.transactionContext }, grunnlagService = mock { doNothing().whenever(it).lagreBosituasjongrunnlag(any(), any()) } ).let { it -> val response = it.søknadsbehandlingService.oppdaterStønadsperiode( SøknadsbehandlingService.OppdaterStønadsperiodeRequest( behandlingId = vilkårsvurdert.id, stønadsperiode = nyStønadsperiode, sakId = sak.id, ), ).getOrFail() vilkårsvurdert.stønadsperiode.periode shouldNotBe nyStønadsperiode verify(it.sakService).hentSak(sak.id) verify(it.søknadsbehandlingRepo).defaultTransactionContext() verify(it.søknadsbehandlingRepo).lagre( argThat { it shouldBe response it.stønadsperiode shouldBe nyStønadsperiode it.vilkårsvurderinger.let { vilkårsvurderinger -> vilkårsvurderinger.uføre.grunnlag.all { it.periode == nyStønadsperiode.periode } shouldBe true vilkårsvurderinger.formue.grunnlag.all { it.periode == nyStønadsperiode.periode } shouldBe true } }, anyOrNull(), ) verify(it.grunnlagService).lagreBosituasjongrunnlag( argThat { it shouldBe vilkårsvurdert.id }, argThat { bosituasjon -> bosituasjon.all { it.periode == nyStønadsperiode.periode } shouldBe true }, ) verify(it.grunnlagService).lagreFradragsgrunnlag( argThat { it shouldBe vilkårsvurdert.id }, argThat { fradrag -> fradrag.all { it.periode == nyStønadsperiode.periode } shouldBe true }, ) it.verifyNoMoreInteractions() } } }
4
null
0
1
d7157394e11b5b3c714a420a96211abb0a53ea45
4,515
su-se-bakover
MIT License
src/client/kotlin/com/cheat/features/SwitchTool.kt
xRetart
760,102,686
false
{"Kotlin": 27144, "Java": 1018}
package com.cheat.features import com.cheat.utility.findInHotbarBy import net.minecraft.block.BlockState import net.minecraft.client.MinecraftClient import net.minecraft.client.network.ClientPlayerEntity import net.minecraft.item.SwordItem import net.minecraft.util.hit.BlockHitResult import net.minecraft.util.hit.EntityHitResult // Feature, dass für den Spieler automatisch das zum anvisierten Block/Entität passende Werkzeug/Schwert auswählt class SwitchTool(override var isEnabled: Boolean) : Feature { override val description: String = "Du wechselst automatisch auf das passende Werkzeug/Schwert in deiner Hotbar." override fun onTick(client: MinecraftClient) { val world = client.world ?: return val player = client.player ?: return val crosshairTarget = client.crosshairTarget if (crosshairTarget is BlockHitResult) { // Guckt der Spieler auf einen Block? val blockHitResult = crosshairTarget val blockState = world.getBlockState(blockHitResult.blockPos) if (!blockState.isAir) { // Ist der etwas außer Luft? // rüstet optimales Werkzeug aus findOptimalToolSlot(player, blockState)?.let { slot -> player.inventory.selectedSlot = slot } } } else if (crosshairTarget is EntityHitResult) { // Guckt der Spieler auf eine Entität? // rüstet bestes schwert aus findStrongestSword(player)?.let { slot -> player.inventory.selectedSlot = slot } } } // gibt die Slotnummer des Werkzeuges an, welches sich am besten für den Block eignet private fun findOptimalToolSlot(player: ClientPlayerEntity, blockState: BlockState?): Int? { return findInHotbarBy(player.inventory) { stack -> stack.getMiningSpeedMultiplier(blockState) } } // gibt die Slotnummer des Schwertes mit dem meisten Schaden an private fun findStrongestSword(player: ClientPlayerEntity): Int? { return findInHotbarBy(player.inventory) { stack -> if (stack.item is SwordItem) { // Ist der Gegenstand ein Schwert? (stack.item as SwordItem).attackDamage } else { 0.5f // default Schaden = 1/2 Herz } } } }
0
Kotlin
0
1
07e485609627442300f738d9c18ba3b0069715fd
2,319
informatikcheat
Creative Commons Zero v1.0 Universal
idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/IfThenToSafeAccessIntention.kt
gigliovale
89,726,097
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class IfThenToSafeAccessInspection : IntentionBasedInspection<KtIfExpression>(IfThenToSafeAccessIntention()) class IfThenToSafeAccessIntention : SelfTargetingOffsetIndependentIntention<KtIfExpression>(KtIfExpression::class.java, "Replace 'if' expression with safe access expression") { override fun isApplicableTo(element: KtIfExpression): Boolean { val condition = element.condition as? KtBinaryExpression ?: return false val thenClause = element.then val elseClause = element.`else` val receiverExpression = condition.expressionComparedToNull() ?: return false if (!receiverExpression.isStableVariable()) return false return when (condition.operationToken) { KtTokens.EQEQ -> thenClause?.isNullExpressionOrEmptyBlock() ?: true && elseClause != null && clauseContainsAppropriateDotQualifiedExpression(elseClause, receiverExpression) KtTokens.EXCLEQ -> elseClause?.isNullExpressionOrEmptyBlock() ?: true && thenClause != null && clauseContainsAppropriateDotQualifiedExpression(thenClause, receiverExpression) else -> false } } override fun applyTo(element: KtIfExpression, editor: Editor?) { val condition = element.condition as KtBinaryExpression val receiverExpression = condition.expressionComparedToNull()!! val selectorExpression = when(condition.operationToken) { KtTokens.EQEQ -> findSelectorExpressionInClause(element.`else`!!, receiverExpression)!! KtTokens.EXCLEQ -> findSelectorExpressionInClause(element.then!!, receiverExpression)!! else -> throw IllegalArgumentException() } val newExpr = KtPsiFactory(element).createExpressionByPattern("$0?.$1", receiverExpression, selectorExpression) as KtSafeQualifiedExpression val safeAccessExpr = element.replaced(newExpr) if (editor != null) { safeAccessExpr.inlineReceiverIfApplicableWithPrompt(editor) } } private fun clauseContainsAppropriateDotQualifiedExpression(clause: KtExpression, receiverExpression: KtExpression) = findSelectorExpressionInClause(clause, receiverExpression) != null private fun findSelectorExpressionInClause(clause: KtExpression, receiverExpression: KtExpression): KtExpression? { val expression = clause.unwrapBlockOrParenthesis() as? KtDotQualifiedExpression ?: return null if (expression.receiverExpression.text != receiverExpression.text) return null return expression.selectorExpression } }
1
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
3,765
kotlin
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/sam/CfnFunctionTableStreamSAMPTPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.sam import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.sam.CfnFunction /** * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.sam.*; * TableSAMPTProperty tableSAMPTProperty = TableSAMPTProperty.builder() * .tableName("tableName") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-serverless-function-tablesampt.html) */ @CdkDslMarker public class CfnFunctionTableSAMPTPropertyDsl { private val cdkBuilder: CfnFunction.TableSAMPTProperty.Builder = CfnFunction.TableSAMPTProperty.builder() /** @param tableName the value to be set. */ public fun tableName(tableName: String) { cdkBuilder.tableName(tableName) } public fun build(): CfnFunction.TableSAMPTProperty = cdkBuilder.build() }
3
Kotlin
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,240
awscdk-dsl-kotlin
Apache License 2.0
snapshots/sample/ui-module/src/androidTest/kotlin/com/emergetools/snapshots/sample/ui/GreetingPreview.kt
EmergeTools
645,957,551
false
{"Kotlin": 255570}
package com.emergetools.snapshots.sample.ui import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview @Preview @Composable fun GreetingPreviewFromAndroidTest() { Greeting("AndroidTest") }
3
Kotlin
1
9
8174b9c6e2d7791e01363aabd4d287736bfa38c4
228
emerge-android
Apache License 2.0
app/src/main/java/com/saxenasachin/redditpics/ui/SplashActivity.kt
saxenasachin
505,074,064
false
null
package com.saxenasachin.redditpics.ui import android.os.Bundle import android.os.Handler import androidx.appcompat.app.AppCompatActivity import com.saxenasachin.redditpics.databinding.ActivitySplashBinding /** Created by <NAME> on 19/06/22. */ class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivitySplashBinding.inflate(layoutInflater) setContentView(binding.root) goToMainActivity() } private fun goToMainActivity() { Handler().postDelayed({ DashboardActivity.getStartIntent(this).apply { startActivity(this) } finish() }, SPLASH_WAITING_TIME ) } companion object { private const val SPLASH_WAITING_TIME = 2000L // 2 seconds. } }
0
Kotlin
0
1
99b570d65bd646877af765e71b1674e3a4113a1c
890
Reddit-PIcs-Browser
Apache License 2.0
src/main/kotlin/com/mineinabyss/blocky/BlockyCommandExecutor.kt
MineInAbyss
468,482,997
false
{"Kotlin": 178711}
package com.mineinabyss.blocky import com.github.shynixn.mccoroutine.bukkit.launch import com.mineinabyss.blocky.components.core.BlockyFurniture import com.mineinabyss.blocky.components.features.blocks.BlockyDirectional import com.mineinabyss.blocky.helpers.gearyInventory import com.mineinabyss.blocky.menus.BlockyMainMenu import com.mineinabyss.blocky.systems.BlockyBlockQuery.prefabKey import com.mineinabyss.blocky.systems.BlockyQuery import com.mineinabyss.blocky.systems.blockyModelEngineQuery import com.mineinabyss.geary.papermc.tracking.items.gearyItems import com.mineinabyss.geary.prefabs.PrefabKey import com.mineinabyss.geary.prefabs.prefabs import com.mineinabyss.guiy.inventory.guiy import com.mineinabyss.idofront.commands.arguments.optionArg import com.mineinabyss.idofront.commands.arguments.stringArg import com.mineinabyss.idofront.commands.execution.IdofrontCommandExecutor import com.mineinabyss.idofront.commands.extensions.actions.playerAction import com.mineinabyss.idofront.items.editItemMeta import com.mineinabyss.idofront.messaging.error import com.mineinabyss.idofront.messaging.success import com.mineinabyss.idofront.plugin.actions import org.bukkit.Color import org.bukkit.command.Command import org.bukkit.command.CommandSender import org.bukkit.command.TabCompleter import org.bukkit.entity.Player import org.bukkit.inventory.EquipmentSlot import org.bukkit.inventory.meta.LeatherArmorMeta import org.bukkit.inventory.meta.MapMeta import org.bukkit.inventory.meta.PotionMeta class BlockyCommandExecutor : IdofrontCommandExecutor(), TabCompleter { override val commands = commands(blocky.plugin) { ("blocky")(desc = "Commands related to Blocky-plugin") { "reload" { fun reloadConfig() { blocky.plugin.createBlockyContext() blocky.plugin.runStartupFunctions() sender.success("Blocky configs has been reloaded!") } fun reloadItems() { blocky.plugin.launch { BlockyQuery.forEach { prefabs.loader.reread(it.entity) } sender.success("Blocky items have been reloaded!") } } "all" { actions { reloadItems() reloadConfig() } } "config" { actions { reloadConfig() } } "items" { actions { reloadItems() } } } "give" { val type by optionArg(options = BlockyQuery.filter { it.entity.get<BlockyDirectional>()?.isParentBlock != false } .map { it.prefabKey.toString() }) { parseErrorMessage = { "No such block: $passed" } } playerAction { if (player.inventory.firstEmpty() == -1) { player.error("No empty slots in inventory") return@playerAction } val item = gearyItems.createItem(PrefabKey.of(type)) if (item == null) { player.error("$type exists but is not a block.") return@playerAction } player.inventory.addItem(item) } } "dye" { val color by stringArg() playerAction { val player = sender as? Player ?: return@playerAction val item = player.inventory.itemInMainHand val furniture = player.gearyInventory?.get(EquipmentSlot.HAND)?.get<BlockyFurniture>() if (furniture == null) { player.error("This command only supports furniture.") return@playerAction } item.editItemMeta { (this as? LeatherArmorMeta)?.setColor(color.toColor) ?: (this as? PotionMeta)?.setColor(color.toColor) ?: (this as? MapMeta)?.setColor(color.toColor) ?: return@playerAction } player.success("Dyed item to <$color>$color") } } "menu" { playerAction { val player = sender as Player guiy { BlockyMainMenu(player) } } } } } override fun onTabComplete( sender: CommandSender, command: Command, alias: String, args: Array<out String> ): List<String> { return if (command.name == "blocky") { when (args.size) { 1 -> listOf("reload", "give", "dye", "menu").filter { it.startsWith(args[0]) } 2 -> { when (args[0]) { "reload" -> listOf("all", "config", "items").filter { it.startsWith(args[1]) } "give" -> BlockyQuery.filter { val arg = args[1].lowercase() (it.prefabKey.key.startsWith(arg) || it.prefabKey.full.startsWith(arg)) && it.entity.get<BlockyDirectional>()?.isParentBlock != false }.map { it.prefabKey.toString() } "menu" -> emptyList() else -> emptyList() } } 3 -> { when (args[0]) { "modelengine" -> blockyModelEngineQuery.filter { it.startsWith(args[2]) } else -> emptyList() } } else -> emptyList() } } else emptyList() } private val String.toColor: Color get() { return when { this.startsWith("#") -> return Color.fromRGB(this.substring(1).toInt(16)) this.startsWith("0x") -> return Color.fromRGB(this.substring(2).toInt(16)) "," in this -> { val colorString = this.replace(" ", "").split(",") if (colorString.any { it.toIntOrNull() == null }) return Color.WHITE try { Color.fromRGB( minOf(colorString[0].toInt(), 255), minOf(colorString[1].toInt(), 255), minOf(colorString[2].toInt(), 255) ) } catch (e: NumberFormatException) { Color.WHITE } } //TODO Make this support text, probably through minimessage else -> return Color.WHITE } } }
8
Kotlin
0
3
a848b556befb7dff5cbd261fe4dba8091c1b70da
7,137
Blocky
MIT License
app/src/main/java/com/mindbodyonline/workshop/ui/theme/Icon.kt
MINDBODY-Mobile
361,985,948
false
null
package com.mindbodyonline.workshop.ui.theme
0
Kotlin
0
1
d0a95229fbd6c728fdccc378c0712dc7dc47aec7
46
2021-Engineering-Summit-Workshop
Apache License 2.0
vid-app-common/src/main/java/org/onap/vid/job/command/RootServiceCommand.kt
onap
115,762,948
false
null
package org.onap.vid.job.command import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate import org.onap.vid.job.Job import org.onap.vid.job.JobAdapter import org.onap.vid.job.JobCommand import org.onap.vid.job.JobsBrokerService import org.onap.vid.job.impl.JobSharedData import org.onap.vid.model.Action import org.onap.vid.model.serviceInstantiation.ServiceInstantiation import org.onap.vid.mso.RestMsoImplementation import org.onap.vid.services.AsyncInstantiationBusinessLogic import org.onap.vid.services.AuditService import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpMethod import org.togglz.core.manager.FeatureManager import java.util.* abstract class RootServiceCommand @Autowired constructor( restMso: RestMsoImplementation, inProgressStatusService: InProgressStatusService, msoResultHandlerService: MsoResultHandlerService, watchChildrenJobsBL: WatchChildrenJobsBL, jobsBrokerService: JobsBrokerService, jobAdapter: JobAdapter, private val asyncInstantiationBL: AsyncInstantiationBusinessLogic, private val auditService: AuditService, private val msoRequestBuilder: MsoRequestBuilder, featureManager: FeatureManager ) : ResourceCommand(restMso, inProgressStatusService, msoResultHandlerService, watchChildrenJobsBL, jobsBrokerService, jobAdapter, featureManager), JobCommand { lateinit var optimisticUniqueServiceInstanceName: String companion object { private val LOGGER = EELFLoggerDelegate.getLogger(RootServiceCommand::class.java) } final override fun onInitial(phase: Action) { if (phase== Action.Delete) { asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, Job.JobStatus.IN_PROGRESS) } } final override fun getExternalInProgressStatus() = Job.JobStatus.IN_PROGRESS final override fun getData(): Map<String, Any?> { return super.getData() + mapOf(UNIQUE_INSTANCE_NAME to optimisticUniqueServiceInstanceName) } final override fun onFinal(jobStatus: Job.JobStatus) { asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, jobStatus) if (jobStatus.isFailure) { asyncInstantiationBL.handleFailedInstantiation(sharedData.jobUuid) } } final override fun init(sharedData: JobSharedData, commandData: Map<String, Any>): ResourceCommand { optimisticUniqueServiceInstanceName = commandData.getOrDefault(UNIQUE_INSTANCE_NAME, "") as String return super<ResourceCommand>.init(sharedData, commandData) } final override fun isServiceCommand(): Boolean = true final override fun getExpiryChecker(): ExpiryChecker { return ServiceExpiryChecker() } override fun resumeMyself(): Job.JobStatus { val requestType = "createInstance" val scope = "service" val serviceInstanceId = getActualInstanceId(getRequest()) try { val requests = auditService.retrieveRequestsFromMsoByServiceIdAndRequestTypeAndScope(serviceInstanceId, requestType, scope) if (requests.isEmpty() || requests[0].requestId == null) { LOGGER.error("Failed to retrieve requestId with type: $type, scope: $scope for service instanceId $serviceInstanceId ") return Job.JobStatus.FAILED } val createMyselfCommand = planResumeMyselfRestCall(requests[0].requestId, sharedData.userId) return executeAndHandleMsoInstanceRequest(createMyselfCommand) } catch (exception: Exception) { LOGGER.error("Failed to resume instanceId $serviceInstanceId ", exception) return Job.JobStatus.FAILED } } private fun planResumeMyselfRestCall(requestId: String, userId: String): MsoRestCallPlan { val path = asyncInstantiationBL.getResumeRequestPath(requestId) return MsoRestCallPlan(HttpMethod.POST, path, Optional.empty(), Optional.of(userId), "resume request $requestId") } override fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan { val requestDetailsWrapper = msoRequestBuilder.generateServiceDeletionRequest( request as ServiceInstantiation, userId ) val path = asyncInstantiationBL.getServiceDeletionPath(request.instanceId) return MsoRestCallPlan(HttpMethod.DELETE, path, Optional.of(requestDetailsWrapper), Optional.empty(), "delete instance with id ${request.instanceId}") } }
4
null
5
6
8cef7fbeed5b8f1255535fcf1cf0c7304df6d447
4,640
archived-vid
Apache License 2.0
mordant/src/commonMain/kotlin/com/github/ajalt/mordant/terminal/TerminalColors.kt
ajalt
104,693,921
false
null
package com.github.ajalt.mordant.terminal import com.github.ajalt.colormath.Color import com.github.ajalt.mordant.internal.DEFAULT_STYLE import com.github.ajalt.mordant.internal.downsample import com.github.ajalt.mordant.rendering.TextColors import com.github.ajalt.mordant.rendering.TextStyle import com.github.ajalt.mordant.rendering.TextStyles import com.github.ajalt.mordant.rendering.Theme /** * TextStyles that are automatically downsampled to the level supported by the current terminal. * * Strings decorated with these styles will be downsampled correctly even if they are printed * directly rather than through [Terminal.print]. */ class TerminalColors internal constructor( // TODO(3.0): remove private val terminalInfo: TerminalInfo, private val theme: Theme, ) { val black: TextStyle get() = downsample(TextColors.black) val red: TextStyle get() = downsample(TextColors.red) val green: TextStyle get() = downsample(TextColors.green) val yellow: TextStyle get() = downsample(TextColors.yellow) val blue: TextStyle get() = downsample(TextColors.blue) val magenta: TextStyle get() = downsample(TextColors.magenta) val cyan: TextStyle get() = downsample(TextColors.cyan) val white: TextStyle get() = downsample(TextColors.white) val gray: TextStyle get() = downsample(TextColors.gray) val brightRed: TextStyle get() = downsample(TextColors.brightRed) val brightGreen: TextStyle get() = downsample(TextColors.brightGreen) val brightYellow: TextStyle get() = downsample(TextColors.brightYellow) val brightBlue: TextStyle get() = downsample(TextColors.brightBlue) val brightMagenta: TextStyle get() = downsample(TextColors.brightMagenta) val brightCyan: TextStyle get() = downsample(TextColors.brightCyan) val brightWhite: TextStyle get() = downsample(TextColors.brightWhite) /** Render text with the [success][Theme.success] style from the current theme */ val success get(): TextStyle = downsample(theme.success) /** Render text with the [danger][Theme.danger] style from the current theme */ val danger get(): TextStyle = downsample(theme.danger) /** Render text with the [warning][Theme.warning] style from the current theme */ val warning get(): TextStyle = downsample(theme.warning) /** Render text with the [info][Theme.info] style from the current theme */ val info get(): TextStyle = downsample(theme.info) /** Render text with the [muted][Theme.muted] style from the current theme */ val muted: TextStyle get() = downsample(theme.muted) /** * Render text as bold or increased intensity. * * Might be rendered as a different color instead of a different font weight. */ val bold: TextStyle get() = downsample(TextStyles.bold.style) /** * Render text as faint or decreased intensity. * * Not widely supported. */ val dim: TextStyle get() = downsample(TextStyles.dim.style) /** * Render text as italic. * * Not widely supported, might be rendered as inverse instead of italic. */ val italic: TextStyle get() = downsample(TextStyles.italic.style) /** * Underline text. * * Might be rendered with different colors instead of underline. */ val underline: TextStyle get() = downsample(TextStyles.underline.style) /** Render text with background and foreground colors switched. */ val inverse: TextStyle get() = downsample(TextStyles.inverse.style) /** * Render text with a strikethrough. * * Not widely supported. */ val strikethrough: TextStyle get() = downsample(TextStyles.strikethrough.style) /** * No style. */ val plain: TextStyle get() = DEFAULT_STYLE /** @param hex An rgb hex string in the form "#ffffff" or "ffffff" */ fun rgb(hex: String): TextStyle = TextColors.rgb(hex, level) /** * Create a color code from an RGB color. * * @param r The red amount, in the range `[0, 1]` * @param g The green amount, in the range `[0, 1]` * @param b The blue amount, in the range `[0, 1]` */ fun rgb(r: Number, g: Number, b: Number): TextStyle = TextColors.rgb(r, g, b, level) /** * Create a color code from an HSL color. * * @param h The hue, in the range `[0, 360]` * @param s The saturation, in the range `[0, 1]` * @param l The lightness, in the range `[0, 1]` */ fun hsl(h: Number, s: Number, l: Number): TextStyle = TextColors.hsl(h, s, l, level) /** * Create a color code from an HSV color. * * @param h The hue, in the range `[0, 360]` * @param s The saturation, in the range `[0, 1]` * @param v The value, in the range `[0, 1]` */ fun hsv(h: Number, s: Number, v: Number): TextStyle = TextColors.hsv(h, s, v, level) /** * Create a color code from a CMYK color. * * @param c The cyan amount, in the range `[0, 100]` * @param m The magenta amount, in the range `[0, 100]` * @param y The yellow amount, in the range `[0, 100]` * @param k The black amount, in the range `[0, 100]` */ fun cmyk(c: Int, m: Int, y: Int, k: Int): TextStyle = TextColors.cmyk(c, m, y, k, level) /** * Create a grayscale color code from a fraction in the range \[0, 1]. * * @param fraction The fraction of white in the color. 0 is pure black, 1 is pure white. */ fun gray(fraction: Number): TextStyle = TextColors.gray(fraction, level) /** * Create a color code from a CIE XYZ color. * * Conversions use D65 reference white, and sRGB profile. * * [x], [y], and [z] are generally in the interval `[0, 1]` */ fun xyz(x: Number, y: Number, z: Number): TextStyle = TextColors.xyz(x, y, z, level) /** * Create a color code from a CIE LAB color. * * Conversions use D65 reference white, and sRGB profile. * * [l] is in the interval `[0, 100]`. [a] and [b] have unlimited range, * but are generally in `[-100, 100]` */ fun lab(l: Number, a: Number, b: Number): TextStyle = TextColors.lab(l, a, b, level) /** * Create a [TextStyle] with a foreground of [color], downsampled to a given [level]. * * It's usually easier to use a function like [rgb] or [hsl] instead. */ fun color(color: Color): TextStyle = TextColors.color(color, level) private fun downsample(style: TextStyle): TextStyle = downsample(style, level, terminalInfo.ansiHyperLinks) private val level get() = terminalInfo.ansiLevel }
18
null
34
946
059b9a71ecbaececb0a58a197981295b0e5e0aec
6,605
mordant
Apache License 2.0
nav/safeargs/common/src/com/android/tools/idea/nav/safeargs/cache/DirectionsShortNamesCache.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.nav.safeargs.cache import com.android.tools.idea.nav.safeargs.module.SafeArgsCacheModuleService import com.android.tools.idea.nav.safeargs.project.ProjectNavigationResourceModificationTracker import com.android.tools.idea.nav.safeargs.project.SafeArgsEnabledFacetsProjectService import com.android.tools.idea.nav.safeargs.psi.java.LightDirectionsClass import com.android.tools.idea.nav.safeargs.safeArgsModeTracker import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchScopeUtil import com.intellij.psi.search.PsiShortNamesCache import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.Processor /** * A short names cache for finding any [LightDirectionsClass] classes or their methods by their unqualified * name. */ class DirectionsShortNamesCache(project: Project) : PsiShortNamesCache() { private val enabledFacetsProvider = SafeArgsEnabledFacetsProjectService.getInstance(project) private val lightClassesCache: CachedValue<Map<String, List<LightDirectionsClass>>> private val allClassNamesCache: CachedValue<Array<String>> init { val cachedValuesManager = CachedValuesManager.getManager(project) lightClassesCache = cachedValuesManager.createCachedValue { val lightClasses = enabledFacetsProvider.modulesUsingSafeArgs .asSequence() .flatMap { facet -> SafeArgsCacheModuleService.getInstance(facet).directions.asSequence() } .groupBy { lightClass -> lightClass.name } CachedValueProvider.Result.create(lightClasses, ProjectNavigationResourceModificationTracker.getInstance(project), project.safeArgsModeTracker) } allClassNamesCache = cachedValuesManager.createCachedValue { CachedValueProvider.Result.create(lightClassesCache.value.keys.toTypedArray(), lightClassesCache) } } override fun getAllClassNames(): Array<String> = allClassNamesCache.value override fun getClassesByName(name: String, scope: GlobalSearchScope): Array<PsiClass> { return lightClassesCache.value[name] ?.asSequence() ?.filter { PsiSearchScopeUtil.isInScope(scope, it) } ?.map { it as PsiClass } ?.toList() ?.toTypedArray() ?: PsiClass.EMPTY_ARRAY } override fun getAllMethodNames() = arrayOf<String>() override fun getMethodsByName(name: String, scope: GlobalSearchScope) = arrayOf<PsiMethod>() override fun getMethodsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiMethod> { return getMethodsByName(name, scope).take(maxCount).toTypedArray() } override fun processMethodsWithName(name: String, scope: GlobalSearchScope, processor: Processor<in PsiMethod>): Boolean { // We are asked to process each method in turn, aborting if false is ever returned, and passing // that result back up the chain. return getMethodsByName(name, scope).all { method -> processor.process(method) } } override fun getAllFieldNames() = arrayOf<String>() override fun getFieldsByName(name: String, scope: GlobalSearchScope) = arrayOf<PsiField>() override fun getFieldsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiField> { return getFieldsByName(name, scope).take(maxCount).toTypedArray() } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
4,352
android
Apache License 2.0
module/bookmark/src/main/java/com/tochy/tochybrowser/bookmark/overflow/model/HideModel.kt
tochyodikwa
613,355,237
false
null
package com.tochy.tochybrowser.bookmark.overflow.model typealias HideModel = Int
0
Kotlin
0
0
a0ca7aca9488134188c5c4cca1c3bae7981863c8
84
Browser
Apache License 2.0
src/test/kotlin/com/aperfilyev/versioncataloghelper/editor/MyCopyPastePreProcessorTest.kt
aperfilyev
743,381,903
false
{"Kotlin": 20547}
package com.aperfilyev.versioncataloghelper.editor import com.intellij.openapi.ide.CopyPasteManager import com.intellij.testFramework.EditorTestUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.intellij.lang.annotations.Language import org.toml.lang.psi.TomlFileType import java.awt.datatransfer.StringSelection class MyCopyPastePreProcessorTest : BasePlatformTestCase() { fun testEmptyFile() { doTest( """implementation 'com.squareup.retrofit2:retrofit:2.9.0'""", """ |[versions] |[libraries] |<caret> |[plugins] """.trimMargin(), """ |[versions] |[libraries] |retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version = "2.9.0" } |[plugins] """.trimMargin(), ) } fun testNonEmptyFile() { doTest( """implementation 'com.squareup.retrofit2:retrofit:2.9.0'""", """ |[versions] |[libraries] |my-lib = "com.mycompany:mylib:1.4" |my-other-lib = { module = "com.mycompany:other", version = "1.4" } |my-other-lib2 = { group = "com.mycompany", name = "name", version = "1.4" } |<caret> |[plugins] """.trimMargin(), """ |[versions] |[libraries] |my-lib = "com.mycompany:mylib:1.4" |my-other-lib = { module = "com.mycompany:other", version = "1.4" } |my-other-lib2 = { group = "com.mycompany", name = "name", version = "1.4" } |retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version = "2.9.0" } |[plugins] """.trimMargin(), ) } fun testOnlyLibrariesBlock() { doTest( """implementation 'com.squareup.retrofit2:retrofit:2.9.0'""", """ |[libraries] |<caret> """.trimMargin(), """ |[libraries] |retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version = "2.9.0" } """.trimMargin(), ) } fun testMultiline() { doTest( """ |val apacheCommonsLang3 = "org.apache.commons:commons-lang3:3.11" |val apacheCommonsPool2 = "org.apache.commons:commons-pool2:2.11.1" |val assertj = "org.assertj:assertj-core:3.24.2" |val awaitility = "org.awaitility:awaitility:4.1.0" |val awaitilityKotlin = "org.awaitility:awaitility-kotlin:4.1.0" |val aws2Bom = "software.amazon.awssdk:bom:2.21.24" |val aws2Dynamodb = "software.amazon.awssdk:dynamodb:2.21.24" |val aws2DynamodbEnhanced = "software.amazon.awssdk:dynamodb-enhanced:2.21.24" |val awsAuth = "software.amazon.awssdk:auth:2.21.24" |val awsCore = "software.amazon.awssdk:aws-core:2.21.24" |val awsDynamodb = "com.amazonaws:aws-java-sdk-dynamodb:1.12.576" |val awsJavaSdkCore = "com.amazonaws:aws-java-sdk-core:1.12.576" |val awsRegions = "software.amazon.awssdk:regions:2.21.24" |val awsS3 = "com.amazonaws:aws-java-sdk-s3:1.12.576" |val awsSdkCore = "software.amazon.awssdk:sdk-core:2.21.24" |val awsSqs = "com.amazonaws:aws-java-sdk-sqs:1.12.576" |val bouncycastle = "org.bouncycastle:bcprov-jdk15on:1.70" |val bouncycastlePgp = "org.bouncycastle:bcpg-jdk15on:1.70" |val bucket4jCore = "com.bucket4j:bucket4j-core:8.5.0" |val bucket4jDynamoDbV1 = "com.bucket4j:bucket4j-dynamodb-sdk-v1:8.5.0" """.trimMargin(), """ |[libraries] |<caret> """.trimMargin(), """ |[libraries] |commons-lang3 = { group = "org.apache.commons", name = "commons-lang3", version = "3.11" } |commons-pool2 = { group = "org.apache.commons", name = "commons-pool2", version = "2.11.1" } |assertj-core = { group = "org.assertj", name = "assertj-core", version = "3.24.2" } |awaitility = { group = "org.awaitility", name = "awaitility", version = "4.1.0" } |awaitility-kotlin = { group = "org.awaitility", name = "awaitility-kotlin", version = "4.1.0" } |bom = { group = "software.amazon.awssdk", name = "bom", version = "2.21.24" } |dynamodb = { group = "software.amazon.awssdk", name = "dynamodb", version = "2.21.24" } |dynamodb-enhanced = { group = "software.amazon.awssdk", name = "dynamodb-enhanced", version = "2.21.24" } |auth = { group = "software.amazon.awssdk", name = "auth", version = "2.21.24" } |aws-core = { group = "software.amazon.awssdk", name = "aws-core", version = "2.21.24" } |aws-java-sdk-dynamodb = { group = "com.amazonaws", name = "aws-java-sdk-dynamodb", version = "1.12.576" } |aws-java-sdk-core = { group = "com.amazonaws", name = "aws-java-sdk-core", version = "1.12.576" } |regions = { group = "software.amazon.awssdk", name = "regions", version = "2.21.24" } |aws-java-sdk-s3 = { group = "com.amazonaws", name = "aws-java-sdk-s3", version = "1.12.576" } |sdk-core = { group = "software.amazon.awssdk", name = "sdk-core", version = "2.21.24" } |aws-java-sdk-sqs = { group = "com.amazonaws", name = "aws-java-sdk-sqs", version = "1.12.576" } |bcprov-jdk15on = { group = "org.bouncycastle", name = "bcprov-jdk15on", version = "1.70" } |bcpg-jdk15on = { group = "org.bouncycastle", name = "bcpg-jdk15on", version = "1.70" } |bucket4j-core = { group = "com.bucket4j", name = "bucket4j-core", version = "8.5.0" } |bucket4j-dynamodb-sdk-v1 = { group = "com.bucket4j", name = "bucket4j-dynamodb-sdk-v1", version = "8.5.0" } """.trimMargin(), ) } fun testWrongBlock() { doTest( """implementation 'com.squareup.retrofit2:retrofit:2.9.0'""", """ |[plugins] |<caret> """.trimMargin(), """ |[plugins] |implementation 'com.squareup.retrofit2:retrofit:2.9.0' """.trimMargin(), ) } fun testCapitalizedName() { doTest( """implementation 'com.zaxxer:HikariCP:4.0.3'""", """ |[libraries] |<caret> """.trimMargin(), """ |[libraries] |hikariCP = { group = "com.zaxxer", name = "HikariCP", version = "4.0.3" } """.trimMargin(), ) } fun testNameContainsPeriod() { doTest( """implementation 'jakarta.inject:jakarta.inject-api:2.0.1'""", """ |[libraries] |<caret> """.trimMargin(), """ |[libraries] |jakarta-inject-api = { group = "jakarta.inject", name = "jakarta.inject-api", version = "2.0.1" } """.trimMargin(), ) } private fun doTest( text: String, @Language("TOML") beforeText: String, @Language("TOML") afterText: String, ) { myFixture.configureByText(TomlFileType, beforeText) CopyPasteManager.getInstance().setContents(StringSelection(text)) EditorTestUtil.performPaste(myFixture.editor) myFixture.checkResult(afterText.trimMargin()) } }
2
Kotlin
0
1
f090f56a1a6a1270bdaba8c7f17bdb4c1c059c67
7,578
version-catalog-helper
Apache License 2.0
multik-openblas/src/commonMain/kotlin/org/jetbrains/kotlinx/multik/openblas/math/NativeMath.kt
Kotlin
265,785,552
false
{"Kotlin": 1233813, "C++": 95317, "C": 8142, "CMake": 6406}
/* * Copyright 2020-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.multik.openblas.math import org.jetbrains.kotlinx.multik.api.math.Math import org.jetbrains.kotlinx.multik.api.math.MathEx import org.jetbrains.kotlinx.multik.ndarray.data.* internal object NativeMath : Math { override val mathEx: MathEx get() = NativeMathEx override fun <T : Number, D : Dimension> argMax(a: MultiArray<T, D>): Int { val strides: IntArray? = if (a.consistent) null else a.strides return JniMath.argMax(a.data.data, a.offset, a.size, a.shape, strides, a.dtype.nativeCode) } override fun <T : Number, D : Dimension, O : Dimension> argMax(a: MultiArray<T, D>, axis: Int): NDArray<Int, O> { TODO("Not yet implemented") } override fun <T : Number> argMaxD2(a: MultiArray<T, D2>, axis: Int): NDArray<Int, D1> { TODO("Not yet implemented") } override fun <T : Number> argMaxD3(a: MultiArray<T, D3>, axis: Int): NDArray<Int, D2> { TODO("Not yet implemented") } override fun <T : Number> argMaxD4(a: MultiArray<T, D4>, axis: Int): NDArray<Int, D3> { TODO("Not yet implemented") } override fun <T : Number> argMaxDN(a: MultiArray<T, DN>, axis: Int): NDArray<Int, DN> { TODO("Not yet implemented") } override fun <T : Number, D : Dimension> argMin(a: MultiArray<T, D>): Int { val strides: IntArray? = if (a.consistent) null else a.strides return JniMath.argMin(a.data.data, a.offset, a.size, a.shape, strides, a.dtype.nativeCode) } override fun <T : Number, D : Dimension, O : Dimension> argMin(a: MultiArray<T, D>, axis: Int): NDArray<Int, O> { TODO("Not yet implemented") } override fun <T : Number> argMinD2(a: MultiArray<T, D2>, axis: Int): NDArray<Int, D1> { TODO("Not yet implemented") } override fun <T : Number> argMinD3(a: MultiArray<T, D3>, axis: Int): NDArray<Int, D2> { TODO("Not yet implemented") } override fun <T : Number> argMinD4(a: MultiArray<T, D4>, axis: Int): NDArray<Int, D3> { TODO("Not yet implemented") } override fun <T : Number> argMinDN(a: MultiArray<T, DN>, axis: Int): NDArray<Int, DN> { TODO("Not yet implemented") } override fun <T : Number, D : Dimension> max(a: MultiArray<T, D>): T { val strides: IntArray? = if (a.consistent) null else a.strides return when (a.dtype) { DataType.ByteDataType -> JniMath.array_max(a.data.getByteArray(), a.offset, a.size, a.shape, strides) DataType.ShortDataType -> JniMath.array_max(a.data.getShortArray(), a.offset, a.size, a.shape, strides) DataType.IntDataType -> JniMath.array_max(a.data.getIntArray(), a.offset, a.size, a.shape, strides) DataType.LongDataType -> JniMath.array_max(a.data.getLongArray(), a.offset, a.size, a.shape, strides) DataType.FloatDataType -> JniMath.array_max(a.data.getFloatArray(), a.offset, a.size, a.shape, strides) DataType.DoubleDataType -> JniMath.array_max(a.data.getDoubleArray(), a.offset, a.size, a.shape, strides) else -> TODO("ComplexFloat and ComplexDouble not yet implemented") } as T } override fun <T : Number, D : Dimension, O : Dimension> max(a: MultiArray<T, D>, axis: Int): NDArray<T, O> { TODO("Not yet implemented") } override fun <T : Number> maxD2(a: MultiArray<T, D2>, axis: Int): NDArray<T, D1> { TODO("Not yet implemented") } override fun <T : Number> maxD3(a: MultiArray<T, D3>, axis: Int): NDArray<T, D2> { TODO("Not yet implemented") } override fun <T : Number> maxD4(a: MultiArray<T, D4>, axis: Int): NDArray<T, D3> { TODO("Not yet implemented") } override fun <T : Number> maxDN(a: MultiArray<T, DN>, axis: Int): NDArray<T, DN> { TODO("Not yet implemented") } override fun <T : Number, D : Dimension> min(a: MultiArray<T, D>): T { val strides: IntArray? = if (a.consistent) null else a.strides return when (a.dtype) { DataType.ByteDataType -> JniMath.array_min(a.data.getByteArray(), a.offset, a.size, a.shape, strides) DataType.ShortDataType -> JniMath.array_min(a.data.getShortArray(), a.offset, a.size, a.shape, strides) DataType.IntDataType -> JniMath.array_min(a.data.getIntArray(), a.offset, a.size, a.shape, strides) DataType.LongDataType -> JniMath.array_min(a.data.getLongArray(), a.offset, a.size, a.shape, strides) DataType.FloatDataType -> JniMath.array_min(a.data.getFloatArray(), a.offset, a.size, a.shape, strides) DataType.DoubleDataType -> JniMath.array_min(a.data.getDoubleArray(), a.offset, a.size, a.shape, strides) else -> TODO("ComplexFloat and ComplexDouble not yet implemented") } as T } override fun <T : Number, D : Dimension, O : Dimension> min(a: MultiArray<T, D>, axis: Int): NDArray<T, O> { TODO("Not yet implemented") } override fun <T : Number> minD2(a: MultiArray<T, D2>, axis: Int): NDArray<T, D1> { TODO("Not yet implemented") } override fun <T : Number> minD3(a: MultiArray<T, D3>, axis: Int): NDArray<T, D2> { TODO("Not yet implemented") } override fun <T : Number> minD4(a: MultiArray<T, D4>, axis: Int): NDArray<T, D3> { TODO("Not yet implemented") } override fun <T : Number> minDN(a: MultiArray<T, DN>, axis: Int): NDArray<T, DN> { TODO("Not yet implemented") } override fun <T : Number, D : Dimension> sum(a: MultiArray<T, D>): T { val strides: IntArray? = if (a.consistent) null else a.strides return when (a.dtype) { DataType.ByteDataType -> JniMath.sum(a.data.getByteArray(), a.offset, a.size, a.shape, strides) DataType.ShortDataType -> JniMath.sum(a.data.getShortArray(), a.offset, a.size, a.shape, strides) DataType.IntDataType -> JniMath.sum(a.data.getIntArray(), a.offset, a.size, a.shape, strides) DataType.LongDataType -> JniMath.sum(a.data.getLongArray(), a.offset, a.size, a.shape, strides) DataType.FloatDataType -> JniMath.sum(a.data.getFloatArray(), a.offset, a.size, a.shape, strides) DataType.DoubleDataType -> JniMath.sum(a.data.getDoubleArray(), a.offset, a.size, a.shape, strides) else -> TODO("ComplexFloat and ComplexDouble not yet implemented") } as T } override fun <T : Number, D : Dimension, O : Dimension> sum(a: MultiArray<T, D>, axis: Int): NDArray<T, O> { TODO("Not yet implemented") } override fun <T : Number> sumD2(a: MultiArray<T, D2>, axis: Int): NDArray<T, D1> { TODO("Not yet implemented") } override fun <T : Number> sumD3(a: MultiArray<T, D3>, axis: Int): NDArray<T, D2> { TODO("Not yet implemented") } override fun <T : Number> sumD4(a: MultiArray<T, D4>, axis: Int): NDArray<T, D3> { TODO("Not yet implemented") } override fun <T : Number> sumDN(a: MultiArray<T, DN>, axis: Int): NDArray<T, DN> { TODO("Not yet implemented") } override fun <T : Number, D : Dimension> cumSum(a: MultiArray<T, D>): D1Array<T> { val ret = D1Array<T>(initMemoryView(a.size, a.dtype), shape = intArrayOf(a.size), dim = D1) val strides: IntArray? = if (a.consistent) null else a.strides when (a.dtype) { DataType.ByteDataType -> JniMath.cumSum(a.data.getByteArray(), a.offset, a.size, a.shape, strides, ret.data.getByteArray()) DataType.ShortDataType -> JniMath.cumSum(a.data.getShortArray(), a.offset, a.size, a.shape, strides, ret.data.getShortArray()) DataType.IntDataType -> JniMath.cumSum(a.data.getIntArray(), a.offset, a.size, a.shape, strides, ret.data.getIntArray()) DataType.LongDataType -> JniMath.cumSum(a.data.getLongArray(), a.offset, a.size, a.shape, strides, ret.data.getLongArray()) DataType.FloatDataType -> JniMath.cumSum(a.data.getFloatArray(), a.offset, a.size, a.shape, strides, ret.data.getFloatArray()) DataType.DoubleDataType -> JniMath.cumSum(a.data.getDoubleArray(), a.offset, a.size, a.shape, strides, ret.data.getDoubleArray()) else -> TODO("ComplexFloat and ComplexDouble not yet implemented") } return ret } override fun <T : Number, D : Dimension> cumSum(a: MultiArray<T, D>, axis: Int): NDArray<T, D> { TODO("Not yet implemented") } }
59
Kotlin
39
636
b121652b8d151782d5770c5e1505864ac0307a5b
8,599
multik
Apache License 2.0
app/src/main/java/com/duckduckgo/widget/SearchAndFavoritesGridCalculator.kt
duckduckgo
78,869,127
false
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2021 DuckDuckGo * * 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.duckduckgo.widget import android.content.Context import com.duckduckgo.common.ui.view.toDp import com.duckduckgo.mobile.android.R as CommonR import timber.log.Timber class SearchAndFavoritesGridCalculator { fun calculateColumns( context: Context, width: Int, ): Int { val margins = context.resources.getDimension(CommonR.dimen.searchWidgetFavoritesSideMargin).toDp() val item = context.resources.getDimension(CommonR.dimen.searchWidgetFavoriteItemContainerWidth).toDp() val divider = context.resources.getDimension(CommonR.dimen.searchWidgetFavoritesHorizontalSpacing).toDp() var n = 2 var totalSize = (n * item) + ((n - 1) * divider) + (margins * 2) Timber.i("SearchAndFavoritesWidget width n:$n $totalSize vs $width") while (totalSize <= width) { ++n totalSize = (n * item) + ((n - 1) * divider) + (margins * 2) Timber.i("SearchAndFavoritesWidget width n:$n $totalSize vs $width") } return WIDGET_COLUMNS_MIN.coerceAtLeast(n - 1) } fun calculateRows( context: Context, height: Int, ): Int { val searchBar = context.resources.getDimension(CommonR.dimen.searchWidgetSearchBarHeight).toDp() val margins = context.resources.getDimension(CommonR.dimen.searchWidgetFavoritesTopMargin).toDp() + (context.resources.getDimension(CommonR.dimen.searchWidgetPadding).toDp() * 2) val item = context.resources.getDimension(CommonR.dimen.searchWidgetFavoriteItemContainerHeight).toDp() val divider = context.resources.getDimension(CommonR.dimen.searchWidgetFavoritesVerticalSpacing).toDp() var n = 1 var totalSize = searchBar + (n * item) + ((n - 1) * divider) + margins Timber.i("SearchAndFavoritesWidget height n:$n $totalSize vs $height") while (totalSize <= height) { ++n totalSize = searchBar + (n * item) + ((n - 1) * divider) + margins Timber.i("SearchAndFavoritesWidget height n:$n $totalSize vs $height") } var rows = n - 1 rows = WIDGET_ROWS_MIN.coerceAtLeast(rows) rows = WIDGET_ROWS_MAX.coerceAtMost(rows) return rows } companion object { private const val WIDGET_COLUMNS_MIN = 2 private const val WIDGET_ROWS_MAX = 4 private const val WIDGET_ROWS_MIN = 1 } }
67
Kotlin
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
3,026
Android
Apache License 2.0
app/src/main/java/com/simbiri/equityjamii/constants/CONSTANTS.kt
SimbaSimbiri
706,250,529
false
{"Kotlin": 240056}
package com.simbiri.equityjamii.constants import com.simbiri.equityjamii.data.model.AuthUtils val POST_COLLECTION ="Post_Gallery" val POST_STORAGE_REF ="PostStorage_Images" val NEWS_STORAGE_REF = "NewsImageStore" val USERS_COLLECTION ="Users" val LIKES_SUB_COLLECTION = "Likes" val NEWS_COLLECTION = "News" val EVENTS_C0LLECTION = "Events" val EVENT_SUB_COLLECTION = "participants"
0
Kotlin
0
0
afe8f3958915c21d6db20701addaa3c2e63f68fc
384
EquiJamii
Apache License 2.0
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/board/methods/BoardGetTopicsMethodExtended.kt
alatushkin
156,866,851
false
null
package name.alatushkin.api.vk.generated.board.methods import com.fasterxml.jackson.core.type.TypeReference import name.alatushkin.api.vk.VkMethod import name.alatushkin.api.vk.api.VkSuccess import name.alatushkin.api.vk.generated.board.GetTopicsResponse import name.alatushkin.api.vk.generated.board.Order import name.alatushkin.api.vk.generated.board.Preview /** * Returns a list of topics on a community's discussion board. * * [https://vk.com/dev/board.getTopics] * @property [group_id] ID of the community that owns the discussion board. * @property [topic_ids] IDs of topics to be returned (100 maximum). By default, all topics are returned. If this parameter is set, the 'order', 'offset', and 'count' parameters are ignored. * @property [order] Sort order: '1' — by date updated in reverse chronological order. '2' — by date created in reverse chronological order. '-1' — by date updated in chronological order. '-2' — by date created in chronological order. If no sort order is specified, topics are returned in the order specified by the group administrator. Pinned topics are returned first, regardless of the sorting. * @property [offset] Offset needed to return a specific subset of topics. * @property [count] Number of topics to return. * @property [preview] '1' — to return the first comment in each topic,, '2' — to return the last comment in each topic,, '0' — to return no comments. By default: '0'. * @property [preview_length] Number of characters after which to truncate the previewed comment. To preview the full comment, specify '0'. */ class BoardGetTopicsMethod() : VkMethod<GetTopicsResponse>( "board.getTopics", mutableMapOf() ) { var groupId: Long? by props var topicIds: Array<Long>? by props var order: Order? by props var offset: Long? by props var count: Long? by props var preview: Preview? by props var previewLength: Long? by props constructor( groupId: Long? = null, topicIds: Array<Long>? = null, order: Order? = null, offset: Long? = null, count: Long? = null, preview: Preview? = null, previewLength: Long? = null ) : this() { this.groupId = groupId this.topicIds = topicIds this.order = order this.offset = offset this.count = count this.preview = preview this.previewLength = previewLength } fun setGroupId(groupId: Long): BoardGetTopicsMethod { this.groupId = groupId return this } fun setTopicIds(topicIds: Array<Long>): BoardGetTopicsMethod { this.topicIds = topicIds return this } fun setOrder(order: Order): BoardGetTopicsMethod { this.order = order return this } fun setOffset(offset: Long): BoardGetTopicsMethod { this.offset = offset return this } fun setCount(count: Long): BoardGetTopicsMethod { this.count = count return this } fun setPreview(preview: Preview): BoardGetTopicsMethod { this.preview = preview return this } fun setPreviewLength(previewLength: Long): BoardGetTopicsMethod { this.previewLength = previewLength return this } override val classRef = BoardGetTopicsMethod.classRef companion object { val classRef = object : TypeReference<VkSuccess<GetTopicsResponse>>() {} } }
2
Kotlin
3
10
123bd61b24be70f9bbf044328b98a3901523cb1b
3,421
kotlin-vk-api
MIT License
agoraui/src/main/kotlin/io/agora/uikit/impl/users/AgoraUIRoster.kt
AgoraIO-Community
330,886,965
false
null
package io.agora.uikit.impl.users import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.graphics.Color import android.graphics.Rect import android.text.SpannableString import android.text.style.ImageSpan import android.util.Log import android.view.* import android.widget.CheckedTextView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.* import io.agora.educontext.* import io.agora.uikit.R import io.agora.uikit.educontext.handlers.UserHandler import io.agora.uikit.impl.AbsComponent import io.agora.uikit.impl.container.AgoraUIConfig.clickInterval import io.agora.uikit.util.TextPinyinUtil import kotlin.Comparator import kotlin.collections.ArrayList import kotlin.math.min class AgoraUIRoster(private val eduContext: EduContextPool?) : AbsComponent() { private val tag = "AgoraUIRoster" private var rosterDialog: RosterDialog? = null private var userList: MutableList<EduContextUserDetailInfo> = mutableListOf() private val handler = object : UserHandler() { override fun onUserListUpdated(list: MutableList<EduContextUserDetailInfo>) { super.onUserListUpdated(list) val list1 = sort(list) updateUserList(list1) rosterDialog?.updateUserList(userList) } override fun onRoster(context: Context, anchor: View, type: Int?) { when (type) { RosterType.SmallClass.value() -> RosterType.SmallClass RosterType.LargeClass.value() -> RosterType.LargeClass else -> null }?.let { rosterType -> dismiss() RosterDialog(context, rosterType, eduContext, userList).let { dialog -> dialog.setOnDismissListener(dismissListener) rosterDialog = dialog showDialog(anchor) } } } override fun onFlexUserPropsChanged(changedProperties: MutableMap<String, Any>, properties: MutableMap<String, Any>, cause: MutableMap<String, Any>?, fromUser: EduContextUserDetailInfo, operator: EduContextUserInfo?) { super.onFlexUserPropsChanged(changedProperties, properties, cause, fromUser, operator) Log.i(tag, "onFlexUserPropertiesChanged") } } companion object { var dismissListener: DialogInterface.OnDismissListener? = null } fun sort(list: MutableList<EduContextUserDetailInfo>): MutableList<EduContextUserDetailInfo> { var coHosts = mutableListOf<EduContextUserDetailInfo>() var users = mutableListOf<EduContextUserDetailInfo>() list.forEach { if (it.coHost) { coHosts.add(it) } else { users.add(it) } } coHosts = sort2(coHosts) val list1 = sort2(users) coHosts.addAll(list1) return coHosts } private fun sort2(list: MutableList<EduContextUserDetailInfo>): MutableList<EduContextUserDetailInfo> { val numList = mutableListOf<EduContextUserDetailInfo>() val listIterator = list.iterator() while (listIterator.hasNext()) { val info = listIterator.next() val tmp = info.user.userName[0] if (!TextPinyinUtil.isChinaString(tmp.toString()) && tmp.toInt() in 48..57) { numList.add(info) listIterator.remove() } } numList.sortWith(object : Comparator<EduContextUserDetailInfo> { override fun compare(o1: EduContextUserDetailInfo?, o2: EduContextUserDetailInfo?): Int { if (o1 == null) { return -1 } if (o2 == null) { return 1 } return o1.user.userName.compareTo(o2.user.userName) } }) list.sortWith(object : Comparator<EduContextUserDetailInfo> { override fun compare(o1: EduContextUserDetailInfo?, o2: EduContextUserDetailInfo?): Int { if (o1 == null) { return -1 } if (o2 == null) { return 1 } var ch1 = "" if (TextPinyinUtil.isChinaString(o1.user.userName)) { TextPinyinUtil.getPinyin(o1.user.userName).let { ch1 = it } } else { ch1 = o1.user.userName } var ch2 = "" if (TextPinyinUtil.isChinaString(o2.user.userName)) { TextPinyinUtil.getPinyin(o2.user.userName).let { ch2 = it } } else { ch2 = o2.user.userName } return ch1.compareTo(ch2) } }) list.addAll(numList) return list } private fun updateUserList(list: MutableList<EduContextUserDetailInfo>) { userList.clear() list.forEach { userList.add(it.copy()) } } private fun isShowing(): Boolean { return rosterDialog?.isShowing ?: false } private fun showDialog(anchor: View) { rosterDialog?.adjustPosition(anchor) rosterDialog?.show() } private fun dismiss() { if (isShowing()) { rosterDialog!!.setOnDismissListener(null) rosterDialog!!.dismiss() rosterDialog = null } } init { eduContext?.userContext()?.addHandler(handler) } enum class RosterType(private val value: Int) { SmallClass(0), LargeClass(1); fun value(): Int { return this.value } } override fun setRect(rect: Rect) { } } class RosterDialog( appContext: Context, private val type: AgoraUIRoster.RosterType, private val eduContext: EduContextPool?, private val userList: MutableList<EduContextUserDetailInfo> ) : Dialog(appContext, R.style.agora_dialog) { private val recyclerView: RecyclerView private val userListAdapter: UserListAdapter private val tvTeacherName: TextView init { setCancelable(true) setCanceledOnTouchOutside(true) setContentView(getLayoutRes()) recyclerView = findViewById(R.id.recycler_view) tvTeacherName = findViewById(R.id.tv_teacher_name) findViewById<View>(R.id.iv_close).setOnClickListener { dismiss() } userListAdapter = UserListAdapter(object : UserItemClickListener { override fun onCameraCheckChanged(item: EduContextUserDetailInfo, checked: Boolean) { eduContext?.userContext()?.muteVideo(!checked) } override fun onMicCheckChanged(item: EduContextUserDetailInfo, checked: Boolean) { eduContext?.userContext()?.muteAudio(!checked) } }) recyclerView.addItemDecoration( DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply { setDrawable(ContextCompat.getDrawable(context, R.drawable.agora_userlist_divider)!!) }) recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() { val itemHeight = context.resources.getDimensionPixelSize(R.dimen.agora_userlist_row_height) override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val layoutParams = view.layoutParams layoutParams.width = parent.measuredWidth layoutParams.height = itemHeight view.layoutParams = layoutParams super.getItemOffsets(outRect, view, parent, state) } }) // remove the animator when refresh item recyclerView.itemAnimator?.addDuration = 0 recyclerView.itemAnimator?.changeDuration = 0 recyclerView.itemAnimator?.moveDuration = 0 recyclerView.itemAnimator?.removeDuration = 0 (recyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false recyclerView.adapter = userListAdapter val studentList = filterStudent(userList) userListAdapter.submitList(ArrayList(studentList)) } private fun getLayoutRes() = when (this.type) { AgoraUIRoster.RosterType.SmallClass -> R.layout.agora_userlist_dialog_layout AgoraUIRoster.RosterType.LargeClass -> R.layout.agora_userlist_largeclass_dialog_layout } fun adjustPosition(anchor: View) { when (type) { AgoraUIRoster.RosterType.SmallClass -> { adjustPosition(anchor, context.resources.getDimensionPixelSize(R.dimen.agora_userlist_dialog_width), context.resources.getDimensionPixelSize(R.dimen.agora_userlist_dialog_height)) } AgoraUIRoster.RosterType.LargeClass -> { adjustPosition(anchor, context.resources.getDimensionPixelSize(R.dimen.agora_userlist_largeclass_dialog_width), context.resources.getDimensionPixelSize(R.dimen.agora_userlist_dialog_height)) } } } @SuppressLint("InflateParams") private fun createItemViewHolder(type: AgoraUIRoster.RosterType, parent: ViewGroup, listener: UserItemClickListener): BaseUserHolder { return when (type) { AgoraUIRoster.RosterType.SmallClass -> { SmallClassUserHolder(LayoutInflater.from(parent.context) .inflate(R.layout.agora_userlist_dialog_list_item, null), listener) } AgoraUIRoster.RosterType.LargeClass -> { LargeClassUserHolder(LayoutInflater.from(parent.context) .inflate(R.layout.agora_userlist_largeclass_dialog_list_item, null), listener) } } } private fun adjustPosition(anchor: View, width: Int, height: Int) { this.window?.let { window -> hideStatusBar(window) val params = window.attributes params.width = width params.height = height val posArray = IntArray(2) anchor.getLocationOnScreen(posArray) params.x = posArray[0] + anchor.width + 12 params.gravity = Gravity.CENTER_VERTICAL or Gravity.LEFT window.attributes = params } } private fun hideStatusBar(window: Window) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = Color.TRANSPARENT val flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.decorView.systemUiVisibility = (flag or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) } fun updateUserList(list: MutableList<EduContextUserDetailInfo>) { val studentList = filterStudent(list) userListAdapter.submitList(ArrayList(studentList)) } private fun filterStudent(list: MutableList<EduContextUserDetailInfo>): MutableList<EduContextUserDetailInfo> { val studentList = mutableListOf<EduContextUserDetailInfo>() list.forEach { item -> if (item.user.role == EduContextUserRole.Student) { studentList.add(item) } else if (item.user.role == EduContextUserRole.Teacher) { updateTeacher(item) } } return studentList } private fun updateTeacher(info: EduContextUserDetailInfo) { tvTeacherName.post { tvTeacherName.text = info.user.userName } } private fun updateStudent(info: EduContextUserDetailInfo) { val index = findIndex(info) if (index >= 0) { userListAdapter.currentList[index] = info userListAdapter.notifyItemChanged(index) } } private fun findIndex(info: EduContextUserDetailInfo): Int { var index = 0 var foundIndex = -1; for (item in userListAdapter.currentList) { if (item.user.userUuid == info.user.userUuid) { foundIndex = index break } index++ } return foundIndex } private class UserListDiff : DiffUtil.ItemCallback<EduContextUserDetailInfo>() { override fun areItemsTheSame(oldItem: EduContextUserDetailInfo, newItem: EduContextUserDetailInfo): Boolean { return oldItem == newItem && oldItem.user.userUuid == newItem.user.userUuid } override fun areContentsTheSame(oldItem: EduContextUserDetailInfo, newItem: EduContextUserDetailInfo): Boolean { return oldItem.user.userName == newItem.user.userName && oldItem.onLine == newItem.onLine && oldItem.coHost == newItem.coHost && oldItem.boardGranted == newItem.boardGranted && oldItem.cameraState == newItem.cameraState && oldItem.microState == newItem.microState && oldItem.enableAudio == newItem.enableAudio && oldItem.enableVideo == newItem.enableVideo && oldItem.rewardCount == newItem.rewardCount } } private abstract inner class BaseUserHolder( private val type: AgoraUIRoster.RosterType, val view: View, val listener: UserItemClickListener) : RecyclerView.ViewHolder(view) { abstract fun bind(item: EduContextUserDetailInfo) } private inner class UserListAdapter(val listener: UserItemClickListener) : ListAdapter<EduContextUserDetailInfo, BaseUserHolder>(UserListDiff()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createItemViewHolder(type, parent, listener) override fun onBindViewHolder(holder: BaseUserHolder, position: Int) { holder.bind(getItem(position)) } } private interface UserItemClickListener { fun onCameraCheckChanged(item: EduContextUserDetailInfo, checked: Boolean) fun onMicCheckChanged(item: EduContextUserDetailInfo, checked: Boolean) } private inner class SmallClassUserHolder(view: View, listener: UserItemClickListener) : BaseUserHolder(type, view, listener) { private val tvName: TextView? = view.findViewById(R.id.tv_user_name) private val ctvDesktop: CheckedTextView? = view.findViewById(R.id.ctv_desktop) private val ctvAccess: CheckedTextView? = view.findViewById(R.id.ctv_access) private val ctvCamera: CheckedTextView? = view.findViewById(R.id.ctv_camera) private val ctvMic: CheckedTextView? = view.findViewById(R.id.ctv_mic) private val ctvSilence: CheckedTextView? = view.findViewById(R.id.ctv_silence) private val ctvStar: CheckedTextView? = view.findViewById(R.id.ctv_star) override fun bind(item: EduContextUserDetailInfo) { tvName?.text = item.user.userName ctvDesktop?.isEnabled = item.coHost ctvAccess?.isEnabled = item.boardGranted ctvCamera?.let { camera -> if (item.cameraState == EduContextDeviceState.Closed) { camera.isEnabled = false camera.isChecked = false return@let } if (item.coHost) { camera.isEnabled = item.isSelf } else { camera.isEnabled = false } camera.isChecked = item.enableVideo camera.setOnClickListener { camera.isClickable = false camera.isChecked = !camera.isChecked listener.onCameraCheckChanged(item, camera.isChecked) camera.postDelayed({ camera.isClickable = true }, clickInterval) } } ctvMic?.let { mic -> if (item.microState == EduContextDeviceState.Closed) { mic.isEnabled = false mic.isChecked = false return@let } if (item.coHost) { mic.isEnabled = item.isSelf } else { mic.isEnabled = false } mic.isChecked = item.enableAudio mic.setOnClickListener { mic.isClickable = false mic.isChecked = !mic.isChecked listener.onMicCheckChanged(item, mic.isChecked) mic.postDelayed({ mic.isClickable = true }, clickInterval) } } ctvSilence?.isEnabled = item.silence val tmp = min(item.rewardCount, 99) ctvStar?.text = view.resources.getString(R.string.agora_video_reward, tmp) } } private inner class LargeClassUserHolder(view: View, listener: UserItemClickListener) : BaseUserHolder(type, view, listener) { private val tvName: TextView? = view.findViewById(R.id.tv_user_name) private val ctvCamera: CheckedTextView? = view.findViewById(R.id.ctv_camera) private val ctvMic: CheckedTextView? = view.findViewById(R.id.ctv_mic) override fun bind(item: EduContextUserDetailInfo) { tvName?.let { nameTextView -> val nameStr = SpannableString(item.user.userName.plus(" ")) if (item.coHost) { nameStr.setSpan(ImageSpan(ContextCompat.getDrawable(view.context, R.drawable.agora_userlist_desktop_icon)!!.apply { setBounds(10, 0, intrinsicWidth + 10, intrinsicHeight) }, ImageSpan.ALIGN_BASELINE), nameStr.length - 1, nameStr.length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE) } nameTextView.text = nameStr } ctvCamera?.let { camera -> if (item.cameraState == EduContextDeviceState.Closed) { camera.isEnabled = false camera.isChecked = false return@let } if (item.coHost) { camera.isEnabled = item.isSelf } else { camera.isEnabled = false } camera.isChecked = item.enableVideo camera.setOnClickListener { camera.isClickable = false camera.isChecked = !camera.isChecked listener.onCameraCheckChanged(item, camera.isChecked) camera.postDelayed({ camera.isClickable = true }, clickInterval) } } ctvMic?.let { mic -> if (item.microState == EduContextDeviceState.Closed) { mic.isEnabled = false mic.isChecked = false return@let } if (item.coHost) { mic.isEnabled = item.isSelf } else { mic.isEnabled = false } mic.isChecked = item.enableAudio mic.setOnClickListener { mic.isClickable = false mic.isChecked = !mic.isChecked listener.onMicCheckChanged(item, mic.isChecked) mic.postDelayed({ mic.isClickable = true }, clickInterval) } } } } }
2
null
10
8
4dbaa7e4a69dce0078d4126ac866a68352a3847d
19,851
CloudClass-Android
MIT License
common/src/main/kotlin/de/sambalmueslie/openevent/common/crud/CrudService.kt
Black-Forrest-Development
542,810,521
false
null
package de.sambalmueslie.openevent.common.crud import io.micronaut.data.model.Page import io.micronaut.data.model.Pageable interface CrudService<T, O : BusinessObject<T>, R : BusinessObjectChangeRequest> { fun get(id: T): O? fun getAll(pageable: Pageable): Page<O> fun create(request: R): O fun update(id: T, request: R): O fun delete(id: T): O? fun register(listener: BusinessObjectChangeListener<T, O>) fun unregister(listener: BusinessObjectChangeListener<T, O>) }
1
Kotlin
0
1
317fbad90ec99908cc527b4082af0ba89525fe42
500
open-event
Apache License 2.0
komga/src/main/kotlin/org/gotson/komga/infrastructure/hash/Hasher.kt
gotson
201,228,816
false
null
package org.gotson.komga.infrastructure.hash import com.appmattus.crypto.Algorithm import mu.KotlinLogging import org.springframework.stereotype.Component import java.io.InputStream import java.nio.file.Path import kotlin.io.path.inputStream private val logger = KotlinLogging.logger {} private const val DEFAULT_BUFFER_SIZE = 8192 private const val SEED = 0 @Component class Hasher { fun computeHash(path: Path): String { logger.debug { "Hashing: $path" } return computeHash(path.inputStream()) } fun computeHash(stream: InputStream): String { val hash = Algorithm.XXH3_128.Seeded(SEED.toLong()).createDigest() stream.use { val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var len: Int do { len = it.read(buffer) if (len >= 0) hash.update(buffer, 0, len) } while (len >= 0) } return hash.digest().toHexString() } @OptIn(ExperimentalUnsignedTypes::class) private fun ByteArray.toHexString(): String = asUByteArray().joinToString("") { it.toString(16).padStart(2, '0') } }
86
null
240
4,029
6cc14e30beac7598284b9ceb2cdaf18da5aed76c
1,060
komga
MIT License
compose/foundation/foundation-layout/src/androidInstrumentedTest/kotlin/androidx/compose/foundation/layout/WindowInsetsDeviceTest.kt
androidx
256,589,781
false
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.layout import android.os.Build import android.view.View import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.LocalView import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.viewinterop.AndroidView import androidx.core.graphics.Insets import androidx.core.view.OnApplyWindowInsetsListener import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.core.view.children import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class WindowInsetsDeviceTest { @get:Rule val rule = createAndroidComposeRule<WindowInsetsActivity>() @Before fun setup() { rule.activity.createdLatch.await(1, TimeUnit.SECONDS) } @OptIn(ExperimentalLayoutApi::class) @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.R) fun disableConsumeDisablesAnimationConsumption() { var imeInset1 = 0 var imeInset2 = 0 val connection = object : NestedScrollConnection { } val dispatcher = NestedScrollDispatcher() // broken out for line length val innerComposable: @Composable () -> Unit = { imeInset2 = WindowInsets.ime.getBottom(LocalDensity.current) Box( Modifier.fillMaxSize().imePadding().imeNestedScroll() .nestedScroll(connection, dispatcher).background( Color.Cyan ) ) } rule.setContent { AndroidView( modifier = Modifier.fillMaxSize(), factory = { outerContext -> ComposeView(outerContext).apply { consumeWindowInsets = false setContent { imeInset1 = WindowInsets.ime.getBottom(LocalDensity.current) Box(Modifier.fillMaxSize()) { AndroidView( modifier = Modifier.fillMaxSize(), factory = { context -> ComposeView(context).apply { consumeWindowInsets = false setContent(innerComposable) } } ) } } } } ) } rule.waitForIdle() // We don't have any way to know when the animation controller is applied, so just // loop until the value changes. var iteration = 0 rule.waitUntil(timeoutMillis = 3000) { rule.runOnIdle { if (iteration % 5 == 0) { // Cuttlefish doesn't consistently show the IME when requested, so // we must poke it. This will poke it every 5 iterations to ensure that // if we miss it once then it will get it on another pass. pokeIME() } dispatcher.dispatchPostScroll( Offset.Zero, Offset(0f, -10f), NestedScrollSource.Drag ) Snapshot.sendApplyNotifications() iteration++ } rule.runOnIdle { imeInset1 > 0 && imeInset1 == imeInset2 } } } @RequiresApi(Build.VERSION_CODES.R) private fun pokeIME() { // This appears to be necessary for cuttlefish devices to show the keyboard val controller = rule.activity.window.insetsController controller?.show(android.view.WindowInsets.Type.ime()) controller?.hide(android.view.WindowInsets.Type.ime()) } @Test fun insetsUsedAfterInitialComposition() { var useInsets by mutableStateOf(false) var systemBarsInsets by mutableStateOf(Insets.NONE) rule.setContent { val view = LocalView.current DisposableEffect(Unit) { // Ensure that the system bars are shown val window = rule.activity.window @Suppress("RedundantNullableReturnType") // nullable on some versions val controller: WindowInsetsControllerCompat? = WindowCompat.getInsetsController(window, view) controller?.show(WindowInsetsCompat.Type.systemBars()) onDispose { } } Box(Modifier.fillMaxSize()) { if (useInsets) { val systemBars = WindowInsets.systemBars val density = LocalDensity.current val left = systemBars.getLeft(density, LayoutDirection.Ltr) val top = systemBars.getTop(density) val right = systemBars.getRight(density, LayoutDirection.Ltr) val bottom = systemBars.getBottom(density) systemBarsInsets = Insets.of(left, top, right, bottom) } } } rule.runOnIdle { useInsets = true } rule.runOnIdle { assertThat(systemBarsInsets).isNotEqualTo(Insets.NONE) } } @Test fun insetsAfterStopWatching() { var useInsets by mutableStateOf(true) var hasStatusBarInsets = false rule.setContent { val view = LocalView.current DisposableEffect(Unit) { // Ensure that the status bars are shown val window = rule.activity.window @Suppress("RedundantNullableReturnType") // nullable on some versions val controller: WindowInsetsControllerCompat? = WindowCompat.getInsetsController(window, view) controller?.hide(WindowInsetsCompat.Type.statusBars()) onDispose { } } Box(Modifier.fillMaxSize()) { if (useInsets) { val statusBars = WindowInsets.statusBars val density = LocalDensity.current val left = statusBars.getLeft(density, LayoutDirection.Ltr) val top = statusBars.getTop(density) val right = statusBars.getRight(density, LayoutDirection.Ltr) val bottom = statusBars.getBottom(density) hasStatusBarInsets = left != 0 || top != 0 || right != 0 || bottom != 0 } } } rule.waitForIdle() rule.waitUntil(1000) { !hasStatusBarInsets } // disable watching the insets rule.runOnIdle { useInsets = false } val statusBarsWatcher = StatusBarsShowListener() // show the insets while we're not watching rule.runOnIdle { ViewCompat.setOnApplyWindowInsetsListener( rule.activity.window.decorView, statusBarsWatcher ) @Suppress("RedundantNullableReturnType") val controller: WindowInsetsControllerCompat? = WindowCompat.getInsetsController( rule.activity.window, rule.activity.window.decorView ) controller?.show(WindowInsetsCompat.Type.statusBars()) } assertThat(statusBarsWatcher.latch.await(1, TimeUnit.SECONDS)).isTrue() // Now look at the insets rule.runOnIdle { useInsets = true } rule.runOnIdle { assertThat(hasStatusBarInsets).isTrue() } } @Test fun insetsAfterReattachingView() { var hasStatusBarInsets = false // hide the insets rule.runOnUiThread { @Suppress("RedundantNullableReturnType") val controller: WindowInsetsControllerCompat? = WindowCompat.getInsetsController( rule.activity.window, rule.activity.window.decorView ) controller?.hide(WindowInsetsCompat.Type.statusBars()) } rule.setContent { Box(Modifier.fillMaxSize()) { val statusBars = WindowInsets.statusBars val density = LocalDensity.current val left = statusBars.getLeft(density, LayoutDirection.Ltr) val top = statusBars.getTop(density) val right = statusBars.getRight(density, LayoutDirection.Ltr) val bottom = statusBars.getBottom(density) hasStatusBarInsets = left != 0 || top != 0 || right != 0 || bottom != 0 } } rule.waitForIdle() rule.waitUntil(1000) { !hasStatusBarInsets } val contentView = rule.activity.findViewById<ViewGroup>(android.R.id.content) val composeView = contentView.children.first() // remove the view rule.runOnUiThread { contentView.removeView(composeView) } val statusBarsWatcher = StatusBarsShowListener() // show the insets while we're not watching rule.runOnUiThread { ViewCompat.setOnApplyWindowInsetsListener( rule.activity.window.decorView, statusBarsWatcher ) @Suppress("RedundantNullableReturnType") val controller: WindowInsetsControllerCompat? = WindowCompat.getInsetsController( rule.activity.window, rule.activity.window.decorView ) controller?.show(WindowInsetsCompat.Type.statusBars()) } assertThat(statusBarsWatcher.latch.await(1, TimeUnit.SECONDS)).isTrue() // Now add the view back again rule.runOnUiThread { contentView.addView(composeView) } rule.waitUntil(1000) { hasStatusBarInsets } } /** * If we have setDecorFitsSystemWindows(false), there should be insets. */ @Test fun insetsSetAtStart() { var leftInset = 0 var topInset = 0 var rightInset = 0 var bottomInset = 0 rule.setContent { val insets = WindowInsets.safeContent leftInset = insets.getLeft(LocalDensity.current, LocalLayoutDirection.current) topInset = insets.getTop(LocalDensity.current) rightInset = insets.getRight(LocalDensity.current, LocalLayoutDirection.current) bottomInset = insets.getBottom(LocalDensity.current) } rule.waitForIdle() assertTrue( leftInset != 0 || topInset != 0 || rightInset != 0 || bottomInset != 0 ) } class StatusBarsShowListener : OnApplyWindowInsetsListener { val latch = CountDownLatch(1) override fun onApplyWindowInsets(v: View, insets: WindowInsetsCompat): WindowInsetsCompat { val statusBars = insets.getInsets(WindowInsetsCompat.Type.statusBars()) if (statusBars != Insets.NONE) { latch.countDown() ViewCompat.setOnApplyWindowInsetsListener(v, null) } return insets } } }
29
null
937
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
13,232
androidx
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsjobsboardapi/unit/messaging/OutboundEventsServiceTest.kt
ministryofjustice
775,484,528
false
{"Kotlin": 44647, "Dockerfile": 1154}
package uk.gov.justice.digital.hmpps.hmppsjobsboardapi.unit.messaging import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContext import uk.gov.justice.digital.hmpps.hmppsjobsboardapi.config.DpsPrincipal import uk.gov.justice.digital.hmpps.hmppsjobsboardapi.messaging.OutboundEventsPublisher import uk.gov.justice.digital.hmpps.hmppsjobsboardapi.messaging.OutboundEventsService @ExtendWith(MockitoExtension::class) class OutboundEventsServiceTest { private var outboundEventsService: OutboundEventsService? = null @Mock private val outboundEventsPublisher: OutboundEventsPublisher? = null @Mock private val securityContext: SecurityContext? = null @Mock private val authentication: Authentication? = null private val dpsPrincipal: DpsPrincipal = DpsPrincipal("Sacintha", "Sacintha Raj") @BeforeEach fun beforeClass() { outboundEventsService = OutboundEventsService(outboundEventsPublisher!!) } @Test fun should_Publish_Event_ForJobCreationAndUpdate() { } }
0
Kotlin
0
0
7be25a1356f2964feed77a3f4b7ea22044b12691
1,256
hmpps-jobs-board-api
MIT License
src/main/kotlin/snc/smartchargingnetwork/node/models/exceptions/ScpiExceptions.kt
Smart-Charging
245,366,665
false
{"Gradle Kotlin DSL": 2, "YAML": 2, "Dockerfile": 1, "INI": 3, "Shell": 3, "Text": 1, "Batchfile": 1, "Markdown": 2, "Kotlin": 152, "Java": 2, "Java Properties": 3, "AsciiDoc": 1, "desktop": 1, "JSON": 2}
/* Copyright 2020 Smart Charging Solutions 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 snc.smartchargingnetwork.node.models.exceptions import org.springframework.http.HttpStatus import snc.smartchargingnetwork.node.models.scpi.ScpiStatus // 2xxx: Client errors class ScpiClientGenericException(message: String, val httpStatus: HttpStatus = HttpStatus.BAD_REQUEST, val scpiStatus: ScpiStatus = ScpiStatus.CLIENT_ERROR): Exception(message) class ScpiClientInvalidParametersException(message: String = "Invalid or missing parameters", val httpStatus: HttpStatus = HttpStatus.BAD_REQUEST, val scpiStatus: ScpiStatus = ScpiStatus.CLIENT_INVALID_PARAMETERS): Exception(message) class ScpiClientNotEnoughInformationException(message: String = "Not enough information", val httpStatus: HttpStatus = HttpStatus.BAD_REQUEST, val scpiStatus: ScpiStatus = ScpiStatus.CLIENT_NOT_ENOUGH_INFO): Exception(message) class ScpiClientUnknownLocationException(message: String = "Unknown location", val httpStatus: HttpStatus = HttpStatus.NOT_FOUND, val scpiStatus: ScpiStatus = ScpiStatus.CLIENT_UNKNOWN_LOCATION): Exception(message) // 3xxx: Server errors class ScpiServerGenericException(message: String, val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.SERVER_ERROR): Exception(message) class ScpiServerUnusableApiException(message: String = "Unable to use client's API", val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.SERVER_UNUSABLE_API): Exception(message) class ScpiServerUnsupportedVersionException(message: String = "Unsupported version", val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.SERVER_UNSUPPORTED_VERSION): Exception(message) class ScpiServerNoMatchingEndpointsException(message: String = "No matching endpoints or expected endpoints missing between parties", val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.SERVER_NO_MATCHING_ENDPOINTS): Exception(message) // 4xxx: Hub errors class ScpiHubUnknownReceiverException(message: String = "Unknown receiver", val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.HUB_UNKNOWN_RECEIVER): Exception(message) class ScpiHubTimeoutOnRequestException(message: String = "Timeout on forwarded request", val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.HUB_REQUEST_TIMEOUT): Exception(message) class ScpiHubConnectionProblemException(message: String = "Connection problem", val httpStatus: HttpStatus = HttpStatus.OK, val scpiStatus: ScpiStatus = ScpiStatus.HUB_CONNECTION_PROBLEM): Exception(message)
1
null
1
1
15d7320f19d5ce94782a8e52635855dc046aa5a4
4,063
scn-node
Apache License 2.0
library/src/main/java/ru/mintrocket/lib/mintpermissions/internal/MintPermissionsControllerImpl.kt
mintrocket
503,334,946
false
{"Kotlin": 111822}
package ru.mintrocket.lib.mintpermissions.internal import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import ru.mintrocket.lib.mintpermissions.MintPermissionsController import ru.mintrocket.lib.mintpermissions.internal.statuses.StatusesController import ru.mintrocket.lib.mintpermissions.models.MintPermission import ru.mintrocket.lib.mintpermissions.models.MintPermissionResult import ru.mintrocket.lib.mintpermissions.models.MintPermissionStatus import ru.mintrocket.lib.mintpermissions.tools.uirequests.UiRequestController internal class MintPermissionsControllerImpl( private val requestsController: UiRequestController<List<MintPermission>, List<MintPermissionResult>>, private val statusesController: StatusesController ) : MintPermissionsController { override fun observe(permission: MintPermission): Flow<MintPermissionStatus> { return statusesController .observe() .map { statusMap -> statusMap.getStatus(permission) } .distinctUntilChanged() } override fun observe(permissions: List<MintPermission>): Flow<List<MintPermissionStatus>> { return statusesController .observe() .map { statusMap -> permissions.map { permission -> statusMap.getStatus(permission) } } .distinctUntilChanged() } override fun observeAll(): Flow<List<MintPermissionStatus>> { return statusesController .observe() .map { it.values.toList() } .distinctUntilChanged() } override suspend fun getAll(): List<MintPermissionStatus> { return observeAll().first() } override suspend fun get(permission: MintPermission): MintPermissionStatus { return observe(permission).first() } override suspend fun get(permissions: List<MintPermission>): List<MintPermissionStatus> { return observe(permissions).first() } override suspend fun request( permissions: List<MintPermission> ): List<MintPermissionResult> { return requestsController.request(permissions) } override suspend fun request(permission: MintPermission): MintPermissionResult { return request(listOf(permission)).first() } private fun Map<MintPermission, MintPermissionStatus>.getStatus( permission: MintPermission ): MintPermissionStatus { return get(permission) ?: MintPermissionStatus.NotFound(permission) } }
1
Kotlin
3
68
2de0d97454e7ab330418e53d9d1a2b899ca06ad0
2,638
MintPermissions
MIT License
tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_7/Step7Activity.kt
Zhuinden
78,756,993
false
null
package com.zhuinden.simplestacktutorials.steps.step_7 import android.content.Context import android.os.Bundle import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import com.zhuinden.simplestack.GlobalServices import com.zhuinden.simplestack.History import com.zhuinden.simplestack.SimpleStateChanger import com.zhuinden.simplestack.StateChange import com.zhuinden.simplestack.navigator.Navigator import com.zhuinden.simplestackextensions.fragments.DefaultFragmentStateChanger import com.zhuinden.simplestacktutorials.R import com.zhuinden.simplestacktutorials.databinding.ActivityStep7Binding import com.zhuinden.simplestacktutorials.steps.step_7.features.login.LoginKey import com.zhuinden.simplestacktutorials.steps.step_7.features.profile.ProfileKey class Step7Activity : AppCompatActivity(), SimpleStateChanger.NavigationHandler { @Suppress("DEPRECATION") private val backPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (!Navigator.onBackPressed(this@Step7Activity)) { this.remove() onBackPressed() // this is the reliable way to handle back for now [email protected](this) } } } private lateinit var fragmentStateChanger: DefaultFragmentStateChanger private lateinit var appContext: Context override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityStep7Binding.inflate(layoutInflater) setContentView(binding.root) onBackPressedDispatcher.addCallback(backPressedCallback) // this is the reliable way to handle back for now fragmentStateChanger = DefaultFragmentStateChanger(supportFragmentManager, R.id.step7Root) appContext = applicationContext Navigator.configure() .setStateChanger(SimpleStateChanger(this)) .setScopedServices(ServiceProvider()) .setGlobalServices( GlobalServices.builder() .addService("appContext", appContext) .build() ) .install( this, binding.step7Root, History.of( when { AuthenticationManager.isAuthenticated(appContext) -> ProfileKey() else -> LoginKey() } ) ) } override fun onNavigationEvent(stateChange: StateChange) { fragmentStateChanger.handleStateChange(stateChange) } override fun onDestroy() { if (isFinishing) { AuthenticationManager.clearRegistration(appContext) // just for sample repeat sake } super.onDestroy() } }
5
Java
76
1,309
c2d55fe826e9fcab995af9efe1270d23cfbd1417
2,833
simple-stack
Apache License 2.0
app/src/main/kotlin/com/sbhachu/bootstrap/extensions/ViewPager.kt
sbhachu
67,833,845
false
null
package com.sbhachu.bootstrap.extensions import android.support.v4.view.ViewPager import com.sbhachu.bootstrap.extensions.listener.PageWatcher fun ViewPager.pageListener(init: PageWatcher.() -> Unit) { addOnPageChangeListener(PageWatcher().apply(init)) }
0
Kotlin
2
2
f40f34667f435c9878ed62e7c066ff466b09fbfe
260
kotlin-bootstrap
Apache License 2.0
modules/feature/feature_schedule/src/test/kotlin/kekmech/ru/feature_schedule/ScheduleReducerTest.kt
tonykolomeytsev
203,239,594
false
null
package kekmech.ru.feature_schedule import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.maps.shouldBeEmpty import io.kotest.matchers.maps.shouldContainExactly import io.kotest.matchers.shouldBe import kekmech.ru.common_kotlin.mutableLinkedHashMap import kekmech.ru.common_schedule.utils.atStartOfWeek import kekmech.ru.domain_app_settings.AppSettings import kekmech.ru.domain_schedule.dto.* import kekmech.ru.feature_schedule.main.elm.ScheduleAction import kekmech.ru.feature_schedule.main.elm.ScheduleEffect import kekmech.ru.feature_schedule.main.elm.ScheduleEvent.News import kekmech.ru.feature_schedule.main.elm.ScheduleEvent.Wish import kekmech.ru.feature_schedule.main.elm.ScheduleReducer import kekmech.ru.feature_schedule.main.elm.ScheduleState import java.time.LocalDate import java.time.Month class ScheduleReducerTest : BehaviorSpec({ val reducer = ScheduleReducer() Given("Initial state, Weekday") { val givenState = STATE When("Wish.Init") { val (state, effects, actions) = reducer.reduce(Wish.Init, givenState) Then("Check state") { state.selectedDate shouldBe CURRENT_DATE state.weekOffset shouldBe 0 state.isAfterError.shouldBeFalse() state.isOnCurrentWeek.shouldBeTrue() state.isNavigationFabVisible.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly( ScheduleAction.LoadSchedule(0), ScheduleAction.LoadSchedule(1) ) } } } Given("Initial state, Weekend (Saturday)") { val givenState = STATE.copy(selectedDate = CURRENT_DATE_WEEKEND_SAT) When("Wish.Init") { val (state, effects, actions) = reducer.reduce(Wish.Init, givenState) Then("Check state") { state.selectedDate shouldBe CURRENT_DATE_WEEKEND_SAT.plusDays(2) state.weekOffset shouldBe 1 state.isAfterError.shouldBeFalse() state.isOnCurrentWeek.shouldBeFalse() state.isNavigationFabVisible.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly( ScheduleAction.LoadSchedule(0), ScheduleAction.LoadSchedule(1) ) } } } Given("Initial state, Weekend (Sunday)") { val givenState = STATE.copy(selectedDate = CURRENT_DATE_WEEKEND_SUN) When("Wish.Init") { val (state, effects, actions) = reducer.reduce(Wish.Init, givenState) Then("Check state") { state.selectedDate shouldBe CURRENT_DATE_WEEKEND_SUN.plusDays(1) state.weekOffset shouldBe 1 state.isAfterError.shouldBeFalse() state.isOnCurrentWeek.shouldBeFalse() state.isNavigationFabVisible.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly( ScheduleAction.LoadSchedule(0), ScheduleAction.LoadSchedule(1) ) } } } Given("While schedule loading") { val givenState = STATE When("News.ScheduleWeekLoadSuccess (0)") { val news = News.ScheduleWeekLoadSuccess(0, SCHEDULE_0) val (state, effects, actions) = reducer.reduce(news, givenState) Then("Check state") { state.schedule.shouldContainExactly(mapOf(0 to SCHEDULE_0)) state.isAfterError.shouldBeFalse() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldBeEmpty() } } When("News.ScheduleWeekLoadError (0)") { val news = News.ScheduleWeekLoadError(IllegalStateException("Wake up Neo")) val (state, effects, actions) = reducer.reduce( news, givenState.copy(schedule = mutableLinkedHashMap(CACHE_ENTRIES_SIZE)) ) Then("Check state") { state.schedule.shouldBeEmpty() state.isAfterError.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldBeEmpty() } } } Given("After schedule loading success") { val givenState = STATE.copy(schedule = mutableLinkedHashMap(CACHE_ENTRIES_SIZE)) When("Wish.Action.SelectWeek (1)") { val (state, effects, actions) = reducer.reduce(Wish.Action.SelectWeek(1), givenState) Then("Check state") { state.isAfterError.shouldBeFalse() state.selectedDate shouldBe givenState.selectedDate.plusDays(7) state.weekOffset shouldBe 1 } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly(ScheduleAction.LoadSchedule(1)) } } When("Wish.Action.SelectWeek (-1)") { val (state, effects, actions) = reducer.reduce(Wish.Action.SelectWeek(-1), givenState) Then("Check state") { state.isAfterError.shouldBeFalse() state.selectedDate shouldBe givenState.selectedDate.minusDays(7) state.weekOffset shouldBe -1 } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly(ScheduleAction.LoadSchedule(-1)) } } When("Wish.Click.Day") { val (state, effects, actions) = reducer.reduce(Wish.Click.Day(CURRENT_DATE_WEEKEND_SAT), givenState) Then("Check state") { state.selectedDate shouldBe CURRENT_DATE_WEEKEND_SAT state.isNavigationFabVisible.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldBeEmpty() } } When("Wish.Action.PageChanged") { val (state, effects, actions) = reducer.reduce(Wish.Action.PageChanged(1), givenState) Then("Check state") { state.selectedDate shouldBe CURRENT_DATE.atStartOfWeek().plusDays(1L) state.isNavigationFabVisible.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldBeEmpty() } } When("Wish.Click.Classes") { val (state, effects, actions) = reducer.reduce(Wish.Click.Classes(CLASSES), givenState) Then("Check state") { state shouldBe givenState } Then("Check effects") { effects.shouldContainExactly(ScheduleEffect.NavigateToNoteList(CLASSES, state.selectedDate)) } Then("Check actions") { actions.shouldBeEmpty() } } When("Wish.Click.FAB") { val (state, effects, actions) = reducer.reduce(Wish.Click.FAB, givenState) Then("Check state") { state.weekOffset shouldBe 1 state.selectedDate shouldBe CURRENT_DATE.plusDays(7L) state.isOnCurrentWeek.shouldBeFalse() state.isAfterError.shouldBeFalse() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly(ScheduleAction.LoadSchedule(1)) } } When("Wish.Action.NotesUpdated") { val (state, effects, actions) = reducer.reduce(Wish.Action.UpdateScheduleIfNeeded, givenState) Then("Check state") { state shouldBe givenState } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly(ScheduleAction.LoadSchedule(0)) } } When("Wish.Action.UpdateScheduleIfNeeded") { val (state, effects, actions) = reducer.reduce(Wish.Action.UpdateScheduleIfNeeded, givenState) Then("Check state") { state shouldBe givenState } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldContainExactly(ScheduleAction.LoadSchedule(0)) } } When("Wish.Action.ClassesScrolled (scrolled down)") { val (state, effects, actions) = reducer.reduce(Wish.Action.ClassesScrolled(1), givenState) Then("Check state") { state.isNavigationFabVisible.shouldBeFalse() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldBeEmpty() } } When("Wish.Action.ClassesScrolled (scrolled up)") { val (state, effects, actions) = reducer.reduce(Wish.Action.ClassesScrolled(-1), givenState) Then("Check state") { state.isNavigationFabVisible.shouldBeTrue() } Then("Check effects") { effects.shouldBeEmpty() } Then("Check actions") { actions.shouldBeEmpty() } } } }) { companion object { private val APP_SETTINGS = object : AppSettings { override val isDarkThemeEnabled: Boolean get() = false override val autoHideBottomSheet: Boolean get() = false override val isSnowEnabled: Boolean get() = false override val isDebugEnvironment: Boolean get() = false override val languageCode: String get() = "ru_RU" override val showNavigationButton: Boolean get() = false override val mapAppearanceType: String get() = "hybrid" } private const val CACHE_ENTRIES_SIZE = 2 private val CURRENT_DATE = LocalDate.of(2020, Month.SEPTEMBER, 17) private val CURRENT_DATE_WEEKEND_SAT = LocalDate.of(2020, Month.SEPTEMBER, 19) // saturday private val CURRENT_DATE_WEEKEND_SUN = LocalDate.of(2020, Month.SEPTEMBER, 20) // saturday private val STATE = ScheduleState( appSettings = APP_SETTINGS, selectedDate = CURRENT_DATE, schedule = mutableLinkedHashMap(CACHE_ENTRIES_SIZE) ) private val CURRENT_MONDAY = LocalDate.of(2020, Month.SEPTEMBER, 14) private val SCHEDULE_0 = Schedule( name = "C-12-16", id = "12345", type = ScheduleType.GROUP, weeks = listOf(Week( weekOfSemester = 3, weekOfYear = 36, firstDayOfWeek = CURRENT_MONDAY, days = listOf( Day( dayOfWeek = 1, date = CURRENT_MONDAY, classes = listOf() ) ) )) ) private val CLASSES = Classes( name = "Гидропневмопривод мехатронных и робототехнчиеских систем", type = ClassesType.PRACTICE, rawType = "", groups = "С-12-16", place = "", person = "<NAME> number = 4 ) } }
9
Kotlin
4
21
4ad7b2fe62efb956dc7f8255d35436695643d229
12,353
mpeiapp
MIT License
src/main/kotlin/org/batteryparkdev/cosmicgraphdb/neo4j/loader/CosmicTumorLoader.kt
fcriscuo
407,274,893
false
{"Java": 281073, "Kotlin": 178148}
package org.batteryparkdev.cosmicgraphdb.neo4j.loader import com.google.common.base.Stopwatch import com.google.common.flogger.FluentLogger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.batteryparkdev.cosmicgraphdb.cosmic.model.CosmicTumor import org.batteryparkdev.cosmicgraphdb.io.TsvRecordSequenceSupplier import org.batteryparkdev.cosmicgraphdb.neo4j.dao.* import java.nio.file.Paths import java.util.concurrent.TimeUnit object CosmicTumorLoader { private val logger: FluentLogger = FluentLogger.forEnclosingClass() @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.parseCosmicMutantExportCensusFile(mutantExportFile: String) = produce<CosmicTumor> { val path = Paths.get(mutantExportFile) TsvRecordSequenceSupplier(path).get() .forEach { send(CosmicTumor.parseCsvRecord(it)) delay(20) } } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.loadCosmicTumors(tumors: ReceiveChannel<CosmicTumor>) = produce<CosmicTumor> { for (tumor in tumors) { loadCosmicTumor(tumor) send(tumor) delay(20) } } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.processTumorSiteType(tumors: ReceiveChannel<CosmicTumor>) = produce<CosmicTumor> { for (tumor in tumors) { CosmicTypeDao.processCosmicTypeNode(tumor.site) send(tumor) delay(20) } } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.processTumorHistologyType(tumors: ReceiveChannel<CosmicTumor>) = produce<CosmicTumor> { for (tumor in tumors) { CosmicTypeDao.processCosmicTypeNode(tumor.histology) send(tumor) delay(20) } } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.processSampleRelationships(tumors: ReceiveChannel<CosmicTumor>) = produce<CosmicTumor> { for (tumor in tumors) { createCosmicSampleRelationship(tumor) send(tumor) delay(20) } } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.processMutationRelationships(tumors: ReceiveChannel<CosmicTumor>) = produce<CosmicTumor> { for (tumor in tumors) { createCosmicMutationRelationship(tumor) send(tumor) delay(20) } } @OptIn(ExperimentalCoroutinesApi::class) private fun CoroutineScope.processPubMedRelationships(tumors: ReceiveChannel<CosmicTumor>) = produce<Int> { for (tumor in tumors) { createPubMedRelationship(tumor) send(tumor.tumorId) delay(20) } } fun processCosmicTumorData(filename: String) = runBlocking { logger.atInfo().log("Loading CosmicMutantExport data from file $filename") var nodeCount = 0 val stopwatch = Stopwatch.createStarted() val ids = processPubMedRelationships( processMutationRelationships( processSampleRelationships( processTumorHistologyType( processTumorSiteType( loadCosmicTumors( parseCosmicMutantExportCensusFile(filename) ) ) ) ) ) ) for (id in ids) { // pipeline stream is lazy - need to consume output nodeCount += 1 } logger.atInfo().log( "CosmicMutantExport data loaded " + " $nodeCount nodes in " + " ${stopwatch.elapsed(TimeUnit.SECONDS)} seconds" ) } } fun main(args: Array<String>) { val filename = if (args.isNotEmpty()) args[0] else "./data/sample_CosmicMutantExportCensus.tsv" CosmicTumorLoader.processCosmicTumorData(filename) }
1
null
1
1
c55422a21c5250e61a8437fba533caff0c1c3b83
4,423
CosmicGraphDb
Creative Commons Zero v1.0 Universal
app/src/test/java/com/garymcgowan/moviepedia/MovieDetailsActivityPresenterTest.kt
GaryMcGowan
89,954,716
false
null
package com.garymcgowan.moviepedia import com.garymcgowan.moviepedia.model.Movie import com.garymcgowan.moviepedia.model.MovieRepository import com.garymcgowan.moviepedia.view.details.MovieDetailsContract import com.garymcgowan.moviepedia.view.details.MovieDetailsPresenter import io.reactivex.Single import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations class MovieDetailsActivityPresenterTest { //@Rule open var mockitoRule = MockitoJUnit.rule() @Mock lateinit var view: MovieDetailsContract.View @Mock lateinit var movieRepository: MovieRepository lateinit var presenter: MovieDetailsPresenter private val MOVIE = Movie() @Before fun setUp() { MockitoAnnotations.initMocks(this) RxJavaPlugins.setIoSchedulerHandler { scheduler -> Schedulers.trampoline() } presenter = MovieDetailsPresenter( movieRepository, Schedulers.trampoline()) } @After fun cleanUp() { RxJavaPlugins.reset() } @Test fun shouldPassMovieDetailsToView() { `when`(movieRepository!!.getMovieDetails("123")).thenReturn(Single.just(MOVIE)) presenter.loadMovieDetails("123") verify<MovieDetailsContract.View>(view).displayMovieDetails(MOVIE) } @Test fun loadMovieDetailsDisplayError() { `when`(movieRepository!!.getMovieDetails("123")).thenReturn(Single.error(Throwable("error occurred"))) presenter.loadMovieDetails("123") verify<MovieDetailsContract.View>(view).displayError(Mockito.anyString()) } }
0
Kotlin
0
0
2010e76a8b771d9d55f9d808d4b8d6f24069d84e
1,788
Moviepedia
Apache License 2.0
compiler-plugin/src/main/java/io/mths/kava/compiler/frontend/k2/resolve/ConstantValueKind.kt
MerlinTHS
598,539,841
false
null
package io.mths.kava.compiler.frontend.k2.resolve import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.expressions.FirConstExpression import org.jetbrains.kotlin.fir.expressions.builder.buildConstExpression import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.expectedConeType import org.jetbrains.kotlin.types.ConstantValueKind /** * Creates a [FirConstExpression] with a resolved typeRef from the receivers value * and the constant [kind]. */ context (FirSession) infix fun <Type> Type.asConstant( kind: ConstantValueKind<Type> ): FirConstExpression<Type> = buildConstExpression( source = null, kind, value = this ) resolvedAs kind.expectedConeType(this@FirSession)
0
Kotlin
0
0
5d038afd21c7099a47eb889422dbdb4b34926d0f
743
KavaCompilerPlugin
Apache License 2.0
src/main/kotlin/care/better/platform/web/template/builder/model/input/range/WebTemplateTemporalRange.kt
better-care
343,549,109
false
null
/* Copyright 2021 Better Ltd (www.better.care) * * 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 care.better.platform.web.template.builder.model.input.range import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonPropertyOrder import org.openehr.base.foundationtypes.IntervalOfDate import org.openehr.base.foundationtypes.IntervalOfDateTime import org.openehr.base.foundationtypes.IntervalOfDuration import org.openehr.base.foundationtypes.IntervalOfTime import java.util.* /** * @author <NAME> * @author <NAME> * @since 3.1.0 */ @JsonPropertyOrder("min", "minOp", "max", "maxOp") class WebTemplateTemporalRange(val min: String?, val minOp: String?, val max: String?, val maxOp: String?) : WebTemplateRange<String> { constructor(interval: IntervalOfTime?) : this( if (interval != null && !interval.isLowerUnbounded()) interval.lower else null, if (interval != null && !interval.isLowerUnbounded()) WebTemplateRange.getMinOp(interval) else null, if (interval != null && !interval.isUpperUnbounded()) interval.upper else null, if (interval != null && !interval.isUpperUnbounded()) WebTemplateRange.getMaxOp(interval) else null) constructor(interval: IntervalOfDateTime?) : this( if (interval != null && !interval.isLowerUnbounded()) interval.lower else null, if (interval != null && !interval.isLowerUnbounded()) WebTemplateRange.getMinOp(interval) else null, if (interval != null && !interval.isUpperUnbounded()) interval.upper else null, if (interval != null && !interval.isUpperUnbounded()) WebTemplateRange.getMaxOp(interval) else null) constructor(interval: IntervalOfDate?) : this( if (interval != null && !interval.isLowerUnbounded()) interval.lower else null, if (interval != null && !interval.isLowerUnbounded()) WebTemplateRange.getMinOp(interval) else null, if (interval != null && !interval.isUpperUnbounded()) interval.upper else null, if (interval != null && !interval.isUpperUnbounded()) WebTemplateRange.getMaxOp(interval) else null) constructor(interval: IntervalOfDuration?) : this( if (interval != null && !interval.isLowerUnbounded()) interval.lower else null, if (interval != null && !interval.isLowerUnbounded()) WebTemplateRange.getMinOp(interval) else null, if (interval != null && !interval.isUpperUnbounded()) interval.upper else null, if (interval != null && !interval.isUpperUnbounded()) WebTemplateRange.getMaxOp(interval) else null) @JsonIgnore override fun isEmpty(): Boolean = min == null && max == null @JsonIgnore override fun isFixed(): Boolean = WebTemplateRange.isFixed(this, minOp, maxOp) @JsonIgnore override fun getMinimal(): String? = min @JsonIgnore override fun getMaximal(): String? = max override fun equals(other: Any?): Boolean = when { this === other -> true other !is WebTemplateTemporalRange -> false else -> min == other.min && minOp == other.minOp && max == other.max && maxOp == other.maxOp } override fun hashCode(): Int = Objects.hash(min, minOp, max, maxOp) }
0
Kotlin
1
1
4aa47c5c598be6687dc2c095b1f7fcee49702a28
3,722
web-template
Apache License 2.0
core/model/src/test/kotlin/au/com/dius/pact/core/model/OptionalBodyTest.kt
pact-foundation
15,750,847
false
null
package au.com.dius.pact.core.model import io.kotlintest.matchers.shouldBe import io.kotlintest.matchers.shouldEqual import io.kotlintest.specs.StringSpec import java.nio.charset.Charset class OptionalBodyTest : StringSpec() { val nullBodyVar: OptionalBody? = null val missingBody = OptionalBody.missing() val nullBody = OptionalBody.nullBody() val emptyBody = OptionalBody.empty() val presentBody = OptionalBody.body("present".toByteArray()) init { "a null body variable is missing" { nullBodyVar.isMissing() shouldBe true } "a missing body is missing" { missingBody.isMissing() shouldBe true } "a body that contains a null is not missing" { nullBody.isMissing() shouldBe false } "an empty body is not missing" { emptyBody.isMissing() shouldBe false } "a present body is not missing" { presentBody.isMissing() shouldBe false } "a null body variable is null" { nullBodyVar.isNull() shouldBe true } "a missing body is not null" { missingBody.isNull() shouldBe false } "a body that contains a null is null" { nullBody.isNull() shouldBe true } "an empty body is not null" { emptyBody.isNull() shouldBe false } "a present body is not null" { presentBody.isNull() shouldBe false } "a null body variable is not empty" { nullBodyVar.isEmpty() shouldBe false } "a missing body is not empty" { missingBody.isEmpty() shouldBe false } "a body that contains a null is not empty" { nullBody.isEmpty() shouldBe false } "an empty body is empty" { emptyBody.isEmpty() shouldBe true } "a present body is not empty" { presentBody.isEmpty() shouldBe false } "a null body variable is not present" { nullBodyVar.isPresent() shouldBe false } "a missing body is not present" { missingBody.isPresent() shouldBe false } "a body that contains a null is not present" { nullBody.isPresent() shouldBe false } "an empty body is not present" { emptyBody.isPresent() shouldBe false } "a present body is present" { presentBody.isPresent() shouldBe true } "a null body or else returns the else" { nullBodyVar.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldEqual "else" } "a missing body or else returns the else" { missingBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldEqual "else" } "a body that contains a null or else returns the else" { nullBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldEqual "else" } "an empty body or else returns empty" { emptyBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldEqual "" } "a present body or else returns the body" { presentBody.orElse("else".toByteArray()).toString(Charset.defaultCharset()) shouldEqual "present" } } }
338
null
466
998
74cd39cc2d2717abce6b44025dd40fc86fc64a74
3,024
pact-jvm
Apache License 2.0
idea/tests/testData/multiModuleQuickFix/createExpect/sealedClass/jvm/My.kt
JetBrains
278,369,660
false
null
// "Create expected class in common module testModule_Common" "true" // DISABLE-ERRORS actual sealed class <caret>My actual constructor(actual val x: Double) { actual abstract val num: Int actual open fun isGood() = false actual object First : My(1.0) { actual override val num = 0 } actual class Some actual constructor(actual override val num: Int) : My(num.toDouble()) actual object Best : My(999.0) { actual override val num = 42 actual override fun isGood() = true } }
284
null
5162
82
cc81d7505bc3e9ad503d706998ae8026c067e838
532
intellij-kotlin
Apache License 2.0
projects/wotw-server/src/commonMain/kotlin/wotw.util/MultiMap.kt
timoschwarzer
371,785,735
true
{"C": 48238133, "C++": 47731793, "C#": 1375424, "Rust": 410871, "Kotlin": 246948, "Scala": 132870, "AutoHotkey": 78595, "CMake": 41111, "Objective-C": 9352, "CSS": 7917, "Batchfile": 3132, "JavaScript": 1623, "Shell": 622, "HTML": 296}
package wotw.util class MultiMap<K, V>(private val backingMap: MutableMap<K, MutableSet<V>>): Map<K, MutableSet<V>> by backingMap{ constructor(): this(hashMapOf()) override operator fun get(key: K): MutableSet<V>{ return backingMap.getOrPut(key){ mutableSetOf()} } fun add(key: K, value: V){ get(key) += value } fun remove(key: K, value: V){ if(containsKey(key)) get(key) -= value } }
0
C
0
0
f5a1582a4d70f0046c20f572c3c4d2b4da2522b6
452
OriWotwRandomizerClient
MIT License
app/src/main/java/org/stepic/droid/ui/fragments/FastContinueFragment.kt
romanbannikov
205,717,847
false
null
package org.stepic.droid.ui.fragments import android.graphics.BitmapFactory import android.os.Bundle import android.support.annotation.StringRes import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.bumptech.glide.request.target.BitmapImageViewTarget import kotlinx.android.synthetic.main.fragment_fast_continue.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.base.Client import org.stepic.droid.base.FragmentBase import org.stepic.droid.core.dropping.contract.DroppingListener import org.stepic.droid.core.joining.contract.JoiningListener import org.stepic.droid.core.presenters.ContinueCoursePresenter import org.stepic.droid.core.presenters.FastContinuePresenter import org.stepic.droid.core.presenters.PersistentCourseListPresenter import org.stepic.droid.core.presenters.contracts.ContinueCourseView import org.stepic.droid.core.presenters.contracts.FastContinueView import org.stepic.droid.model.CourseListType import org.stepik.android.model.Course import org.stepic.droid.ui.activities.MainFeedActivity import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.util.RoundedBitmapImageViewTarget import org.stepic.droid.ui.util.changeVisibility import org.stepic.droid.util.ProgressHelper import org.stepic.droid.util.ProgressUtil import org.stepic.droid.util.StepikLogicHelper import org.stepik.android.domain.last_step.model.LastStep import javax.inject.Inject class FastContinueFragment : FragmentBase(), ContinueCourseView, DroppingListener, JoiningListener, FastContinueView { companion object { fun newInstance(): FastContinueFragment = FastContinueFragment() private const val CONTINUE_LOADING_TAG = "CONTINUE_LOADING_TAG" } @Inject lateinit var courseListPresenter: PersistentCourseListPresenter @Inject lateinit var continueCoursePresenter: ContinueCoursePresenter @Inject lateinit var droppingClient: Client<DroppingListener> @Inject lateinit var joiningListenerClient: Client<JoiningListener> @Inject lateinit var fastContinuePresenter: FastContinuePresenter private lateinit var courseCoverImageViewTarget: BitmapImageViewTarget private val coursePlaceholderDrawable by lazy { val coursePlaceholderBitmap = BitmapFactory.decodeResource(resources, R.drawable.general_placeholder) val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, coursePlaceholderBitmap) circularBitmapDrawable.cornerRadius = resources.getDimension(R.dimen.course_image_radius) return@lazy circularBitmapDrawable } override fun injectComponent() { App .componentManager() .courseGeneralComponent() .courseListComponentBuilder() .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_fast_continue, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) courseCoverImageViewTarget = RoundedBitmapImageViewTarget(resources.getDimension(R.dimen.course_image_radius), fastContinueCourseCover) continueCoursePresenter.attachView(this) droppingClient.subscribe(this) joiningListenerClient.subscribe(this) fastContinueAction.isEnabled = true } override fun onResume() { super.onResume() fastContinuePresenter.attachView(this) fastContinuePresenter.onCreated() } override fun onPause() { fastContinuePresenter.detachView(this) super.onPause() ProgressHelper.dismiss(fragmentManager, CONTINUE_LOADING_TAG) } override fun onDestroyView() { super.onDestroyView() joiningListenerClient.unsubscribe(this) continueCoursePresenter.detachView(this) droppingClient.unsubscribe(this) } override fun onAnonymous() { analytic.reportEvent(Analytic.FastContinue.AUTH_SHOWN) showPlaceholder(R.string.placeholder_login) { _ -> analytic.reportEvent(Analytic.FastContinue.AUTH_CLICK) screenManager.showLaunchScreen(context, true, MainFeedActivity.HOME_INDEX) } } override fun onEmptyCourse() { // tbh: courses might be not empty, but not active // we can show suggestion for enroll, but not write, that you have zero courses analytic.reportEvent(Analytic.FastContinue.EMPTY_COURSES_SHOWN) showPlaceholder(R.string.placeholder_explore_courses) { _ -> analytic.reportEvent(Analytic.FastContinue.EMPTY_COURSES_CLICK) screenManager.showCatalog(context) } } override fun onShowCourse(course: Course) { fastContinueProgress.visibility = View.GONE fastContinuePlaceholder.visibility = View.GONE analytic.reportEvent(Analytic.FastContinue.CONTINUE_SHOWN) setCourse(course) showMainGroup(true) fastContinueAction.setOnClickListener { analytic.reportEvent(Analytic.FastContinue.CONTINUE_CLICK) analytic.reportAmplitudeEvent(AmplitudeAnalytic.Course.CONTINUE_PRESSED, mapOf( AmplitudeAnalytic.Course.Params.COURSE to course.id, AmplitudeAnalytic.Course.Params.SOURCE to AmplitudeAnalytic.Course.Values.HOME_WIDGET )) continueCoursePresenter.continueCourse(course) } } override fun onLoading() { fastContinueProgress.visibility = View.VISIBLE showMainGroup(false) fastContinuePlaceholder.visibility = View.GONE } private fun setCourse(course: Course) { Glide .with(context) .load(StepikLogicHelper.getPathForCourseOrEmpty(course, config)) .asBitmap() .placeholder(coursePlaceholderDrawable) .fitCenter() .into(courseCoverImageViewTarget) fastContinueCourseName.text = course.title val progress = ProgressUtil.getProgressPercent(course.progressObject) ?: 0 fastContinueCourseProgressText.text = getString(R.string.course_current_progress, progress) fastContinueCourseProgress.progress = progress } //ContinueCourseView override fun onShowContinueCourseLoadingDialog() { fastContinueAction.isEnabled = false val loadingProgressDialogFragment = LoadingProgressDialogFragment.newInstance() if (!loadingProgressDialogFragment.isAdded) { loadingProgressDialogFragment.show(fragmentManager, CONTINUE_LOADING_TAG) } } override fun onOpenStep(courseId: Long, lastStep: LastStep) { ProgressHelper.dismiss(fragmentManager, CONTINUE_LOADING_TAG) fastContinueAction.isEnabled = true screenManager.continueCourse(activity, courseId, lastStep.unit, lastStep.lesson, lastStep.step) } override fun onOpenAdaptiveCourse(course: Course) { ProgressHelper.dismiss(fragmentManager, CONTINUE_LOADING_TAG) fastContinueAction.isEnabled = true screenManager.continueAdaptiveCourse(activity, course) } override fun onAnyProblemWhileContinue(course: Course) { ProgressHelper.dismiss(fragmentManager, CONTINUE_LOADING_TAG) fastContinueAction.isEnabled = true screenManager.showCourseModules(activity, course) } //Client<DroppingListener> override fun onSuccessDropCourse(course: Course) { //reload the last course courseListPresenter.refreshData(CourseListType.ENROLLED) } override fun onFailDropCourse(course: Course) { //no-op } private fun showPlaceholder(@StringRes stringRes: Int, listener: (view: View) -> Unit) { fastContinueProgress.visibility = View.GONE fastContinuePlaceholder.setPlaceholderText(stringRes) fastContinuePlaceholder.setOnClickListener(listener) showMainGroup(false) fastContinuePlaceholder.visibility = View.VISIBLE } private fun showMainGroup(needShow: Boolean) { fastContinueMask.changeVisibility(needShow) } override fun onSuccessJoin(joinedCourse: Course) { onShowCourse(joinedCourse) } }
1
null
1
1
8a2ead7334b6b26a281b3a7842e6502fd96b2cc5
8,657
stepik-android
Apache License 2.0
src/test/java/net/swiftzer/semver/SemVerTest.kt
swiftzer
107,759,525
false
null
package net.swiftzer.semver import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFails import kotlin.test.assertFalse import kotlin.test.assertTrue class SemVerTest { @Test fun initValid() { SemVer(12, 23, 34, "alpha.12", "test.34") } @Test fun initInvalidMajor() { assertFails { SemVer(-1, 23, 34, "alpha.12", "test.34") } } @Test fun initInvalidMinor() { assertFails { SemVer(12, -1, 34, "alpha.12", "test.34") } } @Test fun initInvalidPatch() { assertFails { SemVer(12, 23, -1, "alpha.12", "test.34") } } @Test fun initInvalidPreRelease() { assertFails { SemVer(12, 23, 34, "alpha.12#", "test.34") } } @Test fun initInvalidMetadata() { assertFails { SemVer(12, 23, 34, "alpha.12", "test.34#") } } @Test fun parseNumeric() { val actual = SemVer.parse("1.0.45") val expected = SemVer(1, 0, 45) assertEquals(expected, actual) } @Test fun parseIncompleteNumeric1() { val actual = SemVer.parse("432") val expected = SemVer(432) assertEquals(expected, actual) } @Test fun parseIncompleteNumeric2() { val actual = SemVer.parse("53.203") val expected = SemVer(53, 203) assertEquals(expected, actual) } @Test fun parseIncompleteNumeric3() { val actual = SemVer.parse("2..235") val expected = SemVer(2, 0, 235) assertEquals(expected, actual) } @Test fun parsePreRelease() { val actual = SemVer.parse("1.0.0-alpha.beta-a.12") val expected = SemVer(1, 0, 0, preRelease = "alpha.beta-a.12") assertEquals(expected, actual) } @Test fun parseIncompletePreRelease() { val actual = SemVer.parse("34..430-alpha.beta.gamma-a.12") val expected = SemVer(34, 0, 430, preRelease = "alpha.beta.gamma-a.12") assertEquals(expected, actual) } @Test fun parseMetadata() { val actual = SemVer.parse("1.0.0+exp.sha-part.5114f85") val expected = SemVer(1, 0, 0, buildMetadata = "exp.sha-part.5114f85") assertEquals(expected, actual) } @Test fun parseIncompleteMetadata() { val actual = SemVer.parse("88.30+exp.sha-part.5114f85") val expected = SemVer(88, 30, 0, buildMetadata = "exp.sha-part.5114f85") assertEquals(expected, actual) } @Test fun parseAll() { val actual = SemVer.parse("1.0.0-beta+exp.sha.5114f85") val expected = SemVer(1, 0, 0, preRelease = "beta", buildMetadata = "exp.sha.5114f85") assertEquals(expected, actual) } @Test fun parseIncompleteAll1() { val actual = SemVer.parse("..-beta+exp.sha.5114f85") val expected = SemVer(0, 0, 0, preRelease = "beta", buildMetadata = "exp.sha.5114f85") assertEquals(expected, actual) } @Test fun parseIncompleteAll2() { val actual = SemVer.parse(".34.-beta+exp.sha.5114f85") val expected = SemVer(0, 34, 0, preRelease = "beta", buildMetadata = "exp.sha.5114f85") assertEquals(expected, actual) } @Test fun parseInvalid() { assertFails { SemVer.parse("1.0.1.4-beta+exp.sha.5114f85") } } @Test fun isInitialDevelopmentPhaseTrue() { assertTrue { SemVer(0, 23, 34, "alpha.123", "testing.123").isInitialDevelopmentPhase() } } @Test fun isInitialDevelopmentPhaseFalse() { assertFalse { SemVer(1, 23, 34, "alpha.123", "testing.123").isInitialDevelopmentPhase() } } @Test fun toStringNumeric() { val semVer = SemVer(1, 0, 45) assertEquals("1.0.45", semVer.toString()) } @Test fun toStringPreRelease() { val semVer = SemVer(1, 0, 0, preRelease = "alpha.beta-a.12") assertEquals("1.0.0-alpha.beta-a.12", semVer.toString()) } @Test fun toStringMetadata() { val semVer = SemVer(1, 0, 0, buildMetadata = "exp.sha-part.5114f85") assertEquals("1.0.0+exp.sha-part.5114f85", semVer.toString()) } @Test fun toStringAll() { val semVer = SemVer(1, 0, 0, preRelease = "beta", buildMetadata = "exp.sha.5114f85") assertEquals("1.0.0-beta+exp.sha.5114f85", semVer.toString()) } @Test fun compareToNumeric1() { val semVer1 = SemVer(1, 0, 0) val semVer2 = SemVer(1, 0, 0) assertEquals(0, semVer1.compareTo(semVer2)) } @Test fun compareToNumeric2() { val semVer1 = SemVer(1, 0, 0) val semVer2 = SemVer(2, 0, 0) assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToNumeric3() { val semVer1 = SemVer(2, 0, 0) val semVer2 = SemVer(2, 1, 0) assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToNumeric4() { val semVer1 = SemVer(2, 1, 4) val semVer2 = SemVer(2, 1, 0) assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToNumeric5() { val semVer1 = SemVer(2, 0, 0) val semVer2 = SemVer(1, 0, 0) assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToNumeric6() { val semVer1 = SemVer(1, 2, 0) val semVer2 = SemVer(1, 0, 0) assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToNumeric7() { val semVer1 = SemVer(1, 0, 0) val semVer2 = SemVer(1, 0, 2) assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease1() { val semVer1 = SemVer(1, 0, 0) val semVer2 = SemVer(1, 0, 0, preRelease = "alpha") assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease2() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha") val semVer2 = SemVer(1, 0, 0) assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease3() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.1") assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease4() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.1") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha") assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease5() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.1") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.beta") assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease6() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.beta") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.1") assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease7() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.1") val semVer2 = SemVer(1, 0, 0, preRelease = "beta") assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease8() { val semVer1 = SemVer(1, 0, 0, preRelease = "beta") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.1") assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease9() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.1") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.2") assertEquals(-1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease10() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.2") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.1") assertEquals(1, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease11() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha.1") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha.1") assertEquals(0, semVer1.compareTo(semVer2)) } @Test fun compareToPreRelease12() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha") assertEquals(0, semVer1.compareTo(semVer2)) } @Test fun compareToPreReleaseMetadata() { val semVer1 = SemVer(1, 0, 0, preRelease = "alpha", buildMetadata = "xyz") val semVer2 = SemVer(1, 0, 0, preRelease = "alpha", buildMetadata = "abc") assertEquals(0, semVer1.compareTo(semVer2)) } @Test fun compareToPreReleaseNonNumericSmaller() { val semVer1 = SemVer(1, 0, 0, preRelease = Int.MAX_VALUE.toString()) val semVer2 = SemVer(1, 0, 0, preRelease = Long.MAX_VALUE.toString()) assertTrue { semVer1 < semVer2 } } @Test fun compareToPreReleaseNonNumericLarger() { val semVer1 = SemVer(1, 0, 0, preRelease = Long.MAX_VALUE.toString()) val semVer2 = SemVer(1, 0, 0, preRelease = Int.MAX_VALUE.toString()) assertTrue { semVer1 > semVer2 } } @Test fun compareToPreReleaseNonNumericSame() { val semVer1 = SemVer(1, 0, 0, preRelease = Long.MAX_VALUE.toString()) val semVer2 = SemVer(1, 0, 0, preRelease = Long.MAX_VALUE.toString()) assertEquals(0, semVer1.compareTo(semVer2)) } @Test fun createsNextMajor() { val newMajor = SemVer(1, 3, 5).nextMajor() assertEquals(2, newMajor.major) assertEquals(0, newMajor.minor) assertEquals(0, newMajor.patch) } @Test fun createsNextMinor() { val newMinor = SemVer(1, 3, 5).nextMinor() assertEquals(1, newMinor.major) assertEquals(4, newMinor.minor) assertEquals(0, newMinor.patch) } @Test fun createsNextPatch() { val newPatch = SemVer(1, 3, 5).nextPatch() assertEquals(1, newPatch.major) assertEquals(3, newPatch.minor) assertEquals(6, newPatch.patch) } }
6
null
13
70
57dbf2f10c83629e5f7a85d89df7a7383f9c6328
9,929
semver
MIT License
app/src/main/java/com/progix/fridgex/light/functions/Functions.kt
T8RIN
417,568,516
false
{"Kotlin": 454504, "Java": 146}
package com.progix.fridgex.light.functions import android.content.Context import android.content.ContextWrapper import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Handler import android.os.Looper import com.progix.fridgex.light.data.DataArrays import com.progix.fridgex.light.model.RecipeItem import com.progix.fridgex.light.model.RecyclerSortItem import java.io.* object Functions { private const val d = 256 fun strToInt(txt: String): Int { var ida = 0 var cnt = 0 for (element in txt) { ida += Character.codePointAt(charArrayOf(element), 0) cnt++ } if (ida < 200) { ida += (d * 2.8).toInt() } else if (ida < 1000) { ida += 1000 } return ida * cnt } fun saveToInternalStorage( applicationContext: Context, bitmapImage: Bitmap, name: String ): String? { val cw = ContextWrapper(applicationContext) val directory = cw.getDir("imageDir", Context.MODE_PRIVATE) val path = File(directory, name) var fos: FileOutputStream? = null try { fos = FileOutputStream(path) bitmapImage.compress(Bitmap.CompressFormat.PNG, 85, fos) } catch (e: Exception) { e.printStackTrace() } finally { try { fos!!.close() } catch (e: IOException) { e.printStackTrace() } } return directory.absolutePath } fun loadImageFromStorage(context: Context, name: String): Bitmap? { val cw = ContextWrapper(context) val directory = cw.getDir("imageDir", Context.MODE_PRIVATE) try { val f = File(directory, name) return BitmapFactory.decodeStream(FileInputStream(f)) } catch (e: FileNotFoundException) { e.printStackTrace() } return null } fun addItemToList( id: Int, pairList: ArrayList<RecyclerSortItem>, percentage: Double, time: Int, cal: Double, prot: Double, fats: Double, carboh: Double, indicator: Int, name: String, xOfY: String ) { when (id + 1 <= DataArrays.recipeImages.size) { true -> { pairList.add( RecyclerSortItem( percentage, time, cal, prot, fats, carboh, RecipeItem( DataArrays.recipeImages[id], indicator, name, time.toString(), xOfY ) ) ) } else -> { pairList.add( RecyclerSortItem( percentage, time, cal, prot, fats, carboh, RecipeItem( -1, indicator, name, time.toString(), xOfY ) ) ) } } } fun searchString(subString: String, string: String): Int { val q = 101 var h = 1 var i: Int var j: Int var p = 0 var t = 0 val m = subString.length val n = string.length if (m <= n) { i = 0 while (i < m - 1) { h = h * d % q ++i } i = 0 while (i < m) { p = (d * p + subString[i].code) % q t = (d * t + string[i].code) % q ++i } i = 0 while (i <= n - m) { if (p == t) { j = 0 while (j < m) { if (string[i + j] != subString[j]) break ++j } if (j == m) return i } if (i < n - m) { t = (d * (t - string[i].code * h) + string[i + m].code) % q if (t < 0) t += q } ++i } } else return q return q } fun delayedAction(time: Long, func: () -> Unit) { Handler(Looper.getMainLooper()).postDelayed({ func() }, time) } }
0
Kotlin
4
30
dd77e17dc0737e1f0a1a2668a9381838ba627fdf
4,557
FridgeXLight
Apache License 2.0
src/main/kotlin/br/ufpe/liber/controllers/AssetsController.kt
Liber-UFPE
733,309,986
false
{"Kotlin": 121844, "JavaScript": 7520, "SCSS": 3925, "Shell": 805}
package br.ufpe.liber.controllers import br.ufpe.liber.assets.Asset import br.ufpe.liber.assets.AssetsResolver import io.micronaut.core.io.ResourceResolver import io.micronaut.http.HttpHeaders import io.micronaut.http.HttpResponse import io.micronaut.http.MutableHttpResponse import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import io.micronaut.http.annotation.Header import io.micronaut.http.server.types.files.StreamedFile import java.time.LocalDateTime import java.time.ZoneId import java.time.ZoneOffset.UTC import java.time.format.DateTimeFormatter import java.util.Locale import java.util.Optional import java.util.concurrent.TimeUnit @Controller("/static/{+path}") class AssetsController( private val assetsResolver: AssetsResolver, private val resourceResolver: ResourceResolver, ) { object Cache { @Suppress("detekt:MagicNumber", "MAGIC_NUMBER") val ONE_YEAR_IN_SECONDS: Long = TimeUnit.DAYS.toSeconds(365) val HTTP_DATE_FORMATTER: DateTimeFormatter = DateTimeFormatter .ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH) .withZone(ZoneId.of("GMT")) } @Get fun asset(@Header("Accept-Encoding") encoding: String, path: String): HttpResponse<StreamedFile> { return assetsResolver .fromHashed("/$path") .flatMap { asset -> httpResponseForAsset(asset, encoding) } .map { response -> response .header(HttpHeaders.CACHE_CONTROL, "public, max-age=${Cache.ONE_YEAR_IN_SECONDS}, immutable") .header(HttpHeaders.EXPIRES, oneYearFromNow()) } .orElse(HttpResponse.notFound()) } private fun httpResponseForAsset(asset: Asset, encoding: String): Optional<MutableHttpResponse<StreamedFile>> { return asset .preferredEncodedResource(encoding) .flatMap { availableEncoding -> resourceResolver .getResourceAsStream(asset.classpath(availableEncoding.extension)) .map { inputStream -> HttpResponse .ok(StreamedFile(inputStream, asset.mediaType())) .contentEncoding(availableEncoding.http) } } .or { resourceResolver .getResourceAsStream(asset.classpath()) .map { inputStream -> HttpResponse.ok(StreamedFile(inputStream, asset.mediaType())) } } } private fun oneYearFromNow(): String = LocalDateTime.now(UTC).plusYears(1).format(Cache.HTTP_DATE_FORMATTER) }
2
Kotlin
0
0
53fc24dcdc1abfd1bc0e7dd42d7410129f70d358
2,687
visaoholandesa
Apache License 2.0
java/java-impl/src/com/intellij/internal/statistic/libraryUsage/LibraryLayer.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.libraryUsage import com.intellij.openapi.diagnostic.thisLogger import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal class LibraryLayer private constructor( /** * Library on this layer. Must be no more than one per layer. */ private val libraryName: String? = null, /** * Nested layer */ private val nextLayers: Map<String, LibraryLayer> = emptyMap(), ) { fun findSuitableLibrary(packageQualifier: String): String? = findLibrary(packageQualifier) private fun findLibrary(packageQualifier: String?): String? { if (packageQualifier == null) return libraryName val (key, newPrefix) = packageQualifier.splitByDot() return nextLayers[key]?.findLibrary(newPrefix) ?: libraryName } companion object { fun create(libraryDescriptors: List<LibraryDescriptor>): LibraryLayer = LibraryLayerBuilder().apply { for (descriptor in libraryDescriptors) { add(descriptor.packagePrefix, descriptor.libraryName) } }.toLibraryLayer() private fun String.splitByDot(): Pair<String, String?> = indexOf('.').takeUnless { it == -1 }?.let { indexOfDelimiter -> substring(0, indexOfDelimiter) to substring(indexOfDelimiter + 1) } ?: (this to null) } private class LibraryLayerBuilder { var libraryName: String? = null val nextLayers: MutableMap<String, LibraryLayerBuilder> = mutableMapOf() fun add(packagePrefix: String?, libraryName: String) { if (packagePrefix == null) { if (this.libraryName != null) { thisLogger().warn("'${this.libraryName}' library will be replaced with '$libraryName' library") } this.libraryName = libraryName return } val (key, newPrefix) = packagePrefix.splitByDot() nextLayers.getOrPut(key, ::LibraryLayerBuilder).add(newPrefix, libraryName) } fun toLibraryLayer(): LibraryLayer = LibraryLayer( libraryName = libraryName, nextLayers = nextLayers.mapValues { it.value.toLibraryLayer() }, ) } }
191
null
4372
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,202
intellij-community
Apache License 2.0
app/src/main/java/com/corphish/quicktools/activities/WUPActivity.kt
corphish
680,429,782
false
{"Kotlin": 159426}
package com.corphish.quicktools.activities import android.content.Intent import android.net.Uri import android.widget.Toast import com.corphish.quicktools.R import com.corphish.quicktools.data.Constants import com.corphish.quicktools.settings.SettingsHelper /** * WUP (WhatsApp Unknown Phone number) activity handles messaging to * unknown phone numbers in whatsapp without saving them as a contact by * opening it in wa.me/<phone_number>. */ class WUPActivity : NoUIActivity() { override fun handleIntent(intent: Intent): Boolean { if (intent.hasExtra(Intent.EXTRA_PROCESS_TEXT)) { val text = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString() ?: "" val modified = specialCharactersRemovedFrom(text) val regex = Regex(Constants.PHONE_NUMBER_REGEX) if (regex.matches(modified)) { openInWeb(phoneNumber = modified) } else { Toast.makeText(this, R.string.invalid_phone_number, Toast.LENGTH_LONG).show() } } return true } private fun openInWeb(phoneNumber: String) { val url = "https://wa.me/${countryCodedNumber(phoneNumber)}" val browserIntent = Intent(Intent.ACTION_VIEW) browserIntent.data = Uri.parse(url) startActivity(browserIntent) } private fun countryCodedNumber(phoneNumber: String): String { val settingsHelper = SettingsHelper(this) return if (settingsHelper.getPrependCountryCodeEnabled()) { val code = settingsHelper.getPrependCountryCode() if (code == null) { phoneNumber } else if (phoneNumber.startsWith(code)) { // If the number already starts with country code, no need to append. phoneNumber } else if (phoneNumber.startsWith("+")) { // If the number starts with some country code that is not the user specified // country code, it must be considered. phoneNumber } else { "$code$phoneNumber" } } else { phoneNumber } } private fun specialCharactersRemovedFrom(phoneNumber: String) : String { var res = phoneNumber for (char in Constants.PHONE_NUMBER_SPECIAL_CHARACTERS) { res = res.replace(char, "") } return res } }
8
Kotlin
2
72
e1edb5683b5ed60b040f5cff30fa281d45134899
2,426
TextTools
Apache License 2.0
contacts-phone/phone-core/src/commonMain/kotlin/contacts/Phone.kt
aSoft-Ltd
321,297,839
false
{"Gradle Kotlin DSL": 10, "Markdown": 3, "Java Properties": 1, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 2, "INI": 2, "YAML": 2, "Kotlin": 20, "JavaScript": 6, "Java": 1}
package contacts import kotlinx.serialization.Serializable import kotlin.js.JsExport import kotlin.js.JsName @JsExport @Serializable(with = PhoneSerializer::class) class Phone(phone: String) { @JsName("ofNumber") constructor(phone: Int) : this(phone.toString()) @JsName("_ofNumber") constructor(phone: Long) : this(phone.toString()) val value: String = parse(phone) override fun equals(other: Any?): Boolean = when (other) { is String -> value == other is Phone -> value == other.value else -> false } override fun hashCode(): Int = value.hashCode() override fun toString() = value }
0
Kotlin
1
1
06a887855b62b589c4bda8fa5ed520a70e343ad6
650
contacts
MIT License
snackbarutils/src/main/java/com/iws/snackbarutils/SnackbarUtils.kt
AlexeyIWS
156,519,714
false
null
package com.iws.snackbarutils import android.app.Activity import android.content.Context import android.view.View import android.widget.TextView import android.widget.Toast import com.google.android.material.snackbar.Snackbar /** * @param message uses for show snackbar. Snackbar is widget for purpose and purpose and purpose and purpose and purpose and purpose and purpose and purpose and purpose and purpose and purpose and purpose */ fun Activity.showSnackbar(message: String?) = message?.let { message -> if (message.isEmpty() || findViewById<TextView>(com.google.android.material.R.id.snackbar_text)?.text == message) return@let val target: View? = findViewById(R.id.coordinator) ?: findViewById(android.R.id.content) if (target != null) Snackbar.make(target, message, Snackbar.LENGTH_LONG).show() } ?: Unit object SnackbarUtils { /** * use this method wherever * @param context for create * @param message for seeing */ fun showToast(context: Context, message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
f253c860d8b95ea3b8bb827ac6b3bd712f076a7f
1,115
Test
Apache License 2.0
app/src/main/java/com/barisatalay/themoviedatabase/core/network/interceptor/NetworkInterceptor.kt
barisatalay
193,387,251
false
null
package com.barisatalay.themoviedatabase.core.network.interceptor import android.content.Context import android.util.Log import com.barisatalay.themoviedatabase.core.data.constant.ErrorConstant import com.barisatalay.themoviedatabase.core.helper.UtilsNetwork import okhttp3.Interceptor import okhttp3.Response import java.io.IOException class NetworkInterceptor(private var mContext: Context) : Interceptor { @Suppress("PrivatePropertyName") private val TAG = this.javaClass.simpleName @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() if (!UtilsNetwork.networkControl(mContext)) { Log.d(TAG, ErrorConstant.NullNetwork) throw IOException(ErrorConstant.NullNetwork) } return chain.proceed(request) } }
0
Kotlin
0
0
f464f7c846d2729687f326ecd5dc8d668bd5aed8
851
movie-database
Apache License 2.0
compose/src/commonTest/kotlin/androidx/constraintlayout/core/scout/Direction.kt
Lavmee
711,725,142
false
null
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.core.scout /** * Possible directions for a connection */ enum class Direction( /** * get the direction as an integer * * @return direction as an integer */ val direction: Int ) { NORTH(0), SOUTH(1), WEST(2), EAST(3), BASE(4); override fun toString(): String { return when (this) { NORTH -> "N" SOUTH -> "S" EAST -> "E" WEST -> "W" BASE -> "B" } return "?" } /** * gets the opposite direction * * @return the opposite direction */ val opposite: Direction get() = when (this) { NORTH -> SOUTH SOUTH -> NORTH EAST -> WEST WEST -> EAST BASE -> BASE else -> BASE } /** * Directions can be a positive or negative (right and down) being positive * reverse indicates the direction is negative * * @return true for north and east */ fun reverse(): Boolean { return this == NORTH || this == WEST } /** * Return the number of connection types support by this direction * * @return number of types allowed for this connection */ fun connectTypes(): Int { return when (this) { NORTH, SOUTH -> 2 EAST, WEST -> 2 BASE -> 1 } return 1 } companion object { const val ORIENTATION_VERTICAL = 0 const val ORIENTATION_HORIZONTAL = 1 /** * Get an array of all directions * * @return array of all directions */ val allDirections = values() private val sVertical = arrayOf(NORTH, SOUTH, BASE) private val sHorizontal = arrayOf(WEST, EAST) /** * get a String representing the direction integer * * @param directionInteger direction as an integer * @return single letter string to describe the direction */ fun toString(directionInteger: Int): String { return Companion[directionInteger].toString() } /** * convert from an ordinal of direction to actual direction * * @param directionInteger * @return Enum member equivalent to integer */ operator fun get(directionInteger: Int): Direction { return allDirections[directionInteger] } /** * gets the viable directions for horizontal or vertical * * @param orientation 0 = vertical 1 = horizontal * @return array of directions for vertical or horizontal */ fun getDirections(orientation: Int): Array<Direction> { return if (orientation == ORIENTATION_VERTICAL) { sVertical } else sHorizontal } } }
6
null
1
82
6f1563153d06c2e46ff694288bb2c17999a12818
3,524
constraintlayout-compose-multiplatform
Apache License 2.0
tensorflow/src/main/kotlin/org/jetbrains/kotlinx/dl/api/core/util/TfGraphUtil.kt
Kotlin
249,948,572
false
null
/* * Copyright 2023 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.kotlinx.dl.api.core.util import org.tensorflow.Graph import org.tensorflow.GraphOperation // TODO: return to KGraph class internal fun deserializeGraph(graphDef: ByteArray, prefix: String = ""): Graph { return Graph().also { tfGraph -> if (prefix.isEmpty()) { tfGraph.importGraphDef(graphDef) } else { tfGraph.importGraphDef(graphDef, prefix) } } } internal fun Graph.copy(): Graph { return deserializeGraph(toGraphDef()) } internal fun Graph.convertToString(): String { val operations = operations() val sb = StringBuilder() while (operations.hasNext()) { val operation = operations.next() as GraphOperation sb.append("Name: ") .append(operation.name()) .append("; Type: ") .append(operation.type()) .append("; Out #tensors: ") .append(operation.numOutputs()) .append("\n") } return sb.toString() } internal fun Graph.variableNames(): List<String> { val operations = operations() val variableNames = mutableListOf<String>() while (operations.hasNext()) { val operation = operations.next() as GraphOperation if (operation.type().equals("VariableV2")) { variableNames.add(operation.name()) } } return variableNames.toList() }
82
null
108
1,418
0f36d1b481fc755a7108a34aaf7d8cc226bcc4eb
1,598
kotlindl
Apache License 2.0
presentation/view/handlebars/src/main/kotlin/com/neva/javarel/presentation/view/handlebars/HandlebarsViewEngine.kt
neva-dev
52,150,334
false
null
package com.neva.javarel.presentation.view.handlebars import com.github.jknack.handlebars.Handlebars import com.github.jknack.handlebars.io.TemplateLoader import com.google.common.collect.Sets import com.neva.javarel.foundation.api.JavarelConstants import com.neva.javarel.presentation.view.api.View import com.neva.javarel.presentation.view.api.ViewEngine import com.neva.javarel.resource.api.Resource import com.neva.javarel.resource.api.ResourceDescriptor import com.neva.javarel.resource.api.ResourceResolver import org.apache.felix.scr.annotations.* @Component( immediate = true, metatype = true, label = "${JavarelConstants.SERVICE_PREFIX} Handlebars View Engine", description = "Logic-less and semantic Mustache templates with Java" ) @Service(ViewEngine::class) class HandlebarsViewEngine : ViewEngine { companion object { @Property( name = EXTENSION_PROP, value = ".hbs", label = "Extension", description = "Resource extension that engine will handle" ) const val EXTENSION_PROP = "extension" } @Reference private lateinit var resourceResolver: ResourceResolver @Reference( referenceInterface = HandlebarsExtension::class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC ) private var coreExtensions = Sets.newConcurrentHashSet<HandlebarsExtension>() private lateinit var props: Map<String, Any> val loader: TemplateLoader get() { val result = HandlebarsLoader(resourceResolver) result.suffix = extension return result } private var coreCached: Handlebars? = null val core: Handlebars @Synchronized get() { if (coreCached == null) { val handlebars = Handlebars(loader) coreExtensions.forEach { it.extend(handlebars) } coreCached = handlebars } return coreCached!! } @Suppress("UNCHECKED_CAST") val extension: String by lazy { props[EXTENSION_PROP] as String } @Activate private fun activate(props: Map<String, Any>) { this.props = props } override fun handles(descriptor: ResourceDescriptor): Boolean { return descriptor.path.endsWith(extension) } override fun make(resource: Resource): View { return HandlebarsView(this, resource) } private fun bindCoreExtensions(extension: HandlebarsExtension) { coreExtensions.add(extension) coreCached = null } private fun unbindCoreExtensions(extension: HandlebarsExtension) { coreExtensions.remove(extension) coreCached = null } }
8
Kotlin
0
8
6b75efa9d3e83c5eec23ed7cd4368e901f1f54dc
2,816
javarel-framework
Apache License 2.0
plot-api/src/commonMain/kotlin/org/jetbrains/letsPlot/geom/geom_area_ridges.kt
JetBrains
172,682,391
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 org.jetbrains.letsPlot.geom import org.jetbrains.letsPlot.Stat import org.jetbrains.letsPlot.intern.GeomKind import org.jetbrains.letsPlot.intern.Layer import org.jetbrains.letsPlot.intern.layer.* import org.jetbrains.letsPlot.intern.layer.geom.AreaRidgesAesthetics import org.jetbrains.letsPlot.intern.layer.geom.AreaRidgesMapping import org.jetbrains.letsPlot.intern.layer.geom.AreaRidgesParameters import org.jetbrains.letsPlot.intern.layer.stat.DensityRidgesStatAesthetics import org.jetbrains.letsPlot.intern.layer.stat.DensityRidgesStatParameters import org.jetbrains.letsPlot.pos.positionIdentity import org.jetbrains.letsPlot.tooltips.TooltipOptions @Suppress("ClassName", "SpellCheckingInspection") /** * Plots the sum of the `y` and `height` aesthetics versus `x`. Heights of the ridges are relatively scaled. * * ## Examples * * - [ridgeline_plot.ipynb](https://nbviewer.org/github/JetBrains/lets-plot-docs/blob/master/source/kotlin_examples/cookbook/ridgeline_plot.ipynb) * * - [quantile_parameters.ipynb](https://nbviewer.org/github/JetBrains/lets-plot-docs/blob/master/source/kotlin_examples/cookbook/quantile_parameters.ipynb) * * @param data The data to be displayed in this layer. If null, the default, the data * is inherited from the plot data as specified in the call to [letsPlot][org.jetbrains.letsPlot.letsPlot]. * @param stat default = `Stat.densityRidges()`. The statistical transformation to use on the data for this layer. * Supported transformations: `Stat.identity`, `Stat.bin()`, `Stat.count()`, etc. see [Stat][org.jetbrains.letsPlot.Stat]. * @param position Position adjustment: `positionIdentity`, `positionStack()`, `positionDodge()`, etc. see * [Position](https://lets-plot.org/kotlin/-lets--plot--kotlin/org.jetbrains.letsPlot.pos/). * @param showLegend default = true. * false - do not show legend for this layer. * @param manualKey String or result of the call to the `layerKey()` function. * The key to show in the manual legend. Specifies the text for the legend label or advanced settings using the `layerKey()` function. * @param sampling Result of the call to the `samplingXxx()` function. * To prevent any sampling for this layer pass value `samplingNone`. * For more info see [sampling.html](https://lets-plot.org/kotlin/sampling.html). * @param tooltips Result of the call to the `layerTooltips()` function. * Specifies appearance, style and content. * @param x X-axis coordinates. * @param y Y-axis coordinates. * @param height Height of the ridge. Assumed to be between 0 and 1, though this is not required. * @param quantile Quantile values to draw quantile lines and fill quantiles of the geometry by color. * @param alpha Transparency level of a layer. Understands numbers between 0 and 1. * @param color Color of the geometry. * String in the following formats: * - RGB/RGBA (e.g. "rgb(0, 0, 255)") * - HEX (e.g. "#0000FF") * - color name (e.g. "red") * - role name ("pen", "paper" or "brush") * * Or an instance of the `java.awt.Color` class. * @param fill Fill color. * String in the following formats: * - RGB/RGBA (e.g. "rgb(0, 0, 255)") * - HEX (e.g. "#0000FF") * - color name (e.g. "red") * - role name ("pen", "paper" or "brush") * * Or an instance of the `java.awt.Color` class. * @param linetype Type of the line of border. * Codes and names: 0 = "blank", 1 = "solid", 2 = "dashed", 3 = "dotted", 4 = "dotdash", * 5 = "longdash", 6 = "twodash". * @param size Defines line width. * @param weight Used by `Stat.densityRidges()` stat to compute weighted density. * @param scale default = 1.0 * A multiplicative factor applied to height aesthetic. * If `scale = 1.0`, the heights of a ridges are automatically scaled * such that the ridge with `height = 1.0` just touches the one above. * @param minHeight default = 0.0. * A height cutoff on the drawn ridges. * All values that fall below this cutoff will be removed. * @param quantileLines default = false. * Shows the quantile lines. * @param tailsCutoff Extends domain of each ridge on `tailsCutoff * bw` if `trim = false`. * `tailsCutoff = null` (default) extends domain to maximum (domain overall ridges). * @param quantiles default = listOf(0.25, 0.5, 0.75). * Draws horizontal lines at the given quantiles of the density estimate. * @param bw String or Double. * The method (or exact value) of bandwidth. Either a string (choose among "nrd0" and "nrd") or a double. * @param kernel The kernel we use to calculate the density function. Choose among "gaussian", "cosine", "optcosine", * "rectangular" (or "uniform"), "triangular", "biweight" (or "quartic"), "epanechikov" (or "parabolic"). * @param n The number of sampled points for plotting the function. * @param trim default = false. * Trims the tails of the ridges to the range of the data. * @param adjust Adjusts the value of bandwidth by multiplying it. Changes how smooth the frequency curve is. * @param fullScanMax Maximum size of data to use density computation with "full scan". * For bigger data, less accurate but more efficient density computation is applied. * @param colorBy default = "color" ("fill", "color", "paint_a", "paint_b", "paint_c"). * Defines the color aesthetic for the geometry. * @param fillBy default = "fill" ("fill", "color", "paint_a", "paint_b", "paint_c"). * Defines the fill aesthetic for the geometry. * @param mapping Set of aesthetic mappings. * Aesthetic mappings describe the way that variables in the data are * mapped to plot "aesthetics". */ class geomAreaRidges( data: Map<*, *>? = null, stat: StatOptions = Stat.densityRidges(), position: PosOptions = positionIdentity, showLegend: Boolean = true, manualKey: Any? = null, sampling: SamplingOptions? = null, tooltips: TooltipOptions? = null, override val x: Number? = null, override val y: Number? = null, override val height: Number? = null, override val quantile: Number? = null, override val alpha: Number? = null, override val color: Any? = null, override val fill: Any? = null, override val linetype: Any? = null, override val size: Number? = null, override val weight: Number? = null, override val scale: Number? = null, override val minHeight: Number? = null, override val quantileLines: Boolean? = null, override val tailsCutoff: Number? = null, override val quantiles: List<Number>? = null, override val bw: Any? = null, override val kernel: String? = null, override val n: Int? = null, override val trim: Boolean? = null, override val adjust: Number? = null, override val fullScanMax: Int? = null, override val colorBy: String? = null, override val fillBy: String? = null, mapping: AreaRidgesMapping.() -> Unit = {} ) : AreaRidgesAesthetics, AreaRidgesParameters, DensityRidgesStatAesthetics, DensityRidgesStatParameters, WithColorOption, WithFillOption, Layer( mapping = AreaRidgesMapping().apply(mapping).seal(), data = data, geom = GeomOptions(GeomKind.AREA_RIDGES), stat = stat, position = position, showLegend = showLegend, manualKey = manualKey, sampling = sampling, tooltips = tooltips ) { override fun seal() = super<AreaRidgesAesthetics>.seal() + super<AreaRidgesParameters>.seal() + super<DensityRidgesStatAesthetics>.seal() + super<DensityRidgesStatParameters>.seal() + super<WithColorOption>.seal() + super<WithFillOption>.seal() }
19
null
36
433
f6edab1a67783d14e2378675f065ef7111bdc1a0
7,776
lets-plot-kotlin
MIT License
src/main/kotlin/io/github/bayang/jelu/service/imports/CsvImportService.kt
bayang
426,792,636
false
{"Kotlin": 633783, "Vue": 418236, "TypeScript": 113503, "CSS": 7963, "Java": 3470, "JavaScript": 3200, "Dockerfile": 1964, "Shell": 1372, "HTML": 726}
package io.github.bayang.jelu.service.imports import io.github.bayang.jelu.config.JeluProperties import io.github.bayang.jelu.dao.ImportEntity import io.github.bayang.jelu.dao.ImportSource import io.github.bayang.jelu.dao.MessageCategory import io.github.bayang.jelu.dao.ProcessingStatus import io.github.bayang.jelu.dao.ReadingEventType import io.github.bayang.jelu.dto.AuthorDto import io.github.bayang.jelu.dto.BookCreateDto import io.github.bayang.jelu.dto.BookDto import io.github.bayang.jelu.dto.CreateReadingEventDto import io.github.bayang.jelu.dto.CreateUserBookDto import io.github.bayang.jelu.dto.CreateUserMessageDto import io.github.bayang.jelu.dto.ImportConfigurationDto import io.github.bayang.jelu.dto.ImportDto import io.github.bayang.jelu.dto.LibraryFilter import io.github.bayang.jelu.dto.MetadataDto import io.github.bayang.jelu.dto.MetadataRequestDto import io.github.bayang.jelu.dto.TagDto import io.github.bayang.jelu.dto.UserBookLightDto import io.github.bayang.jelu.dto.UserBookUpdateDto import io.github.bayang.jelu.service.BookService import io.github.bayang.jelu.service.ImportService import io.github.bayang.jelu.service.ReadingEventService import io.github.bayang.jelu.service.UserMessageService import io.github.bayang.jelu.service.UserService import io.github.bayang.jelu.service.metadata.FetchMetadataService import io.github.bayang.jelu.service.metadata.providers.CalibreMetadataProvider import io.github.bayang.jelu.utils.toInstant import mu.KotlinLogging import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVParser import org.apache.commons.csv.CSVRecord import org.apache.commons.validator.routines.ISBNValidator import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.io.File import java.time.LocalDate import java.time.OffsetDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.UUID import java.util.concurrent.atomic.AtomicLong import java.util.stream.Collectors import kotlin.random.Random private val logger = KotlinLogging.logger {} const val ISBN_PREFIX = "=\"" const val TO_READ = "to-read" const val READ = "read" const val CURRENTLY_READING = "currently-reading" /** * From storygraph */ const val DROPPED = "did-not-finish" /** * Works for goodreads and storygraph */ val goodreadsDateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd") @Service class CsvImportService( private val properties: JeluProperties, private val importService: ImportService, private val fetchMetadataService: FetchMetadataService, private val bookService: BookService, private val userService: UserService, private val readingEventService: ReadingEventService, private val userMessageService: UserMessageService ) { // maybe later : use coroutines ? @Async fun import(file: File, user: UUID, importConfig: ImportConfigurationDto) { val start = System.currentTimeMillis() val userEntity = userService.findUserEntityById(user) val nowString: String = OffsetDateTime.now(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss")) try { userMessageService.save( CreateUserMessageDto( "Import started at $nowString", null, MessageCategory.INFO ), userEntity ) } catch (e: Exception) { logger.error(e) { "failed to save message for ${file.absolutePath} import" } } // put file content in db parse(file, user, importConfig) var end = System.currentTimeMillis() var deltaInSec = (end - start) / 1000 logger.info { "csv parsing of ${file.absolutePath} ended after : $deltaInSec seconds" } // reset status of previous tasks, in case an import was started but not finished importService.updateStatus(ProcessingStatus.PROCESSING, ProcessingStatus.SAVED, user) // process data from db val (success, failures) = importFromDb(user, importConfig) val renamed = file.renameTo(File(file.parent, "${file.name}.imported")) logger.debug { "File ${file.absolutePath} was successfully renamed after processing : $renamed" } end = System.currentTimeMillis() deltaInSec = (end - start) / 1000 logger.info { "Import for ${file.absolutePath} ended after : $deltaInSec seconds, with $success imports and $failures failures" } try { userMessageService.save( CreateUserMessageDto( "Import for ${file.absolutePath} ended after : $deltaInSec seconds, with $success imports and $failures failures", null, MessageCategory.SUCCESS ), userEntity ) } catch (e: Exception) { logger.error(e) { "failed to save message for ${file.absolutePath} import" } } } fun importFromDb(user: UUID, importConfig: ImportConfigurationDto): Pair<Long, Long> { var importEntities: List<ImportEntity>? = mutableListOf() var success: Long = 0 var failures: Long = 0 while (importEntities != null) { importEntities = importService.getByprocessingStatusAndUser(ProcessingStatus.SAVED, user) if (importEntities.isEmpty()) { importEntities = null break } for (entity in importEntities) { when (importEntity(entity, user, importConfig)) { ProcessingStatus.IMPORTED -> success ++ ProcessingStatus.ERROR -> failures ++ else -> continue } } } return Pair(success, failures) } @Transactional private fun importEntity(importEntity: ImportEntity, user: UUID, importConfig: ImportConfigurationDto): ProcessingStatus { Thread.sleep(Random.nextLong(from = 200, until = 800)) try { importService.updateStatus(importEntity.id.value, ProcessingStatus.PROCESSING) var metadata = MetadataDto() if (importEntity.shouldFetchMetadata && !properties.metadata.calibre.path.isNullOrBlank()) { val isbn: String = getIsbn(importEntity) if (isbn.isNotBlank()) { var config = mutableMapOf<String, String>() config[CalibreMetadataProvider.onlyUseCorePlugins] = "true" config[CalibreMetadataProvider.fetchCover] = importConfig.shouldFetchCovers.toString() metadata = fetchMetadataService .fetchMetadata(MetadataRequestDto(isbn), config) .block()!! } else { logger.debug { "no isbn on entity ${importEntity.id}, not fetching metadata" } } } val userEntity = userService.findUserEntityById(user) val book: BookCreateDto = fillBook(importEntity, metadata) if (book.title.isBlank() && (book.authors == null || book.authors!!.isEmpty())) { logger.error { "no title nor authors on entity ${importEntity.id} ${importEntity.isbn10} ${importEntity.isbn13} , not saving" } importService.updateStatus(importEntity.id.value, ProcessingStatus.IMPORTED) if (importConfig.importSource == ImportSource.ISBN_LIST) { try { val isbn10 = if (importEntity.isbn10.isNullOrBlank()) "" else importEntity.isbn10 val isbn13 = if (importEntity.isbn13.isNullOrBlank()) "" else importEntity.isbn13 userMessageService.save( CreateUserMessageDto( "no title nor authors for input $isbn10 $isbn13, not saving", null, MessageCategory.WARNING ), userEntity ) } catch (e: Exception) { logger.error(e) { "failed to save message for failed isbn fetch" } } } return ProcessingStatus.ERROR } val tags = mutableListOf<TagDto>() val tagNames = mutableSetOf<String>() for (t in metadata.tags) { tagNames.add(t) } var shelves: List<String>? = null if (!importEntity.tags.isNullOrBlank()) { shelves = importEntity.tags?.split(",") } var readStatusFromShelves = "" if (shelves != null) { for (t in shelves) { if (! isreadStatusShelf(t)) { tagNames.add(t) } else { // read status shelves are mutually exclusives readStatusFromShelves = t } } } for (t in tagNames) { tags.add(TagDto(null, null, null, t)) } val readStatusEnum: ReadingEventType? = readingStatus(readStatusFromShelves) book.tags = tags val booksPage: Page<BookDto> = bookService.findAll(null, importEntity.isbn10, importEntity.isbn13, null, null, null, null, Pageable.ofSize(20), userEntity, LibraryFilter.ANY) // first case : the book we try to import from csv already exists in DB, // try to see if user already has it attached to his account (and only update userbook), or create new userbook if not val savedUserBook: UserBookLightDto = if (! booksPage.isEmpty) { val bookFromDb: BookDto = booksPage.content[0] // user already have an userbook for this book if (bookFromDb.userBookId != null) { // update userbook and book // val userbook: UserBookWithoutBookDto = bookWithUserbook.userBooks[0] val userbook: UserBookLightDto = bookService.findUserBookById(bookFromDb.userBookId) // only update fields if they are not filled yet, do not overwrite previously manually filled data bookService.update( userbook.id!!, UserBookUpdateDto( if ((readStatusEnum == ReadingEventType.CURRENTLY_READING || readStatusEnum == ReadingEventType.DROPPED) && userbook.lastReadingEvent == null) readStatusEnum else null, if (userbook.personalNotes.isNullOrBlank()) importEntity.personalNotes else null, if (userbook.owned == null) importEntity.owned else null, merge(book, bookFromDb), if (readStatusFromShelves.equals(TO_READ, true) && userbook.toRead == null) true else null, null, null ), null ) } else { // update book only and create userbook val userbook = CreateUserBookDto( if (readStatusEnum == ReadingEventType.CURRENTLY_READING || readStatusEnum == ReadingEventType.DROPPED) readStatusEnum else null, null, importEntity.personalNotes, importEntity.owned, merge(book, bookFromDb), if (readStatusFromShelves.equals(TO_READ, true)) true else null, null, null ) bookService.save(userbook, userEntity, null) } } else { val userbook = CreateUserBookDto( if (readStatusEnum == ReadingEventType.CURRENTLY_READING || readStatusEnum == ReadingEventType.DROPPED) readStatusEnum else null, null, importEntity.personalNotes, importEntity.owned, book, if (readStatusFromShelves.equals(TO_READ, true)) true else null, null, null ) bookService.save(userbook, userEntity, null) } // csv exports are inconsistents, sometimes readDates are filled but not the // associated bookshelves or the read number field... // so take everything into account and try to avoid duplicates var readsSaved = 0 if (! importEntity.readDates.isNullOrBlank()) { val dates = importEntity.readDates!!.split(";") for (date in dates) { try { val parsedDate = LocalDate.parse(date, goodreadsDateFormatter) // in case of multiple import of the same file // do not create the same finished event twice if possible if (!alreadyHasFinishedEventAtSameDate(savedUserBook, parsedDate)) { readingEventService.save(CreateReadingEventDto(ReadingEventType.FINISHED, savedUserBook.book.id, toInstant(parsedDate), null), userEntity) } readsSaved ++ } catch (e: Exception) { logger.error { "failed to parse date from export $date" } } } } var remainingToSave = 0 if (importEntity.readCount != null && importEntity.readCount!! > readsSaved) { remainingToSave = importEntity.readCount!! - readsSaved } if (readStatusEnum != null && readStatusEnum == ReadingEventType.FINISHED && remainingToSave == 0 && readsSaved == 0 ) { remainingToSave ++ } // bookService.findUserBookById(savedUserBook.id) val nbAlreadyFinishedEvents = if (savedUserBook.readingEvents != null) savedUserBook.readingEvents.stream().filter { it.eventType == ReadingEventType.FINISHED }.count().toInt() else 0 remainingToSave -= nbAlreadyFinishedEvents // we know the book has been read 3 times for example but don't have dates // just create reading events in the past at an arbitrary date // user will correct each event if he wants to val pastDate: LocalDate = LocalDate.of(1970, 1, 1) for (idx in 0 until remainingToSave) { readingEventService.save( CreateReadingEventDto( ReadingEventType.FINISHED, savedUserBook.book.id, toInstant( pastDate.plusDays( idx.toLong() ) ), null ), userEntity ) } importService.updateStatus(importEntity.id.value, ProcessingStatus.IMPORTED) return ProcessingStatus.IMPORTED } catch (e: Exception) { logger.error(e) { "failed to import entity ${importEntity.title}" } importService.updateStatus(importEntity.id.value, ProcessingStatus.ERROR) return ProcessingStatus.ERROR } } fun alreadyHasFinishedEventAtSameDate(userBook: UserBookLightDto, date: LocalDate): Boolean { if (userBook.readingEvents == null) { return false } return userBook.readingEvents.stream() .filter { it.eventType == ReadingEventType.FINISHED } .filter { it.creationDate != null } .map { LocalDate.ofInstant(it.creationDate, ZoneId.systemDefault()) } .filter { it.year == date.year && it.monthValue == date.monthValue && it.dayOfMonth == date.dayOfMonth } .count().toInt() > 0 } private fun readingStatus(readStatusFromShelves: String): ReadingEventType? { return if (readStatusFromShelves.equals(CURRENTLY_READING, true)) { ReadingEventType.CURRENTLY_READING } else if (readStatusFromShelves.equals(DROPPED, true)) { ReadingEventType.DROPPED } else if (readStatusFromShelves.equals(READ, true)) { ReadingEventType.FINISHED } else { null } } /** * only update fields if they are not filled yet, do not overwrite previously manually filled data */ private fun merge(incoming: BookCreateDto, dbBook: BookDto): BookCreateDto { val authors = mutableListOf<AuthorDto>() // only save authors not already in db if (incoming.authors != null) { val existingAuthorsNames: Set<String> = if (dbBook.authors != null) { dbBook.authors.stream().map { it.name }.map { it.lowercase() }.collect(Collectors.toSet()) } else { setOf() } incoming.authors!!.filter { authorDto -> !existingAuthorsNames.contains(authorDto.name.lowercase()) }.forEach { authorDto -> authors.add(authorDto) } } val tags = mutableListOf<TagDto>() // only save tags not already in db if (incoming.tags != null) { val existingTagsNames: Set<String> = if (dbBook.tags != null) { dbBook.tags.stream().map { it.name }.map { it.lowercase() }.collect(Collectors.toSet()) } else { setOf() } incoming.tags!!.filter { tagDto -> !existingTagsNames.contains(tagDto.name.lowercase()) }.forEach { tagDto -> tags.add(tagDto) } } return incoming.copy( id = dbBook.id, title = dbBook.title.ifBlank { incoming.title }, isbn10 = if (dbBook.isbn10.isNullOrBlank()) incoming.isbn10 else null, isbn13 = if (dbBook.isbn13.isNullOrBlank()) incoming.isbn13 else null, summary = if (dbBook.summary.isNullOrBlank()) incoming.summary else null, publisher = if (dbBook.publisher.isNullOrBlank()) incoming.publisher else null, pageCount = if (dbBook.pageCount == null) incoming.pageCount else null, publishedDate = if (dbBook.publishedDate.isNullOrBlank()) incoming.publishedDate else null, series = if (dbBook.series.isNullOrBlank()) incoming.series else null, numberInSeries = if (dbBook.numberInSeries == null) incoming.numberInSeries else null, googleId = if (dbBook.googleId.isNullOrBlank()) incoming.googleId else null, amazonId = if (dbBook.amazonId.isNullOrBlank()) incoming.amazonId else null, goodreadsId = if (dbBook.goodreadsId.isNullOrBlank()) incoming.goodreadsId else null, librarythingId = if (dbBook.librarythingId.isNullOrBlank()) incoming.librarythingId else null, language = if (dbBook.language.isNullOrBlank()) incoming.language else null, // special case : // if image is null, update in bookservice will erase the existing image, // we must send the currently existing image image = if (dbBook.image.isNullOrBlank()) incoming.image else dbBook.image, authors = authors, tags = tags ) } fun fillBook(importEntity: ImportEntity, metadata: MetadataDto): BookCreateDto { val book = BookCreateDto() book.title = testValues(importEntity.title, metadata.title) book.language = metadata.language book.amazonId = metadata.amazonId book.goodreadsId = importEntity.goodreadsId book.googleId = metadata.googleId book.librarythingId = importEntity.librarythingId book.isbn10 = testValues(importEntity.isbn10, metadata.isbn10) book.isbn13 = testValues(importEntity.isbn13, metadata.isbn13) book.numberInSeries = metadata.numberInSeries book.pageCount = importEntity.numberOfPages ?: metadata.pageCount book.publishedDate = testValues(importEntity.publishedDate, metadata.publishedDate) book.publisher = testValues(importEntity.publisher, metadata.publisher) book.summary = metadata.summary book.series = metadata.series book.image = metadata.image val authorsStrings = mutableSetOf<String>() authorsStrings.addAll(metadata.authors) if (! importEntity.authors.isNullOrBlank()) { val split = importEntity.authors!!.split(",") authorsStrings.addAll(split) } val authors = mutableListOf<AuthorDto>() for (authorString in authorsStrings) { authors.add(AuthorDto(null, null, null, authorString, null, null, null, null, null, null, null, null, null, null, null)) } book.authors = authors return book } fun isreadStatusShelf(bookshelf: String): Boolean { if (bookshelf.isNotBlank() && ( bookshelf.equals(TO_READ, true) || bookshelf.equals(CURRENTLY_READING, true) || bookshelf.equals(READ, true) || bookshelf.equals(DROPPED, true) ) ) { return true } return false } fun testValues(first: String?, second: String?): String { return if (!first.isNullOrBlank()) { first } else if (!second.isNullOrBlank()) { second } else { "" } } private fun getIsbn(importEntity: ImportEntity): String { if (!importEntity.isbn13.isNullOrBlank()) { return importEntity.isbn13!! } else if (!importEntity.isbn10.isNullOrBlank()) { return importEntity.isbn10!! } return "" } /* * Goodreads * * 0 Book Id * 1 Title * 2 Author * 3 Author l-f * 4 Additional Authors * 5 ISBN * 6 ISBN13 * 7 My Rating * 8 Average Rating * 9 Publisher * 10 Binding * 11 Number of Pages * 12 Year Published * 13 Original Publication Year * 14 Date Read * 15 Date Added * 16 Bookshelves * 17 Bookshelves with positions * 18 Exclusive Shelf * 19 My Review * 20 Spoiler * 21 Private Notes * 22 Read Count * 23 Recommended For * 24 Recommended By * 25 Owned Copies * 26 Original Purchase Date * 27 Original Purchase Location * 28 Condition * 29 Condition Description * 30 BCID * */ fun parse(file: File, user: UUID, importConfig: ImportConfigurationDto) { if (importConfig.importSource == ImportSource.ISBN_LIST) { val validator: ISBNValidator = ISBNValidator.getInstance(false) val counter = AtomicLong() file.useLines { lines -> lines.forEach { val dto = ImportDto() dto.importSource = ImportSource.ISBN_LIST if (validator.isValidISBN13(it)) { dto.isbn13 = it } else if (validator.isValidISBN10(it)) { dto.isbn10 = it } if (!dto.isbn13.isNullOrBlank() || !dto.isbn10.isNullOrBlank()) { importService.save(dto, ProcessingStatus.SAVED, user, importConfig.shouldFetchMetadata) counter.incrementAndGet() } else { logger.info { "input line $it is not a valid ISBN, line is ignored" } } } } logger.debug { "parsing finished, ${counter.get()} entries recorded" } } else { parseCsv(file, user, importConfig) } } fun parseCsv(file: File, user: UUID, importConfig: ImportConfigurationDto) { val parser = CSVFormat.DEFAULT val reader = file.bufferedReader(Charsets.UTF_8) // skip header line ourselves // CSVFormat.withSkipHeaderRecord() doesn't work reader.readLine() val parsed: CSVParser = parser.parse(reader) val iterator: Iterator<CSVRecord> = parsed.iterator() var count: Long = 0 var dto: ImportDto? = null while (iterator.hasNext()) { try { val record: CSVRecord = iterator.next() dto = parseLine(record, importConfig.importSource) if (dto != null) { // save in DB with user info importService.save(dto, ProcessingStatus.SAVED, user, importConfig.shouldFetchMetadata) count ++ } } catch (e: Exception) { logger.error { "Failed to process line or save data from file ${file.absolutePath}, line : ${dto?.title}" } } } logger.debug { "parsing finished, $count entries recorded" } } private fun parseLine(record: CSVRecord, importSource: ImportSource): ImportDto? { return when (importSource) { ImportSource.GOODREADS -> parseGoodreadsLine(record) ImportSource.STORYGRAPH -> parseStorygraphLine(record) ImportSource.LIBRARYTHING -> parseLibrarythingLine(record) ImportSource.ISBN_LIST -> null } } // TODO private fun parseLibrarythingLine(record: CSVRecord): ImportDto? { val dto = ImportDto() dto.importSource = ImportSource.LIBRARYTHING return dto } // TODO private fun parseStorygraphLine(record: CSVRecord): ImportDto? { val dto = ImportDto() dto.importSource = ImportSource.STORYGRAPH return dto } private fun parseGoodreadsLine(record: CSVRecord): ImportDto? { val dto = ImportDto() val rawIsbn10 = record.get(5) val parsedIsbn10 = parseIsbn(rawIsbn10) val rawIsbn13 = record.get(6) val parsedIsbn13 = parseIsbn(rawIsbn13) val author = cleanString(record.get(2)) val title = cleanString(record.get(1)) val goodreadsId = cleanString(record.get(0)) // we want at least an isbn if (parsedIsbn10.isBlank() && parsedIsbn13.isBlank()) { logger.debug { "Missing isbn for line with goodreadsId $goodreadsId, title $title and author $author, import it yourself manually" } return null } else { val additionalAuthors = cleanString(record.get(4)) val authors = mutableSetOf<String>() authors.add(author) if (additionalAuthors.isNotBlank()) { val split = additionalAuthors.split(",") authors.addAll(split) } dto.authors = authors.joinToString(separator = ",") dto.title = title dto.goodreadsId = goodreadsId if (parsedIsbn10.isNotBlank()) { dto.isbn10 = parsedIsbn10 } if (parsedIsbn13.isNotBlank()) { dto.isbn13 = parsedIsbn13 } val bookshelves = cleanString(record.get(16)) if (bookshelves.isNotBlank()) { bookshelves.split(",").forEach { dto.tags.add(it.trim()) } } val exclusiveShelf = cleanString(record.get(18)) if (exclusiveShelf.isNotBlank()) { dto.tags.add(exclusiveShelf.trim()) } dto.numberOfPages = parseNumber(record.get(11)) dto.personalNotes = cleanString(record.get(21)) dto.publishedDate = cleanString(record.get(12)) dto.publisher = cleanString(record.get(9)) dto.readCount = parseNumber(record.get(22)) dto.readDates = cleanString(record.get(14)) // goodreads csv export changed columns in 2022 apparently // new exports have only 24 columns, older ones have 31 val ownedCopies = if (record.size() > 24 && record.isSet(25)) { parseNumber(record.get(25)) } else { parseNumber(record.get(23)) } if (ownedCopies != null && ownedCopies > 0) { dto.owned = true } dto.importSource = ImportSource.GOODREADS return dto } } fun cleanString(input: String?): String { if (input.isNullOrBlank()) { return "" } return input.trim() } /** * eg in raw goodreads csv : "=""9782841720538""" ... */ private fun parseIsbn(input: String): String { if (input.isBlank()) { return "" } else { var isbn = "" if (input.startsWith(ISBN_PREFIX)) { isbn = input.substring(ISBN_PREFIX.length) } if (isbn.length < 10) { return "" } return isbn.substring(0, isbn.length - 1) } } private fun parseNumber(input: String): Int? { return if (input.isBlank()) { null } else { try { Integer.parseInt(input, 10) } catch (e: Exception) { logger.error { "failed to parse number $input" } null } } } }
9
Kotlin
9
340
32de3210e27f64102052cc596e6602258b433a83
29,802
jelu
MIT License
web/src/main/kotlin/app/visual/log/Application.kt
cxpqwvtj
96,679,825
false
null
package app.visual.log import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.context.annotation.EnableAspectJAutoProxy @SpringBootApplication @EnableAspectJAutoProxy open class Application { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) } } }
0
Kotlin
0
0
ceb0a5859056439f5a3ae8cf7bbb40c2b7024a2e
442
visual-log
MIT License
app/src/main/java/digital/lamp/dagger_test/api/ResultsResponse.kt
amaljofy
248,206,587
false
null
package digital.lamp.dagger_test.api import com.google.gson.annotations.SerializedName /** * Created by <NAME>. on 03,March,2020 */ data class ResultsResponse<T>( @SerializedName("count") val count: Int, @SerializedName("next") val next: String? = null, @SerializedName("previous") val previous: String? = null, @SerializedName("results") val results: List<T> )
0
Kotlin
0
1
e606b55696e428c62cc960128b41483c184b9867
397
NewsList-Part-1
MIT License
presentation/src/commonMain/kotlin/ireader/presentation/ui/home/sources/extension/CatalogItem.kt
kazemcodes
540,829,865
false
null
package ireader.presentation.ui.home.sources.extension import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.LocalContentAlpha import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.PushPin import androidx.compose.material.icons.outlined.PushPin import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider 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.layout.Layout import androidx.compose.ui.layout.layoutId import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import ireader.core.os.InstallStep import ireader.domain.models.entities.Catalog import ireader.domain.models.entities.CatalogBundled import ireader.domain.models.entities.CatalogInstalled import ireader.domain.models.entities.CatalogLocal import ireader.domain.models.entities.CatalogRemote import ireader.i18n.localize import ireader.presentation.imageloader.IImageLoader import ireader.presentation.ui.component.reusable_composable.AppIconButton import ireader.presentation.ui.component.reusable_composable.MidSizeTextComposable import ireader.presentation.ui.core.theme.ContentAlpha import ireader.presentation.ui.home.sources.extension.composables.LetterIcon import java.util.Locale import kotlin.math.max @Composable fun CatalogItem( modifier: Modifier = Modifier, catalog: Catalog, installStep: InstallStep? = null, onClick: (() -> Unit)? = null, onInstall: (() -> Unit)? = null, onUninstall: (() -> Unit)? = null, onPinToggle: (() -> Unit)? = null, onCancelInstaller: ((Catalog) -> Unit)? = null, ) { val title = buildAnnotatedString { append("${catalog.name} ") } val lang = when (catalog) { is CatalogBundled -> null is CatalogInstalled -> catalog.source?.lang is CatalogRemote -> catalog.lang }?.let { Language(it) } Layout( modifier = onClick?.let { modifier.clickable(onClick = it) } ?: modifier, content = { CatalogPic( catalog = catalog, modifier = Modifier .layoutId("pic") .padding(12.dp) .size(48.dp) ) Text( text = title, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier .layoutId("title") .padding(top = 12.dp) ) Text( text = lang?.code?.uppercase(Locale.getDefault()) ?: "", style = MaterialTheme.typography.labelMedium, color = LocalContentColor.current.copy(alpha = ContentAlpha.medium()), maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier .layoutId("desc") .padding(bottom = 12.dp, end = 12.dp) ) CatalogButtons( catalog = catalog, installStep = installStep, onInstall = onInstall, onUninstall = onUninstall, onPinToggle = onPinToggle, modifier = Modifier .layoutId("icons") .padding(end = 4.dp), onCancelInstaller = onCancelInstaller, ) }, measurePolicy = { measurables, fullConstraints -> val picPlaceable = measurables.first { it.layoutId == "pic" }.measure(fullConstraints) val langPlaceable = measurables.find { it.layoutId == "lang" }?.measure(fullConstraints) val constraints = fullConstraints.copy( maxWidth = fullConstraints.maxWidth - picPlaceable.width ) val iconsPlaceable = measurables.first { it.layoutId == "icons" }.measure(constraints) val titlePlaceable = measurables.first { it.layoutId == "title" } .measure(constraints.copy(maxWidth = constraints.maxWidth - iconsPlaceable.width)) val descPlaceable = measurables.first { it.layoutId == "desc" }.measure(constraints) val height = max(picPlaceable.height, titlePlaceable.height + descPlaceable.height) layout(fullConstraints.maxWidth, height) { picPlaceable.placeRelative(0, 0) langPlaceable?.placeRelative( x = picPlaceable.width - langPlaceable.width, y = picPlaceable.height - langPlaceable.height ) titlePlaceable.placeRelative(picPlaceable.width, 0) descPlaceable.placeRelative(picPlaceable.width, titlePlaceable.height) iconsPlaceable.placeRelative( x = constraints.maxWidth - iconsPlaceable.width + picPlaceable.width, y = 0 ) } } ) } @Composable private fun CatalogPic(catalog: Catalog, modifier: Modifier = Modifier) { when(catalog) { is CatalogBundled -> { LetterIcon(catalog.name, modifier) } else -> { IImageLoader( model = catalog, contentDescription = null, modifier = modifier, ) } } IImageLoader( model = catalog, contentDescription = null, modifier = modifier, ) } @Composable private fun CatalogButtons( catalog: Catalog, installStep: InstallStep?, onInstall: (() -> Unit)?, onUninstall: (() -> Unit)?, onPinToggle: (() -> Unit)?, onCancelInstaller: ((Catalog) -> Unit)?, modifier: Modifier = Modifier, ) { Row(modifier = modifier) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium()) { // Show either progress indicator or install button if (installStep != null && !installStep.isFinished()) { Box { CircularProgressIndicator( modifier = Modifier .size(48.dp) .padding(12.dp) ) AppIconButton(imageVector = Icons.Default.Close, onClick = { if (onCancelInstaller != null) { onCancelInstaller(catalog) } }) } } else if (onInstall != null) { if (catalog is CatalogLocal) { MidSizeTextComposable( text = localize { xml -> xml.update }, color = MaterialTheme.colorScheme.primary, modifier = Modifier.clickable { onInstall() } ) } else if (catalog is CatalogRemote) { MidSizeTextComposable( text = localize { xml -> xml.install }, color = MaterialTheme.colorScheme.primary, modifier = Modifier.clickable { onInstall() } ) } } if (catalog !is CatalogRemote) { CatalogMenuButton( catalog = catalog, onPinToggle = onPinToggle, onUninstall = onUninstall ) } } } } @Composable internal fun CatalogMenuButton( catalog: Catalog, onPinToggle: (() -> Unit)?, onUninstall: (() -> Unit)?, ) { var expanded by remember { mutableStateOf(false) } Box(modifier = Modifier.padding(horizontal = 8.dp)) { if (onPinToggle != null && catalog is CatalogLocal && onUninstall == null) { if (catalog.isPinned) { AppIconButton( imageVector = Icons.Filled.PushPin, tint = androidx.compose.material3.MaterialTheme.colorScheme.primary, contentDescription = localize { xml -> xml.pin }, onClick = onPinToggle ) } else { AppIconButton( imageVector = Icons.Outlined.PushPin, tint = androidx.compose.material3.MaterialTheme.colorScheme.onBackground.copy( .5f ), contentDescription = localize { xml -> xml.unpin }, onClick = onPinToggle ) } } else { Spacer(modifier = Modifier.padding(horizontal = 4.dp)) if (onUninstall != null && catalog is CatalogLocal) { MidSizeTextComposable( text = localize { xml -> xml.uninstall }, color = androidx.compose.material3.MaterialTheme.colorScheme.primary, modifier = Modifier.clickable { onUninstall() } ) } Spacer(modifier = Modifier.padding(horizontal = 4.dp)) } } }
11
null
21
6
b6b2414fa002cec2aa0d199871fcfb4c2e190a8f
9,792
IReader
Apache License 2.0
sources/cli/test/org/jetbrains/amper/util/ExecuteOnChangedInputsTest.kt
JetBrains
709,379,874
false
null
/* * Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.amper.util import kotlinx.coroutines.runBlocking import org.jetbrains.amper.cli.AmperBuildOutputRoot import org.junit.jupiter.api.io.TempDir import java.nio.file.Path import java.util.concurrent.atomic.AtomicInteger import kotlin.io.path.createDirectories import kotlin.io.path.deleteExisting import kotlin.io.path.readText import kotlin.io.path.writeText import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.fail class ExecuteOnChangedInputsTest { @TempDir lateinit var tempDir: Path private val executeOnChanged by lazy { ExecuteOnChangedInputs(AmperBuildOutputRoot(tempDir)) } private val executionsCount = AtomicInteger(0) @Test fun trackingFile() { val file = tempDir.resolve("file.txt") fun call() = runBlocking { executeOnChanged.execute("1", emptyMap(), listOf(file)) { executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(emptyList()) } } // initial, MISSING state call() assertEquals(executionsCount.get(), 1) // up-to-date, file is still MISSING call() assertEquals(executionsCount.get(), 1) // changed file.writeText("1") call() assertEquals(executionsCount.get(), 2) // up-to-date call() assertEquals(executionsCount.get(), 2) } @Test fun changeAmperBuildNumber() { val file = tempDir.resolve("file.txt").also { it.writeText("a") } fun call(amperBuild: String) = runBlocking { ExecuteOnChangedInputs(AmperBuildOutputRoot(tempDir), currentAmperBuildNumber = amperBuild).execute( "1", emptyMap(), listOf(file)) { executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(emptyList()) } } // initial call("1") assertEquals(executionsCount.get(), 1) // up-to-date call("1") assertEquals(executionsCount.get(), 1) // changed call("2") assertEquals(executionsCount.get(), 2) // up-to-date call("2") assertEquals(executionsCount.get(), 2) } @Test fun trackingFileInSubdirectory() { val dir = tempDir.resolve("dir").also { it.createDirectories() } val file = dir.resolve("file.txt") fun call() = runBlocking { executeOnChanged.execute("1", emptyMap(), listOf(dir)) { executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(emptyList()) } } // initial, MISSING state call() assertEquals(executionsCount.get(), 1) // up-to-date, file is still MISSING call() assertEquals(executionsCount.get(), 1) // changed file.writeText("1") call() assertEquals(executionsCount.get(), 2) // up-to-date call() assertEquals(executionsCount.get(), 2) } @Test fun trackingEmptyDirectories() { val dir = tempDir.resolve("dir").also { it.createDirectories() } val subdir = dir.resolve("subdir") fun call() = runBlocking { executeOnChanged.execute("1", emptyMap(), listOf(dir)) { executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(emptyList()) } } // initial, MISSING state call() assertEquals(executionsCount.get(), 1) // up-to-date, subdir is still MISSING call() assertEquals(executionsCount.get(), 1) // changed subdir.createDirectories() call() assertEquals(executionsCount.get(), 2) // up-to-date call() assertEquals(executionsCount.get(), 2) } @Test fun `executes on missing output`() { runBlocking { val output = tempDir.resolve("out.txt") val result1 = executeOnChanged.execute("1", emptyMap(), emptyList()) { output.writeText("1") executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(listOf(output)) } assertEquals(listOf(output), result1.outputs) assertEquals("1", output.readText()) // up-to-date val result2 = executeOnChanged.execute("1", emptyMap(), emptyList()) { output.writeText("2") executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(listOf(output)) } assertEquals(listOf(output), result2.outputs) assertEquals("1", output.readText()) output.deleteExisting() // output was deleted val result3 = executeOnChanged.execute("1", emptyMap(), emptyList()) { output.writeText("3") executionsCount.incrementAndGet() ExecuteOnChangedInputs.ExecutionResult(listOf(output)) } assertEquals(listOf(output), result3.outputs) assertEquals("3", output.readText()) } assertEquals(2, executionsCount.get()) } @Test fun `output properties`() { runBlocking { val result1 = executeOnChanged.execute("1", emptyMap(), emptyList()) { ExecuteOnChangedInputs.ExecutionResult(emptyList(), mapOf("k" to "v", "e" to "")) } assertEquals("e:|k:v", result1.outputProperties.entries.sortedBy { it.key }.joinToString("|") { "${it.key}:${it.value}"}) val result2 = executeOnChanged.execute("1", emptyMap(), emptyList()) { fail("should not reach") } assertEquals("e:|k:v", result2.outputProperties.entries.sortedBy { it.key }.joinToString("|") { "${it.key}:${it.value}"}) } } @Test fun `reporting missing output must fail`() { assertFailsWith(NoSuchFileException::class) { runBlocking { executeOnChanged.execute("1", emptyMap(), emptyList()) { ExecuteOnChangedInputs.ExecutionResult(listOf(tempDir.resolve("1.out"))) } } } } }
1
null
30
988
6a2c7f0b86b36c85e9034f3de9bfe416516b323b
6,482
amper
Apache License 2.0
shimmer/src/main/java/com/valentinilk/shimmer/ShimmerTheme.kt
valentinilk
399,151,906
false
null
package io.spherelabs.system.ui.shimmer import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.tween import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * Copied from https://github.com/valentinilk/compose-shimmer/tree/master */ data class ShimmerTheme( /** * The [AnimationSpec] which will be used for the traversal. Use an infinite spec to repeat * shimmering. * * @see defaultShimmerTheme */ val animationSpec: AnimationSpec<Float>, /** * The [BlendMode] used in the shimmer's [androidx.compose.ui.graphics.Paint]. Have a look at * the theming samples to get an idea on how to utilize the blend mode. * * @see ThemingSamples in the sample app. */ val blendMode: BlendMode, /** * Describes the orientation of the shimmer in degrees. Zero is thereby defined as shimmer * traversing from the left to the right. The rotation is applied clockwise. * Only values >= 0 will be accepted. */ val rotation: Float, /** * The [shaderColors] can be used to control the colors and alpha values of the shimmer. The * size of the list has to be kept in sync with the [shaderColorStops]. Consult the docs of the * [androidx.compose.ui.graphics.LinearGradientShader] for more information and have a look * at the theming samples. * * @see ThemingSamples in the samples app. */ val shaderColors: List<Color>, /** * See docs of [shaderColors]. */ val shaderColorStops: List<Float>?, /** * Controls the width used to distribute the [shaderColors]. */ val shimmerWidth: Dp, ) val defaultShimmerTheme: ShimmerTheme = ShimmerTheme( animationSpec = infiniteRepeatable( animation = tween( 800, easing = LinearEasing, delayMillis = 1_500, ), repeatMode = RepeatMode.Restart, ), blendMode = BlendMode.DstIn, rotation = 15.0f, shaderColors = listOf( Color.Unspecified.copy(alpha = 0.25f), Color.Unspecified.copy(alpha = 1.00f), Color.Unspecified.copy(alpha = 0.25f), ), shaderColorStops = listOf( 0.0f, 0.5f, 1.0f, ), shimmerWidth = 400.dp, ) val LocalShimmerTheme = staticCompositionLocalOf { defaultShimmerTheme }
6
null
5
81
3e55e953536c7f53ae824beb5536103254b3733f
2,684
compose-shimmer
Apache License 2.0
tabulate-core/src/main/kotlin/io/github/voytech/tabulate/core/template/operation/AttributeSetBasedCache.kt
voytech
262,033,710
false
null
package io.github.voytech.tabulate.core.operation import io.github.voytech.tabulate.core.model.AttributeAware import io.github.voytech.tabulate.core.model.Attributes @JvmInline internal value class AttributeClassBasedCache<K : AttributeAware, V>( private val cache: MutableMap<Attributes, V> = mutableMapOf(), ) { @JvmSynthetic operator fun get(key: Attributes): V? = cache[key] @JvmSynthetic operator fun set(key: Attributes, value: V) { cache[key] = value } @JvmSynthetic fun compute(key: Attributes, provider: () -> V): V = cache.computeIfAbsent(key) { provider() } } internal typealias AttributeClassBasedMapCache<K> = AttributeClassBasedCache<K, MutableMap<String, Any>> /** * Obtains or creates (if does not exist) a cache instance. Cache resides in [ContextData.additionalAttributes] * @author <NAME> * @since 0.1.0 */ @JvmSynthetic internal fun <T : AttributedContext> T.ensureAttributeSetBasedCache(): AttributeClassBasedMapCache<T> { additionalAttributes.putIfAbsent("_attribute_set_based_cache", AttributeClassBasedMapCache<T>()) return additionalAttributes["_attribute_set_based_cache"] as AttributeClassBasedMapCache<T> } /** * Given [AttributedContext], resolves mutable map (internal cache). This internal cache is accessed by attribute set * (`attributes` property) of this particular [AttributedContext] receiver. * @author <NAME> * @since 0.1.0 */ @JvmSynthetic internal fun <T : AttributedContext> T.setupCacheAndGet(): MutableMap<String, Any>? { return this.attributes?.takeIf { it.isNotEmpty() }?.let { ensureAttributeSetBasedCache().compute(it) { mutableMapOf() } } } /** * Allows to perform operations in scope of given [AttributedContext] with its internal cache exposed using [AttributedContext]'s * attribute-set. * When using invocations like : * `attributedCell.skipAttributes().let { cellContext -> cellContext.cacheOnAttributeSet("someKey", "someVal") }` * we can put value to, or query internal cache valid for attribute-set `attributeCell.attributes` from `cellContext` which * itself does not expose attributes to consumer. * @author <NAME> * @since 0.1.0 */ @JvmSynthetic internal fun <T : AttributedContext> T.withAttributeSetBasedCache(block: (cache: MutableMap<String, Any>?) -> Unit) = setupCacheAndGet().apply(block) /** * Given [ModelAttributeAccessor] (truncated, attribute-set-less [AttributedContext] view), caches any value under specific key. * Key-value pair is stored in internal cache valid for / accessed by [AttributedContext]'s attributes (attribute-set). * @author <NAME> * @since 0.1.0 */ @Suppress("UNCHECKED_CAST") fun <T> T.cacheOnAttributeSet(key: String, value: () -> Any): Any where T : AttributedContext, T : Context = setupCacheAndGet()?.computeIfAbsent(key) { value() } ?: value() /** * Given [ModelAttributeAccessor] (truncated, attribute-set-less [AttributedContext] view), gets cached value stored under given key. * Key-value pair is stored in internal cache valid for / accessed by [AttributedContext]'s attributes (attribute-set). * @author <NAME> * @since 0.1.0 */ @Suppress("UNCHECKED_CAST") fun <T> T.getCachedOnAttributeSet(key: String): Any where T : AttributedContext, T : Context = setupCacheAndGet()?.get(key) ?: error("cannot resolve cached value in scope!")
17
Kotlin
0
2
c7886212148dbaba9cfcaeba826ce752b4971bea
3,418
tabulate
Apache License 2.0
example/app/src/main/kotlin/me/omico/lux/compose/material3/pullrefresh/test/MainActivity.kt
Omico
576,859,638
false
{"Kotlin": 45494}
package me.omico.lux.compose.material3.pullrefresh.test import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.material3.pullrefresh.PullRefreshIndicator import androidx.compose.material3.pullrefresh.pullRefresh import androidx.compose.material3.pullrefresh.rememberPullRefreshState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import kotlinx.coroutines.launch import me.omico.lux.compose.material3.pullrefresh.test.theme.AppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme { // From https://developer.android.com/reference/kotlin/androidx/compose/material/pullrefresh/package-summary#(androidx.compose.ui.Modifier).pullRefresh(androidx.compose.material.pullrefresh.PullRefreshState,kotlin.Boolean) val refreshScope = rememberCoroutineScope() var refreshing by remember { mutableStateOf(false) } var itemCount by remember { mutableIntStateOf(15) } fun refresh() = refreshScope.launch { refreshing = true delay(1500) itemCount += 5 refreshing = false } val state = rememberPullRefreshState(refreshing, ::refresh) Box(modifier = Modifier.pullRefresh(state = state)) { LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(space = 8.dp), ) { if (!refreshing) { items(itemCount) { Card { Box(modifier = Modifier.padding(all = 8.dp)) { Text(text = "Item ${itemCount - it}") } } } } } PullRefreshIndicator( modifier = Modifier.align(alignment = Alignment.TopCenter), refreshing = refreshing, state = state, ) } } } } }
0
Kotlin
6
58
04e019da3a923d68d111cc0bf5a2141dc711966f
3,128
androidx-compose-material3-pullrefresh
Apache License 2.0
android/app/src/main/kotlin/com/example/verygoodcore/MainActivity.kt
NjokiCynthia
466,003,459
false
{"Dart": 53693, "C++": 16819, "CMake": 7941, "HTML": 3941, "C": 715, "Swift": 404, "Kotlin": 138, "Objective-C": 38}
package com.example.verygoodcore.the_list import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
22a8f6c65c73de81f04a426a31074762640f274d
138
cubit_list
MIT License
common/src/commonMain/kotlin/com/artemchep/keyguard/common/service/relays/api/firefoxrelay/FirefoxRelayEmailRelay.kt
AChep
669,697,660
false
{"Kotlin": 5254408, "HTML": 45810}
package com.artemchep.keyguard.common.service.relays.api.firefoxrelay import com.artemchep.keyguard.common.io.IO import com.artemchep.keyguard.common.io.ioEffect import com.artemchep.keyguard.common.model.GeneratorContext import com.artemchep.keyguard.common.service.relays.api.EmailRelay import com.artemchep.keyguard.common.service.relays.api.EmailRelaySchema import com.artemchep.keyguard.feature.confirmation.ConfirmationRoute import com.artemchep.keyguard.feature.localization.TextHolder import com.artemchep.keyguard.res.Res import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.http.isSuccess import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.persistentMapOf import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive import org.kodein.di.DirectDI import org.kodein.di.instance class FirefoxRelayEmailRelay( private val httpClient: HttpClient, ) : EmailRelay { companion object { private const val ENDPOINT = "https://relay.firefox.com/api/v1/relayaddresses/" private const val KEY_API_KEY = "apiKey" private const val HINT_API_KEY = "<KEY>" } override val type = "FirefoxRelay" override val name = "Firefox Relay" override val docUrl = "https://bitwarden.com/help/generator/#tab-firefox-relay-3Uj911RtQsJD9OAhUuoKrz" override val schema = persistentMapOf( KEY_API_KEY to EmailRelaySchema( title = TextHolder.Res(Res.strings.api_key), hint = TextHolder.Value(HINT_API_KEY), type = ConfirmationRoute.Args.Item.StringItem.Type.Token, canBeEmpty = false, ), ) constructor(directDI: DirectDI) : this( httpClient = directDI.instance(), ) override fun generate( context: GeneratorContext, config: ImmutableMap<String, String>, ): IO<String> = ioEffect { val apiKey = requireNotNull(config[KEY_API_KEY]) { "API key is required for creating an email alias." } // https://relay.firefox.com/ val response = httpClient .post(ENDPOINT) { header("Authorization", "Token $apiKey") val body = FirefoxRelayRequest( enabled = true, description = "Generated by Keyguard.", ) contentType(ContentType.Application.Json) setBody(body) } require(response.status.isSuccess()) { // Example of an error: // {"detail":"Invalid token."} val message = runCatching { val result = response .body<JsonObject>() result["detail"]?.jsonPrimitive?.content }.getOrNull() message ?: HttpStatusCode.fromValue(response.status.value).description } val result = response .body<JsonObject>() val alias = result["full_address"]?.jsonPrimitive?.content requireNotNull(alias) { "Email alias is missing from the response. " + "Please report this to the developer." } } @Serializable private data class FirefoxRelayRequest( val enabled: Boolean, val description: String, ) }
57
Kotlin
22
735
4e9809d0252257b9e918e44050570769d9326bc2
3,585
keyguard-app
Linux Kernel Variant of OpenIB.org license
src/main/kotlin/ro/kreator/GenerateWith.kt
random-object-kreator
96,997,454
false
null
package io.github.memoizr.kofix import kotlin.reflect.KProperty inline fun <reified T, reified A, reified B> custom(noinline custom: (A, B) -> T) = Generator1(custom) class Generator1<T, A, B>(private val custom: (A, B) -> T) { operator fun getValue(a: Any, property: KProperty<*>): Generator1<T, A, B> { val type = property.returnType.arguments.first().type!! val type1 = property.returnType.arguments[1].type!! val type2 = property.returnType.arguments[2].type!! CreationLogic.ObjectFactory[type] = { _, _, property, token -> custom( CreationLogic.instantiateRandomClass(type1, token = token, kProperty = property) as A, CreationLogic.instantiateRandomClass(type2, token = token, kProperty = property) as B) as Any } return this } } inline fun <reified T, A> custom(noinline custom: (A) -> T) = Generator0(custom) inline fun <reified T> custom(noinline custom: () -> T) = Generator0<T, Any> {custom()} class Generator0<T, A>(private val custom: (A) -> T) { operator fun getValue(a: Any, property: KProperty<*>): Generator0<T, A> { val type = property.returnType.arguments.first().type!! val type1 = property.returnType.arguments[1].type!! CreationLogic.ObjectFactory[type] = { _, _, property, token -> custom( CreationLogic.instantiateRandomClass( type1, token = token, kProperty = property ) as A) as Any } return this } }
1
null
1
1
e8bfd68a2b1e0f00e1e282f0f8ad7e6724cf6c74
1,523
random-object-kreator
Apache License 2.0
src/main/kotlin/com/github/h0tk3y/compilersCourse/x86/StackToX86Compiler.kt
h0tk3y
84,680,038
false
{"Kotlin": 121497, "C": 6067}
package com.github.h0tk3y.compilersCourse.x86 import com.github.h0tk3y.compilersCourse.Compiler import com.github.h0tk3y.compilersCourse.language.* import com.github.h0tk3y.compilersCourse.stack.* import java.util.* import kotlin.math.absoluteValue enum class TargetPlatform { UNIX, WIN } class StackToX86Compiler(val targetPlatform: TargetPlatform) : Compiler<StackProgram, String> { private fun formatFunctionName(name: String) = when (targetPlatform) { TargetPlatform.UNIX -> name TargetPlatform.WIN -> "_$name" } class CompilationEnvironment(val program: StackProgram) { val result = mutableListOf<AsmDirective>() fun emit(i: AsmDirective) { result.add(i) } fun pushSsType(type: Type) = pushSs(FromConstant(type.flag)) fun pushSs(src: AsmLocation): SymbolicStackLocation { if (src is SymbolicStackRegister) { check(src !in symbolicStack) symbolicStack.push(src) emit(CommentLine("pseudo push: ${prettyPrintStack(1)}")) return src } else { val location = allocOnSymStack() if (location is SymbolicStackRegister) { emit(Movl(src, location, prettyPrintStack(1))) return location } else { emit(Pushl(src, prettyPrintStack(1))) return programStack } } } fun popSs(dst: AsmLocation?) { val location = symbolicStack.pop() if (dst == null) when (location) { programStack -> emit(Addl(FromConstant(4), esp, prettyPrintStack(-1))) else -> emit(CommentLine("dropping stack item, ${prettyPrintStack(-1)}")) } else when (location) { programStack -> emit(Popl(dst, prettyPrintStack(-1))) else -> emit(Movl(location, dst, prettyPrintStack(-1))) } } fun dropTypePopSsToReg1(toRegWhenNotSuitable: AsmRegister = eax, requires8BitOps: Boolean = false): AsmRegister { val reg = popSsToReg1(toRegWhenNotSuitable, requires8BitOps) return popSsToReg1(reg, requires8BitOps) } fun popSsToReg1(toRegWhenNotSuitable: AsmRegister = eax, requires8BitOps: Boolean = false): AsmRegister { val currentLocation = symbolicStack.peek() return if ( currentLocation == programStack || currentLocation is SymbolicStackRegister && requires8BitOps && !currentLocation.supports8Bits ) { popSs(toRegWhenNotSuitable) toRegWhenNotSuitable } else { emit(CommentLine("virtual pop: ${prettyPrintStack(-1)}")) return symbolicStack.pop() as SymbolicStackRegister } } fun dropTypesPopToTwoRegs(require8BitOps: Boolean) = dropTypePopSsToReg1(ebx, require8BitOps) to dropTypePopSsToReg1(eax, require8BitOps) private fun allocOnSymStack(): SymbolicStackLocation { val nextItem = SymbolicStackRegister.values().firstOrNull { it !in symbolicStack } ?: programStack symbolicStack.push(nextItem) return nextItem } val symbolicStackAtInsn = sortedMapOf<Int, Stack<SymbolicStackLocation>>() var symbolicStack = Stack<SymbolicStackLocation>() private fun prettyPrintStack(lastSizeChange: Int) = when { lastSizeChange == 0 -> symbolicStack.joinToString(" ") lastSizeChange > 0 -> symbolicStack.dropLast(1).joinToString(" ") { it.render() } + " -> " + symbolicStack.lastOrNull()?.render().orEmpty() else -> symbolicStack.joinToString(" ") { it.render() } + " <- " } } enum class Type(val flag: Int) { SCALAR(0), SCALAR_ARRAY(1), BOXED_ARRAY(2) } private fun CompilationEnvironment.compileFunction(functionDeclaration: FunctionDeclaration, source: List<StackStatement>) { val intrinsicRefIncreaseName = formatFunctionName("ref_increase") val intrinsicRefDecreaseName = formatFunctionName("ref_decrease") functionDeclaration.name.let { fName -> val labelName = formatFunctionName(fName) val label = Label(labelName) emit(Globl(label)) emit(label) } symbolicStackAtInsn.clear() emit(Pushl(ebp)) emit(Movl(esp, ebp)) val functionScope = (collectVariables(source)).distinct() val locals = functionScope - functionDeclaration.parameters val localOffsets = locals.asSequence() .zip(generateSequence(-4) { it - 8 }) { local, offset -> local to Indirect(ebp, offset) } .toMap() val localTypeOffsets = locals.asSequence() .zip(generateSequence(-8) { it - 8 }) { local, offset -> local to Indirect(ebp, offset) } .toMap() val paramsBoundary = 2 * 4 // 2 words for the previous frame's EBP and the return address val paramOffsets = functionDeclaration.parameters.asSequence() .zip(generateSequence(paramsBoundary + 4) { it + 8 }) { param, offset -> param to Indirect(ebp, offset) } .toMap() val paramTypeOffsets = functionDeclaration.parameters.asSequence() .zip(generateSequence(paramsBoundary) { it + 8 }) { param, offset -> param to Indirect(ebp, offset) } .toMap() fun emitRefIncrease(refLocation: AsmLocation, typeLocation: AsmLocation) { emit(Pushl(ecx)) emit(Pushl(edx)) emit(Pushl(refLocation)) emit(Pushl(typeLocation)) emit(CallLabel(Label(intrinsicRefIncreaseName))) emit(Addl(FromConstant(8), esp)) emit(Popl(edx)) emit(Popl(ecx)) } fun emitRefDecrease(refLocation: AsmLocation, typeLocation: AsmLocation) { emit(Pushl(ecx)) emit(Pushl(edx)) emit(Pushl(refLocation)) emit(Pushl(typeLocation)) emit(CallLabel(Label(intrinsicRefDecreaseName))) emit(Addl(FromConstant(8), esp)) emit(Popl(edx)) emit(Popl(ecx)) } functionDeclaration.parameters.forEach { emit(CommentLine("# value offset for param $it: ${paramOffsets[it]!!.offset}")) emit(CommentLine("# type offset for param $it: ${paramTypeOffsets[it]!!.offset}")) emitRefIncrease(paramOffsets[it]!!, paramTypeOffsets[it]!!) } locals.forEach { emit(Pushl(FromConstant(0), "value offset for $it: ${localOffsets[it]!!.offset}")) emit(Pushl(FromConstant(0), "type offset for $it: ${localTypeOffsets[it]!!.offset}")) } val valueOffsets = localOffsets + paramOffsets val typeOffsets = localTypeOffsets + paramTypeOffsets val lastLocalEbpOffset = (localOffsets.values + localTypeOffsets.values).map(Indirect::offset).min() ?: 0 var insnCanContinue: Boolean fun lineLabel(i: Int, s: StackStatement? = null): Label = Label("${functionDeclaration.name}_l$i", s?.toString()) fun compileInstruction(i: Int, s: StackStatement) { insnCanContinue = true if (i in symbolicStackAtInsn) { symbolicStack = symbolicStackAtInsn[i]!! } when (s) { Nop -> Unit is Push -> { pushSs(FromConstant(s.constant.value)) pushSsType(Type.SCALAR) } is PushPooled -> { pushSs(FromConstant(pooledStringLabel(s.id).name)) pushSsType(Type.SCALAR) } is Ld -> { pushSs(valueOffsets[s.v]!!) pushSs(typeOffsets[s.v]!!) } is St -> { val varValueOffset = valueOffsets[s.v]!! val varTypeOffset = typeOffsets[s.v]!! emitRefDecrease(varValueOffset, varTypeOffset) popSs(varTypeOffset) popSs(varValueOffset) emitRefIncrease(varValueOffset, varTypeOffset) } is Unop -> when (s.kind) { Not -> { val reg = dropTypePopSsToReg1() emit(Cmp(FromConstant(0), reg)) val labelNz = Label("${functionDeclaration.name}_l${i}_nz") emit(JnzLabel(labelNz)) val stackLocation = pushSs(FromConstant(1)) val targetLoc = when (stackLocation) { is SymbolicStackRegister -> stackLocation is programStack -> Indirect(esp, 0) } pushSsType(Type.SCALAR) val labelAfter = Label("${functionDeclaration.name}_l${i}_after") emit(JmpLabel(labelAfter)) emit(labelNz) emit(Movl(FromConstant(0), targetLoc, "replace 1 with 0")) emit(labelAfter) } } is Binop -> { val (opB, opA) = dropTypesPopToTwoRegs(opRequires8Bits(s.kind)) var resultRegister = opB when (s.kind) { Plus -> emit(Addl(opA, opB)) Minus -> { resultRegister = opA emit(Subl(opB, opA)) } Times -> emit(Imul(opA, opB)) Div, Rem -> { resultRegister = eax emit(Pushl(edx)) emit(Movl(opA, eax)) emit(Movl(opB, ebx)) emit(Cltd) emit(Idiv(ebx)) if (s.kind == Rem) emit(Movl(edx, eax)) emit(Popl(edx)) } And, Or -> { emit(Andl(opA, opA)) emit(Set8Bit(ComparisonOperation.nz, lower8Bits(opA))) emit(Andl(FromConstant(1), opA)) emit(Andl(opB, opB)) emit(Set8Bit(ComparisonOperation.nz, lower8Bits(opB))) emit(Andl(FromConstant(1), opB)) emit( if (s.kind == And) Andl(opA, opB) else Orl(opA, opB) ) } Eq, Neq, Gt, Lt, Leq, Geq -> { emit(Subl(opA, opB)) emit(Set8Bit(setComparisonOp[s.kind]!!, lower8Bits(opB))) emit(Andl(FromConstant(1), opB)) } } pushSs(resultRegister) pushSsType(Type.SCALAR) } is Jmp -> { symbolicStackAtInsn[s.nextInstruction] = Stack<SymbolicStackLocation>().apply { addAll(symbolicStack) } insnCanContinue = false emit(JmpLabel(lineLabel(s.nextInstruction))) } is Jz -> { val op = dropTypePopSsToReg1() symbolicStackAtInsn[s.nextInstruction] = Stack<SymbolicStackLocation>().apply { addAll(symbolicStack) } emit(Cmp(FromConstant(0), op)) emit(JumpConditional(ComparisonOperation.z, lineLabel(s.nextInstruction))) } is Call -> { val fName = functionBackEndName(s.function) val existingProgramStackItemsCount = symbolicStack.filter { it == programStack }.count() val lastTakenEbpOffset = existingProgramStackItemsCount * 4 + lastLocalEbpOffset.absoluteValue val regItemsCount = symbolicStack.size - existingProgramStackItemsCount val programStackEbpOffsetBySymbolicStackIndex = symbolicStack.withIndex().associate { (index, stackItem) -> val offset = if (stackItem is SymbolicStackRegister) { emit(Pushl(stackItem)) -lastTakenEbpOffset - 4 * (1 + index) } else { -lastTakenEbpOffset - 4 * (1 + index - regItemsCount - existingProgramStackItemsCount) } index to Indirect(ebp, offset) } val specialItemsForCalleeOnStack = if (s.function.canThrow) { emit(Pushl(FromConstant(0))) // thrown exception id 1 } else 0 val nParamStackItems = s.function.parameters.size * 2 // value and type for each parameter val paramStackIndices = symbolicStack.indices.toList().takeLast(nParamStackItems) .reversed() .chunked(2) { it.reversed() } .flatten() for (paramStackIndex in paramStackIndices) { emit(Pushl(programStackEbpOffsetBySymbolicStackIndex[paramStackIndex]!!)) } emit(CallLabel(Label(formatFunctionName(fName)))) (nParamStackItems * 4).let { argBytesOnStack -> if (argBytesOnStack > 0) emit(Addl(FromConstant(argBytesOnStack), esp)) } if (s.function.canThrow) { emit(Pushl(eax)) emit(Movl(Indirect(esp, 4), eax)) emit(Cmp(FromConstant(0), eax)) val labelWhenThrown = Label("whenThrown_${functionDeclaration.name}_$i") val labelAfterCall = Label("afterCall_${functionDeclaration.name}_$i") emit(JumpConditional(ComparisonOperation.g, labelWhenThrown)) emit(JmpLabel(labelAfterCall)) //todo optimize jumps emit(labelWhenThrown) pushSs(Indirect(esp, 4)) pushSsType(Type.SCALAR) compileInstruction(i, St(thrownExceptionVariable)) emit(labelAfterCall) emit(Popl(eax)) } (specialItemsForCalleeOnStack * 4).let { specialItemBytesOnStack -> if (specialItemBytesOnStack > 0) emit(Addl(FromConstant(specialItemBytesOnStack), esp)) } for (loc in symbolicStack.filter { it is SymbolicStackRegister }.reversed()) { // restore symstack registers emit(Popl(loc)) } s.function.parameters.forEach { popSs(null) // drop the parameters from the stack popSs(null) } pushSs(eax) pushSs(ebx) // push type returned in ebx from the function } TransEx -> { if (functionDeclaration.name != "main") { pushSs(valueOffsets[currentExceptionVariable]!!) val offsetBeyondParams = 0 val parentFrameThrownExOffset = paramOffsets.values.map(Indirect::offset).max()?.plus(4) ?: paramsBoundary+ offsetBeyondParams popSs(Indirect(ebp, parentFrameThrownExOffset)) } } Ret0, Ret1 -> { for ((k, valueOffset) in valueOffsets) { if (k == exceptionDataVariable) continue val typeOffset = typeOffsets[k]!! emitRefDecrease(valueOffset, typeOffset) } if (s == Ret1) { popSs(ebx) popSs(eax) } else { emit(Movl(FromConstant(Type.SCALAR.flag), ebx)) emit(Movl(FromConstant(0), eax)) } emit(Leave) if (functionDeclaration.name == "main") { // Make main always return 0 emit(Movl(FromConstant(0), eax)) } emit(Ret) } Pop -> { compileInstruction(i, St(poppedUnusedValueVariable)) } } if (i + 1 in symbolicStackAtInsn && insnCanContinue) { check(symbolicStackAtInsn[i + 1] == symbolicStack) } } check(symbolicStack.isEmpty()) for ((i, s) in source.withIndex()) { emit(lineLabel(i, s)) compileInstruction(i, s) } check(symbolicStack.isEmpty()) } override fun compile(source: StackProgram): String { val compilationEnvironment = CompilationEnvironment(source) with(compilationEnvironment) { emit(TextSection) for ((f, fCode) in source.functions) { compileFunction(f, fCode) } emit(SectionRodata) for ((i, l) in source.literalPool.withIndex()) { emit(StringData(i, String(l))) } } return compilationEnvironment.result.joinToString("\n") { it.renderDirective() } + "\n" } } private val setComparisonOp = mapOf( Eq to ComparisonOperation.z, Neq to ComparisonOperation.nz, Gt to ComparisonOperation.l, Lt to ComparisonOperation.g, Leq to ComparisonOperation.ge, Geq to ComparisonOperation.le ) private fun opRequires8Bits(binaryOperationKind: BinaryOperationKind) = when (binaryOperationKind) { And, Or, Eq, Neq, Gt, Lt, Leq, Geq -> true else -> false } private fun functionBackEndName(functionDeclaration: FunctionDeclaration): String = if (functionDeclaration is Intrinsic) { when (functionDeclaration) { Intrinsic.STRLEN -> "strlen_2" Intrinsic.STRDUP -> "strdup_2" Intrinsic.STRCMP -> "strcmp_4" Intrinsic.STRCAT -> "strcat_4" else -> functionDeclaration.name } } else functionDeclaration.name
0
Kotlin
3
8
3ce171ab6870c44c93233dbca5ccffebc631d3c4
19,096
compilers-course
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/CustomResourceProviderProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 137826907}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.collections.Map /** * Initialization properties for `CustomResourceProvider`. * * Example: * * ``` * CustomResourceProvider provider = CustomResourceProvider.getOrCreateProvider(this, * "Custom::MyCustomResourceType", CustomResourceProviderProps.builder() * .codeDirectory(String.format("%s/my-handler", __dirname)) * .runtime(CustomResourceProviderRuntime.NODEJS_18_X) * .build()); * provider.addToRolePolicy(Map.of( * "Effect", "Allow", * "Action", "s3:GetObject", * "Resource", "*")); * ``` */ public interface CustomResourceProviderProps : CustomResourceProviderOptions { /** * A local file system directory with the provider's code. * * The code will be * bundled into a zip asset and wired to the provider's AWS Lambda function. */ public fun codeDirectory(): String /** * The AWS Lambda runtime and version to use for the provider. */ public fun runtime(): CustomResourceProviderRuntime /** * A builder for [CustomResourceProviderProps] */ @CdkDslMarker public interface Builder { /** * @param codeDirectory A local file system directory with the provider's code. * The code will be * bundled into a zip asset and wired to the provider's AWS Lambda function. */ public fun codeDirectory(codeDirectory: String) /** * @param description A description of the function. */ public fun description(description: String) /** * @param environment Key-value pairs that are passed to Lambda as Environment. */ public fun environment(environment: Map<String, String>) /** * @param memorySize The amount of memory that your function has access to. * Increasing the * function's memory also increases its CPU allocation. */ public fun memorySize(memorySize: Size) /** * @param policyStatements A set of IAM policy statements to include in the inline policy of the * provider's lambda function. * **Please note**: these are direct IAM JSON policy blobs, *not* `iam.PolicyStatement` * objects like you will see in the rest of the CDK. */ public fun policyStatements(policyStatements: List<Any>) /** * @param policyStatements A set of IAM policy statements to include in the inline policy of the * provider's lambda function. * **Please note**: these are direct IAM JSON policy blobs, *not* `iam.PolicyStatement` * objects like you will see in the rest of the CDK. */ public fun policyStatements(vararg policyStatements: Any) /** * @param runtime The AWS Lambda runtime and version to use for the provider. */ public fun runtime(runtime: CustomResourceProviderRuntime) /** * @param timeout AWS Lambda timeout for the provider. */ public fun timeout(timeout: Duration) /** * @param useCfnResponseWrapper Whether or not the cloudformation response wrapper * (`nodejs-entrypoint.ts`) is used. If set to `true`, `nodejs-entrypoint.js` is bundled in the * same asset as the custom resource and set as the entrypoint. If set to `false`, the custom * resource provided is the entrypoint. */ public fun useCfnResponseWrapper(useCfnResponseWrapper: Boolean) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.CustomResourceProviderProps.Builder = software.amazon.awscdk.CustomResourceProviderProps.builder() /** * @param codeDirectory A local file system directory with the provider's code. * The code will be * bundled into a zip asset and wired to the provider's AWS Lambda function. */ override fun codeDirectory(codeDirectory: String) { cdkBuilder.codeDirectory(codeDirectory) } /** * @param description A description of the function. */ override fun description(description: String) { cdkBuilder.description(description) } /** * @param environment Key-value pairs that are passed to Lambda as Environment. */ override fun environment(environment: Map<String, String>) { cdkBuilder.environment(environment) } /** * @param memorySize The amount of memory that your function has access to. * Increasing the * function's memory also increases its CPU allocation. */ override fun memorySize(memorySize: Size) { cdkBuilder.memorySize(memorySize.let(Size::unwrap)) } /** * @param policyStatements A set of IAM policy statements to include in the inline policy of the * provider's lambda function. * **Please note**: these are direct IAM JSON policy blobs, *not* `iam.PolicyStatement` * objects like you will see in the rest of the CDK. */ override fun policyStatements(policyStatements: List<Any>) { cdkBuilder.policyStatements(policyStatements.map{CdkObjectWrappers.unwrap(it)}) } /** * @param policyStatements A set of IAM policy statements to include in the inline policy of the * provider's lambda function. * **Please note**: these are direct IAM JSON policy blobs, *not* `iam.PolicyStatement` * objects like you will see in the rest of the CDK. */ override fun policyStatements(vararg policyStatements: Any): Unit = policyStatements(policyStatements.toList()) /** * @param runtime The AWS Lambda runtime and version to use for the provider. */ override fun runtime(runtime: CustomResourceProviderRuntime) { cdkBuilder.runtime(runtime.let(CustomResourceProviderRuntime::unwrap)) } /** * @param timeout AWS Lambda timeout for the provider. */ override fun timeout(timeout: Duration) { cdkBuilder.timeout(timeout.let(Duration::unwrap)) } /** * @param useCfnResponseWrapper Whether or not the cloudformation response wrapper * (`nodejs-entrypoint.ts`) is used. If set to `true`, `nodejs-entrypoint.js` is bundled in the * same asset as the custom resource and set as the entrypoint. If set to `false`, the custom * resource provided is the entrypoint. */ override fun useCfnResponseWrapper(useCfnResponseWrapper: Boolean) { cdkBuilder.useCfnResponseWrapper(useCfnResponseWrapper) } public fun build(): software.amazon.awscdk.CustomResourceProviderProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.CustomResourceProviderProps, ) : CdkObject(cdkObject), CustomResourceProviderProps { /** * A local file system directory with the provider's code. * * The code will be * bundled into a zip asset and wired to the provider's AWS Lambda function. */ override fun codeDirectory(): String = unwrap(this).getCodeDirectory() /** * A description of the function. * * Default: - No description. */ override fun description(): String? = unwrap(this).getDescription() /** * Key-value pairs that are passed to Lambda as Environment. * * Default: - No environment variables. */ override fun environment(): Map<String, String> = unwrap(this).getEnvironment() ?: emptyMap() /** * The amount of memory that your function has access to. * * Increasing the * function's memory also increases its CPU allocation. * * Default: Size.mebibytes(128) */ override fun memorySize(): Size? = unwrap(this).getMemorySize()?.let(Size::wrap) /** * A set of IAM policy statements to include in the inline policy of the provider's lambda * function. * * **Please note**: these are direct IAM JSON policy blobs, *not* `iam.PolicyStatement` * objects like you will see in the rest of the CDK. * * Default: - no additional inline policy * * Example: * * ``` * CustomResourceProvider provider = CustomResourceProvider.getOrCreateProvider(this, * "Custom::MyCustomResourceType", CustomResourceProviderProps.builder() * .codeDirectory(String.format("%s/my-handler", __dirname)) * .runtime(CustomResourceProviderRuntime.NODEJS_18_X) * .policyStatements(List.of(Map.of( * "Effect", "Allow", * "Action", "s3:PutObject*", * "Resource", "*"))) * .build()); * ``` */ override fun policyStatements(): List<Any> = unwrap(this).getPolicyStatements() ?: emptyList() /** * The AWS Lambda runtime and version to use for the provider. */ override fun runtime(): CustomResourceProviderRuntime = unwrap(this).getRuntime().let(CustomResourceProviderRuntime::wrap) /** * AWS Lambda timeout for the provider. * * Default: Duration.minutes(15) */ override fun timeout(): Duration? = unwrap(this).getTimeout()?.let(Duration::wrap) /** * Whether or not the cloudformation response wrapper (`nodejs-entrypoint.ts`) is used. If set * to `true`, `nodejs-entrypoint.js` is bundled in the same asset as the custom resource and set as * the entrypoint. If set to `false`, the custom resource provided is the entrypoint. * * Default: - `true` if `inlineCode: false` and `false` otherwise. */ override fun useCfnResponseWrapper(): Boolean? = unwrap(this).getUseCfnResponseWrapper() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CustomResourceProviderProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.CustomResourceProviderProps): CustomResourceProviderProps = CdkObjectWrappers.wrap(cdkObject) as? CustomResourceProviderProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CustomResourceProviderProps): software.amazon.awscdk.CustomResourceProviderProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.CustomResourceProviderProps } }
4
Kotlin
0
4
e15f2e27e08adeb755ad44b2424c195521a6f5ba
10,432
kotlin-cdk-wrapper
Apache License 2.0
picker/src/main/java/com/afollestad/materialdialogs/picker/DialogNumberPicker.kt
kamaelyoung
112,328,897
true
{"Kotlin": 308220}
package com.afollestad.materialdialogs.picker import android.widget.NumberPicker import androidx.annotation.CheckResult import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.list.ItemListener import com.afollestad.materialdialogs.utils.MDUtil.isLandscape fun MaterialDialog.numberPicker(items: Array<String>, initialSelection: Int = - 1, selection: ItemListener = null): MaterialDialog { require(initialSelection >= - 1 || initialSelection < items.size) { "Initial selection $initialSelection must be between -1 and " + "the size of your items array ${items.size}" } customView(R.layout.md_number_picker_layout, noVerticalPadding = true, horizontalPadding = true, dialogWrapContent = windowContext.isLandscape()) with(getNumberPicker()) { displayedValues = items descendantFocusability = NumberPicker.FOCUS_BLOCK_DESCENDANTS wrapSelectorWheel = false minValue = 0 maxValue = items.size - 1 value = initialSelection setOnValueChangedListener {picker, oldVal, newVal -> } } positiveButton(android.R.string.ok) { selection?.invoke(it, getNumberPicker().value, items[getNumberPicker().value]) } negativeButton(android.R.string.cancel) return this } @CheckResult fun MaterialDialog.selectedValue(): Int { return getNumberPicker().value } internal fun MaterialDialog.getNumberPicker() = findViewById<NumberPicker>(R.id.md_number_picker)
0
Kotlin
0
0
64c2a9a74fcf944326664603997d16c36774e3e6
1,519
material-dialogs
Apache License 2.0
app/src/main/java/com/example/foodappwithmvi/view/favorite/FavoriteViewModel.kt
rezakardan
719,055,375
false
{"Kotlin": 59035}
package com.example.foodappwithmvi.view.favorite import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.foodappwithmvi.data.repository.FavoriteRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class FavoriteViewModel@Inject constructor(private val repository: FavoriteRepository):ViewModel() { init { handleIntents() } val favoriteChannel=Channel<FavoriteIntent>() private val _state=MutableStateFlow<FavoriteState>(FavoriteState.EmptyList) val state:StateFlow<FavoriteState>get() = _state private fun handleIntents()=viewModelScope.launch { favoriteChannel.consumeAsFlow().collect{favoriteIntent-> when(favoriteIntent){ is FavoriteIntent.GetAllFoods->{getAllFoods()} } } } private fun getAllFoods()=viewModelScope.launch { repository.getAllFoods().collect{ if (it.isNotEmpty()) { _state.value=FavoriteState.GetAllFoods(it) }else{ _state.value=FavoriteState.EmptyList } } } }
0
Kotlin
0
0
e10b7caaf0cb37752702f030bbb4417023216757
1,408
foodWithMvi_Git
MIT License
data/src/main/kotlin/com/vultisig/wallet/data/repositories/TransactionRepository.kt
vultisig
789,965,982
false
{"Kotlin": 1481084, "Ruby": 1713}
package com.vultisig.wallet.data.repositories import com.vultisig.wallet.data.models.Transaction import com.vultisig.wallet.data.models.TransactionId import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import javax.inject.Inject internal interface TransactionRepository { suspend fun addTransaction(transaction: Transaction) fun getTransaction(id: TransactionId): Flow<Transaction> } internal class TransactionRepositoryImpl @Inject constructor() : TransactionRepository { private val transactions = MutableStateFlow(mapOf<TransactionId, Transaction>()) override suspend fun addTransaction(transaction: Transaction) { transactions.update { it + (transaction.id to transaction) } } override fun getTransaction(id: TransactionId): Flow<Transaction> = transactions.map { it[id] ?: error("Transaction with id $id not found") } }
58
Kotlin
2
6
98e6a0754d4872ce4d44fa4a631488d4f805397f
1,019
vultisig-android
Apache License 2.0
src/main/kotlin/no/nav/syfo/application/api/authentication/JwtIssuer.kt
navikt
402,451,651
false
{"Kotlin": 1051781, "Dockerfile": 226}
package no.nav.syfo.application.api.authentication data class JwtIssuer( val acceptedAudienceList: List<String>, val jwtIssuerType: JwtIssuerType, val wellKnown: WellKnown, ) enum class JwtIssuerType { VEILEDER_V2, }
2
Kotlin
2
0
b153cb253f54e8f26c498234a341722d34b6d959
235
syfooversiktsrv
MIT License
sqiffy-test/src/test/kotlin/com/dzikoysk/sqiffy/e2e/JdbiE2ETest.kt
dzikoysk
589,226,903
false
null
@file:Suppress("RemoveRedundantQualifierName") package com.dzikoysk.sqiffy.e2e import com.dzikoysk.sqiffy.dialect.Dialect.POSTGRESQL import com.dzikoysk.sqiffy.api.Role import com.dzikoysk.sqiffy.domain.UnidentifiedUser import com.dzikoysk.sqiffy.domain.User import com.dzikoysk.sqiffy.e2e.specification.SqiffyE2ETestSpecification import com.dzikoysk.sqiffy.e2e.specification.postgresDataSource import com.dzikoysk.sqiffy.infra.UserTableNames import com.dzikoysk.sqiffy.shared.multiline import com.zaxxer.hikari.HikariDataSource import java.util.UUID import org.assertj.core.api.Assertions.assertThat import org.jdbi.v3.core.kotlin.mapTo import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test internal class EmbeddedPostgresJdbiE2ETest : JdbiE2ETest() { private val postgres = postgresDataSource() override fun createDataSource(): HikariDataSource = postgres.dataSource @AfterEach fun stop() { postgres.embeddedPostgres.close() } } internal abstract class JdbiE2ETest : SqiffyE2ETestSpecification() { @Test fun `should insert and select entity`() { val insertedUser = database.getJdbi().withHandle<User, Exception> { handle -> val userToInsert = UnidentifiedUser( name = "Panda", uuid = UUID.randomUUID(), displayName = "Only Panda", role = Role.MODERATOR, wallet = 100f ) handle .createUpdate(multiline(""" INSERT INTO "${UserTableNames.TABLE}" ("${UserTableNames.UUID}", "${UserTableNames.NAME}", "${UserTableNames.DISPLAYNAME}", "${UserTableNames.ROLE}", "${UserTableNames.WALLET}") VALUES (:0, :1, :2, :3${when (database.getDialect()) { POSTGRESQL -> "::${Role.TYPE_NAME}" // jdbc requires explicit casts for enums in postgres else -> "" }}, :4) """)) .bind("0", userToInsert.uuid) .bind("1", userToInsert.name) .bind("2", userToInsert.displayName) .bind("3", userToInsert.role) .bind("4", userToInsert.wallet) .executeAndReturnGeneratedKeys() .map { row -> row.getColumn(UserTableNames.ID, Int::class.javaObjectType) } .first() .let { userToInsert.withId(it) } } println("Inserted user: $insertedUser") val userFromDatabaseUsingRawJdbi = database.getJdbi().withHandle<User, Exception> { handle -> handle .select(multiline(""" SELECT * FROM "${UserTableNames.TABLE}" WHERE "${UserTableNames.NAME}" = :nameToMatch """)) .bind("nameToMatch", "Panda") .mapTo<User>() .firstOrNull() } println("Loaded user: $userFromDatabaseUsingRawJdbi") assertThat(insertedUser).isNotNull assertThat(userFromDatabaseUsingRawJdbi).isNotNull assertThat(userFromDatabaseUsingRawJdbi).isEqualTo(insertedUser) } }
9
null
2
41
67093bc13803248ab5b9a54b9bd104d68adee62c
3,191
sqiffy
Apache License 2.0
app/src/main/java/com/tyhoo/nba/data/players/PlayersSeasonResponse.kt
cnwutianhao
367,525,529
false
null
package com.tyhoo.nba.data.players import com.google.gson.annotations.SerializedName data class PlayersSeasonResponse( @field:SerializedName("yearDisplay") val yearDisplay: String )
0
Kotlin
2
3
8336ee1889e10aee2b31dec35c105af0c1584218
187
android-architecture-components-sample
Apache License 2.0
src/test/enhetstester/kotlin/no/nav/familie/ks/sak/kjerne/behandling/steg/vilkårsvurdering/forskyvBarnehageplassVilkårTest.kt
navikt
533,308,075
false
{"Kotlin": 2851682, "Shell": 1039, "Dockerfile": 141}
package no.nav.familie.ks.sak.kjerne.behandling.steg.vilkårsvurdering import no.nav.familie.ks.sak.data.lagVilkårResultat import no.nav.familie.ks.sak.kjerne.behandling.steg.vilkårsvurdering.domene.Vilkår import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import java.math.BigDecimal import java.time.LocalDate import java.time.YearMonth import org.hamcrest.CoreMatchers.`is` as Is class forskyvBarnehageplassVilkårTest { private val januar = YearMonth.of(2022, 1) private val februar = YearMonth.of(2022, 2) private val mars = YearMonth.of(2022, 3) private val april = YearMonth.of(2022, 4) private val juli = YearMonth.of(2022, 7) private val august = YearMonth.of(2022, 8) private val september = YearMonth.of(2022, 9) private val oktober = YearMonth.of(2022, 10) private val november = YearMonth.of(2022, 11) private val desember = YearMonth.of(2022, 12) // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 1 - Barn går fra ingen barnehageplass til deltids barnehageplass`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(15), periodeTom = oktober.atDay(14), antallTimer = null ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(15), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(8) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(september.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(oktober.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 2 - Barn går fra deltids barnehageplass til ingen barnehageplass`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(15), periodeTom = oktober.atDay(14), antallTimer = BigDecimal.valueOf(8) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(15), periodeTom = desember.atDay(1), antallTimer = null ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(oktober.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(november.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 3,0 - Barnet går fra deltids barnehageplass til økt barnehageplass i månedsskifte`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(8) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(17) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(september.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(oktober.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 3,5 - Barnet går fra fulltids barnehageplass til deltids barnehageplass`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = oktober.atDay(14), antallTimer = BigDecimal.valueOf(33) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(15), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(17) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(oktober.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(november.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Spesialhåndtering 1 - Barnet slutter i barnehage siste dag i september, skal ha full KS fra oktober`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(17) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atDay(1), antallTimer = null ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(september.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(oktober.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Spesialhåndtering 2 - Barnet reduserer barnehageplass i slutten av september, skal ha mer KS fra oktober`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(17) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(8) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(september.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(oktober.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 5 - Barnet går fra deltids barnehageplass til full barnehageplass`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = oktober.atDay(13), antallTimer = BigDecimal.valueOf(8) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(14), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(33) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(september.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(oktober.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 6 - Barnet går fra full barnehageplass til deltids barnehageplass`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = oktober.atDay(13), antallTimer = BigDecimal.valueOf(33) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(14), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(8) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(oktober.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(november.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 7,1 - forskyvBarnehageplassVilkår skal støtte flere perioder i en måned`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = januar.atEndOfMonth(), periodeTom = februar.atDay(12), antallTimer = BigDecimal.valueOf(8) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = februar.atDay(13), periodeTom = februar.atDay(23), antallTimer = BigDecimal.valueOf(32) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = februar.atDay(24), periodeTom = mars.atDay(1), antallTimer = BigDecimal.valueOf(8) ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() Assertions.assertEquals(1, forskjøvedeVilkårResultater.size) Assertions.assertEquals(februar.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(februar.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(BigDecimal.valueOf(32), forskjøvedeVilkårResultater.first().verdi.antallTimer) } // Eksempel i src/test/resources/barnehageplassscenarioer @Test fun `Scenario 7,2 - forskyvBarnehageplassVilkår skal støtte flere perioder i en måned`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = januar.atEndOfMonth(), periodeTom = februar.atDay(12), antallTimer = BigDecimal.valueOf(32) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = februar.atDay(13), periodeTom = februar.atDay(23), antallTimer = BigDecimal.valueOf(8) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = februar.atDay(24), periodeTom = april.atDay(1), antallTimer = BigDecimal.valueOf(16) ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(februar.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(februar.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(BigDecimal.valueOf(32), forskjøvedeVilkårResultater.first().verdi.antallTimer) Assertions.assertEquals(mars.atDay(1), forskjøvedeVilkårResultater.last().fom) Assertions.assertEquals(mars.atEndOfMonth(), forskjøvedeVilkårResultater.last().tom) Assertions.assertEquals(BigDecimal.valueOf(16), forskjøvedeVilkårResultater.last().verdi.antallTimer) } @Test fun `Scenario 1 fra rundskrivet - Endring i KS skjer fra og med samme måned som en økning i barnehageplass`() { val vilkårResultaterForBarn1 = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = juli.atEndOfMonth(), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(17) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = BigDecimal.valueOf(35) ) ) val vilkårResultaterForBarn2 = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = juli.atEndOfMonth(), periodeTom = oktober.atDay(15), antallTimer = BigDecimal.valueOf(24) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(16), periodeTom = desember.atEndOfMonth(), antallTimer = BigDecimal.valueOf(40) ) ) val forskjøvedeVilkårResultaterForBarn1 = vilkårResultaterForBarn1.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultaterForBarn1.size, Is(2)) assertThat(forskjøvedeVilkårResultaterForBarn1.first().fom, Is(august.atDay(1))) assertThat(forskjøvedeVilkårResultaterForBarn1.first().tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultaterForBarn1.first().verdi.antallTimer, Is(BigDecimal(17))) assertThat(forskjøvedeVilkårResultaterForBarn1.last().fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultaterForBarn1.last().tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultaterForBarn1.last().verdi.antallTimer, Is(BigDecimal(35))) val forskjøvedeVilkårResultaterForBarn2 = vilkårResultaterForBarn2.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultaterForBarn2.size, Is(2)) assertThat(forskjøvedeVilkårResultaterForBarn2.first().fom, Is(august.atDay(1))) assertThat(forskjøvedeVilkårResultaterForBarn2.first().tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultaterForBarn2.first().verdi.antallTimer, Is(BigDecimal(24))) assertThat(forskjøvedeVilkårResultaterForBarn2.last().fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultaterForBarn2.last().tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultaterForBarn2.last().verdi.antallTimer, Is(BigDecimal(40))) } @Test fun `Scenario 2 fra rundskrivet - Kontantstøtte ytes fra og med måneden etter at vilkårene er oppfylt`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = september.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = BigDecimal.valueOf(15) ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultater.size, Is(1)) assertThat(forskjøvedeVilkårResultater.first().fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultater.first().tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater.first().verdi.antallTimer, Is(BigDecimal(15))) } @Test fun `Scenario 3 fra rundskrivet - Kontantstøtte opphører fra og med måneden retten til støtte opphører`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = juli.atDay(1), periodeTom = september.atEndOfMonth(), antallTimer = null ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = BigDecimal(8) ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultater.size, Is(2)) assertThat(forskjøvedeVilkårResultater.first().fom, Is(august.atDay(1))) assertThat(forskjøvedeVilkårResultater.first().tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater.first().verdi.antallTimer, Is(nullValue())) assertThat(forskjøvedeVilkårResultater.last().fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultater.last().tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater.last().verdi.antallTimer, Is(BigDecimal(8))) } @Test fun `Scenario 4 fra rundskrivet - Kontantstøtte ytes fra og med måneden etter at barnet sluttet i barnehagen`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = juli.atDay(1), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(25) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = null ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultater.size, Is(2)) assertThat(forskjøvedeVilkårResultater.first().fom, Is(august.atDay(1))) assertThat(forskjøvedeVilkårResultater.first().tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater.first().verdi.antallTimer, Is(BigDecimal.valueOf(25))) assertThat(forskjøvedeVilkårResultater.last().fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultater.last().tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater.last().verdi.antallTimer, Is(nullValue())) } @Test fun `Scenario 5 fra rundskrivet - Reduksjon av barnehageplass skal forskyves riktig`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = januar.atDay(1), periodeTom = august.atEndOfMonth(), antallTimer = null ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = september.atDay(1), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(33) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = BigDecimal.valueOf(15) ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultater.size, Is(3)) assertThat(forskjøvedeVilkårResultater[0].fom, Is(februar.atDay(1))) assertThat(forskjøvedeVilkårResultater[0].tom, Is(august.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[0].verdi.antallTimer, Is(nullValue())) assertThat(forskjøvedeVilkårResultater[1].fom, Is(september.atDay(1))) assertThat(forskjøvedeVilkårResultater[1].tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[1].verdi.antallTimer, Is(BigDecimal.valueOf(33))) assertThat(forskjøvedeVilkårResultater[2].fom, Is(november.atDay(1))) assertThat(forskjøvedeVilkårResultater[2].tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[2].verdi.antallTimer, Is(BigDecimal.valueOf(15))) } @Test fun `Scenario 6 fra rundskrivet - Slutt i barnehage skal forskyves riktig`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = januar.atDay(1), periodeTom = august.atEndOfMonth(), antallTimer = null ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = september.atDay(1), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(33) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = null ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultater.size, Is(3)) assertThat(forskjøvedeVilkårResultater[0].fom, Is(februar.atDay(1))) assertThat(forskjøvedeVilkårResultater[0].tom, Is(august.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[0].verdi.antallTimer, Is(nullValue())) assertThat(forskjøvedeVilkårResultater[1].fom, Is(september.atDay(1))) assertThat(forskjøvedeVilkårResultater[1].tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[1].verdi.antallTimer, Is(BigDecimal.valueOf(33))) assertThat(forskjøvedeVilkårResultater[2].fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultater[2].tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[2].verdi.antallTimer, Is(nullValue())) } @Test fun `Scenario 7 fra rundskrivet - Økt barnehageplass skal forskyves riktig`() { val vilkårResultater = listOf( lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = januar.atDay(1), periodeTom = august.atEndOfMonth(), antallTimer = null ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = september.atDay(1), periodeTom = september.atEndOfMonth(), antallTimer = BigDecimal.valueOf(8) ), lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = oktober.atDay(1), periodeTom = desember.atEndOfMonth(), antallTimer = BigDecimal.valueOf(15) ) ) val forskjøvedeVilkårResultater = vilkårResultater.forskyvBarnehageplassVilkår() assertThat(forskjøvedeVilkårResultater.size, Is(3)) assertThat(forskjøvedeVilkårResultater[0].fom, Is(februar.atDay(1))) assertThat(forskjøvedeVilkårResultater[0].tom, Is(august.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[0].verdi.antallTimer, Is(nullValue())) assertThat(forskjøvedeVilkårResultater[1].fom, Is(september.atDay(1))) assertThat(forskjøvedeVilkårResultater[1].tom, Is(september.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[1].verdi.antallTimer, Is(BigDecimal.valueOf(8))) assertThat(forskjøvedeVilkårResultater[2].fom, Is(oktober.atDay(1))) assertThat(forskjøvedeVilkårResultater[2].tom, Is(desember.atEndOfMonth())) assertThat(forskjøvedeVilkårResultater[2].verdi.antallTimer, Is(BigDecimal.valueOf(15))) } @Test fun `forskyvBarnehageplassVilkår skal ikke forskyves ved overgang til periode med 33 timer eller mer`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = august.atDay(14), periodeTom = oktober.atEndOfMonth(), antallTimer = BigDecimal.valueOf(8) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = november.atDay(1), periodeTom = desember.atDay(1), antallTimer = BigDecimal.valueOf(33) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(2, forskjøvedeVilkårResultater.size) Assertions.assertEquals(september.atDay(1), forskjøvedeVilkårResultater.first().fom) Assertions.assertEquals(oktober.atEndOfMonth(), forskjøvedeVilkårResultater.first().tom) Assertions.assertEquals(BigDecimal.valueOf(8), forskjøvedeVilkårResultater.first().verdi.antallTimer) Assertions.assertEquals(november.atDay(1), forskjøvedeVilkårResultater[1].fom) Assertions.assertEquals(november.atEndOfMonth(), forskjøvedeVilkårResultater[1].tom) Assertions.assertEquals(BigDecimal.valueOf(33), forskjøvedeVilkårResultater[1].verdi.antallTimer) } @Test fun `Skal forskyve riktig ved opphold av barnehageplass`() { val vilkårResultat1 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = LocalDate.of(2022, 1, 14), periodeTom = LocalDate.of(2022, 2, 13), antallTimer = BigDecimal.valueOf(8) ) val vilkårResultat2 = lagVilkårResultat( vilkårType = Vilkår.BARNEHAGEPLASS, periodeFom = LocalDate.of(2022, 2, 15), periodeTom = LocalDate.of(2022, 4, 14), antallTimer = BigDecimal.valueOf(16) ) val forskjøvedeVilkårResultater = listOf(vilkårResultat1, vilkårResultat2).forskyvBarnehageplassVilkår() Assertions.assertEquals(1, forskjøvedeVilkårResultater.size) Assertions.assertEquals(LocalDate.of(2022, 3, 1), forskjøvedeVilkårResultater.single().fom) Assertions.assertEquals(LocalDate.of(2022, 3, 31), forskjøvedeVilkårResultater.single().tom) } }
5
Kotlin
1
2
c39fb12189c468a433ca2920b1aa0f5509b23d54
27,989
familie-ks-sak
MIT License
app/src/main/java/com/example/mediclick/OTPActivity.kt
Utkarsh1244p
803,613,938
false
{"Kotlin": 72381, "Java": 40993}
package com.codingstuff import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.codingstuff.phoneauthkt.R import com.google.firebase.FirebaseException import com.google.firebase.FirebaseTooManyRequestsException import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException import com.google.firebase.auth.PhoneAuthCredential import com.google.firebase.auth.PhoneAuthOptions import com.google.firebase.auth.PhoneAuthProvider import java.util.concurrent.TimeUnit class OTPActivity1 : AppCompatActivity() { private lateinit var auth: FirebaseAuth private lateinit var verifyBtn: Button private lateinit var resendTV: TextView private lateinit var inputOTP1: EditText private lateinit var inputOTP2: EditText private lateinit var inputOTP3: EditText private lateinit var inputOTP4: EditText private lateinit var inputOTP5: EditText private lateinit var inputOTP6: EditText private lateinit var progressBar: ProgressBar private lateinit var OTP: String private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken private lateinit var phoneNumber: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.otp) OTP = intent.getStringExtra("OTP").toString() resendToken = intent.getParcelableExtra("resendToken")!! phoneNumber = intent.getStringExtra("phoneNumber")!! init() progressBar.visibility = View.INVISIBLE addTextChangeListener() resendOTPTvVisibility() resendTV.setOnClickListener { resendVerificationCode() resendOTPTvVisibility() } verifyBtn.setOnClickListener { //collect otp from all the edit texts val typedOTP = (inputOTP1.text.toString() + inputOTP2.text.toString() + inputOTP3.text.toString() + inputOTP4.text.toString() + inputOTP5.text.toString() + inputOTP6.text.toString()) if (typedOTP.isNotEmpty()) { if (typedOTP.length == 6) { val credential: PhoneAuthCredential = PhoneAuthProvider.getCredential( OTP, typedOTP ) progressBar.visibility = View.VISIBLE signInWithPhoneAuthCredential(credential) } else { Toast.makeText(this, "Please Enter Correct OTP", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "Please Enter OTP", Toast.LENGTH_SHORT).show() } } } private fun resendOTPTvVisibility() { inputOTP1.setText("") inputOTP2.setText("") inputOTP3.setText("") inputOTP4.setText("") inputOTP5.setText("") inputOTP6.setText("") resendTV.visibility = View.INVISIBLE resendTV.isEnabled = false Handler(Looper.myLooper()!!).postDelayed(Runnable { resendTV.visibility = View.VISIBLE resendTV.isEnabled = true }, 60000) } private fun resendVerificationCode() { val options = PhoneAuthOptions.newBuilder(auth) .setPhoneNumber(phoneNumber) // Phone number to verify .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit .setActivity(this) // Activity (for callback binding) .setCallbacks(callbacks) .setForceResendingToken(resendToken)// OnVerificationStateChangedCallbacks .build() PhoneAuthProvider.verifyPhoneNumber(options) } private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) { // This callback will be invoked in two situations: // 1 - Instant verification. In some cases the phone number can be instantly // verified without needing to send or enter a verification code. // 2 - Auto-retrieval. On some devices Google Play services can automatically // detect the incoming verification SMS and perform verification without // user action. signInWithPhoneAuthCredential(credential) } override fun onVerificationFailed(e: FirebaseException) { // This callback is invoked in an invalid request for verification is made, // for instance if the the phone number format is not valid. if (e is FirebaseAuthInvalidCredentialsException) { // Invalid request Log.d("TAG", "onVerificationFailed: ${e.toString()}") } else if (e is FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded Log.d("TAG", "onVerificationFailed: ${e.toString()}") } progressBar.visibility = View.VISIBLE // Show a message and update the UI } override fun onCodeSent( verificationId: String, token: PhoneAuthProvider.ForceResendingToken ) { // The SMS verification code has been sent to the provided phone number, we // now need to ask the user to enter the code and then construct a credential // by combining the code with a verification ID. // Save verification ID and resending token so we can use them later OTP = verificationId resendToken = token } } private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Toast.makeText(this, "Authenticate Successfully", Toast.LENGTH_SHORT).show() sendToMain() } else { // Sign in failed, display a message and update the UI Log.d("TAG", "signInWithPhoneAuthCredential: ${task.exception.toString()}") if (task.exception is FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid } // Update UI } progressBar.visibility = View.VISIBLE } } private fun sendToMain() { startActivity(Intent(this, scode::class.java)) } private fun addTextChangeListener() { inputOTP1.addTextChangedListener(EditTextWatcher(inputOTP1)) inputOTP2.addTextChangedListener(EditTextWatcher(inputOTP2)) inputOTP3.addTextChangedListener(EditTextWatcher(inputOTP3)) inputOTP4.addTextChangedListener(EditTextWatcher(inputOTP4)) inputOTP5.addTextChangedListener(EditTextWatcher(inputOTP5)) inputOTP6.addTextChangedListener(EditTextWatcher(inputOTP6)) } private fun init() { auth = FirebaseAuth.getInstance() progressBar = findViewById(R.id.otpProgressBar) verifyBtn = findViewById(R.id.verifyOTPBtn) resendTV = findViewById(R.id.resendTextView) inputOTP1 = findViewById(R.id.otpEditText1) inputOTP2 = findViewById(R.id.otpEditText2) inputOTP3 = findViewById(R.id.otpEditText3) inputOTP4 = findViewById(R.id.otpEditText4) inputOTP5 = findViewById(R.id.otpEditText5) inputOTP6 = findViewById(R.id.otpEditText6) } inner class EditTextWatcher(private val view: View) : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(p0: Editable?) { val text = p0.toString() when (view.id) { R.id.otpEditText1 -> if (text.length == 1) inputOTP2.requestFocus() R.id.otpEditText2 -> if (text.length == 1) inputOTP3.requestFocus() else if (text.isEmpty()) inputOTP1.requestFocus() R.id.otpEditText3 -> if (text.length == 1) inputOTP4.requestFocus() else if (text.isEmpty()) inputOTP2.requestFocus() R.id.otpEditText4 -> if (text.length == 1) inputOTP5.requestFocus() else if (text.isEmpty()) inputOTP3.requestFocus() R.id.otpEditText5 -> if (text.length == 1) inputOTP6.requestFocus() else if (text.isEmpty()) inputOTP4.requestFocus() R.id.otpEditText6 -> if (text.isEmpty()) inputOTP5.requestFocus() } } } }
0
Kotlin
2
0
ec4132569f5af107800878d86afd72daaadf1207
9,182
SIH
MIT License
vyne-core-types/src/main/java/com/orbitalhq/schemas/DefaultTypeCache.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.schemas import com.orbitalhq.models.* import com.orbitalhq.schemas.taxi.TaxiSchema import com.orbitalhq.utils.timed import lang.taxi.TaxiDocument import lang.taxi.types.ArrayType import lang.taxi.types.EnumValueQualifiedName import lang.taxi.types.ObjectType import lang.taxi.types.StreamType import java.util.concurrent.CopyOnWriteArrayList abstract class BaseTypeCache : TypeCache { data class CachedEnumSynonymValues( val synonyms: List<TypedEnumValue> ) private val cache: MutableMap<QualifiedName, Type> = mutableMapOf() private val defaultValueCache: MutableMap<QualifiedName, Map<AttributeName, TypedInstance>?> = mutableMapOf() private val shortNames: MutableMap<String, MutableList<Type>> = mutableMapOf() private val enumSynonymValues: MutableMap<EnumValueQualifiedName, CachedEnumSynonymValues> = mutableMapOf() val types: Set<Type> get() { return this.cache.values.toSet() } // private fun populateDefaultValuesForType(type: Type) { // defaultValueCache[type.qualifiedName] = (type.taxiType as? ObjectType) // ?.fields // ?.filter { field -> field.defaultValue != null } // ?.map { field -> // Pair( // field.name, // TypedValue.from( // type = type(field.type.qualifiedName.fqn()), // value = field.defaultValue!!, // converter = ConversionService.DEFAULT_CONVERTER, source = DefinedInSchema // ) // ) // } // ?.toMap() // } /** * Adds the type to the cache, and returns a new copy, with the * type cache updated. */ override fun add(type: Type): Type { val withReference = if (type.typeCache == this) type else type.copy(typeCache = this) cache[type.name] = withReference shortNames.compute(type.name.name) { _, existingList -> if (existingList == null) { val list = CopyOnWriteArrayList<Type>() list.add(withReference) list } else { existingList.add(withReference) existingList } } // populateDefaultValuesForType(withReference) return withReference } override fun type(name: String): Type { return type(name.fqn()) } override fun type(name: QualifiedName): Type { return typeOrNull(name) ?: throw IllegalArgumentException("Type ${name.parameterizedName} was not found within this schema, and is not a valid short name") } protected open fun typeOrNull(name: QualifiedName): Type? { try { return this.cache[name] ?: fromShortName(name) ?: parameterisedType(name) } catch (e:StackOverflowError) { throw RuntimeException("Stack Overflow caused by typeOrNull for ${name.parameterizedName}", e) } } internal fun fromShortName(name: QualifiedName): Type? = this.shortNames[name.fullyQualifiedName]?.let { matchingTypes -> if (matchingTypes.size == 1) matchingTypes.first() else null } private fun parameterisedType(name: QualifiedName): Type? { if (name.parameters.isEmpty()) return null return if (hasType(name.fullyQualifiedName) && name.parameters.all { hasType(it) }) { // We've been asked for a parameterized type. // All the parameters are correctly defined, but no type exists. // This is caused by (for example), a service returning Array<Foo>, where both Array and Foo have been declared as types // but not Array<Foo> directly. // It's still valid, so we'll construct the type val baseType = type(name.fullyQualifiedName) val taxiType = when { ArrayType.isArrayTypeName(baseType.fullyQualifiedName) -> ArrayType.of(type(name.parameters[0]).taxiType) StreamType.isStream(baseType.fullyQualifiedName) -> StreamType.of(type(name.parameters[0]).taxiType) else -> // Not sure what to do here. baseType.taxiType } val parameterisedType = baseType.copy(name = name, typeParametersTypeNames = name.parameters, taxiType = taxiType) add(parameterisedType) } else { null } } override fun hasType(name: QualifiedName): Boolean { if (cache.containsKey(name)) return true if (name.parameters.isNotEmpty()) { return hasType(name.fullyQualifiedName) // this is the base type && name.parameters.all { hasType(it) } } return false } override fun defaultValues(name: QualifiedName): Map<AttributeName, TypedInstance>? { return defaultValueCache[name] } private fun getEnumSynonyms(typedEnumValue: TypedEnumValue): CachedEnumSynonymValues { return this.enumSynonymValues.getOrPut(typedEnumValue.enumValueQualifiedName) { val synonymTypedValues = typedEnumValue.enumValue.synonyms.map { synonymName -> val synonymQualifiedName = synonymName.synonymFullyQualifiedName() val synonymEnumValue = synonymName.synonymValue() val synonymEnumType = this.type(synonymQualifiedName) synonymEnumType.enumTypedInstance(synonymEnumValue, source = DefinedInSchema) }.toList() CachedEnumSynonymValues(synonymTypedValues) } } override fun enumSynonyms(typedEnumValue: TypedEnumValue): List<TypedEnumValue> { return getEnumSynonyms(typedEnumValue).synonyms } private val isAssignableWithTypeParameters = mutableMapOf<String, Boolean>() private val isAssignableWithoutTypeParameters = mutableMapOf<String, Boolean>() override fun isAssignable( typeA: Type, typeB: Type, considerTypeParameters: Boolean, func: (Type, Type, Boolean) -> Boolean ): Boolean { val key = typeA.fullyQualifiedName + "-[isAssignableTo]->" + typeB.fullyQualifiedName return if (considerTypeParameters) { isAssignableWithTypeParameters.getOrPut(key) { func(typeA, typeB, considerTypeParameters) } } else { isAssignableWithoutTypeParameters.getOrPut(key) { func(typeA, typeB, considerTypeParameters) } } } override fun hasType(name: String): Boolean { return shortNames[name]?.size == 1 || hasType(name.fqn()) } } /** * Simple TypeCache which takes a set of types. * Upon creation, the types are copied into this type cache, with their * internal typeCache property updated to this cache */ class DefaultTypeCache(types: Set<Type> = emptySet()) : BaseTypeCache() { init { timed("DefaultTypeCache initialisation") { types.forEach { add(it) } } } override fun copy(): TypeCache { return DefaultTypeCache(types.toSet()) } } /** * A type cache which can on-demand populate its values * from an underlying Taxi schema */ class TaxiTypeCache(private val taxi: TaxiDocument, private val schema: Schema) : BaseTypeCache() { init { TaxiSchema.taxiPrimitiveTypes.forEach { add(it) } taxi.types.forEach { addTaxiType(it) } } override fun copy(): TypeCache { return TaxiTypeCache(taxi, schema) } override fun hasType(name: String): Boolean { return super.hasType(name) || taxi.containsType(name) } override fun typeOrNull(name: QualifiedName): Type { val fromBaseCache = super.typeOrNull(name) if (fromBaseCache != null) { return fromBaseCache } val taxiType = taxi.type(name.parameterizedName) return addTaxiType(taxiType) } private fun addTaxiType(taxiType: lang.taxi.types.Type): Type { val type = TaxiTypeMapper.fromTaxiType(taxiType, schema, this) return add(type) } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
7,747
orbital
Apache License 2.0
platform/platform-api/src/com/intellij/openapi/wm/StartPagePromoter.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm import com.intellij.openapi.extensions.ExtensionPointName import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @ApiStatus.Internal interface StartPagePromoter { companion object { @JvmField val START_PAGE_PROMOTER_EP = ExtensionPointName<StartPagePromoter>("com.intellij.startPagePromoter") @JvmField val PRIORITY_LEVEL_NORMAL = 0 @JvmField val PRIORITY_LEVEL_HIGH = 100 } /** * On start page only one random banner with the highest priority is shown */ fun getPriorityLevel(): Int = PRIORITY_LEVEL_NORMAL /** * @param isEmptyState true if there are no recent projects */ fun canCreatePromo(isEmptyState: Boolean): Boolean = isEmptyState fun getPromotion(isEmptyState: Boolean): JComponent }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
942
intellij-community
Apache License 2.0
ulyp-ui/src/main/kotlin/com/ulyp/ui/FileRecordingsTab.kt
0xaa4eb
393,146,539
false
null
package com.ulyp.ui import com.ulyp.core.ProcessMetadata import com.ulyp.storage.Recording import com.ulyp.ui.util.FxThreadExecutor.execute import javafx.event.EventHandler import javafx.scene.control.Tab import javafx.scene.control.TabPane import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component import java.util.concurrent.ConcurrentHashMap import javax.annotation.PostConstruct @Component @Scope(scopeName = "prototype") class FileRecordingsTab internal constructor( val name: FileRecordingsTabName, private val applicationContext: ApplicationContext ) : Tab(name.toString()) { private lateinit var recordingTabs: TabPane private val tabsByRecordingId: MutableMap<Int, RecordingTab> = ConcurrentHashMap() @PostConstruct fun init() { val tabPane = TabPane() recordingTabs = tabPane content = tabPane } fun getOrCreateRecordingTab(processMetadata: ProcessMetadata, recording: Recording): RecordingTab { val id = recording.id return execute { tabsByRecordingId.computeIfAbsent(id) { recordingId: Int -> val tab = applicationContext.getBean( RecordingTab::class.java, recordingTabs, processMetadata, recording ) recordingTabs.tabs.add(tab) tab.onClosed = EventHandler { tabsByRecordingId.remove(recordingId) } tab } } } val selectedTreeTab: RecordingTab get() = recordingTabs.selectionModel.selectedItem as RecordingTab fun dispose() { for (tab in recordingTabs.tabs) { val fxRecordingTab = tab as RecordingTab fxRecordingTab.dispose() } } }
1
null
1
4
8a19f8b0efecf863693d35878d87b50e975e7af8
1,890
ulyp
Apache License 2.0
shared/src/main/java/xyz/klinker/messenger/shared/service/notification/NotificationSummaryProvider.kt
zacharee
295,825,167
false
null
package com.stream_suite.link.shared.service.notification import android.app.Notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import android.text.Html import com.stream_suite.link.shared.R import com.stream_suite.link.shared.data.Settings import com.stream_suite.link.shared.data.pojo.NotificationConversation import com.stream_suite.link.shared.service.NotificationDismissedReceiver import com.stream_suite.link.shared.util.ActivityUtils import com.stream_suite.link.shared.util.NotificationUtils /** * Displays a summary notification for all conversations using the rows returned by each * individual notification. */ class NotificationSummaryProvider(private val service: Context) { fun giveSummaryNotification(conversations: List<NotificationConversation>, rows: List<String>): Notification { val title = service.resources.getQuantityString(R.plurals.new_conversations, conversations.size, conversations.size) val summary = buildSummary(conversations) val style = buildStyle(rows) .setBigContentTitle(title) .setSummaryText(summary) val notification = buildNotification(title, summary) .setPublicVersion(buildPublicNotification(title).build()) .setWhen(conversations.first().timestamp) .setStyle(style) val built = applyPendingIntents(notification).build() NotificationManagerCompat.from(service).notify(NotificationConstants.SUMMARY_ID, built) return built } private fun buildSummary(conversations: List<NotificationConversation>): String { val summaryBuilder = StringBuilder() for (i in conversations.indices) { if (conversations[i].privateNotification) { summaryBuilder.append(service.getString(R.string.new_message)) } else { summaryBuilder.append(conversations[i].title) } summaryBuilder.append(", ") } var summary = summaryBuilder.toString() if (summary.endsWith(", ")) { summary = summary.substring(0, summary.length - 2) } return summary } private fun buildStyle(rows: List<String>): NotificationCompat.InboxStyle { val style = NotificationCompat.InboxStyle() for (row in rows) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { style.addLine(Html.fromHtml(row, 0)) } else { style.addLine(Html.fromHtml(row)) } } catch (t: Throwable) { // there was a motorola device running api 24, but was on 6.0.1? WTF? // so catch the throwable instead of checking the api version style.addLine(Html.fromHtml(row)) } } return style } private fun buildNotification(title: String, summary: String) = buildCommonNotification(title) .setContentText(summary) .setShowWhen(true) .setTicker(title) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) private fun buildPublicNotification(title: String) = buildCommonNotification(title) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) private fun buildCommonNotification(title: String) = NotificationCompat.Builder(service, NotificationUtils.DEFAULT_CONVERSATION_CHANNEL_ID) .setSmallIcon(R.drawable.ic_stat_notify_group) .setContentTitle(title) .setGroup(NotificationConstants.GROUP_KEY_MESSAGES) .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) .setGroupSummary(true) .setAutoCancel(true) .setCategory(Notification.CATEGORY_MESSAGE) .setColor(Settings.mainColorSet.color) .setPriority(if (Settings.headsUp) Notification.PRIORITY_MAX else Notification.PRIORITY_DEFAULT) private fun applyPendingIntents(builder: NotificationCompat.Builder): NotificationCompat.Builder { val delete = Intent(service, NotificationDismissedReceiver::class.java) val pendingDelete = PendingIntent.getBroadcast(service, 0, delete, PendingIntent.FLAG_UPDATE_CURRENT) val open = ActivityUtils.buildForComponent(ActivityUtils.MESSENGER_ACTIVITY) open.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val pendingOpen = PendingIntent.getActivity(service, 0, open, PendingIntent.FLAG_UPDATE_CURRENT) builder.setDeleteIntent(pendingDelete) builder.setContentIntent(pendingOpen) return builder } }
1
null
7
4
f957421823801b617194cd68e31ba31b96e6100b
5,007
pulse-sms-android
Apache License 2.0
kotlinx-coroutines-core/jvm/test/examples/test/FlowDelayTest.kt
hltj
151,721,407
false
null
// This file was automatically generated from Delay.kt by Knit tool. Do not edit. package kotlinx.coroutines.examples.test import kotlinx.coroutines.knit.* import org.junit.Test class FlowDelayTest { @Test fun testExampleDelay01() { test("ExampleDelay01") { kotlinx.coroutines.examples.exampleDelay01.main() }.verifyLines( "3, 4, 5" ) } @Test fun testExampleDelay02() { test("ExampleDelay02") { kotlinx.coroutines.examples.exampleDelay02.main() }.verifyLines( "1, 3, 4, 5" ) } @Test fun testExampleDelayDuration01() { test("ExampleDelayDuration01") { kotlinx.coroutines.examples.exampleDelayDuration01.main() }.verifyLines( "3, 4, 5" ) } @Test fun testExampleDelayDuration02() { test("ExampleDelayDuration02") { kotlinx.coroutines.examples.exampleDelayDuration02.main() }.verifyLines( "1, 3, 4, 5" ) } @Test fun testExampleDelay03() { test("ExampleDelay03") { kotlinx.coroutines.examples.exampleDelay03.main() }.verifyLines( "1, 3, 5, 7, 9" ) } @Test fun testExampleDelayDuration03() { test("ExampleDelayDuration03") { kotlinx.coroutines.examples.exampleDelayDuration03.main() }.verifyLines( "1, 3, 5, 7, 9" ) } @Test fun testExampleTimeoutDuration01() { test("ExampleTimeoutDuration01") { kotlinx.coroutines.examples.exampleTimeoutDuration01.main() }.verifyLines( "1, 2, 3, -1" ) } }
295
null
1850
255
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
1,573
kotlinx.coroutines-cn
Apache License 2.0
src/main/kotlin/no/nav/sokos/spk/mottak/domain/CommonType.kt
navikt
758,019,980
false
{"Kotlin": 204477, "Shell": 2474, "Dockerfile": 142}
package no.nav.sokos.spk.mottak.domain const val SPK = "SPK" const val NAV = "NAV" // FILETYPE const val FILETYPE_ANVISER = "ANV" // FILTILSTANDTYPE const val FILTILSTANDTYPE_AVV = "AVV" const val FILTILSTANDTYPE_GOD = "GOD" const val FILTILSTANDTYPE_INN = "INN" const val FILTILSTANDTYPE_RET = "RET" const val FILTILSTANDTYPE_KTR = "KTR" // TRANSAKSJONTYPE const val TRANSAKSJONSTATUS_OK = "00" // RECTYPE const val RECTYPE_STARTRECORD = "01" const val RECTYPE_TRANSAKSJONSRECORD = "02" const val RECTYPE_SLUTTRECORD = "09" // BEHANDLET const val BEHANDLET_NEI = "N" const val BEHANDLET_JA = "J" // BELOPTYPE const val BELOPTYPE_SKATTEPLIKTIG_UTBETALING = "01" // TRANSAKSJON TOLKNING const val TRANS_TOLKNING_NY = "NY" const val TRANS_TOLKNING_NY_EKSIST = "NY_EKSIST" // TRANSAKSJON TILSTAND STATUS const val TRANS_TILSTAND_OPR = "OPR" // TREKK ANSVAR const val TREKKANSVAR_4819 = "4819"
1
Kotlin
0
0
bda9bb90d652f62cdd4eddd5429b76d3c9f8edcf
900
sokos-spk-mottak
MIT License
c2-ssm/ssm-tx/ssm-tx-f2/src/main/kotlin/ssm/chaincode/f2/features/command/SsmTxSessionPerformActionFunctionImpl.kt
komune-io
746,795,057
false
{"Kotlin": 381968, "MDX": 96903, "Java": 39028, "Gherkin": 18221, "Makefile": 15434, "Dockerfile": 8936, "Go": 5435, "Shell": 1993, "JavaScript": 1453, "CSS": 102}
package ssm.chaincode.f2.features.command import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import ssm.chaincode.dsl.model.uri.burst import ssm.chaincode.dsl.config.InvokeChunkedProps import ssm.chaincode.dsl.config.chunk import ssm.chaincode.dsl.config.flattenConcurrently import ssm.sdk.core.SsmTxService import ssm.sdk.core.command.SsmPerformCommand import ssm.tx.dsl.features.ssm.SsmSessionPerformActionCommand import ssm.tx.dsl.features.ssm.SsmSessionPerformActionResult import ssm.tx.dsl.features.ssm.SsmTxSessionPerformActionFunction class SsmTxSessionPerformActionFunctionImpl( private val chunking: InvokeChunkedProps, private val ssmTxService: SsmTxService ) : SsmTxSessionPerformActionFunction { override suspend fun invoke( msgs: Flow<SsmSessionPerformActionCommand> ): Flow<SsmSessionPerformActionResult> = msgs.map { payload -> SsmPerformCommand( action = payload.action, context = payload.context, chaincodeUri = payload.chaincodeUri.burst(), signerName = payload.signerName ) }.chunk(chunking) { ssmTxService.sendPerform(it).map { result -> SsmSessionPerformActionResult( transactionId = result.transactionId, ) } }.flattenConcurrently() }
2
Kotlin
0
0
7c534953e0a0a8a6afbbc09f10b862444975edb0
1,218
fixers-c2
Apache License 2.0
app/src/main/java/br/com/movieapp/MainActivity.kt
renatobentorocha
523,154,607
false
null
package com.example.movieapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.example.movieapp.navigation.MovieNavigation import com.example.movieapp.ui.theme.MovieAppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApp { MovieNavigation() } } } } @Composable fun MyApp(content: @Composable () -> Unit){ MovieAppTheme { content() } } @Preview(showBackground = true) @Composable fun DefaultPreview() { MyApp { MovieNavigation() } }
0
Kotlin
0
0
ab80cafebb721028c93fc706140b95db3d55e4f4
809
android
MIT License
android/versioned-abis/expoview-abi46_0_0/src/main/java/abi46_0_0/expo/modules/kotlin/objects/PropertyComponent.kt
expo
65,750,241
false
null
package abi46_0_0.expo.modules.kotlin.objects import abi46_0_0.com.facebook.react.bridge.Arguments import abi46_0_0.expo.modules.kotlin.functions.SyncFunctionComponent import abi46_0_0.expo.modules.kotlin.jni.CppType import abi46_0_0.expo.modules.kotlin.jni.JNIFunctionBody import abi46_0_0.expo.modules.kotlin.jni.JavaScriptModuleObject class PropertyComponent( /** * Name of the property. */ val name: String, /** * Synchronous function that is called when the property is being accessed. */ val getter: SyncFunctionComponent? = null, /** * Synchronous function that is called when the property is being set. */ val setter: SyncFunctionComponent? = null ) { /** * Attaches property to the provided js object. */ fun attachToJSObject(jsObject: JavaScriptModuleObject) { val jniGetter = if (getter != null) { JNIFunctionBody { val result = getter.call(emptyArray()) return@JNIFunctionBody Arguments.fromJavaArgs(arrayOf(result)) } } else { null } val jniSetter = if (setter != null) { JNIFunctionBody { args -> setter.call(args) return@JNIFunctionBody null } } else { null } jsObject.registerProperty( name, setter?.getCppRequiredTypes()?.first() ?: CppType.NONE.value, jniGetter, jniSetter ) } }
454
null
3947
19,768
af47d96ef6e73a5bced7ec787fea430905f072d6
1,369
expo
MIT License
compose/material3/material3/src/androidMain/kotlin/androidx/compose/material3/DynamicTonalPalette.android.kt
androidx
256,589,781
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("DynamicTonalPaletteKt") package androidx.compose.material3 import android.content.Context import android.os.Build import androidx.annotation.ColorRes import androidx.annotation.DoNotInline import androidx.annotation.FloatRange import androidx.annotation.RequiresApi import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.colorspace.ColorSpaces import androidx.core.math.MathUtils import kotlin.math.pow import kotlin.math.roundToInt /** Dynamic colors in Material. */ @RequiresApi(31) internal fun dynamicTonalPalette(context: Context): TonalPalette = TonalPalette( // The neutral tonal range from the generated dynamic color palette. neutral100 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_0), neutral99 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_10), neutral98 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(98f), neutral96 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(96f), neutral95 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_50), neutral94 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(94f), neutral92 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(92f), neutral90 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_100), neutral87 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(87f), neutral80 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_200), neutral70 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_300), neutral60 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_400), neutral50 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_500), neutral40 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600), neutral30 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_700), neutral24 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(24f), neutral22 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(22f), neutral20 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_800), neutral17 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(17f), neutral12 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(12f), neutral10 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_900), neutral6 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(6f), neutral4 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_600) .setLuminance(4f), neutral0 = ColorResourceHelper.getColor(context, android.R.color.system_neutral1_1000), // The neutral variant tonal range, sometimes called "neutral 2", from the // generated dynamic color palette. neutralVariant100 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_0), neutralVariant99 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_10), neutralVariant98 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(98f), neutralVariant96 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(96f), neutralVariant95 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_50), neutralVariant94 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(94f), neutralVariant92 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(92f), neutralVariant90 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_100), neutralVariant87 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(87f), neutralVariant80 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_200), neutralVariant70 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_300), neutralVariant60 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_400), neutralVariant50 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_500), neutralVariant40 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600), neutralVariant30 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_700), neutralVariant24 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(24f), neutralVariant22 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(22f), neutralVariant20 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_800), neutralVariant17 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(17f), neutralVariant12 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(12f), neutralVariant10 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_900), neutralVariant6 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(6f), neutralVariant4 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_600) .setLuminance(4f), neutralVariant0 = ColorResourceHelper.getColor(context, android.R.color.system_neutral2_1000), // The primary tonal range from the generated dynamic color palette. primary100 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_0), primary99 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_10), primary95 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_50), primary90 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_100), primary80 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_200), primary70 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_300), primary60 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_400), primary50 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_500), primary40 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_600), primary30 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_700), primary20 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_800), primary10 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_900), primary0 = ColorResourceHelper.getColor(context, android.R.color.system_accent1_1000), // The secondary tonal range from the generated dynamic color palette. secondary100 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_0), secondary99 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_10), secondary95 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_50), secondary90 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_100), secondary80 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_200), secondary70 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_300), secondary60 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_400), secondary50 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_500), secondary40 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_600), secondary30 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_700), secondary20 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_800), secondary10 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_900), secondary0 = ColorResourceHelper.getColor(context, android.R.color.system_accent2_1000), // The tertiary tonal range from the generated dynamic color palette. tertiary100 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_0), tertiary99 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_10), tertiary95 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_50), tertiary90 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_100), tertiary80 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_200), tertiary70 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_300), tertiary60 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_400), tertiary50 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_500), tertiary40 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_600), tertiary30 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_700), tertiary20 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_800), tertiary10 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_900), tertiary0 = ColorResourceHelper.getColor(context, android.R.color.system_accent3_1000), ) /** * Creates a light dynamic color scheme. * * Use this function to create a color scheme based off the system wallpaper. If the developer * changes the wallpaper this color scheme will change accordingly. This dynamic scheme is a * light theme variant. * * @param context The context required to get system resource data. */ @RequiresApi(Build.VERSION_CODES.S) fun dynamicLightColorScheme(context: Context): ColorScheme { return if (Build.VERSION.SDK_INT >= 34) { // SDKs 34 and greater return appropriate Chroma6 values for neutral palette dynamicLightColorScheme34(context) } else { // SDKs 31-33 return Chroma4 values for neutral palette, we instead leverage neutral // variant which provides chroma8 for less grey tones. val tonalPalette = dynamicTonalPalette(context) dynamicLightColorScheme31(tonalPalette) } } /** * Creates a dark dynamic color scheme. * * Use this function to create a color scheme based off the system wallpaper. If the developer * changes the wallpaper this color scheme will change accordingly. This dynamic scheme is a dark * theme variant. * * @param context The context required to get system resource data. */ @RequiresApi(Build.VERSION_CODES.S) fun dynamicDarkColorScheme(context: Context): ColorScheme { return if (Build.VERSION.SDK_INT >= 34) { // SDKs 34 and greater return appropriate Chroma6 values for neutral palette dynamicDarkColorScheme34(context) } else { // SDKs 31-33 return Chroma4 values for neutral palette, we instead leverage neutral // variant which provides chroma8 for less grey tones. val tonalPalette = dynamicTonalPalette(context) dynamicDarkColorScheme31(tonalPalette) } } @RequiresApi(23) private object ColorResourceHelper { @DoNotInline fun getColor(context: Context, @ColorRes id: Int): Color { return Color(context.resources.getColor(id, context.theme)) } } /** * Set the luminance(tone) of this color. Chroma may decrease because chroma has a different maximum * for any given hue and luminance. * * @param newLuminance 0 <= newLuminance <= 100; invalid values are corrected. */ internal fun Color.setLuminance( @FloatRange(from = 0.0, to = 100.0) newLuminance: Float ): Color { if ((newLuminance < 0.0001) or (newLuminance > 99.9999)) { // aRGBFromLstar() from monet ColorUtil.java val y = 100 * labInvf((newLuminance + 16) / 116) val component = delinearized(y) return Color( /* red = */component, /* green = */component, /* blue = */component, ) } val sLAB = this.convert(ColorSpaces.CieLab) return Color( /* luminance = */newLuminance, /* a = */sLAB.component2(), /* b = */sLAB.component3(), colorSpace = ColorSpaces.CieLab ).convert(ColorSpaces.Srgb) } /** Helper method from monet ColorUtils.java */ private fun labInvf(ft: Float): Float { val e = 216f / 24389f val kappa = 24389f / 27f val ft3 = ft * ft * ft return if (ft3 > e) { ft3 } else { (116 * ft - 16) / kappa } } /** * Helper method from monet ColorUtils.java * * Delinearizes an RGB component. * * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel * @return 0 <= output <= 255, color channel converted to regular RGB space */ private fun delinearized(rgbComponent: Float): Int { val normalized = rgbComponent / 100 val delinearized = if (normalized <= 0.0031308) { normalized * 12.92 } else { 1.055 * normalized.toDouble().pow(1.0 / 2.4) - 0.055 } return MathUtils.clamp((delinearized * 255.0).roundToInt(), 0, 255) } @RequiresApi(31) internal fun dynamicLightColorScheme31(tonalPalette: TonalPalette) = lightColorScheme( primary = tonalPalette.primary40, onPrimary = tonalPalette.primary100, primaryContainer = tonalPalette.primary90, onPrimaryContainer = tonalPalette.primary10, inversePrimary = tonalPalette.primary80, secondary = tonalPalette.secondary40, onSecondary = tonalPalette.secondary100, secondaryContainer = tonalPalette.secondary90, onSecondaryContainer = tonalPalette.secondary10, tertiary = tonalPalette.tertiary40, onTertiary = tonalPalette.tertiary100, tertiaryContainer = tonalPalette.tertiary90, onTertiaryContainer = tonalPalette.tertiary10, background = tonalPalette.neutralVariant98, onBackground = tonalPalette.neutralVariant10, surface = tonalPalette.neutralVariant98, onSurface = tonalPalette.neutralVariant10, surfaceVariant = tonalPalette.neutralVariant90, onSurfaceVariant = tonalPalette.neutralVariant30, inverseSurface = tonalPalette.neutralVariant20, inverseOnSurface = tonalPalette.neutralVariant95, outline = tonalPalette.neutralVariant50, outlineVariant = tonalPalette.neutralVariant80, scrim = tonalPalette.neutralVariant0, surfaceBright = tonalPalette.neutralVariant98, surfaceDim = tonalPalette.neutralVariant87, surfaceContainer = tonalPalette.neutralVariant94, surfaceContainerHigh = tonalPalette.neutralVariant92, surfaceContainerHighest = tonalPalette.neutralVariant90, surfaceContainerLow = tonalPalette.neutralVariant96, surfaceContainerLowest = tonalPalette.neutralVariant100, surfaceTint = tonalPalette.primary40, ) @RequiresApi(34) internal fun dynamicLightColorScheme34(context: Context) = lightColorScheme( primary = ColorResourceHelper.getColor(context, android.R.color.system_primary_light), onPrimary = ColorResourceHelper.getColor(context, android.R.color.system_on_primary_light), primaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_primary_container_light), onPrimaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_on_primary_container_light), inversePrimary = ColorResourceHelper.getColor(context, android.R.color.system_primary_dark), secondary = ColorResourceHelper.getColor(context, android.R.color.system_secondary_light), onSecondary = ColorResourceHelper.getColor(context, android.R.color.system_on_secondary_light), secondaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_secondary_container_light), onSecondaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_on_secondary_container_light), tertiary = ColorResourceHelper.getColor(context, android.R.color.system_tertiary_light), onTertiary = ColorResourceHelper.getColor(context, android.R.color.system_on_tertiary_light), tertiaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_tertiary_container_light), onTertiaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_on_tertiary_container_light), background = ColorResourceHelper.getColor(context, android.R.color.system_background_light), onBackground = ColorResourceHelper.getColor(context, android.R.color.system_on_background_light), surface = ColorResourceHelper.getColor(context, android.R.color.system_surface_light), onSurface = ColorResourceHelper.getColor(context, android.R.color.system_on_surface_light), surfaceVariant = ColorResourceHelper.getColor(context, android.R.color.system_surface_variant_light), onSurfaceVariant = ColorResourceHelper.getColor(context, android.R.color.system_on_surface_variant_light), inverseSurface = ColorResourceHelper.getColor(context, android.R.color.system_surface_dark), inverseOnSurface = ColorResourceHelper.getColor(context, android.R.color.system_on_surface_dark), outline = ColorResourceHelper.getColor(context, android.R.color.system_outline_light), outlineVariant = ColorResourceHelper.getColor(context, android.R.color.system_outline_variant_light), // scrim surfaceBright = ColorResourceHelper.getColor(context, android.R.color.system_surface_bright_light), surfaceDim = ColorResourceHelper.getColor(context, android.R.color.system_surface_dim_light), surfaceContainer = ColorResourceHelper.getColor(context, android.R.color.system_surface_container_light), surfaceContainerHigh = ColorResourceHelper.getColor(context, android.R.color.system_surface_container_high_light), surfaceContainerHighest = ColorResourceHelper.getColor( context, android.R.color.system_surface_container_highest_light ), surfaceContainerLow = ColorResourceHelper.getColor(context, android.R.color.system_surface_container_low_light), surfaceContainerLowest = ColorResourceHelper.getColor( context, android.R.color.system_surface_container_lowest_light ), surfaceTint = ColorResourceHelper.getColor(context, android.R.color.system_primary_light), ) @RequiresApi(31) internal fun dynamicDarkColorScheme31(tonalPalette: TonalPalette) = darkColorScheme( primary = tonalPalette.primary80, onPrimary = tonalPalette.primary20, primaryContainer = tonalPalette.primary30, onPrimaryContainer = tonalPalette.primary90, inversePrimary = tonalPalette.primary40, secondary = tonalPalette.secondary80, onSecondary = tonalPalette.secondary20, secondaryContainer = tonalPalette.secondary30, onSecondaryContainer = tonalPalette.secondary90, tertiary = tonalPalette.tertiary80, onTertiary = tonalPalette.tertiary20, tertiaryContainer = tonalPalette.tertiary30, onTertiaryContainer = tonalPalette.tertiary90, background = tonalPalette.neutralVariant6, onBackground = tonalPalette.neutralVariant90, surface = tonalPalette.neutralVariant6, onSurface = tonalPalette.neutralVariant90, surfaceVariant = tonalPalette.neutralVariant30, onSurfaceVariant = tonalPalette.neutralVariant80, inverseSurface = tonalPalette.neutralVariant90, inverseOnSurface = tonalPalette.neutralVariant20, outline = tonalPalette.neutralVariant60, outlineVariant = tonalPalette.neutralVariant30, scrim = tonalPalette.neutralVariant0, surfaceBright = tonalPalette.neutralVariant24, surfaceDim = tonalPalette.neutralVariant6, surfaceContainer = tonalPalette.neutralVariant12, surfaceContainerHigh = tonalPalette.neutralVariant17, surfaceContainerHighest = tonalPalette.neutralVariant22, surfaceContainerLow = tonalPalette.neutralVariant10, surfaceContainerLowest = tonalPalette.neutralVariant4, surfaceTint = tonalPalette.primary80, ) @RequiresApi(34) internal fun dynamicDarkColorScheme34(context: Context) = darkColorScheme( primary = ColorResourceHelper.getColor(context, android.R.color.system_primary_dark), onPrimary = ColorResourceHelper.getColor(context, android.R.color.system_on_primary_dark), primaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_primary_container_dark), onPrimaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_on_primary_container_dark), inversePrimary = ColorResourceHelper.getColor(context, android.R.color.system_primary_light), secondary = ColorResourceHelper.getColor(context, android.R.color.system_secondary_dark), onSecondary = ColorResourceHelper.getColor(context, android.R.color.system_on_secondary_dark), secondaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_secondary_container_dark), onSecondaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_on_secondary_container_dark), tertiary = ColorResourceHelper.getColor(context, android.R.color.system_tertiary_dark), onTertiary = ColorResourceHelper.getColor(context, android.R.color.system_on_tertiary_dark), tertiaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_tertiary_container_dark), onTertiaryContainer = ColorResourceHelper.getColor(context, android.R.color.system_on_tertiary_container_dark), background = ColorResourceHelper.getColor(context, android.R.color.system_background_dark), onBackground = ColorResourceHelper.getColor(context, android.R.color.system_on_background_dark), surface = ColorResourceHelper.getColor(context, android.R.color.system_surface_dark), onSurface = ColorResourceHelper.getColor(context, android.R.color.system_on_surface_dark), surfaceVariant = ColorResourceHelper.getColor(context, android.R.color.system_surface_variant_dark), onSurfaceVariant = ColorResourceHelper.getColor(context, android.R.color.system_on_surface_variant_dark), inverseSurface = ColorResourceHelper.getColor(context, android.R.color.system_surface_light), inverseOnSurface = ColorResourceHelper.getColor(context, android.R.color.system_on_surface_light), outline = ColorResourceHelper.getColor(context, android.R.color.system_outline_dark), outlineVariant = ColorResourceHelper.getColor(context, android.R.color.system_outline_variant_dark), // scrim surfaceBright = ColorResourceHelper.getColor(context, android.R.color.system_surface_bright_dark), surfaceDim = ColorResourceHelper.getColor(context, android.R.color.system_surface_dim_dark), surfaceContainer = ColorResourceHelper.getColor(context, android.R.color.system_surface_container_dark), surfaceContainerHigh = ColorResourceHelper.getColor(context, android.R.color.system_surface_container_high_dark), surfaceContainerHighest = ColorResourceHelper.getColor( context, android.R.color.system_surface_container_highest_dark ), surfaceContainerLow = ColorResourceHelper.getColor(context, android.R.color.system_surface_container_low_dark), surfaceContainerLowest = ColorResourceHelper.getColor( context, android.R.color.system_surface_container_lowest_dark ), surfaceTint = ColorResourceHelper.getColor(context, android.R.color.system_primary_dark), )
30
null
950
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
24,592
androidx
Apache License 2.0