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
utilify/src/main/java/com/boryans/utilify/date/DateFormatter.kt
borYans
542,781,458
false
{"Kotlin": 25440}
package com.boryans.utilify.date import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import java.text.SimpleDateFormat import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* fun Calendar.addToCalendar(type: Int, amount: Int): Calendar { add(type, amount) return this } fun Date.formatDate(dateFormat: DateFormat): String? { kotlin.runCatching { return SimpleDateFormat(dateFormat.name, Locale.getDefault()).format(this) } return null } fun getCalendar( hourOfDay: Int, minute: Int, second: Int, year: Int, month: Int, dayOfMonth: Int, milliseconds: Int = 0, calendar: Calendar = Calendar.getInstance() ): Calendar { calendar.set(Calendar.HOUR_OF_DAY, hourOfDay) calendar.set(Calendar.MINUTE, minute) calendar.set(Calendar.SECOND, second) calendar.set(Calendar.YEAR, year) calendar.set(Calendar.MONTH, month) calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) calendar.set(Calendar.MILLISECOND, milliseconds) return calendar } fun Date.formatDate(dateFormat: DateFormat, timeZone: TimeZone): String { kotlin.runCatching { val format = SimpleDateFormat(dateFormat.name, Locale.getDefault()) format.timeZone = timeZone return format.format(this) } return "" } fun Pair<Date?,Date?>.getClosestDate(): Date? { when { first == null && second == null -> return null first != null && second == null -> first first == null && second != null -> second else -> if(first!! < second) first else second } return null } fun getTodayCalendar(): Calendar { val calendar = Calendar.getInstance() calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) return calendar } @RequiresApi(Build.VERSION_CODES.O) fun String.parseDateToLocalDate( dateFormat: DateFormat = DateFormat.FORMAT_ISO_8601_DATE, ): LocalDate { val formatter = DateTimeFormatter.ofPattern(dateFormat.name, Locale.getDefault()) return LocalDate.parse(this, formatter) } fun Date.toShortDate(timeZone: TimeZone) = this.formatDate(DateFormat.FORMAT_DD_MMM, timeZone) fun Date.toLongDate(timeZone: TimeZone) = this.formatDate(DateFormat.FORMAT_DD_MMM_YYYY, timeZone) fun Date.formatMonth(timeZone: TimeZone) = this.formatDate(DateFormat.FORMAT_DD_MM_YYYY, timeZone) fun Date.formatDisplay(context: Context): String = android.text.format.DateFormat.getDateFormat(context).format(this) private fun Date?.toCalendar(): Calendar { val calendar = Calendar.getInstance() this?.let { calendar.time = it } return calendar } fun String.parseDate( dateFormat: DateFormat = DateFormat.FORMAT_ISO_8601_DATE, timeZone: TimeZone ): Date? { kotlin.runCatching { val format = SimpleDateFormat(dateFormat.name, Locale.getDefault()).apply { this.timeZone = timeZone } return format.parse(this) } return null } fun String?.toDate(dateFormat: DateFormat): Date? { runCatching { return SimpleDateFormat(dateFormat.name, Locale.getDefault()) .parse(this.orEmpty()) } return null } private fun String.dateIsToday(): Boolean { val dateInMillis = this.toDate(DateFormat.FORMAT_ISO_8601_DATE)?.time return dateInMillis?.let { android.text.format.DateUtils.isToday(it) } ?: false } fun getCurrentYear(): String { return Calendar.getInstance().get(Calendar.YEAR).toString() } /** * Date formats. */ enum class DateFormat( private val genericFormat: String, private val fr: String = genericFormat, private val ge: String = genericFormat, private val it: String = genericFormat, private val en: String = genericFormat, ) { FORMAT_DD_MMM_YYYY("dd. MMM yyyy", "dd MMM yyyy"), FORMAT_EE_DD_MMM_YYYY("EE dd. MMM yyyy", "EE dd MMM yyyy"), FORMAT_DD_MMM("dd. MMM", "dd MMM"), FORMAT_MMMM_YYYY("MMMM yyyy"), FORMAT_MMMM("MMMM"), FORMAT_DD_MMMM_YYYY("dd MMMM yyyy"), FORMAT_ISO_8601_DATE("yyyy-MM-dd'T'HH:mm:ss'Z'"), FORMAT_ISO_8601_DATE_MILISECONDS("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'"), FORMAT_ISO_DATE("yyyy-MM-dd", "dd-MM-yyyy"), FORMAT_MM_YY("MM/yy"), FORMAT_DD_MM_YYYY("dd.MM.yyyy", "dd MM yyyy"), }
3
Kotlin
0
0
adf98ca6442bf9f3271a6ea4c31715db2322e5cb
4,166
Utilify
The Unlicense
src/main/kotlin/com/tankobon/utils/CallToFile.kt
fopwoc
445,686,330
false
null
package com.tankobon.utils import com.tankobon.api.BadRequestError import io.ktor.server.application.ApplicationCall import java.io.File fun callToFile(call: ApplicationCall, initialPath: File): File { val idTitle = call.parameters["id-title"] val idVolume = call.parameters["id-volume"] val idPage = call.parameters["id-page"] if (isValidUUID(idTitle) && isValidUUID(idVolume) && isValidUUID(idPage)) { return File( "${initialPath.path}/$idTitle/$idVolume/$idPage.jpg" ) } else { throw BadRequestError() } }
1
Kotlin
0
4
3007c8c711a3b5982b710cff58ca6923b49bead0
572
tankobon-backend-kotlin
MIT License
countrypicker/src/commonMain/kotlin/io/androidpoet/countrypicker/Country.kt
AndroidPoet
857,442,535
false
{"Kotlin": 77704}
/* * Designed and developed by 2024 androidpoet (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.androidpoet.countrypicker import kotlinx.serialization.Serializable @Serializable public data class Country( val name: String, val alpha2: String, val phoneCountryCode: String, val localeForICU: String? = null, val currencyCode: String? = null, val currencySign: String? = null, val flag: String? = null, )
1
Kotlin
1
7
4cc21b7813d501ddb5c663163fcfa8460a9b8751
950
CountryPicker
Apache License 2.0
src/main/java/com/extollit/gaming/ai/path/model/Element.kt
LeoDog896
336,321,014
true
{"Kotlin": 229776, "Java": 187571}
package com.extollit.gaming.ai.path.model import kotlin.experimental.and import kotlin.experimental.inv import kotlin.experimental.or /** * Passibility of blocks is stored in nibbles by an occlusion field. The lower two bits of this nibble indicates * the material and basic passibility of the block. This is determined from the flags on [IBlockDescription]. * * @see IBlockDescription * * @see Logic */ enum class Element { /** * Represents a passible block having no collision bounds. * A block description that is not impeding, a liquid or incinerating produces an 'air' element. * * @see IBlockDescription.impeding * @see IBlockDescription.liquid * @see IBlockDescription.incinerating */ air, /** * Represents an impassible block having at least some collision bounds. * A block description that is impeding produces an 'earth' element with the following additional conditions: * - If the block is a door, [IBlockObject.impeding] is called to determine dynamic collision bounds * from the specific block's state inside the instance. If the door is open then the element 'air' results * instead. * - Climable blocks with no collision bounds (i.e. vines and ladders) also produce an 'earth' element. This is * a special provision due to bit restrictions. This is acceptable because something that has collision bounds * cannot also be a climbable ladder or vine due to how these work in the Notchian implementation. * * @see Logic.climbable * @see IBlockObject.impeding * @see IBlockDescription.door * @see .air */ earth, /** * Represents a fluid block having no collision bounds but can potentially drown an entity or requires swimming. * This is used only for non-incinerating fluids such as water, quicksand or mud. Lava or magma is expressed * differently. * * A block description that is liquid and not incinerating produces a 'water' element. * * @see IBlockDescription.liquid * @see IBlockDescription.incinerating */ water, /** * Represents a block that can burn entities that pass through it (if they are not fire resistant). This is also * used to represent lava or magma blocks with the additional [Logic.fuzzy] flag. * * A block description that is incinerating produces a 'fire' element. * * @see IBlockDescription.incinerating * @see Logic.fuzzy */ fire; @kotlin.jvm.JvmField val mask: Byte = ordinal.toByte() /** * Helper function for determining whether this element is represented by the specified nibble. The nibble may * contain [Logic] flags in the high two bits, these will be ignored. * * @param flags A four-bit nibble containing a lower two bit element representation * * @return true if the lower two bits map to this element */ fun flagsIn(flags: Byte): Boolean = flags and MASK == mask /** * Helper function for setting the lower two bits of the specified nibble to represent this element. The nibble * may contain [Logic] flags in the high two bits, these bits will not be affected. * * @param flags A four-bit nibble that will be modified to represent this element * @return the passed-in flags modified to represent this element */ fun to(flags: Byte): Byte = flags and MASK.inv() or mask companion object { // TODO ?? figure out these magic values. const val MASK: Byte = 4 - 1 /** * Helper function for determining the element represented by the specified nibble. The nibble may contain * [Logic] flags in the high two bits, these will be ignored. * * @param flags A four-bit nibble containing a lower two bit element representation * * @return the element represented by the nibble */ fun of(flags: Byte): Element = values()[(flags and MASK).toInt()] } }
0
Kotlin
0
0
e8df64d2fee76bf70d567032871d8cd9019cfe77
4,041
hydrazine-path-finding
Apache License 2.0
src/main/kotlin/de/bybackfish/avomod/WynncraftMod.kt
byBackfish
510,866,399
false
{"Kotlin": 65429, "Java": 1232}
package de.bybackfish.avomod import de.bybackfish.avomod.commands.dev.GetItemNBTCommand import de.bybackfish.avomod.commands.dev.SetSettingCommand import de.bybackfish.avomod.commands.dev.TestCommand import de.bybackfish.avomod.commands.dev.ToggleCommand import de.bybackfish.avomod.commands.util.OnlineMembers import de.bybackfish.avomod.config.PersistantConfig import de.bybackfish.avomod.features.FeatureHandler import de.bybackfish.avomod.features.impl.test.TestFeature import de.bybackfish.avomod.util.DataContainer import de.bybackfish.wynnapi.WynnStats import net.minecraft.client.Minecraft import net.minecraft.client.gui.GuiScreen import net.minecraftforge.client.event.RenderGameOverlayEvent import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.TickEvent @Mod( modid = WynncraftMod.MOD_ID, name = WynncraftMod.MOD_NAME, version = WynncraftMod.VERSION, modLanguageAdapter = "adapter.Adapter" ) object WynncraftMod { const val MOD_ID = "wynncraftmod" const val MOD_NAME = "Wynncraft Mod" const val VERSION = "2.0.0" val featureHandler = FeatureHandler() val wynnstats: WynnStats = WynnStats() var guiToDraw: GuiScreen? = null var data: DataContainer = DataContainer() var inLocations = false; @Mod.EventHandler fun preinit(event: FMLPreInitializationEvent) { print("[AvoMod] Loaded") featureHandler.addFeature(TestFeature()) GetItemNBTCommand() ToggleCommand() SetSettingCommand() TestCommand() OnlineMembers(); val config = PersistantConfig("avomod.json") config.load() Runtime.getRuntime().addShutdownHook(Thread(config::save)) MinecraftForge.EVENT_BUS.register(this) MinecraftForge.EVENT_BUS.register(de.bybackfish.avomod.listener.GuiScreenEvent()) } @SubscribeEvent fun onRender(_event: TickEvent.RenderTickEvent) { if (guiToDraw != null) { Minecraft.getMinecraft().displayGuiScreen(guiToDraw) guiToDraw = null } } @SubscribeEvent fun onRenderChat(_event: RenderGameOverlayEvent.Chat) { if (inLocations) return; featureHandler.getFeatures().filter { it.value.enabled }.forEach { feature -> if (feature.value.feature.isDrawing) feature.value.instance.render(feature.value.locationData.x, feature.value.locationData.y) } } }
0
Kotlin
0
0
d82639e486fc5d892890038f0c41b15a8854ce7b
2,656
AvoMod-Recode
MIT License
basic/src/main/java/com/mozhimen/composek/basic/runtime/external/kotlinx/collections/immutable/implementations/immutableList/TrieIterator.kt
mozhimen
695,569,271
false
{"Kotlin": 864315, "Java": 1272}
package com.mozhimen.composek.basic.runtime.external.kotlinx.collections.immutable.implementations.immutableList /** * @ClassName TrieIterator * @Description TODO * @Author Mozhimen / <NAME> * @Date 2024/10/20 0:05 * @Version 1.0 */ internal class TrieIterator<out E>(root: Array<Any?>, index: Int, size: Int, private var height: Int) : AbstractListIterator<E>(index, size) { private var path: Array<Any?> = arrayOfNulls<Any?>(height) private var isInRightEdge = index == size init { path[0] = root fillPath(index - if (isInRightEdge) 1 else 0, 1) } internal fun reset(root: Array<Any?>, index: Int, size: Int, height: Int) { this.index = index this.size = size this.height = height if (path.size < height) path = arrayOfNulls(height) path[0] = root isInRightEdge = index == size fillPath(index - if (isInRightEdge) 1 else 0, 1) } private fun fillPath(index: Int, startLevel: Int) { var shift = (height - startLevel) * LOG_MAX_BUFFER_SIZE var i = startLevel while (i < height) { @Suppress("UNCHECKED_CAST") path[i] = (path[i - 1] as Array<Any?>)[indexSegment(index, shift)] shift -= LOG_MAX_BUFFER_SIZE i += 1 } } // TODO: Document that it positions path to the first or the last element private fun fillPathIfNeeded(indexPredicate: Int) { var shift = 0 while (indexSegment(index, shift) == indexPredicate) { shift += LOG_MAX_BUFFER_SIZE } if (shift > 0) { val level = height - 1 - shift / LOG_MAX_BUFFER_SIZE fillPath(index, level + 1) } } private fun elementAtCurrentIndex(): E { val leafBufferIndex = index and MAX_BUFFER_SIZE_MINUS_ONE @Suppress("UNCHECKED_CAST") return (path[height - 1] as Array<E>)[leafBufferIndex] } override fun next(): E { if (!hasNext()) { throw NoSuchElementException() } val result = elementAtCurrentIndex() index += 1 if (index == size) { isInRightEdge = true return result } fillPathIfNeeded(0) return result } override fun previous(): E { if (!hasPrevious()) { throw NoSuchElementException() } index -= 1 if (isInRightEdge) { isInRightEdge = false return elementAtCurrentIndex() } fillPathIfNeeded(MAX_BUFFER_SIZE_MINUS_ONE) return elementAtCurrentIndex() } }
0
Kotlin
0
0
a7c6d1e306638af40f41c2b89958c7335ebe8806
2,734
AComposeKit
Apache License 2.0
app/src/main/java/uk/ac/warwick/postroom/services/ItemService.kt
UniversityofWarwick
242,980,422
false
null
package uk.ac.warwick.postroom.services import android.graphics.Bitmap import com.github.kittinunf.fuel.core.FuelError import com.github.kittinunf.result.Result import uk.ac.warwick.postroom.domain.ItemResult import uk.ac.warwick.postroom.domain.MiniRecipient import uk.ac.warwick.postroom.vm.AddItemViewModel import java.io.ByteArrayOutputStream import java.util.* interface ItemService { suspend fun uploadImageForItem(id: UUID, image: Bitmap) suspend fun addItem(model: AddItemViewModel): Result<ItemResult, FuelError> }
0
Kotlin
0
1
fa0be72f7a727fa4abaa0502f2add6313b1dd916
533
postroom-android
ISC License
crowdin/src/main/java/com/crowdin/platform/CrowdinPreferences.kt
crowdin
193,449,073
false
{"Kotlin": 447819, "MDX": 27738, "Java": 4715, "JavaScript": 3829, "CSS": 1107}
package com.crowdin.platform import android.content.Context import android.content.SharedPreferences import android.util.Log import androidx.core.content.edit import com.google.gson.Gson import java.lang.reflect.Type private const val SHARED_PREF_NAME = "com.crowdin.platform.string.preferences" private const val LAST_UPDATE = "com.crowdin.platform.string.preferences.last_update" internal class CrowdinPreferences(context: Context) : Preferences { private lateinit var sharedPreferences: SharedPreferences init { initSharedPreferences(context) } private fun initSharedPreferences(context: Context) { sharedPreferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE) } override fun setString(key: String, value: String) { sharedPreferences.edit().putString(key, value).apply() } override fun getString(key: String): String? = sharedPreferences.getString(key, "") override fun setLastUpdate(lastUpdate: Long) { sharedPreferences.edit { putLong(LAST_UPDATE, lastUpdate) } } override fun getLastUpdate(): Long = sharedPreferences.getLong(LAST_UPDATE, 0) override fun saveData(type: String, data: Any?) { try { if (data == null) { sharedPreferences.edit().remove(type).apply() } val json = Gson().toJson(data) sharedPreferences.edit().putString(type, json).apply() } catch (ex: Exception) { Log.d(CrowdinPreferences::class.java.simpleName, ex.message ?: "Error saving data") } } override fun <T> getData(type: String, classType: Type): T? { val json = sharedPreferences.getString(type, null) json?.let { return Gson().fromJson(json, classType) } return null } } internal interface Preferences { fun setString(key: String, value: String) fun getString(key: String): String? fun setLastUpdate(lastUpdate: Long) fun getLastUpdate(): Long fun saveData(type: String, data: Any?) fun <T> getData(type: String, classType: Type): T? }
5
Kotlin
38
104
5580be6d9c4b844094b8869ac6fb4e0921e14a98
2,124
mobile-sdk-android
MIT License
crowdin/src/main/java/com/crowdin/platform/CrowdinPreferences.kt
crowdin
193,449,073
false
{"Kotlin": 447819, "MDX": 27738, "Java": 4715, "JavaScript": 3829, "CSS": 1107}
package com.crowdin.platform import android.content.Context import android.content.SharedPreferences import android.util.Log import androidx.core.content.edit import com.google.gson.Gson import java.lang.reflect.Type private const val SHARED_PREF_NAME = "com.crowdin.platform.string.preferences" private const val LAST_UPDATE = "com.crowdin.platform.string.preferences.last_update" internal class CrowdinPreferences(context: Context) : Preferences { private lateinit var sharedPreferences: SharedPreferences init { initSharedPreferences(context) } private fun initSharedPreferences(context: Context) { sharedPreferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE) } override fun setString(key: String, value: String) { sharedPreferences.edit().putString(key, value).apply() } override fun getString(key: String): String? = sharedPreferences.getString(key, "") override fun setLastUpdate(lastUpdate: Long) { sharedPreferences.edit { putLong(LAST_UPDATE, lastUpdate) } } override fun getLastUpdate(): Long = sharedPreferences.getLong(LAST_UPDATE, 0) override fun saveData(type: String, data: Any?) { try { if (data == null) { sharedPreferences.edit().remove(type).apply() } val json = Gson().toJson(data) sharedPreferences.edit().putString(type, json).apply() } catch (ex: Exception) { Log.d(CrowdinPreferences::class.java.simpleName, ex.message ?: "Error saving data") } } override fun <T> getData(type: String, classType: Type): T? { val json = sharedPreferences.getString(type, null) json?.let { return Gson().fromJson(json, classType) } return null } } internal interface Preferences { fun setString(key: String, value: String) fun getString(key: String): String? fun setLastUpdate(lastUpdate: Long) fun getLastUpdate(): Long fun saveData(type: String, data: Any?) fun <T> getData(type: String, classType: Type): T? }
5
Kotlin
38
104
5580be6d9c4b844094b8869ac6fb4e0921e14a98
2,124
mobile-sdk-android
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/PesetaSign.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.PesetaSign: ImageVector get() { if (_pesetaSign != null) { return _pesetaSign!! } _pesetaSign = Builder(name = "PesetaSign", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(22.5f, 7.5f) horizontalLineToRelative(-1.63f) curveTo(20.16f, 3.25f, 16.45f, 0.0f, 12.0f, 0.0f) horizontalLineToRelative(-3.5f) curveTo(5.47f, 0.0f, 3.0f, 2.47f, 3.0f, 5.5f) verticalLineToRelative(2.0f) lineTo(1.5f, 7.5f) curveToRelative(-0.83f, 0.0f, -1.5f, 0.67f, -1.5f, 1.5f) reflectiveCurveToRelative(0.67f, 1.5f, 1.5f, 1.5f) horizontalLineToRelative(1.5f) verticalLineToRelative(12.0f) curveToRelative(0.0f, 0.83f, 0.67f, 1.5f, 1.5f, 1.5f) reflectiveCurveToRelative(1.5f, -0.67f, 1.5f, -1.5f) verticalLineToRelative(-4.5f) horizontalLineToRelative(6.0f) curveToRelative(4.45f, 0.0f, 8.16f, -3.25f, 8.87f, -7.5f) horizontalLineToRelative(1.63f) curveToRelative(0.83f, 0.0f, 1.5f, -0.67f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.67f, -1.5f, -1.5f, -1.5f) close() moveTo(6.0f, 5.5f) curveToRelative(0.0f, -1.38f, 1.12f, -2.5f, 2.5f, -2.5f) horizontalLineToRelative(3.5f) curveToRelative(2.79f, 0.0f, 5.14f, 1.91f, 5.81f, 4.5f) lineTo(6.0f, 7.5f) verticalLineToRelative(-2.0f) close() moveTo(12.0f, 15.0f) lineTo(6.0f, 15.0f) verticalLineToRelative(-4.5f) horizontalLineToRelative(11.81f) curveToRelative(-0.67f, 2.59f, -3.02f, 4.5f, -5.81f, 4.5f) close() } } .build() return _pesetaSign!! } private var _pesetaSign: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,912
icons
MIT License
common/src/main/java/com/ably/tracking/common/AblyModels.kt
ably
313,556,297
false
null
package com.ably.tracking.common import com.ably.tracking.Resolution data class PresenceMessage(val action: PresenceAction, val data: PresenceData, val clientId: String) enum class PresenceAction { PRESENT_OR_ENTER, LEAVE_OR_ABSENT, UPDATE; } data class PresenceData(val type: String, val resolution: Resolution? = null, val rawLocations: Boolean? = null)
83
Kotlin
2
4
e30dc588ca13e8b4ceed2af79d833350ba423667
364
ably-asset-tracking-android
Apache License 2.0
api/src/main/kotlin/nebulosa/api/alignment/polar/darv/DARVPolarAlignmentEvent.kt
tiagohm
568,578,345
false
{"Kotlin": 1894356, "TypeScript": 276399, "HTML": 135660, "SCSS": 7279, "JavaScript": 1164}
package nebulosa.api.alignment.polar.darv import nebulosa.api.sequencer.SequenceJobEvent import nebulosa.indi.device.camera.Camera import nebulosa.indi.device.guide.GuideOutput sealed interface DARVPolarAlignmentEvent : SequenceJobEvent { val camera: Camera val guideOutput: GuideOutput val state: DARVPolarAlignmentState }
1
Kotlin
0
1
31e59b5215fc54a9330357cd7ae0733ab94ec2fb
341
nebulosa
MIT License
src/main/kotlin/Comachine.kt
teneko
674,096,200
true
{"Kotlin": 96417}
package de.halfbit.comachine import de.halfbit.comachine.dsl.ComachineBlock import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import kotlin.reflect.KClass fun <State : Any, Event : Any> Comachine( initialState: State, stateTransitionAllowlist: Map<KClass<out State>, Set<KClass<out State>>>? = null, block: ComachineBlock<State, Event>.() -> Unit ): Comachine<State, Event> = ComachineBlock<State, Event>(initialState).also(block).buildComachine(stateTransitionAllowlist) /** * Launches the machine in the given scope and suspends until the initial state is * emitted. The machine is fully prepared and usable after this method exists. * * @return the coroutine job, in which the machine processes the events. */ suspend fun Comachine<*, *>.launchIn(scope: CoroutineScope): Job { val whenStarted = CompletableDeferred<Unit>() val job = scope.launch { loop { whenStarted.complete(Unit) } } whenStarted.await() return job } context(CoroutineScope) suspend fun Comachine<*, *>.launch(): Job = launchIn(this@CoroutineScope) interface Comachine<State : Any, Event : Any> { val state: Flow<State> suspend fun send(event: Event) suspend fun loop(whenStarted: (() -> Unit)? = null) }
0
Kotlin
0
0
7aa8fde20045dcd6594bd379a76e57d44b770f4d
1,370
comachine
Apache License 2.0
packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidMapper.kt
breez
756,472,870
false
{"Rust": 1086459, "Dart": 828821, "Swift": 189485, "Kotlin": 133118, "C": 52134, "C++": 28861, "CMake": 23355, "TypeScript": 22683, "Java": 15818, "Makefile": 10685, "Ruby": 8199, "Objective-C": 7187, "Shell": 4502, "Objective-C++": 4456, "Just": 3453, "Python": 1614, "JavaScript": 1118, "HTML": 985, "Starlark": 602}
package com.breezsdkliquid import breez_sdk_liquid.* import com.facebook.react.bridge.* import java.util.* fun asAesSuccessActionDataDecrypted(aesSuccessActionDataDecrypted: ReadableMap): AesSuccessActionDataDecrypted? { if (!validateMandatoryFields( aesSuccessActionDataDecrypted, arrayOf( "description", "plaintext", ), ) ) { return null } val description = aesSuccessActionDataDecrypted.getString("description")!! val plaintext = aesSuccessActionDataDecrypted.getString("plaintext")!! return AesSuccessActionDataDecrypted( description, plaintext, ) } fun readableMapOf(aesSuccessActionDataDecrypted: AesSuccessActionDataDecrypted): ReadableMap = readableMapOf( "description" to aesSuccessActionDataDecrypted.description, "plaintext" to aesSuccessActionDataDecrypted.plaintext, ) fun asAesSuccessActionDataDecryptedList(arr: ReadableArray): List<AesSuccessActionDataDecrypted> { val list = ArrayList<AesSuccessActionDataDecrypted>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asAesSuccessActionDataDecrypted(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asBackupRequest(backupRequest: ReadableMap): BackupRequest? { if (!validateMandatoryFields( backupRequest, arrayOf(), ) ) { return null } val backupPath = if (hasNonNullKey(backupRequest, "backupPath")) backupRequest.getString("backupPath") else null return BackupRequest( backupPath, ) } fun readableMapOf(backupRequest: BackupRequest): ReadableMap = readableMapOf( "backupPath" to backupRequest.backupPath, ) fun asBackupRequestList(arr: ReadableArray): List<BackupRequest> { val list = ArrayList<BackupRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asBackupRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asBitcoinAddressData(bitcoinAddressData: ReadableMap): BitcoinAddressData? { if (!validateMandatoryFields( bitcoinAddressData, arrayOf( "address", "network", ), ) ) { return null } val address = bitcoinAddressData.getString("address")!! val network = bitcoinAddressData.getString("network")?.let { asNetwork(it) }!! val amountSat = if (hasNonNullKey(bitcoinAddressData, "amountSat")) bitcoinAddressData.getDouble("amountSat").toULong() else null val label = if (hasNonNullKey(bitcoinAddressData, "label")) bitcoinAddressData.getString("label") else null val message = if (hasNonNullKey(bitcoinAddressData, "message")) bitcoinAddressData.getString("message") else null return BitcoinAddressData( address, network, amountSat, label, message, ) } fun readableMapOf(bitcoinAddressData: BitcoinAddressData): ReadableMap = readableMapOf( "address" to bitcoinAddressData.address, "network" to bitcoinAddressData.network.name.lowercase(), "amountSat" to bitcoinAddressData.amountSat, "label" to bitcoinAddressData.label, "message" to bitcoinAddressData.message, ) fun asBitcoinAddressDataList(arr: ReadableArray): List<BitcoinAddressData> { val list = ArrayList<BitcoinAddressData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asBitcoinAddressData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asBuyBitcoinRequest(buyBitcoinRequest: ReadableMap): BuyBitcoinRequest? { if (!validateMandatoryFields( buyBitcoinRequest, arrayOf( "prepareRes", ), ) ) { return null } val prepareRes = buyBitcoinRequest.getMap("prepareRes")?.let { asPrepareBuyBitcoinResponse(it) }!! val redirectUrl = if (hasNonNullKey(buyBitcoinRequest, "redirectUrl")) buyBitcoinRequest.getString("redirectUrl") else null return BuyBitcoinRequest( prepareRes, redirectUrl, ) } fun readableMapOf(buyBitcoinRequest: BuyBitcoinRequest): ReadableMap = readableMapOf( "prepareRes" to readableMapOf(buyBitcoinRequest.prepareRes), "redirectUrl" to buyBitcoinRequest.redirectUrl, ) fun asBuyBitcoinRequestList(arr: ReadableArray): List<BuyBitcoinRequest> { val list = ArrayList<BuyBitcoinRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asBuyBitcoinRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asConfig(config: ReadableMap): Config? { if (!validateMandatoryFields( config, arrayOf( "liquidElectrumUrl", "bitcoinElectrumUrl", "mempoolspaceUrl", "workingDir", "network", "paymentTimeoutSec", "zeroConfMinFeeRateMsat", ), ) ) { return null } val liquidElectrumUrl = config.getString("liquidElectrumUrl")!! val bitcoinElectrumUrl = config.getString("bitcoinElectrumUrl")!! val mempoolspaceUrl = config.getString("mempoolspaceUrl")!! val workingDir = config.getString("workingDir")!! val network = config.getString("network")?.let { asLiquidNetwork(it) }!! val paymentTimeoutSec = config.getDouble("paymentTimeoutSec").toULong() val zeroConfMinFeeRateMsat = config.getInt("zeroConfMinFeeRateMsat").toUInt() val zeroConfMaxAmountSat = if (hasNonNullKey( config, "zeroConfMaxAmountSat", ) ) { config.getDouble("zeroConfMaxAmountSat").toULong() } else { null } return Config( liquidElectrumUrl, bitcoinElectrumUrl, mempoolspaceUrl, workingDir, network, paymentTimeoutSec, zeroConfMinFeeRateMsat, zeroConfMaxAmountSat, ) } fun readableMapOf(config: Config): ReadableMap = readableMapOf( "liquidElectrumUrl" to config.liquidElectrumUrl, "bitcoinElectrumUrl" to config.bitcoinElectrumUrl, "mempoolspaceUrl" to config.mempoolspaceUrl, "workingDir" to config.workingDir, "network" to config.network.name.lowercase(), "paymentTimeoutSec" to config.paymentTimeoutSec, "zeroConfMinFeeRateMsat" to config.zeroConfMinFeeRateMsat, "zeroConfMaxAmountSat" to config.zeroConfMaxAmountSat, ) fun asConfigList(arr: ReadableArray): List<Config> { val list = ArrayList<Config>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asConfig(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asConnectRequest(connectRequest: ReadableMap): ConnectRequest? { if (!validateMandatoryFields( connectRequest, arrayOf( "config", "mnemonic", ), ) ) { return null } val config = connectRequest.getMap("config")?.let { asConfig(it) }!! val mnemonic = connectRequest.getString("mnemonic")!! return ConnectRequest( config, mnemonic, ) } fun readableMapOf(connectRequest: ConnectRequest): ReadableMap = readableMapOf( "config" to readableMapOf(connectRequest.config), "mnemonic" to connectRequest.mnemonic, ) fun asConnectRequestList(arr: ReadableArray): List<ConnectRequest> { val list = ArrayList<ConnectRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asConnectRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asCurrencyInfo(currencyInfo: ReadableMap): CurrencyInfo? { if (!validateMandatoryFields( currencyInfo, arrayOf( "name", "fractionSize", "localizedName", "localeOverrides", ), ) ) { return null } val name = currencyInfo.getString("name")!! val fractionSize = currencyInfo.getInt("fractionSize").toUInt() val spacing = if (hasNonNullKey(currencyInfo, "spacing")) currencyInfo.getInt("spacing").toUInt() else null val symbol = if (hasNonNullKey(currencyInfo, "symbol")) currencyInfo.getMap("symbol")?.let { asSymbol(it) } else null val uniqSymbol = if (hasNonNullKey(currencyInfo, "uniqSymbol")) currencyInfo.getMap("uniqSymbol")?.let { asSymbol(it) } else null val localizedName = currencyInfo.getArray("localizedName")?.let { asLocalizedNameList(it) }!! val localeOverrides = currencyInfo.getArray("localeOverrides")?.let { asLocaleOverridesList(it) }!! return CurrencyInfo( name, fractionSize, spacing, symbol, uniqSymbol, localizedName, localeOverrides, ) } fun readableMapOf(currencyInfo: CurrencyInfo): ReadableMap = readableMapOf( "name" to currencyInfo.name, "fractionSize" to currencyInfo.fractionSize, "spacing" to currencyInfo.spacing, "symbol" to currencyInfo.symbol?.let { readableMapOf(it) }, "uniqSymbol" to currencyInfo.uniqSymbol?.let { readableMapOf(it) }, "localizedName" to readableArrayOf(currencyInfo.localizedName), "localeOverrides" to readableArrayOf(currencyInfo.localeOverrides), ) fun asCurrencyInfoList(arr: ReadableArray): List<CurrencyInfo> { val list = ArrayList<CurrencyInfo>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asCurrencyInfo(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asFiatCurrency(fiatCurrency: ReadableMap): FiatCurrency? { if (!validateMandatoryFields( fiatCurrency, arrayOf( "id", "info", ), ) ) { return null } val id = fiatCurrency.getString("id")!! val info = fiatCurrency.getMap("info")?.let { asCurrencyInfo(it) }!! return FiatCurrency( id, info, ) } fun readableMapOf(fiatCurrency: FiatCurrency): ReadableMap = readableMapOf( "id" to fiatCurrency.id, "info" to readableMapOf(fiatCurrency.info), ) fun asFiatCurrencyList(arr: ReadableArray): List<FiatCurrency> { val list = ArrayList<FiatCurrency>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asFiatCurrency(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asGetInfoResponse(getInfoResponse: ReadableMap): GetInfoResponse? { if (!validateMandatoryFields( getInfoResponse, arrayOf( "balanceSat", "pendingSendSat", "pendingReceiveSat", "pubkey", ), ) ) { return null } val balanceSat = getInfoResponse.getDouble("balanceSat").toULong() val pendingSendSat = getInfoResponse.getDouble("pendingSendSat").toULong() val pendingReceiveSat = getInfoResponse.getDouble("pendingReceiveSat").toULong() val pubkey = getInfoResponse.getString("pubkey")!! return GetInfoResponse( balanceSat, pendingSendSat, pendingReceiveSat, pubkey, ) } fun readableMapOf(getInfoResponse: GetInfoResponse): ReadableMap = readableMapOf( "balanceSat" to getInfoResponse.balanceSat, "pendingSendSat" to getInfoResponse.pendingSendSat, "pendingReceiveSat" to getInfoResponse.pendingReceiveSat, "pubkey" to getInfoResponse.pubkey, ) fun asGetInfoResponseList(arr: ReadableArray): List<GetInfoResponse> { val list = ArrayList<GetInfoResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asGetInfoResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnInvoice(lnInvoice: ReadableMap): LnInvoice? { if (!validateMandatoryFields( lnInvoice, arrayOf( "bolt11", "network", "payeePubkey", "paymentHash", "timestamp", "expiry", "routingHints", "paymentSecret", "minFinalCltvExpiryDelta", ), ) ) { return null } val bolt11 = lnInvoice.getString("bolt11")!! val network = lnInvoice.getString("network")?.let { asNetwork(it) }!! val payeePubkey = lnInvoice.getString("payeePubkey")!! val paymentHash = lnInvoice.getString("paymentHash")!! val description = if (hasNonNullKey(lnInvoice, "description")) lnInvoice.getString("description") else null val descriptionHash = if (hasNonNullKey(lnInvoice, "descriptionHash")) lnInvoice.getString("descriptionHash") else null val amountMsat = if (hasNonNullKey(lnInvoice, "amountMsat")) lnInvoice.getDouble("amountMsat").toULong() else null val timestamp = lnInvoice.getDouble("timestamp").toULong() val expiry = lnInvoice.getDouble("expiry").toULong() val routingHints = lnInvoice.getArray("routingHints")?.let { asRouteHintList(it) }!! val paymentSecret = lnInvoice.getArray("paymentSecret")?.let { asUByteList(it) }!! val minFinalCltvExpiryDelta = lnInvoice.getDouble("minFinalCltvExpiryDelta").toULong() return LnInvoice( bolt11, network, payeePubkey, paymentHash, description, descriptionHash, amountMsat, timestamp, expiry, routingHints, paymentSecret, minFinalCltvExpiryDelta, ) } fun readableMapOf(lnInvoice: LnInvoice): ReadableMap = readableMapOf( "bolt11" to lnInvoice.bolt11, "network" to lnInvoice.network.name.lowercase(), "payeePubkey" to lnInvoice.payeePubkey, "paymentHash" to lnInvoice.paymentHash, "description" to lnInvoice.description, "descriptionHash" to lnInvoice.descriptionHash, "amountMsat" to lnInvoice.amountMsat, "timestamp" to lnInvoice.timestamp, "expiry" to lnInvoice.expiry, "routingHints" to readableArrayOf(lnInvoice.routingHints), "paymentSecret" to readableArrayOf(lnInvoice.paymentSecret), "minFinalCltvExpiryDelta" to lnInvoice.minFinalCltvExpiryDelta, ) fun asLnInvoiceList(arr: ReadableArray): List<LnInvoice> { val list = ArrayList<LnInvoice>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnInvoice(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLightningPaymentLimitsResponse(lightningPaymentLimitsResponse: ReadableMap): LightningPaymentLimitsResponse? { if (!validateMandatoryFields( lightningPaymentLimitsResponse, arrayOf( "send", "receive", ), ) ) { return null } val send = lightningPaymentLimitsResponse.getMap("send")?.let { asLimits(it) }!! val receive = lightningPaymentLimitsResponse.getMap("receive")?.let { asLimits(it) }!! return LightningPaymentLimitsResponse( send, receive, ) } fun readableMapOf(lightningPaymentLimitsResponse: LightningPaymentLimitsResponse): ReadableMap = readableMapOf( "send" to readableMapOf(lightningPaymentLimitsResponse.send), "receive" to readableMapOf(lightningPaymentLimitsResponse.receive), ) fun asLightningPaymentLimitsResponseList(arr: ReadableArray): List<LightningPaymentLimitsResponse> { val list = ArrayList<LightningPaymentLimitsResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLightningPaymentLimitsResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLimits(limits: ReadableMap): Limits? { if (!validateMandatoryFields( limits, arrayOf( "minSat", "maxSat", "maxZeroConfSat", ), ) ) { return null } val minSat = limits.getDouble("minSat").toULong() val maxSat = limits.getDouble("maxSat").toULong() val maxZeroConfSat = limits.getDouble("maxZeroConfSat").toULong() return Limits( minSat, maxSat, maxZeroConfSat, ) } fun readableMapOf(limits: Limits): ReadableMap = readableMapOf( "minSat" to limits.minSat, "maxSat" to limits.maxSat, "maxZeroConfSat" to limits.maxZeroConfSat, ) fun asLimitsList(arr: ReadableArray): List<Limits> { val list = ArrayList<Limits>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLimits(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asListPaymentsRequest(listPaymentsRequest: ReadableMap): ListPaymentsRequest? { if (!validateMandatoryFields( listPaymentsRequest, arrayOf(), ) ) { return null } val filters = if (hasNonNullKey(listPaymentsRequest, "filters")) { listPaymentsRequest.getArray("filters")?.let { asPaymentTypeList(it) } } else { null } val fromTimestamp = if (hasNonNullKey( listPaymentsRequest, "fromTimestamp", ) ) { listPaymentsRequest.getDouble("fromTimestamp").toLong() } else { null } val toTimestamp = if (hasNonNullKey(listPaymentsRequest, "toTimestamp")) listPaymentsRequest.getDouble("toTimestamp").toLong() else null val offset = if (hasNonNullKey(listPaymentsRequest, "offset")) listPaymentsRequest.getInt("offset").toUInt() else null val limit = if (hasNonNullKey(listPaymentsRequest, "limit")) listPaymentsRequest.getInt("limit").toUInt() else null return ListPaymentsRequest( filters, fromTimestamp, toTimestamp, offset, limit, ) } fun readableMapOf(listPaymentsRequest: ListPaymentsRequest): ReadableMap = readableMapOf( "filters" to listPaymentsRequest.filters?.let { readableArrayOf(it) }, "fromTimestamp" to listPaymentsRequest.fromTimestamp, "toTimestamp" to listPaymentsRequest.toTimestamp, "offset" to listPaymentsRequest.offset, "limit" to listPaymentsRequest.limit, ) fun asListPaymentsRequestList(arr: ReadableArray): List<ListPaymentsRequest> { val list = ArrayList<ListPaymentsRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asListPaymentsRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlAuthRequestData(lnUrlAuthRequestData: ReadableMap): LnUrlAuthRequestData? { if (!validateMandatoryFields( lnUrlAuthRequestData, arrayOf( "k1", "domain", "url", ), ) ) { return null } val k1 = lnUrlAuthRequestData.getString("k1")!! val domain = lnUrlAuthRequestData.getString("domain")!! val url = lnUrlAuthRequestData.getString("url")!! val action = if (hasNonNullKey(lnUrlAuthRequestData, "action")) lnUrlAuthRequestData.getString("action") else null return LnUrlAuthRequestData( k1, domain, url, action, ) } fun readableMapOf(lnUrlAuthRequestData: LnUrlAuthRequestData): ReadableMap = readableMapOf( "k1" to lnUrlAuthRequestData.k1, "domain" to lnUrlAuthRequestData.domain, "url" to lnUrlAuthRequestData.url, "action" to lnUrlAuthRequestData.action, ) fun asLnUrlAuthRequestDataList(arr: ReadableArray): List<LnUrlAuthRequestData> { val list = ArrayList<LnUrlAuthRequestData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlAuthRequestData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlErrorData(lnUrlErrorData: ReadableMap): LnUrlErrorData? { if (!validateMandatoryFields( lnUrlErrorData, arrayOf( "reason", ), ) ) { return null } val reason = lnUrlErrorData.getString("reason")!! return LnUrlErrorData( reason, ) } fun readableMapOf(lnUrlErrorData: LnUrlErrorData): ReadableMap = readableMapOf( "reason" to lnUrlErrorData.reason, ) fun asLnUrlErrorDataList(arr: ReadableArray): List<LnUrlErrorData> { val list = ArrayList<LnUrlErrorData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlErrorData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlPayErrorData(lnUrlPayErrorData: ReadableMap): LnUrlPayErrorData? { if (!validateMandatoryFields( lnUrlPayErrorData, arrayOf( "paymentHash", "reason", ), ) ) { return null } val paymentHash = lnUrlPayErrorData.getString("paymentHash")!! val reason = lnUrlPayErrorData.getString("reason")!! return LnUrlPayErrorData( paymentHash, reason, ) } fun readableMapOf(lnUrlPayErrorData: LnUrlPayErrorData): ReadableMap = readableMapOf( "paymentHash" to lnUrlPayErrorData.paymentHash, "reason" to lnUrlPayErrorData.reason, ) fun asLnUrlPayErrorDataList(arr: ReadableArray): List<LnUrlPayErrorData> { val list = ArrayList<LnUrlPayErrorData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlPayErrorData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlPayRequest(lnUrlPayRequest: ReadableMap): LnUrlPayRequest? { if (!validateMandatoryFields( lnUrlPayRequest, arrayOf( "data", "amountMsat", ), ) ) { return null } val data = lnUrlPayRequest.getMap("data")?.let { asLnUrlPayRequestData(it) }!! val amountMsat = lnUrlPayRequest.getDouble("amountMsat").toULong() val comment = if (hasNonNullKey(lnUrlPayRequest, "comment")) lnUrlPayRequest.getString("comment") else null val paymentLabel = if (hasNonNullKey(lnUrlPayRequest, "paymentLabel")) lnUrlPayRequest.getString("paymentLabel") else null val validateSuccessActionUrl = if (hasNonNullKey( lnUrlPayRequest, "validateSuccessActionUrl", ) ) { lnUrlPayRequest.getBoolean("validateSuccessActionUrl") } else { null } return LnUrlPayRequest( data, amountMsat, comment, paymentLabel, validateSuccessActionUrl, ) } fun readableMapOf(lnUrlPayRequest: LnUrlPayRequest): ReadableMap = readableMapOf( "data" to readableMapOf(lnUrlPayRequest.data), "amountMsat" to lnUrlPayRequest.amountMsat, "comment" to lnUrlPayRequest.comment, "paymentLabel" to lnUrlPayRequest.paymentLabel, "validateSuccessActionUrl" to lnUrlPayRequest.validateSuccessActionUrl, ) fun asLnUrlPayRequestList(arr: ReadableArray): List<LnUrlPayRequest> { val list = ArrayList<LnUrlPayRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlPayRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlPayRequestData(lnUrlPayRequestData: ReadableMap): LnUrlPayRequestData? { if (!validateMandatoryFields( lnUrlPayRequestData, arrayOf( "callback", "minSendable", "maxSendable", "metadataStr", "commentAllowed", "domain", "allowsNostr", ), ) ) { return null } val callback = lnUrlPayRequestData.getString("callback")!! val minSendable = lnUrlPayRequestData.getDouble("minSendable").toULong() val maxSendable = lnUrlPayRequestData.getDouble("maxSendable").toULong() val metadataStr = lnUrlPayRequestData.getString("metadataStr")!! val commentAllowed = lnUrlPayRequestData.getInt("commentAllowed").toUShort() val domain = lnUrlPayRequestData.getString("domain")!! val allowsNostr = lnUrlPayRequestData.getBoolean("allowsNostr") val nostrPubkey = if (hasNonNullKey(lnUrlPayRequestData, "nostrPubkey")) lnUrlPayRequestData.getString("nostrPubkey") else null val lnAddress = if (hasNonNullKey(lnUrlPayRequestData, "lnAddress")) lnUrlPayRequestData.getString("lnAddress") else null return LnUrlPayRequestData( callback, minSendable, maxSendable, metadataStr, commentAllowed, domain, allowsNostr, nostrPubkey, lnAddress, ) } fun readableMapOf(lnUrlPayRequestData: LnUrlPayRequestData): ReadableMap = readableMapOf( "callback" to lnUrlPayRequestData.callback, "minSendable" to lnUrlPayRequestData.minSendable, "maxSendable" to lnUrlPayRequestData.maxSendable, "metadataStr" to lnUrlPayRequestData.metadataStr, "commentAllowed" to lnUrlPayRequestData.commentAllowed, "domain" to lnUrlPayRequestData.domain, "allowsNostr" to lnUrlPayRequestData.allowsNostr, "nostrPubkey" to lnUrlPayRequestData.nostrPubkey, "lnAddress" to lnUrlPayRequestData.lnAddress, ) fun asLnUrlPayRequestDataList(arr: ReadableArray): List<LnUrlPayRequestData> { val list = ArrayList<LnUrlPayRequestData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlPayRequestData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlPaySuccessData(lnUrlPaySuccessData: ReadableMap): LnUrlPaySuccessData? { if (!validateMandatoryFields( lnUrlPaySuccessData, arrayOf( "payment", ), ) ) { return null } val successAction = if (hasNonNullKey(lnUrlPaySuccessData, "successAction")) { lnUrlPaySuccessData.getMap("successAction")?.let { asSuccessActionProcessed(it) } } else { null } val payment = lnUrlPaySuccessData.getMap("payment")?.let { asPayment(it) }!! return LnUrlPaySuccessData( successAction, payment, ) } fun readableMapOf(lnUrlPaySuccessData: LnUrlPaySuccessData): ReadableMap = readableMapOf( "successAction" to lnUrlPaySuccessData.successAction?.let { readableMapOf(it) }, "payment" to readableMapOf(lnUrlPaySuccessData.payment), ) fun asLnUrlPaySuccessDataList(arr: ReadableArray): List<LnUrlPaySuccessData> { val list = ArrayList<LnUrlPaySuccessData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlPaySuccessData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlWithdrawRequest(lnUrlWithdrawRequest: ReadableMap): LnUrlWithdrawRequest? { if (!validateMandatoryFields( lnUrlWithdrawRequest, arrayOf( "data", "amountMsat", ), ) ) { return null } val data = lnUrlWithdrawRequest.getMap("data")?.let { asLnUrlWithdrawRequestData(it) }!! val amountMsat = lnUrlWithdrawRequest.getDouble("amountMsat").toULong() val description = if (hasNonNullKey(lnUrlWithdrawRequest, "description")) lnUrlWithdrawRequest.getString("description") else null return LnUrlWithdrawRequest( data, amountMsat, description, ) } fun readableMapOf(lnUrlWithdrawRequest: LnUrlWithdrawRequest): ReadableMap = readableMapOf( "data" to readableMapOf(lnUrlWithdrawRequest.data), "amountMsat" to lnUrlWithdrawRequest.amountMsat, "description" to lnUrlWithdrawRequest.description, ) fun asLnUrlWithdrawRequestList(arr: ReadableArray): List<LnUrlWithdrawRequest> { val list = ArrayList<LnUrlWithdrawRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlWithdrawRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlWithdrawRequestData(lnUrlWithdrawRequestData: ReadableMap): LnUrlWithdrawRequestData? { if (!validateMandatoryFields( lnUrlWithdrawRequestData, arrayOf( "callback", "k1", "defaultDescription", "minWithdrawable", "maxWithdrawable", ), ) ) { return null } val callback = lnUrlWithdrawRequestData.getString("callback")!! val k1 = lnUrlWithdrawRequestData.getString("k1")!! val defaultDescription = lnUrlWithdrawRequestData.getString("defaultDescription")!! val minWithdrawable = lnUrlWithdrawRequestData.getDouble("minWithdrawable").toULong() val maxWithdrawable = lnUrlWithdrawRequestData.getDouble("maxWithdrawable").toULong() return LnUrlWithdrawRequestData( callback, k1, defaultDescription, minWithdrawable, maxWithdrawable, ) } fun readableMapOf(lnUrlWithdrawRequestData: LnUrlWithdrawRequestData): ReadableMap = readableMapOf( "callback" to lnUrlWithdrawRequestData.callback, "k1" to lnUrlWithdrawRequestData.k1, "defaultDescription" to lnUrlWithdrawRequestData.defaultDescription, "minWithdrawable" to lnUrlWithdrawRequestData.minWithdrawable, "maxWithdrawable" to lnUrlWithdrawRequestData.maxWithdrawable, ) fun asLnUrlWithdrawRequestDataList(arr: ReadableArray): List<LnUrlWithdrawRequestData> { val list = ArrayList<LnUrlWithdrawRequestData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlWithdrawRequestData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlWithdrawSuccessData(lnUrlWithdrawSuccessData: ReadableMap): LnUrlWithdrawSuccessData? { if (!validateMandatoryFields( lnUrlWithdrawSuccessData, arrayOf( "invoice", ), ) ) { return null } val invoice = lnUrlWithdrawSuccessData.getMap("invoice")?.let { asLnInvoice(it) }!! return LnUrlWithdrawSuccessData( invoice, ) } fun readableMapOf(lnUrlWithdrawSuccessData: LnUrlWithdrawSuccessData): ReadableMap = readableMapOf( "invoice" to readableMapOf(lnUrlWithdrawSuccessData.invoice), ) fun asLnUrlWithdrawSuccessDataList(arr: ReadableArray): List<LnUrlWithdrawSuccessData> { val list = ArrayList<LnUrlWithdrawSuccessData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlWithdrawSuccessData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLocaleOverrides(localeOverrides: ReadableMap): LocaleOverrides? { if (!validateMandatoryFields( localeOverrides, arrayOf( "locale", "symbol", ), ) ) { return null } val locale = localeOverrides.getString("locale")!! val spacing = if (hasNonNullKey(localeOverrides, "spacing")) localeOverrides.getInt("spacing").toUInt() else null val symbol = localeOverrides.getMap("symbol")?.let { asSymbol(it) }!! return LocaleOverrides( locale, spacing, symbol, ) } fun readableMapOf(localeOverrides: LocaleOverrides): ReadableMap = readableMapOf( "locale" to localeOverrides.locale, "spacing" to localeOverrides.spacing, "symbol" to readableMapOf(localeOverrides.symbol), ) fun asLocaleOverridesList(arr: ReadableArray): List<LocaleOverrides> { val list = ArrayList<LocaleOverrides>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLocaleOverrides(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLocalizedName(localizedName: ReadableMap): LocalizedName? { if (!validateMandatoryFields( localizedName, arrayOf( "locale", "name", ), ) ) { return null } val locale = localizedName.getString("locale")!! val name = localizedName.getString("name")!! return LocalizedName( locale, name, ) } fun readableMapOf(localizedName: LocalizedName): ReadableMap = readableMapOf( "locale" to localizedName.locale, "name" to localizedName.name, ) fun asLocalizedNameList(arr: ReadableArray): List<LocalizedName> { val list = ArrayList<LocalizedName>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLocalizedName(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLogEntry(logEntry: ReadableMap): LogEntry? { if (!validateMandatoryFields( logEntry, arrayOf( "line", "level", ), ) ) { return null } val line = logEntry.getString("line")!! val level = logEntry.getString("level")!! return LogEntry( line, level, ) } fun readableMapOf(logEntry: LogEntry): ReadableMap = readableMapOf( "line" to logEntry.line, "level" to logEntry.level, ) fun asLogEntryList(arr: ReadableArray): List<LogEntry> { val list = ArrayList<LogEntry>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLogEntry(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asMessageSuccessActionData(messageSuccessActionData: ReadableMap): MessageSuccessActionData? { if (!validateMandatoryFields( messageSuccessActionData, arrayOf( "message", ), ) ) { return null } val message = messageSuccessActionData.getString("message")!! return MessageSuccessActionData( message, ) } fun readableMapOf(messageSuccessActionData: MessageSuccessActionData): ReadableMap = readableMapOf( "message" to messageSuccessActionData.message, ) fun asMessageSuccessActionDataList(arr: ReadableArray): List<MessageSuccessActionData> { val list = ArrayList<MessageSuccessActionData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asMessageSuccessActionData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asOnchainPaymentLimitsResponse(onchainPaymentLimitsResponse: ReadableMap): OnchainPaymentLimitsResponse? { if (!validateMandatoryFields( onchainPaymentLimitsResponse, arrayOf( "send", "receive", ), ) ) { return null } val send = onchainPaymentLimitsResponse.getMap("send")?.let { asLimits(it) }!! val receive = onchainPaymentLimitsResponse.getMap("receive")?.let { asLimits(it) }!! return OnchainPaymentLimitsResponse( send, receive, ) } fun readableMapOf(onchainPaymentLimitsResponse: OnchainPaymentLimitsResponse): ReadableMap = readableMapOf( "send" to readableMapOf(onchainPaymentLimitsResponse.send), "receive" to readableMapOf(onchainPaymentLimitsResponse.receive), ) fun asOnchainPaymentLimitsResponseList(arr: ReadableArray): List<OnchainPaymentLimitsResponse> { val list = ArrayList<OnchainPaymentLimitsResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asOnchainPaymentLimitsResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPayOnchainRequest(payOnchainRequest: ReadableMap): PayOnchainRequest? { if (!validateMandatoryFields( payOnchainRequest, arrayOf( "address", "prepareRes", ), ) ) { return null } val address = payOnchainRequest.getString("address")!! val prepareRes = payOnchainRequest.getMap("prepareRes")?.let { asPreparePayOnchainResponse(it) }!! return PayOnchainRequest( address, prepareRes, ) } fun readableMapOf(payOnchainRequest: PayOnchainRequest): ReadableMap = readableMapOf( "address" to payOnchainRequest.address, "prepareRes" to readableMapOf(payOnchainRequest.prepareRes), ) fun asPayOnchainRequestList(arr: ReadableArray): List<PayOnchainRequest> { val list = ArrayList<PayOnchainRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPayOnchainRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPayment(payment: ReadableMap): Payment? { if (!validateMandatoryFields( payment, arrayOf( "timestamp", "amountSat", "feesSat", "paymentType", "status", "description", ), ) ) { return null } val timestamp = payment.getInt("timestamp").toUInt() val amountSat = payment.getDouble("amountSat").toULong() val feesSat = payment.getDouble("feesSat").toULong() val paymentType = payment.getString("paymentType")?.let { asPaymentType(it) }!! val status = payment.getString("status")?.let { asPaymentState(it) }!! val description = payment.getString("description")!! val txId = if (hasNonNullKey(payment, "txId")) payment.getString("txId") else null val swapId = if (hasNonNullKey(payment, "swapId")) payment.getString("swapId") else null val preimage = if (hasNonNullKey(payment, "preimage")) payment.getString("preimage") else null val bolt11 = if (hasNonNullKey(payment, "bolt11")) payment.getString("bolt11") else null val refundTxId = if (hasNonNullKey(payment, "refundTxId")) payment.getString("refundTxId") else null val refundTxAmountSat = if (hasNonNullKey(payment, "refundTxAmountSat")) payment.getDouble("refundTxAmountSat").toULong() else null return Payment( timestamp, amountSat, feesSat, paymentType, status, description, txId, swapId, preimage, bolt11, refundTxId, refundTxAmountSat, ) } fun readableMapOf(payment: Payment): ReadableMap = readableMapOf( "timestamp" to payment.timestamp, "amountSat" to payment.amountSat, "feesSat" to payment.feesSat, "paymentType" to payment.paymentType.name.lowercase(), "status" to payment.status.name.lowercase(), "description" to payment.description, "txId" to payment.txId, "swapId" to payment.swapId, "preimage" to payment.preimage, "bolt11" to payment.bolt11, "refundTxId" to payment.refundTxId, "refundTxAmountSat" to payment.refundTxAmountSat, ) fun asPaymentList(arr: ReadableArray): List<Payment> { val list = ArrayList<Payment>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPayment(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareBuyBitcoinRequest(prepareBuyBitcoinRequest: ReadableMap): PrepareBuyBitcoinRequest? { if (!validateMandatoryFields( prepareBuyBitcoinRequest, arrayOf( "provider", "amountSat", ), ) ) { return null } val provider = prepareBuyBitcoinRequest.getString("provider")?.let { asBuyBitcoinProvider(it) }!! val amountSat = prepareBuyBitcoinRequest.getDouble("amountSat").toULong() return PrepareBuyBitcoinRequest( provider, amountSat, ) } fun readableMapOf(prepareBuyBitcoinRequest: PrepareBuyBitcoinRequest): ReadableMap = readableMapOf( "provider" to prepareBuyBitcoinRequest.provider.name.lowercase(), "amountSat" to prepareBuyBitcoinRequest.amountSat, ) fun asPrepareBuyBitcoinRequestList(arr: ReadableArray): List<PrepareBuyBitcoinRequest> { val list = ArrayList<PrepareBuyBitcoinRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareBuyBitcoinRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareBuyBitcoinResponse(prepareBuyBitcoinResponse: ReadableMap): PrepareBuyBitcoinResponse? { if (!validateMandatoryFields( prepareBuyBitcoinResponse, arrayOf( "provider", "amountSat", "feesSat", ), ) ) { return null } val provider = prepareBuyBitcoinResponse.getString("provider")?.let { asBuyBitcoinProvider(it) }!! val amountSat = prepareBuyBitcoinResponse.getDouble("amountSat").toULong() val feesSat = prepareBuyBitcoinResponse.getDouble("feesSat").toULong() return PrepareBuyBitcoinResponse( provider, amountSat, feesSat, ) } fun readableMapOf(prepareBuyBitcoinResponse: PrepareBuyBitcoinResponse): ReadableMap = readableMapOf( "provider" to prepareBuyBitcoinResponse.provider.name.lowercase(), "amountSat" to prepareBuyBitcoinResponse.amountSat, "feesSat" to prepareBuyBitcoinResponse.feesSat, ) fun asPrepareBuyBitcoinResponseList(arr: ReadableArray): List<PrepareBuyBitcoinResponse> { val list = ArrayList<PrepareBuyBitcoinResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareBuyBitcoinResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPreparePayOnchainRequest(preparePayOnchainRequest: ReadableMap): PreparePayOnchainRequest? { if (!validateMandatoryFields( preparePayOnchainRequest, arrayOf( "receiverAmountSat", ), ) ) { return null } val receiverAmountSat = preparePayOnchainRequest.getDouble("receiverAmountSat").toULong() val satPerVbyte = if (hasNonNullKey( preparePayOnchainRequest, "satPerVbyte", ) ) { preparePayOnchainRequest.getInt("satPerVbyte").toUInt() } else { null } return PreparePayOnchainRequest( receiverAmountSat, satPerVbyte, ) } fun readableMapOf(preparePayOnchainRequest: PreparePayOnchainRequest): ReadableMap = readableMapOf( "receiverAmountSat" to preparePayOnchainRequest.receiverAmountSat, "satPerVbyte" to preparePayOnchainRequest.satPerVbyte, ) fun asPreparePayOnchainRequestList(arr: ReadableArray): List<PreparePayOnchainRequest> { val list = ArrayList<PreparePayOnchainRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPreparePayOnchainRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPreparePayOnchainResponse(preparePayOnchainResponse: ReadableMap): PreparePayOnchainResponse? { if (!validateMandatoryFields( preparePayOnchainResponse, arrayOf( "receiverAmountSat", "claimFeesSat", "totalFeesSat", ), ) ) { return null } val receiverAmountSat = preparePayOnchainResponse.getDouble("receiverAmountSat").toULong() val claimFeesSat = preparePayOnchainResponse.getDouble("claimFeesSat").toULong() val totalFeesSat = preparePayOnchainResponse.getDouble("totalFeesSat").toULong() return PreparePayOnchainResponse( receiverAmountSat, claimFeesSat, totalFeesSat, ) } fun readableMapOf(preparePayOnchainResponse: PreparePayOnchainResponse): ReadableMap = readableMapOf( "receiverAmountSat" to preparePayOnchainResponse.receiverAmountSat, "claimFeesSat" to preparePayOnchainResponse.claimFeesSat, "totalFeesSat" to preparePayOnchainResponse.totalFeesSat, ) fun asPreparePayOnchainResponseList(arr: ReadableArray): List<PreparePayOnchainResponse> { val list = ArrayList<PreparePayOnchainResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPreparePayOnchainResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareReceiveOnchainRequest(prepareReceiveOnchainRequest: ReadableMap): PrepareReceiveOnchainRequest? { if (!validateMandatoryFields( prepareReceiveOnchainRequest, arrayOf( "payerAmountSat", ), ) ) { return null } val payerAmountSat = prepareReceiveOnchainRequest.getDouble("payerAmountSat").toULong() return PrepareReceiveOnchainRequest( payerAmountSat, ) } fun readableMapOf(prepareReceiveOnchainRequest: PrepareReceiveOnchainRequest): ReadableMap = readableMapOf( "payerAmountSat" to prepareReceiveOnchainRequest.payerAmountSat, ) fun asPrepareReceiveOnchainRequestList(arr: ReadableArray): List<PrepareReceiveOnchainRequest> { val list = ArrayList<PrepareReceiveOnchainRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareReceiveOnchainRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareReceiveOnchainResponse(prepareReceiveOnchainResponse: ReadableMap): PrepareReceiveOnchainResponse? { if (!validateMandatoryFields( prepareReceiveOnchainResponse, arrayOf( "payerAmountSat", "feesSat", ), ) ) { return null } val payerAmountSat = prepareReceiveOnchainResponse.getDouble("payerAmountSat").toULong() val feesSat = prepareReceiveOnchainResponse.getDouble("feesSat").toULong() return PrepareReceiveOnchainResponse( payerAmountSat, feesSat, ) } fun readableMapOf(prepareReceiveOnchainResponse: PrepareReceiveOnchainResponse): ReadableMap = readableMapOf( "payerAmountSat" to prepareReceiveOnchainResponse.payerAmountSat, "feesSat" to prepareReceiveOnchainResponse.feesSat, ) fun asPrepareReceiveOnchainResponseList(arr: ReadableArray): List<PrepareReceiveOnchainResponse> { val list = ArrayList<PrepareReceiveOnchainResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareReceiveOnchainResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareReceivePaymentRequest(prepareReceivePaymentRequest: ReadableMap): PrepareReceivePaymentRequest? { if (!validateMandatoryFields( prepareReceivePaymentRequest, arrayOf( "payerAmountSat", ), ) ) { return null } val payerAmountSat = prepareReceivePaymentRequest.getDouble("payerAmountSat").toULong() return PrepareReceivePaymentRequest( payerAmountSat, ) } fun readableMapOf(prepareReceivePaymentRequest: PrepareReceivePaymentRequest): ReadableMap = readableMapOf( "payerAmountSat" to prepareReceivePaymentRequest.payerAmountSat, ) fun asPrepareReceivePaymentRequestList(arr: ReadableArray): List<PrepareReceivePaymentRequest> { val list = ArrayList<PrepareReceivePaymentRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareReceivePaymentRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareReceivePaymentResponse(prepareReceivePaymentResponse: ReadableMap): PrepareReceivePaymentResponse? { if (!validateMandatoryFields( prepareReceivePaymentResponse, arrayOf( "payerAmountSat", "feesSat", ), ) ) { return null } val payerAmountSat = prepareReceivePaymentResponse.getDouble("payerAmountSat").toULong() val feesSat = prepareReceivePaymentResponse.getDouble("feesSat").toULong() return PrepareReceivePaymentResponse( payerAmountSat, feesSat, ) } fun readableMapOf(prepareReceivePaymentResponse: PrepareReceivePaymentResponse): ReadableMap = readableMapOf( "payerAmountSat" to prepareReceivePaymentResponse.payerAmountSat, "feesSat" to prepareReceivePaymentResponse.feesSat, ) fun asPrepareReceivePaymentResponseList(arr: ReadableArray): List<PrepareReceivePaymentResponse> { val list = ArrayList<PrepareReceivePaymentResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareReceivePaymentResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareRefundRequest(prepareRefundRequest: ReadableMap): PrepareRefundRequest? { if (!validateMandatoryFields( prepareRefundRequest, arrayOf( "swapAddress", "refundAddress", "satPerVbyte", ), ) ) { return null } val swapAddress = prepareRefundRequest.getString("swapAddress")!! val refundAddress = prepareRefundRequest.getString("refundAddress")!! val satPerVbyte = prepareRefundRequest.getInt("satPerVbyte").toUInt() return PrepareRefundRequest( swapAddress, refundAddress, satPerVbyte, ) } fun readableMapOf(prepareRefundRequest: PrepareRefundRequest): ReadableMap = readableMapOf( "swapAddress" to prepareRefundRequest.swapAddress, "refundAddress" to prepareRefundRequest.refundAddress, "satPerVbyte" to prepareRefundRequest.satPerVbyte, ) fun asPrepareRefundRequestList(arr: ReadableArray): List<PrepareRefundRequest> { val list = ArrayList<PrepareRefundRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareRefundRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareRefundResponse(prepareRefundResponse: ReadableMap): PrepareRefundResponse? { if (!validateMandatoryFields( prepareRefundResponse, arrayOf( "txVsize", "txFeeSat", ), ) ) { return null } val txVsize = prepareRefundResponse.getInt("txVsize").toUInt() val txFeeSat = prepareRefundResponse.getDouble("txFeeSat").toULong() val refundTxId = if (hasNonNullKey(prepareRefundResponse, "refundTxId")) prepareRefundResponse.getString("refundTxId") else null return PrepareRefundResponse( txVsize, txFeeSat, refundTxId, ) } fun readableMapOf(prepareRefundResponse: PrepareRefundResponse): ReadableMap = readableMapOf( "txVsize" to prepareRefundResponse.txVsize, "txFeeSat" to prepareRefundResponse.txFeeSat, "refundTxId" to prepareRefundResponse.refundTxId, ) fun asPrepareRefundResponseList(arr: ReadableArray): List<PrepareRefundResponse> { val list = ArrayList<PrepareRefundResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareRefundResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareSendRequest(prepareSendRequest: ReadableMap): PrepareSendRequest? { if (!validateMandatoryFields( prepareSendRequest, arrayOf( "invoice", ), ) ) { return null } val invoice = prepareSendRequest.getString("invoice")!! return PrepareSendRequest( invoice, ) } fun readableMapOf(prepareSendRequest: PrepareSendRequest): ReadableMap = readableMapOf( "invoice" to prepareSendRequest.invoice, ) fun asPrepareSendRequestList(arr: ReadableArray): List<PrepareSendRequest> { val list = ArrayList<PrepareSendRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareSendRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPrepareSendResponse(prepareSendResponse: ReadableMap): PrepareSendResponse? { if (!validateMandatoryFields( prepareSendResponse, arrayOf( "invoice", "feesSat", ), ) ) { return null } val invoice = prepareSendResponse.getString("invoice")!! val feesSat = prepareSendResponse.getDouble("feesSat").toULong() return PrepareSendResponse( invoice, feesSat, ) } fun readableMapOf(prepareSendResponse: PrepareSendResponse): ReadableMap = readableMapOf( "invoice" to prepareSendResponse.invoice, "feesSat" to prepareSendResponse.feesSat, ) fun asPrepareSendResponseList(arr: ReadableArray): List<PrepareSendResponse> { val list = ArrayList<PrepareSendResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asPrepareSendResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRate(rate: ReadableMap): Rate? { if (!validateMandatoryFields( rate, arrayOf( "coin", "value", ), ) ) { return null } val coin = rate.getString("coin")!! val value = rate.getDouble("value") return Rate( coin, value, ) } fun readableMapOf(rate: Rate): ReadableMap = readableMapOf( "coin" to rate.coin, "value" to rate.value, ) fun asRateList(arr: ReadableArray): List<Rate> { val list = ArrayList<Rate>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRate(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asReceiveOnchainResponse(receiveOnchainResponse: ReadableMap): ReceiveOnchainResponse? { if (!validateMandatoryFields( receiveOnchainResponse, arrayOf( "address", "bip21", ), ) ) { return null } val address = receiveOnchainResponse.getString("address")!! val bip21 = receiveOnchainResponse.getString("bip21")!! return ReceiveOnchainResponse( address, bip21, ) } fun readableMapOf(receiveOnchainResponse: ReceiveOnchainResponse): ReadableMap = readableMapOf( "address" to receiveOnchainResponse.address, "bip21" to receiveOnchainResponse.bip21, ) fun asReceiveOnchainResponseList(arr: ReadableArray): List<ReceiveOnchainResponse> { val list = ArrayList<ReceiveOnchainResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asReceiveOnchainResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asReceivePaymentRequest(receivePaymentRequest: ReadableMap): ReceivePaymentRequest? { if (!validateMandatoryFields( receivePaymentRequest, arrayOf( "prepareRes", ), ) ) { return null } val prepareRes = receivePaymentRequest.getMap("prepareRes")?.let { asPrepareReceivePaymentResponse(it) }!! val description = if (hasNonNullKey(receivePaymentRequest, "description")) receivePaymentRequest.getString("description") else null return ReceivePaymentRequest( prepareRes, description, ) } fun readableMapOf(receivePaymentRequest: ReceivePaymentRequest): ReadableMap = readableMapOf( "prepareRes" to readableMapOf(receivePaymentRequest.prepareRes), "description" to receivePaymentRequest.description, ) fun asReceivePaymentRequestList(arr: ReadableArray): List<ReceivePaymentRequest> { val list = ArrayList<ReceivePaymentRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asReceivePaymentRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asReceivePaymentResponse(receivePaymentResponse: ReadableMap): ReceivePaymentResponse? { if (!validateMandatoryFields( receivePaymentResponse, arrayOf( "id", "invoice", ), ) ) { return null } val id = receivePaymentResponse.getString("id")!! val invoice = receivePaymentResponse.getString("invoice")!! return ReceivePaymentResponse( id, invoice, ) } fun readableMapOf(receivePaymentResponse: ReceivePaymentResponse): ReadableMap = readableMapOf( "id" to receivePaymentResponse.id, "invoice" to receivePaymentResponse.invoice, ) fun asReceivePaymentResponseList(arr: ReadableArray): List<ReceivePaymentResponse> { val list = ArrayList<ReceivePaymentResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asReceivePaymentResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRecommendedFees(recommendedFees: ReadableMap): RecommendedFees? { if (!validateMandatoryFields( recommendedFees, arrayOf( "fastestFee", "halfHourFee", "hourFee", "economyFee", "minimumFee", ), ) ) { return null } val fastestFee = recommendedFees.getDouble("fastestFee").toULong() val halfHourFee = recommendedFees.getDouble("halfHourFee").toULong() val hourFee = recommendedFees.getDouble("hourFee").toULong() val economyFee = recommendedFees.getDouble("economyFee").toULong() val minimumFee = recommendedFees.getDouble("minimumFee").toULong() return RecommendedFees( fastestFee, halfHourFee, hourFee, economyFee, minimumFee, ) } fun readableMapOf(recommendedFees: RecommendedFees): ReadableMap = readableMapOf( "fastestFee" to recommendedFees.fastestFee, "halfHourFee" to recommendedFees.halfHourFee, "hourFee" to recommendedFees.hourFee, "economyFee" to recommendedFees.economyFee, "minimumFee" to recommendedFees.minimumFee, ) fun asRecommendedFeesList(arr: ReadableArray): List<RecommendedFees> { val list = ArrayList<RecommendedFees>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRecommendedFees(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRefundRequest(refundRequest: ReadableMap): RefundRequest? { if (!validateMandatoryFields( refundRequest, arrayOf( "swapAddress", "refundAddress", "satPerVbyte", ), ) ) { return null } val swapAddress = refundRequest.getString("swapAddress")!! val refundAddress = refundRequest.getString("refundAddress")!! val satPerVbyte = refundRequest.getInt("satPerVbyte").toUInt() return RefundRequest( swapAddress, refundAddress, satPerVbyte, ) } fun readableMapOf(refundRequest: RefundRequest): ReadableMap = readableMapOf( "swapAddress" to refundRequest.swapAddress, "refundAddress" to refundRequest.refundAddress, "satPerVbyte" to refundRequest.satPerVbyte, ) fun asRefundRequestList(arr: ReadableArray): List<RefundRequest> { val list = ArrayList<RefundRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRefundRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRefundResponse(refundResponse: ReadableMap): RefundResponse? { if (!validateMandatoryFields( refundResponse, arrayOf( "refundTxId", ), ) ) { return null } val refundTxId = refundResponse.getString("refundTxId")!! return RefundResponse( refundTxId, ) } fun readableMapOf(refundResponse: RefundResponse): ReadableMap = readableMapOf( "refundTxId" to refundResponse.refundTxId, ) fun asRefundResponseList(arr: ReadableArray): List<RefundResponse> { val list = ArrayList<RefundResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRefundResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRefundableSwap(refundableSwap: ReadableMap): RefundableSwap? { if (!validateMandatoryFields( refundableSwap, arrayOf( "swapAddress", "timestamp", "amountSat", ), ) ) { return null } val swapAddress = refundableSwap.getString("swapAddress")!! val timestamp = refundableSwap.getInt("timestamp").toUInt() val amountSat = refundableSwap.getDouble("amountSat").toULong() return RefundableSwap( swapAddress, timestamp, amountSat, ) } fun readableMapOf(refundableSwap: RefundableSwap): ReadableMap = readableMapOf( "swapAddress" to refundableSwap.swapAddress, "timestamp" to refundableSwap.timestamp, "amountSat" to refundableSwap.amountSat, ) fun asRefundableSwapList(arr: ReadableArray): List<RefundableSwap> { val list = ArrayList<RefundableSwap>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRefundableSwap(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRestoreRequest(restoreRequest: ReadableMap): RestoreRequest? { if (!validateMandatoryFields( restoreRequest, arrayOf(), ) ) { return null } val backupPath = if (hasNonNullKey(restoreRequest, "backupPath")) restoreRequest.getString("backupPath") else null return RestoreRequest( backupPath, ) } fun readableMapOf(restoreRequest: RestoreRequest): ReadableMap = readableMapOf( "backupPath" to restoreRequest.backupPath, ) fun asRestoreRequestList(arr: ReadableArray): List<RestoreRequest> { val list = ArrayList<RestoreRequest>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRestoreRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRouteHint(routeHint: ReadableMap): RouteHint? { if (!validateMandatoryFields( routeHint, arrayOf( "hops", ), ) ) { return null } val hops = routeHint.getArray("hops")?.let { asRouteHintHopList(it) }!! return RouteHint( hops, ) } fun readableMapOf(routeHint: RouteHint): ReadableMap = readableMapOf( "hops" to readableArrayOf(routeHint.hops), ) fun asRouteHintList(arr: ReadableArray): List<RouteHint> { val list = ArrayList<RouteHint>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRouteHint(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asRouteHintHop(routeHintHop: ReadableMap): RouteHintHop? { if (!validateMandatoryFields( routeHintHop, arrayOf( "srcNodeId", "shortChannelId", "feesBaseMsat", "feesProportionalMillionths", "cltvExpiryDelta", ), ) ) { return null } val srcNodeId = routeHintHop.getString("srcNodeId")!! val shortChannelId = routeHintHop.getDouble("shortChannelId").toULong() val feesBaseMsat = routeHintHop.getInt("feesBaseMsat").toUInt() val feesProportionalMillionths = routeHintHop.getInt("feesProportionalMillionths").toUInt() val cltvExpiryDelta = routeHintHop.getDouble("cltvExpiryDelta").toULong() val htlcMinimumMsat = if (hasNonNullKey(routeHintHop, "htlcMinimumMsat")) routeHintHop.getDouble("htlcMinimumMsat").toULong() else null val htlcMaximumMsat = if (hasNonNullKey(routeHintHop, "htlcMaximumMsat")) routeHintHop.getDouble("htlcMaximumMsat").toULong() else null return RouteHintHop( srcNodeId, shortChannelId, feesBaseMsat, feesProportionalMillionths, cltvExpiryDelta, htlcMinimumMsat, htlcMaximumMsat, ) } fun readableMapOf(routeHintHop: RouteHintHop): ReadableMap = readableMapOf( "srcNodeId" to routeHintHop.srcNodeId, "shortChannelId" to routeHintHop.shortChannelId, "feesBaseMsat" to routeHintHop.feesBaseMsat, "feesProportionalMillionths" to routeHintHop.feesProportionalMillionths, "cltvExpiryDelta" to routeHintHop.cltvExpiryDelta, "htlcMinimumMsat" to routeHintHop.htlcMinimumMsat, "htlcMaximumMsat" to routeHintHop.htlcMaximumMsat, ) fun asRouteHintHopList(arr: ReadableArray): List<RouteHintHop> { val list = ArrayList<RouteHintHop>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asRouteHintHop(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asSendPaymentResponse(sendPaymentResponse: ReadableMap): SendPaymentResponse? { if (!validateMandatoryFields( sendPaymentResponse, arrayOf( "payment", ), ) ) { return null } val payment = sendPaymentResponse.getMap("payment")?.let { asPayment(it) }!! return SendPaymentResponse( payment, ) } fun readableMapOf(sendPaymentResponse: SendPaymentResponse): ReadableMap = readableMapOf( "payment" to readableMapOf(sendPaymentResponse.payment), ) fun asSendPaymentResponseList(arr: ReadableArray): List<SendPaymentResponse> { val list = ArrayList<SendPaymentResponse>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asSendPaymentResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asSymbol(symbol: ReadableMap): Symbol? { if (!validateMandatoryFields( symbol, arrayOf(), ) ) { return null } val grapheme = if (hasNonNullKey(symbol, "grapheme")) symbol.getString("grapheme") else null val template = if (hasNonNullKey(symbol, "template")) symbol.getString("template") else null val rtl = if (hasNonNullKey(symbol, "rtl")) symbol.getBoolean("rtl") else null val position = if (hasNonNullKey(symbol, "position")) symbol.getInt("position").toUInt() else null return Symbol( grapheme, template, rtl, position, ) } fun readableMapOf(symbol: Symbol): ReadableMap = readableMapOf( "grapheme" to symbol.grapheme, "template" to symbol.template, "rtl" to symbol.rtl, "position" to symbol.position, ) fun asSymbolList(arr: ReadableArray): List<Symbol> { val list = ArrayList<Symbol>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asSymbol(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asUrlSuccessActionData(urlSuccessActionData: ReadableMap): UrlSuccessActionData? { if (!validateMandatoryFields( urlSuccessActionData, arrayOf( "description", "url", "matchesCallbackDomain", ), ) ) { return null } val description = urlSuccessActionData.getString("description")!! val url = urlSuccessActionData.getString("url")!! val matchesCallbackDomain = urlSuccessActionData.getBoolean("matchesCallbackDomain") return UrlSuccessActionData( description, url, matchesCallbackDomain, ) } fun readableMapOf(urlSuccessActionData: UrlSuccessActionData): ReadableMap = readableMapOf( "description" to urlSuccessActionData.description, "url" to urlSuccessActionData.url, "matchesCallbackDomain" to urlSuccessActionData.matchesCallbackDomain, ) fun asUrlSuccessActionDataList(arr: ReadableArray): List<UrlSuccessActionData> { val list = ArrayList<UrlSuccessActionData>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asUrlSuccessActionData(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asAesSuccessActionDataResult(aesSuccessActionDataResult: ReadableMap): AesSuccessActionDataResult? { val type = aesSuccessActionDataResult.getString("type") if (type == "decrypted") { return AesSuccessActionDataResult.Decrypted( aesSuccessActionDataResult.getMap("data")?.let { asAesSuccessActionDataDecrypted(it) }!!, ) } if (type == "errorStatus") { return AesSuccessActionDataResult.ErrorStatus(aesSuccessActionDataResult.getString("reason")!!) } return null } fun readableMapOf(aesSuccessActionDataResult: AesSuccessActionDataResult): ReadableMap? { val map = Arguments.createMap() when (aesSuccessActionDataResult) { is AesSuccessActionDataResult.Decrypted -> { pushToMap(map, "type", "decrypted") pushToMap(map, "data", readableMapOf(aesSuccessActionDataResult.data)) } is AesSuccessActionDataResult.ErrorStatus -> { pushToMap(map, "type", "errorStatus") pushToMap(map, "reason", aesSuccessActionDataResult.reason) } } return map } fun asAesSuccessActionDataResultList(arr: ReadableArray): List<AesSuccessActionDataResult> { val list = ArrayList<AesSuccessActionDataResult>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asAesSuccessActionDataResult(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asBuyBitcoinProvider(type: String): BuyBitcoinProvider = BuyBitcoinProvider.valueOf(camelToUpperSnakeCase(type)) fun asBuyBitcoinProviderList(arr: ReadableArray): List<BuyBitcoinProvider> { val list = ArrayList<BuyBitcoinProvider>() for (value in arr.toArrayList()) { when (value) { is String -> list.add(asBuyBitcoinProvider(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asInputType(inputType: ReadableMap): InputType? { val type = inputType.getString("type") if (type == "bitcoinAddress") { return InputType.BitcoinAddress(inputType.getMap("address")?.let { asBitcoinAddressData(it) }!!) } if (type == "bolt11") { return InputType.Bolt11(inputType.getMap("invoice")?.let { asLnInvoice(it) }!!) } if (type == "nodeId") { return InputType.NodeId(inputType.getString("nodeId")!!) } if (type == "url") { return InputType.Url(inputType.getString("url")!!) } if (type == "lnUrlPay") { return InputType.LnUrlPay(inputType.getMap("data")?.let { asLnUrlPayRequestData(it) }!!) } if (type == "lnUrlWithdraw") { return InputType.LnUrlWithdraw(inputType.getMap("data")?.let { asLnUrlWithdrawRequestData(it) }!!) } if (type == "lnUrlAuth") { return InputType.LnUrlAuth(inputType.getMap("data")?.let { asLnUrlAuthRequestData(it) }!!) } if (type == "lnUrlError") { return InputType.LnUrlError(inputType.getMap("data")?.let { asLnUrlErrorData(it) }!!) } return null } fun readableMapOf(inputType: InputType): ReadableMap? { val map = Arguments.createMap() when (inputType) { is InputType.BitcoinAddress -> { pushToMap(map, "type", "bitcoinAddress") pushToMap(map, "address", readableMapOf(inputType.address)) } is InputType.Bolt11 -> { pushToMap(map, "type", "bolt11") pushToMap(map, "invoice", readableMapOf(inputType.invoice)) } is InputType.NodeId -> { pushToMap(map, "type", "nodeId") pushToMap(map, "nodeId", inputType.nodeId) } is InputType.Url -> { pushToMap(map, "type", "url") pushToMap(map, "url", inputType.url) } is InputType.LnUrlPay -> { pushToMap(map, "type", "lnUrlPay") pushToMap(map, "data", readableMapOf(inputType.data)) } is InputType.LnUrlWithdraw -> { pushToMap(map, "type", "lnUrlWithdraw") pushToMap(map, "data", readableMapOf(inputType.data)) } is InputType.LnUrlAuth -> { pushToMap(map, "type", "lnUrlAuth") pushToMap(map, "data", readableMapOf(inputType.data)) } is InputType.LnUrlError -> { pushToMap(map, "type", "lnUrlError") pushToMap(map, "data", readableMapOf(inputType.data)) } } return map } fun asInputTypeList(arr: ReadableArray): List<InputType> { val list = ArrayList<InputType>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asInputType(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLiquidNetwork(type: String): LiquidNetwork = LiquidNetwork.valueOf(camelToUpperSnakeCase(type)) fun asLiquidNetworkList(arr: ReadableArray): List<LiquidNetwork> { val list = ArrayList<LiquidNetwork>() for (value in arr.toArrayList()) { when (value) { is String -> list.add(asLiquidNetwork(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlCallbackStatus(lnUrlCallbackStatus: ReadableMap): LnUrlCallbackStatus? { val type = lnUrlCallbackStatus.getString("type") if (type == "ok") { return LnUrlCallbackStatus.Ok } if (type == "errorStatus") { return LnUrlCallbackStatus.ErrorStatus(lnUrlCallbackStatus.getMap("data")?.let { asLnUrlErrorData(it) }!!) } return null } fun readableMapOf(lnUrlCallbackStatus: LnUrlCallbackStatus): ReadableMap? { val map = Arguments.createMap() when (lnUrlCallbackStatus) { is LnUrlCallbackStatus.Ok -> { pushToMap(map, "type", "ok") } is LnUrlCallbackStatus.ErrorStatus -> { pushToMap(map, "type", "errorStatus") pushToMap(map, "data", readableMapOf(lnUrlCallbackStatus.data)) } } return map } fun asLnUrlCallbackStatusList(arr: ReadableArray): List<LnUrlCallbackStatus> { val list = ArrayList<LnUrlCallbackStatus>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlCallbackStatus(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlPayResult(lnUrlPayResult: ReadableMap): LnUrlPayResult? { val type = lnUrlPayResult.getString("type") if (type == "endpointSuccess") { return LnUrlPayResult.EndpointSuccess(lnUrlPayResult.getMap("data")?.let { asLnUrlPaySuccessData(it) }!!) } if (type == "endpointError") { return LnUrlPayResult.EndpointError(lnUrlPayResult.getMap("data")?.let { asLnUrlErrorData(it) }!!) } if (type == "payError") { return LnUrlPayResult.PayError(lnUrlPayResult.getMap("data")?.let { asLnUrlPayErrorData(it) }!!) } return null } fun readableMapOf(lnUrlPayResult: LnUrlPayResult): ReadableMap? { val map = Arguments.createMap() when (lnUrlPayResult) { is LnUrlPayResult.EndpointSuccess -> { pushToMap(map, "type", "endpointSuccess") pushToMap(map, "data", readableMapOf(lnUrlPayResult.data)) } is LnUrlPayResult.EndpointError -> { pushToMap(map, "type", "endpointError") pushToMap(map, "data", readableMapOf(lnUrlPayResult.data)) } is LnUrlPayResult.PayError -> { pushToMap(map, "type", "payError") pushToMap(map, "data", readableMapOf(lnUrlPayResult.data)) } } return map } fun asLnUrlPayResultList(arr: ReadableArray): List<LnUrlPayResult> { val list = ArrayList<LnUrlPayResult>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlPayResult(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asLnUrlWithdrawResult(lnUrlWithdrawResult: ReadableMap): LnUrlWithdrawResult? { val type = lnUrlWithdrawResult.getString("type") if (type == "ok") { return LnUrlWithdrawResult.Ok(lnUrlWithdrawResult.getMap("data")?.let { asLnUrlWithdrawSuccessData(it) }!!) } if (type == "timeout") { return LnUrlWithdrawResult.Timeout(lnUrlWithdrawResult.getMap("data")?.let { asLnUrlWithdrawSuccessData(it) }!!) } if (type == "errorStatus") { return LnUrlWithdrawResult.ErrorStatus(lnUrlWithdrawResult.getMap("data")?.let { asLnUrlErrorData(it) }!!) } return null } fun readableMapOf(lnUrlWithdrawResult: LnUrlWithdrawResult): ReadableMap? { val map = Arguments.createMap() when (lnUrlWithdrawResult) { is LnUrlWithdrawResult.Ok -> { pushToMap(map, "type", "ok") pushToMap(map, "data", readableMapOf(lnUrlWithdrawResult.data)) } is LnUrlWithdrawResult.Timeout -> { pushToMap(map, "type", "timeout") pushToMap(map, "data", readableMapOf(lnUrlWithdrawResult.data)) } is LnUrlWithdrawResult.ErrorStatus -> { pushToMap(map, "type", "errorStatus") pushToMap(map, "data", readableMapOf(lnUrlWithdrawResult.data)) } } return map } fun asLnUrlWithdrawResultList(arr: ReadableArray): List<LnUrlWithdrawResult> { val list = ArrayList<LnUrlWithdrawResult>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asLnUrlWithdrawResult(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asNetwork(type: String): Network = Network.valueOf(camelToUpperSnakeCase(type)) fun asNetworkList(arr: ReadableArray): List<Network> { val list = ArrayList<Network>() for (value in arr.toArrayList()) { when (value) { is String -> list.add(asNetwork(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPaymentState(type: String): PaymentState = PaymentState.valueOf(camelToUpperSnakeCase(type)) fun asPaymentStateList(arr: ReadableArray): List<PaymentState> { val list = ArrayList<PaymentState>() for (value in arr.toArrayList()) { when (value) { is String -> list.add(asPaymentState(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asPaymentType(type: String): PaymentType = PaymentType.valueOf(camelToUpperSnakeCase(type)) fun asPaymentTypeList(arr: ReadableArray): List<PaymentType> { val list = ArrayList<PaymentType>() for (value in arr.toArrayList()) { when (value) { is String -> list.add(asPaymentType(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asSdkEvent(sdkEvent: ReadableMap): SdkEvent? { val type = sdkEvent.getString("type") if (type == "paymentFailed") { return SdkEvent.PaymentFailed(sdkEvent.getMap("details")?.let { asPayment(it) }!!) } if (type == "paymentPending") { return SdkEvent.PaymentPending(sdkEvent.getMap("details")?.let { asPayment(it) }!!) } if (type == "paymentRefunded") { return SdkEvent.PaymentRefunded(sdkEvent.getMap("details")?.let { asPayment(it) }!!) } if (type == "paymentRefundPending") { return SdkEvent.PaymentRefundPending(sdkEvent.getMap("details")?.let { asPayment(it) }!!) } if (type == "paymentSucceeded") { return SdkEvent.PaymentSucceeded(sdkEvent.getMap("details")?.let { asPayment(it) }!!) } if (type == "paymentWaitingConfirmation") { return SdkEvent.PaymentWaitingConfirmation(sdkEvent.getMap("details")?.let { asPayment(it) }!!) } if (type == "synced") { return SdkEvent.Synced } return null } fun readableMapOf(sdkEvent: SdkEvent): ReadableMap? { val map = Arguments.createMap() when (sdkEvent) { is SdkEvent.PaymentFailed -> { pushToMap(map, "type", "paymentFailed") pushToMap(map, "details", readableMapOf(sdkEvent.details)) } is SdkEvent.PaymentPending -> { pushToMap(map, "type", "paymentPending") pushToMap(map, "details", readableMapOf(sdkEvent.details)) } is SdkEvent.PaymentRefunded -> { pushToMap(map, "type", "paymentRefunded") pushToMap(map, "details", readableMapOf(sdkEvent.details)) } is SdkEvent.PaymentRefundPending -> { pushToMap(map, "type", "paymentRefundPending") pushToMap(map, "details", readableMapOf(sdkEvent.details)) } is SdkEvent.PaymentSucceeded -> { pushToMap(map, "type", "paymentSucceeded") pushToMap(map, "details", readableMapOf(sdkEvent.details)) } is SdkEvent.PaymentWaitingConfirmation -> { pushToMap(map, "type", "paymentWaitingConfirmation") pushToMap(map, "details", readableMapOf(sdkEvent.details)) } is SdkEvent.Synced -> { pushToMap(map, "type", "synced") } } return map } fun asSdkEventList(arr: ReadableArray): List<SdkEvent> { val list = ArrayList<SdkEvent>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asSdkEvent(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asSuccessActionProcessed(successActionProcessed: ReadableMap): SuccessActionProcessed? { val type = successActionProcessed.getString("type") if (type == "aes") { return SuccessActionProcessed.Aes(successActionProcessed.getMap("result")?.let { asAesSuccessActionDataResult(it) }!!) } if (type == "message") { return SuccessActionProcessed.Message(successActionProcessed.getMap("data")?.let { asMessageSuccessActionData(it) }!!) } if (type == "url") { return SuccessActionProcessed.Url(successActionProcessed.getMap("data")?.let { asUrlSuccessActionData(it) }!!) } return null } fun readableMapOf(successActionProcessed: SuccessActionProcessed): ReadableMap? { val map = Arguments.createMap() when (successActionProcessed) { is SuccessActionProcessed.Aes -> { pushToMap(map, "type", "aes") pushToMap(map, "result", readableMapOf(successActionProcessed.result)) } is SuccessActionProcessed.Message -> { pushToMap(map, "type", "message") pushToMap(map, "data", readableMapOf(successActionProcessed.data)) } is SuccessActionProcessed.Url -> { pushToMap(map, "type", "url") pushToMap(map, "data", readableMapOf(successActionProcessed.data)) } } return map } fun asSuccessActionProcessedList(arr: ReadableArray): List<SuccessActionProcessed> { val list = ArrayList<SuccessActionProcessed>() for (value in arr.toArrayList()) { when (value) { is ReadableMap -> list.add(asSuccessActionProcessed(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun readableMapOf(vararg values: Pair<String, *>): ReadableMap { val map = Arguments.createMap() for ((key, value) in values) { pushToMap(map, key, value) } return map } fun hasNonNullKey( map: ReadableMap, key: String, ): Boolean = map.hasKey(key) && !map.isNull(key) fun validateMandatoryFields( map: ReadableMap, keys: Array<String>, ): Boolean { for (k in keys) { if (!hasNonNullKey(map, k)) return false } return true } fun pushToArray( array: WritableArray, value: Any?, ) { when (value) { null -> array.pushNull() is FiatCurrency -> array.pushMap(readableMapOf(value)) is LocaleOverrides -> array.pushMap(readableMapOf(value)) is LocalizedName -> array.pushMap(readableMapOf(value)) is Payment -> array.pushMap(readableMapOf(value)) is PaymentType -> array.pushString(value.name.lowercase()) is Rate -> array.pushMap(readableMapOf(value)) is RefundableSwap -> array.pushMap(readableMapOf(value)) is RouteHint -> array.pushMap(readableMapOf(value)) is RouteHintHop -> array.pushMap(readableMapOf(value)) is UByte -> array.pushInt(value.toInt()) is Array<*> -> array.pushArray(readableArrayOf(value.asIterable())) is List<*> -> array.pushArray(readableArrayOf(value)) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } fun pushToMap( map: WritableMap, key: String, value: Any?, ) { when (value) { null -> map.putNull(key) is Boolean -> map.putBoolean(key, value) is Byte -> map.putInt(key, value.toInt()) is Double -> map.putDouble(key, value) is Float -> map.putDouble(key, value.toDouble()) is Int -> map.putInt(key, value) is Long -> map.putDouble(key, value.toDouble()) is ReadableArray -> map.putArray(key, value) is ReadableMap -> map.putMap(key, value) is String -> map.putString(key, value) is UByte -> map.putInt(key, value.toInt()) is UInt -> map.putInt(key, value.toInt()) is UShort -> map.putInt(key, value.toInt()) is ULong -> map.putDouble(key, value.toDouble()) is Array<*> -> map.putArray(key, readableArrayOf(value.asIterable())) is List<*> -> map.putArray(key, readableArrayOf(value)) else -> throw SdkException.Generic("Unexpected type ${value::class.java.name} for key [$key]") } } fun readableArrayOf(values: Iterable<*>?): ReadableArray { val array = Arguments.createArray() if (values != null) { for (value in values) { pushToArray(array, value) } } return array } fun asUByteList(arr: ReadableArray): List<UByte> { val list = ArrayList<UByte>() for (value in arr.toArrayList()) { when (value) { is Double -> list.add(value.toInt().toUByte()) is Int -> list.add(value.toUByte()) is UByte -> list.add(value) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } fun asStringList(arr: ReadableArray): List<String> { val list = ArrayList<String>() for (value in arr.toArrayList()) { list.add(value.toString()) } return list } fun errMissingMandatoryField( fieldName: String, typeName: String, ): String = "Missing mandatory field $fieldName for type $typeName" fun errUnexpectedType(typeName: String): String = "Unexpected type $typeName" fun errUnexpectedValue(fieldName: String): String = "Unexpected value for optional field $fieldName" fun camelToUpperSnakeCase(str: String): String { val pattern = "(?<=.)[A-Z]".toRegex() return str.replace(pattern, "_$0").uppercase() }
44
Rust
3
13
44ee969e433af90100b192e75c03dcfd79dbab4e
92,746
breez-sdk-liquid
MIT License
src/main/kotlin/com/dood/kotlin/basicstuff/classesAndSuch/4_CustomAccessors.kt
coderdude1
164,117,770
false
null
package com.dood.kotlin.basicstuff.classesAndSuch /** * declare a class with 2 properties, and add a custom accessor (isSquare) method. This example uses an accessor * (get) vs a function on the class itself. */ class Rectangle(val height: Int, val width: Int) { val isSquare: Boolean get() { return height == width } }
0
Kotlin
0
0
5f5dcb954152b81f458bf614c79a5116dd554385
356
KotlinBasicExperiments
Apache License 2.0
app/src/main/java/com/techchallange/app/ui/activities/login/LoginActivityViewModel.kt
hasankucuk
209,618,765
false
null
package com.techchallange.app.ui.activities.login import com.techchallange.app.base.BaseViewModel class LoginActivityViewModel : BaseViewModel() { }
0
Kotlin
1
6
8204cc8ce3e2cae24da7056a94ecd1dbb31a562f
150
Android-Developer-Tech-Challenge
Apache License 2.0
data/src/main/java/com/codewithfk/data/network/NetworkServiceImpl.kt
furqanullah717
850,539,879
false
{"Kotlin": 18319}
package com.codewithfk.data.network import com.codewithfk.data.model.DataProductModel import com.codewithfk.domain.model.Product import com.codewithfk.domain.network.NetworkService import com.codewithfk.domain.network.ResultWrapper import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.ClientRequestException import io.ktor.client.plugins.ServerResponseException import io.ktor.client.request.header import io.ktor.client.request.request import io.ktor.http.ContentType import io.ktor.http.HttpMethod import io.ktor.http.Parameters import io.ktor.http.contentType import io.ktor.util.InternalAPI import io.ktor.utils.io.errors.IOException class NetworkServiceImpl(val client: HttpClient) : NetworkService { override suspend fun getProducts(): ResultWrapper<List<Product>> { return makeWebRequest( url = "https://fakestoreapi.com/products", method = HttpMethod.Get, mapper = { dataModels: List<DataProductModel> -> dataModels.map { it.toProduct() } } ) } @OptIn(InternalAPI::class) suspend inline fun <reified T, R> makeWebRequest( url: String, method: HttpMethod, body: Any? = null, headers: Map<String, String> = emptyMap(), parameters: Map<String, String> = emptyMap(), noinline mapper: ((T) -> R)? = null ): ResultWrapper<R> { return try { val response = client.request(url) { this.method = method // Apply query parameters url { this.parameters.appendAll(Parameters.build { parameters.forEach { (key, value) -> append(key, value) } }) } // Apply headers headers.forEach { (key, value) -> header(key, value) } // Set body for POST, PUT, etc. if (body != null) { this.body = body } // Set content type contentType(ContentType.Application.Json) }.body<T>() val result: R = mapper?.invoke(response) ?: response as R ResultWrapper.Success(result) } catch (e: ClientRequestException) { ResultWrapper.Failure(e) } catch (e: ServerResponseException) { ResultWrapper.Failure(e) } catch (e: IOException) { ResultWrapper.Failure(e) } catch (e: Exception) { ResultWrapper.Failure(e) } } }
0
Kotlin
0
6
2c4539b975e80b4a7db23709e00be4da10c8d3e6
2,670
Shopper-compose
Apache License 2.0
lib/src/main/kotlin/de/unisaarland/pcdfanalyser/eventStream/PCDFEventExtensions.kt
udsdepend
404,319,499
false
{"Kotlin": 108306}
package de.unisaarland.pcdfanalyser.eventStream import pcdfEvent.PCDFEvent import pcdfEvent.events.obdEvents.obdIntermediateEvents.multiComponentEvents.* import pcdfEvent.events.obdEvents.obdIntermediateEvents.reducedComponentEvents.FuelRateReducedEvent import pcdfEvent.events.obdEvents.obdIntermediateEvents.reducedComponentEvents.NOXReducedEvent import pcdfEvent.events.obdEvents.obdIntermediateEvents.singleComponentEvents.FuelAirEquivalenceRatioEvent import pcdfEvent.events.obdEvents.obdIntermediateEvents.singleComponentEvents.FuelRateEvent import pcdfEvent.events.obdEvents.obdIntermediateEvents.singleComponentEvents.MAFAirFlowRateEvent import pcdfUtilities.ExhaustMassFlowComputation import pcdfUtilities.FuelRateComputation fun PCDFEvent.getNOX(): Int? { return when (this) { is NOXSensorEvent -> this.getNOX() is NOXSensorAlternativeEvent -> this.getNOX() is NOXSensorCorrectedEvent -> this.getNOX() is NOXSensorCorrectedAlternativeEvent -> this.getNOX() else -> null } } fun PCDFEvent.reduce(): PCDFEvent { return when (this) { is NOXSensorEvent -> this.reduce() is NOXSensorAlternativeEvent -> this.reduce() is NOXSensorCorrectedEvent -> this.reduce() is NOXSensorCorrectedAlternativeEvent -> this.reduce() is FuelRateEvent -> this.reduce() is FuelRateMultiEvent -> this.reduce() else -> this } } fun NOXSensorAlternativeEvent.getNOX(): Int? { val allValues = listOf(this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2) val availableValues = allValues.filter { it >= 0 } return availableValues.minOrNull() } fun NOXSensorCorrectedAlternativeEvent.getNOX(): Int? { val allValues = listOf(this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2) val availableValues = allValues.filter { it >= 0 } return availableValues.minOrNull() } fun NOXSensorCorrectedEvent.getNOX(): Int? { val allValues = listOf(this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2) val availableValues = allValues.filter { it >= 0 } return availableValues.minOrNull() } fun NOXSensorEvent.getNOX(): Int? { val allValues = listOf(this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2) val availableValues = allValues.filter { it >= 0 } return availableValues.minOrNull() } fun NOXSensorEvent.reduce(): NOXReducedEvent { return NOXReducedEvent( this.source, this.timestamp, this.bytes, this.pid, this.mode, this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2, ) } fun NOXSensorCorrectedEvent.reduce(): NOXReducedEvent { return NOXReducedEvent( this.source, this.timestamp, this.bytes, this.pid, this.mode, this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2, ) } fun NOXSensorAlternativeEvent.reduce(): NOXReducedEvent { return NOXReducedEvent( this.source, this.timestamp, this.bytes, this.pid, this.mode, this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2, ) } fun NOXSensorCorrectedAlternativeEvent.reduce(): NOXReducedEvent { return NOXReducedEvent( this.source, this.timestamp, this.bytes, this.pid, this.mode, this.sensor1_1, this.sensor1_2, this.sensor2_1, this.sensor2_2, ) } fun MAFSensorEvent.getMassAirFlow(): Double? { val values = listOf(mafSensorA, mafSensorB).filter { it >= 0.0 } return if (values.isEmpty()) { null } else { values.average() } } fun MAFAirFlowRateEvent.getMassAirFlow(): Double? { return if (this.rate >= 0.0) rate else null } fun PCDFEvent.getMassAirFlow(): Double? { return when(this) { is MAFSensorEvent -> this.getMassAirFlow() is MAFAirFlowRateEvent -> this.getMassAirFlow() else -> null } } fun FuelRateMultiEvent.getFuelRate(): Double? { return when { engineFuelRate >= 0.0 -> engineFuelRate / 832.0 * 3600.0 vehicleFuelRate >= 0.0 -> vehicleFuelRate / 832.0 * 3600.0 else -> null } } fun FuelRateEvent.getFuelRate(): Double? { return if (engineFuelRate >= 0.0) engineFuelRate else null } fun PCDFEvent.getFuelRate(): Double? { return when (this) { is FuelRateEvent -> getFuelRate() is FuelRateMultiEvent -> getFuelRate() else -> null } } fun FuelRateMultiEvent.reduce(): FuelRateReducedEvent { return FuelRateReducedEvent( this.source, this.timestamp, this.bytes, this.pid, this.mode, if (this.engineFuelRate != -1.0) { this.engineFuelRate / 832.0 * 3600.0 } else { -1.0 }, if (this.vehicleFuelRate != -1.0) { this.vehicleFuelRate / 832.0 * 3600.0 } else { -1.0 } ) } fun FuelRateEvent.reduce(): FuelRateReducedEvent { return FuelRateReducedEvent( this.source, this.timestamp, this.bytes, this.pid, this.mode, this.engineFuelRate, -1.0, ) } fun PCDFEvent.getFuelAirEquivalenceRatio(): Double? { return if (this is FuelAirEquivalenceRatioEvent) { if (this.ratio >= 0.0) ratio else null } else { null } } //fun FuelRateComputation.ComputedFuelRateEventData.getComputedFuelRate(): Double? { // return this.fuelrate //} fun FuelRateComputation.ComputedFuelRateEvent.getComputedFuelRate(): Double? { return this.fuelRate } fun PCDFEvent.getComputedFuelRate(): Double? { if (this is FuelRateComputation.ComputedFuelRateEvent) { return this.getComputedFuelRate() } else { return null } } fun ExhaustMassFlowComputation.ExhaustMassFlowEvent.getComputedExhaustMassFlow(): Double? { return this.exhaustMassFlow } fun PCDFEvent.getComputedExhaustMassFlow(): Double? { return if (this is ExhaustMassFlowComputation.ExhaustMassFlowEvent) { this.getComputedExhaustMassFlow() } else { null } }
0
Kotlin
0
0
d6d8ada844ac374835f11705103ba3590d6b862e
6,224
pcdf-analyser
MIT License
src/commonMain/kotlin/com.adamratzman.spotify/http/Endpoints.kt
LDuncAndroid
245,807,017
true
{"Kotlin": 532839}
/* Spotify Web API, Kotlin Wrapper; MIT License, 2017-2020; Original author: <NAME> */ package com.adamratzman.spotify.http import com.adamratzman.spotify.SpotifyApi import com.adamratzman.spotify.SpotifyClientApi import com.adamratzman.spotify.SpotifyException import com.adamratzman.spotify.SpotifyException.BadRequestException import com.adamratzman.spotify.SpotifyRestAction import com.adamratzman.spotify.SpotifyRestActionPaging import com.adamratzman.spotify.base import com.adamratzman.spotify.models.AbstractPagingObject import com.adamratzman.spotify.models.ErrorObject import com.adamratzman.spotify.models.ErrorResponse import com.adamratzman.spotify.models.serialization.toObject import com.adamratzman.spotify.utils.ConcurrentHashMap import com.adamratzman.spotify.utils.getCurrentTimeMs import kotlin.math.ceil abstract class SpotifyEndpoint(val api: SpotifyApi<*, *>) { val cache = SpotifyCache() internal val json get() = api.json internal suspend fun get(url: String): String { return execute(url) } internal suspend fun post(url: String, body: String? = null, contentType: String? = null): String { return execute(url, body, HttpRequestMethod.POST, contentType = contentType) } internal suspend fun put(url: String, body: String? = null, contentType: String? = null): String { return execute(url, body, HttpRequestMethod.PUT, contentType = contentType) } internal suspend fun delete( url: String, body: String? = null, contentType: String? = null ): String { return execute(url, body, HttpRequestMethod.DELETE, contentType = contentType) } private suspend fun execute( url: String, body: String? = null, method: HttpRequestMethod = HttpRequestMethod.GET, retry202: Boolean = true, contentType: String? = null, attemptedRefresh: Boolean = false ): String { if (api is SpotifyClientApi && getCurrentTimeMs() >= api.expireTime) { if (!api.automaticRefresh) throw SpotifyException.AuthenticationException("The access token has expired.") else api.refreshToken() } val spotifyRequest = SpotifyRequest(url, method, body, api) val cacheState = if (api.useCache) cache[spotifyRequest] else null if (cacheState?.isStillValid() == true) return cacheState.data else if (cacheState?.let { it.eTag == null } == true) { cache -= spotifyRequest } return try { val document = createConnection(url, body, method, contentType).execute( cacheState?.eTag?.let { listOf(HttpHeader("If-None-Match", it)) } ) handleResponse(document, cacheState, spotifyRequest, retry202) ?: execute( url, body, method, false, contentType ) } catch (e: BadRequestException) { if (e.statusCode?.equals(401) == true && !attemptedRefresh) { execute( url, body, method, retry202, contentType, true ) } else throw e } } private fun handleResponse( document: HttpResponse, cacheState: CacheState?, spotifyRequest: SpotifyRequest, retry202: Boolean ): String? { val statusCode = document.responseCode if (statusCode == HttpConnectionStatus.HTTP_NOT_MODIFIED.code) { requireNotNull(cacheState?.eTag) { "304 status only allowed on Etag-able endpoints" } return cacheState?.data } val responseBody = document.body document.headers.find { it.key.equals("Cache-Control", true) }?.also { cacheControlHeader -> if (api.useCache) { cache[spotifyRequest] = (cacheState ?: CacheState( responseBody, document.headers .find { it.key.equals("ETag", true) }?.value )).update(cacheControlHeader.value) } } if (document.responseCode / 200 != 1 /* Check if status is 2xx or 3xx */) { val response = try { document.body.toObject(ErrorResponse.serializer(), api, json) } catch (e: Exception) { ErrorResponse(ErrorObject(400, "malformed request sent"), e) } throw BadRequestException(response.error) } else if (document.responseCode == 202 && retry202) return null return responseBody } private fun createConnection( url: String, body: String? = null, method: HttpRequestMethod = HttpRequestMethod.GET, contentType: String? = null ) = HttpConnection( url, method, null, body, contentType, listOf(HttpHeader("Authorization", "Bearer ${api.token.accessToken}")), api ) internal fun <T> toAction(supplier: suspend () -> T) = SpotifyRestAction(api, supplier) internal fun <Z : Any, T : AbstractPagingObject<Z>> toActionPaging(supplier: suspend () -> T) = SpotifyRestActionPaging(api, supplier) } internal class EndpointBuilder(private val path: String) { private val builder = StringBuilder(base + path) fun with(key: String, value: Any?): EndpointBuilder { if (value != null && (value !is String || value.isNotEmpty())) { if (builder.toString() == base + path) builder.append("?") else builder.append("&") builder.append(key).append("=").append(value.toString()) } return this } override fun toString() = builder.toString() } class SpotifyCache { val cachedRequests: ConcurrentHashMap<SpotifyRequest, CacheState> = ConcurrentHashMap() internal operator fun get(request: SpotifyRequest): CacheState? { checkCache(request) return cachedRequests[request] } internal operator fun set(request: SpotifyRequest, state: CacheState) { if (request.api.useCache) cachedRequests.put(request, state) checkCache(request) } internal operator fun minusAssign(request: SpotifyRequest) { checkCache(request) cachedRequests.remove(request) } fun clear() = cachedRequests.clear() private fun checkCache(request: SpotifyRequest) { if (!request.api.useCache) clear() else { cachedRequests.entries.removeAll { !it.value.isStillValid() } val cacheLimit = request.api.cacheLimit val cacheUse = cachedRequests.size if (cacheLimit != null && cacheUse > cacheLimit) { val amountRemoveFromEach = ceil((cacheUse - cacheLimit).toDouble() / request.api.endpoints.size).toInt() val entries = cachedRequests.entries val toRemove = entries.sortedBy { it.value.expireBy }.take(amountRemoveFromEach) if (toRemove.isNotEmpty()) entries.removeAll(toRemove) } } } } data class SpotifyRequest( val url: String, val method: HttpRequestMethod, val body: String?, val api: SpotifyApi<*, *> ) data class CacheState(val data: String, val eTag: String?, val expireBy: Long = 0) { private val cacheRegex = "max-age=(\\d+)".toRegex() internal fun isStillValid(): Boolean = getCurrentTimeMs() <= this.expireBy internal fun update(expireBy: String): CacheState { val group = cacheRegex.find(expireBy)?.groupValues val time = group?.getOrNull(1)?.toLongOrNull() ?: throw BadRequestException("Unable to match regex") return this.copy( expireBy = getCurrentTimeMs() + 1000 * time ) } } internal expect fun String.base64ByteEncode(): String internal expect fun String.encodeUrl(): String
0
null
0
0
e02d96cd57cb35fca8ee4e15e135c671b36f47d9
8,043
spotify-web-api-kotlin
MIT License
app/src/main/java/com/example/gymtracker/ui/logHistoryScreen/LogHistoryFragment.kt
EduDA92
595,563,950
false
null
package com.example.gymtracker.ui.logHistoryScreen import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import androidx.paging.LoadState import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.gymtracker.databinding.FragmentLogHistoryBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @AndroidEntryPoint class LogHistoryFragment : Fragment() { private val viewModel: LogHistoryViewModel by viewModels() private var _binding: FragmentLogHistoryBinding? = null private val binding get() = _binding!! private val navigationArgs: LogHistoryFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentLogHistoryBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) /* setting up the topAppBar */ val navController = findNavController() val appBarConfiguration = AppBarConfiguration(navController.graph) binding.topAppBar.setupWithNavController(navController, appBarConfiguration) /*setting up the adapter*/ val adapter = LogHistoryListAdapter() binding.apply { exerciseLogListRV.layoutManager = LinearLayoutManager(this@LogHistoryFragment.context) exerciseLogListRV.adapter = adapter } adapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch{ viewModel.getPagedListOfLogsFromExercise(navigationArgs.exerciseId).collectLatest { adapter.submitData(it) } } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
1
bf47b0af7f4abf6502964d4b1cd966359a61215d
2,707
GymTracker
MIT License
model/src/main/java/org/ligi/kithub/model/GithubIssueCloseEvent.kt
komputing
92,964,439
false
{"Kotlin": 12622}
package org.ligi.kithub.model data class GithubIssueCloseEvent(val action: String, val issue: GithubIssue, val sender: GithubUser, val repository: GithubRepository, val installation: GithubInstallationInfo)
6
Kotlin
2
6
64b29affbe1d3aadde5747e3ad39f6fc90518083
339
Kithub
MIT License
src/main/kotlin/com/teknologiumum/commons/ResponseDTO.kt
teknologi-umum
454,398,376
false
null
package com.teknologiumum.commons import kotlinx.serialization.Serializable @Serializable class ResponseDTO( val success: Boolean, val statusCode: Int, val requestDuration: Long )
0
Kotlin
0
1
2b2e918c76c5ab7dd5a040d0159904143ff7df9d
195
ohana
Apache License 2.0
ktmidi/src/jvmTest/kotlin/dev/atsushieno/ktmidi/MidiReaderWriterTest.kt
atsushieno
340,913,447
false
null
package dev.atsushieno.ktmidi import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals class MidiReaderWriterTest { @Test fun readMusicFromResource() { val music = MidiMusic() val stream = javaClass.getResource("/mugene-fantasy-suite/1-das-stromreiters.mid") music.read(stream.readBytes().toList()) } @Test fun writeMetaText() { val music = MidiMusic() music.deltaTimeSpec = 0x30 music.tracks.add(MidiTrack()) music.tracks[0].messages.addAll(listOf( MidiMessage(0, MidiEvent(0xFF, 3, 0, byteArrayOf(0x41, 0x41, 0x41, 0x41), 0, 4)), MidiMessage(0, MidiEvent(0xFF, 0x2F, 0, byteArrayOf())))) val result = mutableListOf<Byte>() SmfWriter(result).writeMusic(music) val expected = intArrayOf( 'M'.code, 'T'.code, 'h'.code, 'd'.code, 0, 0, 0, 6, 0, 1, 0, 1, 0, 0x30, 'M'.code, 'T'.code, 'r'.code, 'k'.code, 0, 0, 0, 0x0C, 0, 0xFF, 3, 4, 0x41, 0x41, 0x41, 0x41, 0, 0xFF, 0x2F, 0).map { i -> i.toByte() }.toByteArray() val actual = result.toByteArray() assertContentEquals(expected, actual, "test1") } }
9
Kotlin
3
36
787994bd0a0bd9f44ac98b935261ede747c45e21
1,228
ktmidi
MIT License
app/src/main/java/com/example/nifasku/TipsMasaNifas.kt
mochasep
213,590,667
false
null
package com.example.nifasku import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.example.nifasku.deskripsiA.* import kotlinx.android.synthetic.main.content_tips_masa_nifas.* class TipsMasaNifas : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tips_masa_nifas) mobilisasi_diri.setOnClickListener { startActivity(Intent(this, DescMobilisasiDini::class.java)) } nutrisi.setOnClickListener { startActivity(Intent(this, DescNutrisi::class.java)) } kebersihan_diri.setOnClickListener { startActivity(Intent(this, DescKebersihanDiri::class.java)) } istirahat.setOnClickListener { startActivity(Intent(this, DescIstirahat::class.java)) } tanda_bahaya_nifas.setOnClickListener { startActivity(Intent(this, DescTandaBahayaNifas::class.java)) } hal_dihindari.setOnClickListener { startActivity(Intent(this, DescHarusDihindari::class.java)) } senam_nifas.setOnClickListener { startActivity(Intent(this, DescSenamNifas::class.java)) } mengatasi_cemas.setOnClickListener { startActivity(Intent(this, DescMengatasiIbuNifas::class.java)) } } }
0
Kotlin
0
0
837d5ef6d7c2d3d658ab10d31d6a0980756afe1e
1,443
Nifasku
MIT License
app/src/test/java/org/simple/clinic/summary/bloodpressures/BloodPressureSummaryViewUiRendererTest.kt
abhishekvermax
238,414,803
true
{"Kotlin": 3095300, "C": 680052, "Java": 8206, "Shell": 1878, "Makefile": 635}
package org.simple.clinic.summary.bloodpressures import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.verifyZeroInteractions import org.junit.Test import org.simple.clinic.bp.BloodPressureMeasurement import org.simple.clinic.patient.PatientMocker import java.util.UUID class BloodPressureSummaryViewUiRendererTest { private val patientUuid = UUID.fromString("8b298cc4-da11-4df9-a318-01e113f3abe3") private val ui = mock<BloodPressureSummaryViewUi>() private val config = BloodPressureSummaryViewConfig(3) private val uiRenderer = BloodPressureSummaryViewUiRenderer(ui, config) private val defaultModel = BloodPressureSummaryViewModel.create(patientUuid) @Test fun `when blood pressures are loading, then do nothing`() { // when uiRenderer.render(defaultModel) // then verifyZeroInteractions(ui) } @Test fun `when loaded blood pressures are empty, then show no blood pressures view`() { // given val bloodPressures = listOf<BloodPressureMeasurement>() // when uiRenderer.render(defaultModel.bloodPressuresLoaded(bloodPressures)) // then verify(ui).showNoBloodPressuresView() verify(ui).hideSeeAllButton() verifyNoMoreInteractions(ui) } @Test fun `when blood pressures are loaded, then show blood pressures`() { // given val bloodPressure = PatientMocker.bp( uuid = UUID.fromString("58ff9789-c295-41ca-bab3-becb4e9b7861"), patientUuid = patientUuid ) val bloodPressures = listOf(bloodPressure) // when uiRenderer.render(defaultModel.bloodPressuresLoaded(bloodPressures)) // then verify(ui).showBloodPressures(bloodPressures) verify(ui).hideSeeAllButton() verifyNoMoreInteractions(ui) } @Test fun `show see all button if blood pressures count is more than number of blood pressures to display`() { // given val bloodPressure1 = PatientMocker.bp( uuid = UUID.fromString("f0b79c3f-b57d-4c1f-85c9-3c0045412aac"), patientUuid = patientUuid ) val bloodPressure2 = PatientMocker.bp( uuid = UUID.fromString("7057728a-2021-459f-9aa4-d659c0404189"), patientUuid = patientUuid ) val bloodPressure3 = PatientMocker.bp( uuid = UUID.fromString("870c83d7-b554-455d-9289-373eb3de1644"), patientUuid = patientUuid ) val bloodPressure4 = PatientMocker.bp( uuid = UUID.fromString("6c69e196-a3a0-442b-a6ca-d9d20d2cd8c0"), patientUuid = patientUuid ) val bloodPressures = listOf(bloodPressure1, bloodPressure2, bloodPressure3, bloodPressure4) val bloodPressuresCount = bloodPressures.size // when uiRenderer.render( defaultModel .bloodPressuresLoaded(bloodPressures) .bloodPressuresCountLoaded(bloodPressuresCount) ) // then verify(ui).showBloodPressures(bloodPressures) verify(ui).showSeeAllButton() verifyNoMoreInteractions(ui) } @Test fun `hide see all button if there are less than or equal to number of blood pressures to display`() { // given val bloodPressure1 = PatientMocker.bp( uuid = UUID.fromString("462842bc-fd28-4d34-9102-61556e1cb9e0"), patientUuid = patientUuid ) val bloodPressure2 = PatientMocker.bp( uuid = UUID.fromString("aabcfc40-f114-4453-9876-1707f61676db"), patientUuid = patientUuid ) val bloodPressure3 = PatientMocker.bp( uuid = UUID.fromString("0c782d93-c62c-4823-bb70-5e8b355c8b89"), patientUuid = patientUuid ) val bloodPressures = listOf(bloodPressure1, bloodPressure2, bloodPressure3) val bloodPressureCount = bloodPressures.size // when uiRenderer.render( defaultModel .bloodPressuresLoaded(bloodPressures) .bloodPressuresCountLoaded(bloodPressureCount) ) // then verify(ui).showBloodPressures(bloodPressures) verify(ui).hideSeeAllButton() verifyNoMoreInteractions(ui) } }
0
null
0
0
458730f232eab371dd8f3ddaa3d46b1a0a22d8bc
4,080
simple-android
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/gallery/GetAllSceneGalleryInfoRsp.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.gallery import org.anime_game_servers.core.base.Version.GI_1_4_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand import org.anime_game_servers.multi_proto.gi.data.general.Retcode @AddedIn(GI_1_4_0) @ProtoCommand(RESPONSE) internal interface GetAllSceneGalleryInfoRsp { var retcode: Retcode var galleryInfoList: List<SceneGalleryInfo> }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
552
anime-game-multi-proto
MIT License
data/preferences/session/src/commonTest/kotlin/dev/alvr/katana/data/preferences/session/di/module.kt
alvr
446,535,707
false
{"Kotlin": 450399, "Swift": 594}
package dev.alvr.katana.data.preferences.session.di import androidx.datastore.core.DataStoreFactory import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import androidx.datastore.core.okio.OkioStorage import dev.alvr.katana.data.preferences.base.encrypt.PreferencesEncrypt import dev.alvr.katana.data.preferences.session.models.Session import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.random.Random import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import okio.FileSystem import okio.Path import org.koin.core.module.dsl.singleOf import org.koin.core.qualifier.named import org.koin.dsl.bind import org.koin.dsl.module internal expect val fileSystem: FileSystem internal expect fun corruptionHandler(createFile: Path): ReplaceFileCorruptionHandler<Session> private const val DATASTORE = "dataStore" private const val CORRUPTED_DATASTORE = "corruptedDataStore" private const val DATASTORE_FILE = "test_session.pb" private const val CORRUPTED_DATASTORE_FILE = "err_test_session.pb" internal val dataStoreNamed = named(DATASTORE) internal val corruptedDataStoreNamed = named(CORRUPTED_DATASTORE) private val dataStoreFile get() = FileSystem.SYSTEM_TEMPORARY_DIRECTORY.resolve(DATASTORE_FILE) private val corruptedDataStoreFile get() = FileSystem.SYSTEM_TEMPORARY_DIRECTORY.resolve(CORRUPTED_DATASTORE_FILE) @OptIn(ExperimentalCoroutinesApi::class, ExperimentalEncodingApi::class) internal fun testDataStoreModule() = module { singleOf(::FakePreferencesEncrypt) bind PreferencesEncrypt::class single(dataStoreNamed) { DataStoreFactory.create( storage = OkioStorage( fileSystem = fileSystem, producePath = { dataStoreFile }, serializer = Session.serializer(get()), ), scope = TestScope(UnconfinedTestDispatcher()), ) } single(corruptedDataStoreNamed) { val createFile by lazy { fileSystem.write(corruptedDataStoreFile) { writeUtf8(Base64.encode(Random.nextBytes(32))) } corruptedDataStoreFile } DataStoreFactory.create( storage = OkioStorage( fileSystem = fileSystem, producePath = { createFile }, serializer = Session.serializer(get()), ), scope = TestScope(UnconfinedTestDispatcher()), corruptionHandler = corruptionHandler(createFile), ) } } internal fun deleteDataStoreFiles() { with(fileSystem) { delete(path = dataStoreFile, mustExist = false) delete(path = corruptedDataStoreFile, mustExist = false) } }
4
Kotlin
0
52
36977eaf91cef21fce4ac88d7d587a74fbb2ec6c
2,812
katana
Apache License 2.0
app/src/main/java/com/example/joren/partynightplanner/domain/User.kt
JDevbois
156,414,710
false
null
package com.example.joren.partynightplanner.domain data class User(val id: String, val name: String)
0
Kotlin
0
0
d485e7bd84927d7e313702f4a7a7dfb57474846c
101
PartyNightPlanner
MIT License
core/src/main/kotlin/com/github/bkhablenko/outreach/proxx/game/Game.kt
bkhablenko
631,917,403
false
null
package com.github.bkhablenko.outreach.proxx.game import com.github.bkhablenko.outreach.proxx.arrays.Array2D import com.github.bkhablenko.outreach.proxx.exception.GameOverException /** * State of the game. */ class Game(private val board: GameBoard) { var isOver: Boolean = false private set var isLost: Boolean = false private set companion object { fun new(difficulty: GameDifficulty): Game { val board = with(difficulty) { GameBoard.squareShaped(boardSideLength, numBlackHoles) } return Game(board) } } val tiles: Array2D<Tile> get() = board.tiles /** * Reveal a tile on the board and update the game state. */ fun revealTile(i: Int, j: Int) { if (isOver) { throw GameOverException() } val tile = board.revealTile(i, j) when { tile is BlackHoleTile -> { isOver = true isLost = true } board.safeTilesLeft == 0 -> isOver = true } } }
0
Kotlin
0
0
7d0463323280414cde101ed29d7eba0ece76f76f
1,091
outreach-proxx
MIT License
app/src/main/java/com/an/github/datasource/factory/GithubDataFactory.kt
Fenscode
176,228,829
false
null
package com.an.github.datasource.factory import androidx.lifecycle.MutableLiveData import androidx.paging.DataSource import com.an.github.datasource.GithubDataSource import com.an.github.model.Repository class GithubDataFactory: DataSource.Factory<Long, Repository>() { val mutableLiveData: MutableLiveData<GithubDataSource> = MutableLiveData() override fun create(): DataSource<Long, Repository> { var githubDataSource = GithubDataSource() mutableLiveData.postValue(githubDataSource) return githubDataSource } }
0
Kotlin
0
0
8dc6cb8f3d8a187b7d1e6f4d0c63fe8704a337ca
556
GitHub-MVVM-ArchCompoments-Sample
Apache License 2.0
src/test/kotlin/no/nav/pensjon/kalkulator/simulering/client/pen/map/SimuleringMapperTest.kt
navikt
596,104,195
false
{"Kotlin": 405035, "Java": 1630, "Dockerfile": 132}
package no.nav.pensjon.kalkulator.simulering.client.pen.map import no.nav.pensjon.kalkulator.general.Alder import no.nav.pensjon.kalkulator.general.Uttaksgrad import no.nav.pensjon.kalkulator.mock.DateFactory import no.nav.pensjon.kalkulator.mock.PersonFactory.pid import no.nav.pensjon.kalkulator.person.Sivilstand import no.nav.pensjon.kalkulator.simulering.ImpersonalSimuleringSpec import no.nav.pensjon.kalkulator.simulering.PersonalSimuleringSpec import no.nav.pensjon.kalkulator.simulering.SimuleringType import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.LocalDate import java.util.* class SimuleringMapperTest { @Test fun `toDto maps sivilstand, simuleringstype, dato to PEN values`() { with(SimuleringMapper.toDto(impersonalSpec(), personalSpec())) { assertEquals("UGIF", sivilstand) assertEquals("ALDER", simuleringstype) assertEquals(DateFactory.date(2030, Calendar.MARCH), forsteUttaksdato) } } private companion object { private fun impersonalSpec() = ImpersonalSimuleringSpec( simuleringType = SimuleringType.ALDERSPENSJON, uttaksgrad = Uttaksgrad.HUNDRE_PROSENT, foersteUttaksalder = Alder(67, 1), foedselsdato = LocalDate.of(1963, 1, 1), epsHarInntektOver2G = true ) private fun personalSpec() = PersonalSimuleringSpec( pid = pid, forventetInntekt = 100_000, sivilstand = Sivilstand.UGIFT ) } }
0
Kotlin
0
0
66132839e1da3a162eb78e8ad4bf842ced680995
1,633
pensjonskalkulator-backend
MIT License
src/main/kotlin/no/nav/yrkesskade/meldingmottak/services/ArbeidsfordelingService.kt
navikt
413,400,372
false
null
package no.nav.yrkesskade.meldingmottak.services import com.expediagroup.graphql.generated.enums.AdressebeskyttelseGradering import com.expediagroup.graphql.generated.hentperson.Adressebeskyttelse import com.expediagroup.graphql.generated.hentperson.Person import no.nav.familie.kontrakter.felles.arbeidsfordeling.Enhet import no.nav.yrkesskade.meldingmottak.clients.arbeidsfordeling.ArbeidsfordelingClient import no.nav.yrkesskade.meldingmottak.clients.arbeidsfordeling.ArbeidsfordelingKriterie import no.nav.yrkesskade.meldingmottak.clients.graphql.PdlClient import no.nav.yrkesskade.meldingmottak.clients.tilgang.SkjermedePersonerClient import no.nav.yrkesskade.meldingmottak.clients.tilgang.SkjermetPersonRequest import no.nav.yrkesskade.meldingmottak.util.getSecureLogger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class ArbeidsfordelingService( private val arbeidsfordelingClient: ArbeidsfordelingClient, private val pdlClient: PdlClient, private val skjermedePersonerClient: SkjermedePersonerClient ) { companion object { const val KODE_6_STRENGT_FORTROLIG = "SPSF" const val KODE_7_FORTROLIG = "SPFO" @Suppress("JAVA_CLASS_ON_COMPANION") private val log = LoggerFactory.getLogger(javaClass.enclosingClass) private val secureLogger = getSecureLogger() } fun finnBehandlendeEnhetForPerson(foedselsnummer: String): Enhet { val person = pdlClient.hentPerson(foedselsnummer) if (person == null) { secureLogger.error("Fant ikke personen med fødselsnummer $foedselsnummer i pdl.") throw RuntimeException("Fant ikke personen i pdl. Se secure log.") } val arbeidsfordelingskriterie = ArbeidsfordelingKriterie( tema = "YRK", geografiskOmraade = geografiskOmraade(person), diskresjonskode = diskresjonskode(person), skjermet = skjermet(foedselsnummer) ) val response = arbeidsfordelingClient.finnBehandlendeEnhetMedBesteMatch(arbeidsfordelingskriterie) val enhet = response.enheter.firstOrNull() return Enhet( enhetId = enhet?.enhetNr ?: "9999", enhetNavn = enhet?.navn ?: "" ) } internal fun geografiskOmraade(person: Person): String? { return person.bostedsadresse.firstOrNull()?.vegadresse?.kommunenummer } internal fun diskresjonskode(person: Person): String? { if (erKode7Fortrolig(person)) { return KODE_7_FORTROLIG } else if (erKode6StrengtFortrolig(person)) { return KODE_6_STRENGT_FORTROLIG } return null } internal fun skjermet(foedselsnummer: String): Boolean { val request = SkjermetPersonRequest(foedselsnummer) return skjermedePersonerClient.erSkjermet(request) } private fun erKode7Fortrolig(person: Person): Boolean { return person.adressebeskyttelse.contains(Adressebeskyttelse(AdressebeskyttelseGradering.FORTROLIG)) } private fun erKode6StrengtFortrolig(person: Person): Boolean { return (person.adressebeskyttelse.contains(Adressebeskyttelse(AdressebeskyttelseGradering.STRENGT_FORTROLIG)) || person.adressebeskyttelse.contains(Adressebeskyttelse(AdressebeskyttelseGradering.STRENGT_FORTROLIG_UTLAND))) } }
1
Kotlin
0
0
6ab936e3d9b2bd55f559bdc282009aada1bd10ca
3,378
yrkesskade-melding-mottak
MIT License
app/src/main/java/com/masterplus/trdictionary/core/shared_features/select_list/list_menu_dia/SelectListMenuState.kt
Ramazan713
634,957,286
false
{"Kotlin": 1110654}
package com.masterplus.trdictionary.core.shared_features.select_list.list_menu_dia import com.masterplus.trdictionary.core.shared_features.select_list.constants.SelectListMenuEnum data class SelectListMenuState( val listMenuItems: List<SelectListMenuEnum> = emptyList(), val isFavorite: Boolean = false, val isAddedToList: Boolean = false, val listIdControl: Int? = null, val showDialog: Boolean = false, val dialogEvent: SelectListMenuDialogEvent? = null )
0
Kotlin
0
1
5c096081d631a769ba3a6390c298611c70295ccc
484
Turkce-ve-Osmanlica-Sozluk
Apache License 2.0
BluetoothLowEnergyLibrary/src/main/java/com/sscl/bluetoothlowenergylibrary/enums/BleConnectTransport.kt
JackiePenghe
576,202,844
false
null
package com.sscl.bluetoothlowenergylibrary.enums import androidx.annotation.RequiresApi import android.os.Build import android.bluetooth.BluetoothDevice /** * GATT 连接到远程双模设备的首选传输方式 * * [BluetoothDevice.TRANSPORT_AUTO] * [BluetoothDevice.TRANSPORT_BREDR] * [BluetoothDevice.TRANSPORT_LE] * * @author pengh */ @RequiresApi(Build.VERSION_CODES.M) enum class BleConnectTransport(val value: Int) { /** * 不设置偏好,由系统自动处理 */ TRANSPORT_AUTO(BluetoothDevice.TRANSPORT_AUTO), /** * 首选 BR/EDR 传输 */ TRANSPORT_BR_EDR(BluetoothDevice.TRANSPORT_BREDR), /** * 首选 LE 传输 */ TRANSPORT_LE(BluetoothDevice.TRANSPORT_LE); }
0
Kotlin
0
0
629d489e6f6c94afd66c9c84184fbea819b08bd7
667
ble-library-for-kotlin
Apache License 2.0
kludge-api/src/main/kotlin/kludge/api/transform/BaseTransform.kt
Zhupff
374,409,210
false
null
package kludge.api.transform import com.android.build.api.transform.* import com.android.build.gradle.internal.pipeline.TransformManager import com.android.utils.FileUtils import kludge.api.common.Logln import kludge.api.common.i /** * Author: Zhupf * Description: transform 处理流程基类。 */ abstract class BaseTransform( protected val transformers: List<ClassTransformer> = emptyList()) : Transform() { override fun getName(): String = javaClass.simpleName override fun isIncremental(): Boolean = true override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> = TransformManager.CONTENT_CLASS override fun transform(transformInvocation: TransformInvocation?) { super.transform(transformInvocation) transformInvocation?.let { invocation -> val context = TransformContext(invocation) invocation.outputProvider?.let { outputProvider -> if (context.isIncremental) { outputProvider.deleteAll() } onTransformStart(context) handleTransformInvocation(transformInvocation, outputProvider, context) onTransformFinish(context) } } } private var transformStartTime: Long = 0L protected open fun onTransformStart(context: TransformContext) { transformStartTime = System.currentTimeMillis() Logln.min("${i(name)} onTransformStart, isIncremental=${i(context.isIncremental)}") transformers.forEach { it.onTransformStart(context) } } private var transformFinishTime: Long = 0L protected open fun onTransformFinish(context: TransformContext) { transformers.forEach { it.onTransformFinish(context) } transformFinishTime = System.currentTimeMillis() Logln.min("${i(name)} onTransformFinish, duration=${i(transformFinishTime - transformStartTime)}") } protected open fun handleTransformInvocation(transformInvocation: TransformInvocation, outputProvider: TransformOutputProvider, context: TransformContext) { transformInvocation.inputs.forEach { input -> input.directoryInputs.forEach { handleDirInput(it, outputProvider, context) } input.jarInputs.forEach { handleJarInput(it, outputProvider, context) } } } protected open fun handleDirInput(input: DirectoryInput, outputProvider: TransformOutputProvider, context: TransformContext) { FileUtils.copyDirectory(input.file, outputProvider .getContentLocation(input.name, input.contentTypes, input.scopes, Format.DIRECTORY)) } protected open fun handleJarInput(input: JarInput, outputProvider: TransformOutputProvider, context: TransformContext) { FileUtils.copyFile(input.file, outputProvider .getContentLocation(input.name, input.contentTypes, input.scopes, Format.JAR)) } protected open fun handleDirClass(className: String, classBytes: ByteArray): ByteArray { var bytes = classBytes transformers.forEach { bytes = it.handleDirClass(className, classBytes) } return bytes } protected open fun handleJarClass(className: String, classBytes: ByteArray): ByteArray { var bytes = classBytes transformers.forEach { bytes = it.handleJarClass(className, classBytes) } return bytes } }
0
Kotlin
0
0
d5b5eb3c94733625c3c9dddb2473960ccc9667eb
3,356
kludges
Apache License 2.0
application/src/main/kotlin/business/textCustomization.kt
JingfeiPeng
490,572,392
false
null
package business import androidx.compose.runtime.MutableState import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.getSelectedText import androidx.compose.ui.text.input.getTextAfterSelection import androidx.compose.ui.text.input.getTextBeforeSelection class TextCustomization { companion object { fun appendAroundSelected( textState: MutableState<TextFieldValue>, frontChars: String, backChars: String, ) { val beforeSelection = textState.value.getTextBeforeSelection(Int.MAX_VALUE) val selectedText = textState.value.getSelectedText() val afterSelection = textState.value.getTextAfterSelection( textState.value.text.length - beforeSelection.length - selectedText.length ) if (beforeSelection.text.takeLast(frontChars.length) == frontChars && afterSelection.text.take(backChars.length) == backChars) { // undo previous text customization textState.value = TextFieldValue( "${beforeSelection.substring(0, beforeSelection.length-frontChars.length)}" + "$selectedText" + "${afterSelection.substring(backChars.length)}", TextRange( beforeSelection.length-frontChars.length, beforeSelection.length-frontChars.length+selectedText.length ) ) } else { // append the chars around the selected text and set selection textState.value = TextFieldValue( "$beforeSelection$frontChars$selectedText$backChars$afterSelection", TextRange( beforeSelection.length+frontChars.length, beforeSelection.length+frontChars.length+selectedText.length ) ) } } fun appendAroundSelected( textState: MutableState<TextFieldValue>, chars: String, ) { appendAroundSelected(textState, chars, chars) } fun insertImageTag( textState: MutableState<TextFieldValue>, imagePath: String, ) { val beforeSelection = textState.value.getTextBeforeSelection(Int.MAX_VALUE) val selectedText = textState.value.getSelectedText() val afterSelection = textState.value.getTextAfterSelection( textState.value.text.length - beforeSelection.length - selectedText.length ) // Alternatively: ![alt text](maxresdefault.jpg "Title") val imgInsert = "<img src=\"file:$imagePath\">" textState.value = TextFieldValue( "$beforeSelection$selectedText$imgInsert$afterSelection", TextRange(beforeSelection.length+imgInsert.length) ) } } }
0
Kotlin
1
0
34828da38f92baf48c73ae7a8343b803e8ad9e97
3,061
NoteDown
MIT License
app/src/main/java/com/krykun/movieapp/feature/person/view/EmptyView.kt
JekaK
508,341,591
false
{"Kotlin": 470505}
package com.krykun.movieapp.feature.person.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.krykun.movieapp.R @Composable fun EmptyView() { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.empty_state)) LottieAnimation( composition = composition, iterations = LottieConstants.IterateForever, modifier = Modifier.size(150.dp) ) Text( text = stringResource(R.string.nothing_to_show), color = Color.White, fontSize = 24.sp, fontWeight = FontWeight.Bold ) } }
0
Kotlin
0
7
b46b296c16e23a6394e382a7d30b34176d443d90
1,470
MoviesApp
Apache License 2.0
Android/BLUR/domain/src/main/java/com/blur/blur/domain/usecase/main/home/SendMessage/GetMessageUseCase.kt
kim-do-hyeon
752,461,840
false
{"Kotlin": 365399, "Swift": 75215, "Python": 66512, "JavaScript": 41759, "CSS": 6957, "HTML": 2674, "Shell": 176}
package com.blur.blur.domain.usecase.main.home.SendMessage interface GetMessageUseCase { suspend operator fun invoke( username:String, ): Result<String> }
0
Kotlin
2
6
f350b6d1bc1a7630cb787107713ed47f50a7e84b
172
2024-jj-capstone-design
MIT License
app/src/main/java/org/mixitconf/model/dao/TalkDao.kt
mixitconf
123,981,169
false
null
package org.mixitconf.model.dao import androidx.room.* import org.mixitconf.model.entity.Talk @Dao interface TalkDao { @Insert fun create(talk: Talk) @Query("select * from Talk") fun readAll(): List<Talk> @Query("select * from Talk where speakerIds like '%' || :id || '%'") fun readAllBySpeakerId(id: String): List<Talk> @Query("select * from Talk where id=:id") fun readOne(id: String): Talk? @Update fun update(talk: Talk) @Delete fun delete(talk: Talk) @Query("delete from Talk") fun deleteAll() @Query("delete from Talk where id in (:ids)") fun deleteAllById(ids: List<String>) }
1
Kotlin
1
2
ba39fdb7f0767c112fff91e888a0dc86b3fa8c40
657
mixit-android
Apache License 2.0
langsmith-java-core/src/main/kotlin/com/langsmith/api/models/AnnotationQueueSchema.kt
langchain-ai
774,515,765
false
{"Kotlin": 2288977, "Shell": 1314, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. package com.langsmith.api.models import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.langsmith.api.core.ExcludeMissing import com.langsmith.api.core.JsonField import com.langsmith.api.core.JsonMissing import com.langsmith.api.core.JsonValue import com.langsmith.api.core.NoAutoDetect import com.langsmith.api.core.toUnmodifiable import java.time.OffsetDateTime import java.util.Objects import java.util.Optional /** AnnotationQueue schema. */ @JsonDeserialize(builder = AnnotationQueueSchema.Builder::class) @NoAutoDetect class AnnotationQueueSchema private constructor( private val name: JsonField<String>, private val description: JsonField<String>, private val createdAt: JsonField<OffsetDateTime>, private val updatedAt: JsonField<OffsetDateTime>, private val id: JsonField<String>, private val tenantId: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 fun name(): String = name.getRequired("name") fun description(): Optional<String> = Optional.ofNullable(description.getNullable("description")) fun createdAt(): Optional<OffsetDateTime> = Optional.ofNullable(createdAt.getNullable("created_at")) fun updatedAt(): Optional<OffsetDateTime> = Optional.ofNullable(updatedAt.getNullable("updated_at")) fun id(): String = id.getRequired("id") fun tenantId(): String = tenantId.getRequired("tenant_id") @JsonProperty("name") @ExcludeMissing fun _name() = name @JsonProperty("description") @ExcludeMissing fun _description() = description @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt() = updatedAt @JsonProperty("id") @ExcludeMissing fun _id() = id @JsonProperty("tenant_id") @ExcludeMissing fun _tenantId() = tenantId @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): AnnotationQueueSchema = apply { if (!validated) { name() description() createdAt() updatedAt() id() tenantId() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is AnnotationQueueSchema && this.name == other.name && this.description == other.description && this.createdAt == other.createdAt && this.updatedAt == other.updatedAt && this.id == other.id && this.tenantId == other.tenantId && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( name, description, createdAt, updatedAt, id, tenantId, additionalProperties, ) } return hashCode } override fun toString() = "AnnotationQueueSchema{name=$name, description=$description, createdAt=$createdAt, updatedAt=$updatedAt, id=$id, tenantId=$tenantId, additionalProperties=$additionalProperties}" companion object { @JvmStatic fun builder() = Builder() } class Builder { private var name: JsonField<String> = JsonMissing.of() private var description: JsonField<String> = JsonMissing.of() private var createdAt: JsonField<OffsetDateTime> = JsonMissing.of() private var updatedAt: JsonField<OffsetDateTime> = JsonMissing.of() private var id: JsonField<String> = JsonMissing.of() private var tenantId: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() @JvmSynthetic internal fun from(annotationQueueSchema: AnnotationQueueSchema) = apply { this.name = annotationQueueSchema.name this.description = annotationQueueSchema.description this.createdAt = annotationQueueSchema.createdAt this.updatedAt = annotationQueueSchema.updatedAt this.id = annotationQueueSchema.id this.tenantId = annotationQueueSchema.tenantId additionalProperties(annotationQueueSchema.additionalProperties) } fun name(name: String) = name(JsonField.of(name)) @JsonProperty("name") @ExcludeMissing fun name(name: JsonField<String>) = apply { this.name = name } fun description(description: String) = description(JsonField.of(description)) @JsonProperty("description") @ExcludeMissing fun description(description: JsonField<String>) = apply { this.description = description } fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) @JsonProperty("created_at") @ExcludeMissing fun createdAt(createdAt: JsonField<OffsetDateTime>) = apply { this.createdAt = createdAt } fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) @JsonProperty("updated_at") @ExcludeMissing fun updatedAt(updatedAt: JsonField<OffsetDateTime>) = apply { this.updatedAt = updatedAt } fun id(id: String) = id(JsonField.of(id)) @JsonProperty("id") @ExcludeMissing fun id(id: JsonField<String>) = apply { this.id = id } fun tenantId(tenantId: String) = tenantId(JsonField.of(tenantId)) @JsonProperty("tenant_id") @ExcludeMissing fun tenantId(tenantId: JsonField<String>) = apply { this.tenantId = tenantId } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): AnnotationQueueSchema = AnnotationQueueSchema( name, description, createdAt, updatedAt, id, tenantId, additionalProperties.toUnmodifiable(), ) } }
1
Kotlin
0
2
922058acd6e168f6e1db8d9e67a24850ab7e93a0
7,003
langsmith-java
Apache License 2.0
src/Day12.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
import java.util.LinkedList fun main() { fun toKey(x: Int, y: Int) = x * 10000 + y fun toCord(key: Int) = key / 10000 to key % 10000 fun shortestPath(grid: Array<CharArray>, edgeMap: Map<Int, MutableSet<Int>>, sx: Int, sy: Int, tx: Int, ty: Int): Int { val m = grid.size val n = grid[0].size val ans = Array(m) { Array(n) { Int.MAX_VALUE } } ans[sx][sy] = 0 val sKey = toKey(sx, sy) val Q = LinkedList<Int>() val inQ = mutableSetOf<Int>() Q += sKey inQ += sKey while (Q.isNotEmpty()) { val top = Q.poll() inQ.remove(top) val (ax, ay) = toCord(top) val edges = edgeMap[top] ?: emptySet() for (b in edges) { val (bx, by) = toCord(b) if (ans[bx][by] > ans[ax][ay] + 1) { ans[bx][by] = ans[ax][ay] + 1 if (b !in inQ) { inQ += b Q += b } } } } return ans[tx][ty] } fun getSourceAndDest(grid: Array<CharArray>): List<Int> { var (sx, sy, tx, ty) = listOf(0, 0, 0, 0) for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 'S') { grid[i][j] = 'a' sx = i sy = j } if (grid[i][j] == 'E') { grid[i][j] = 'z' tx = i ty = j } } } return listOf(sx, sy, tx, ty) } fun getEdgeMap(grid: Array<CharArray>): Map<Int, MutableSet<Int>> { val dx = listOf(0, 0, 1, -1) val dy = listOf(1, -1, 0, 0) val edgeMap = mutableMapOf<Int, MutableSet<Int>>() for (i in grid.indices) { for (j in grid[0].indices) { for (k in dx.indices) { val zx = i + dx[k] val zy = j + dy[k] if (zx !in grid.indices || zy !in grid[0].indices) continue if (grid[zx][zy] - grid[i][j] > 1) continue val aKey = toKey(i, j) val bKey = toKey(zx, zy) edgeMap.getOrPut(aKey) { mutableSetOf() } += bKey } } } return edgeMap } fun part1(input: List<String>): Int { val grid = input.map { it.toCharArray() }.toTypedArray() val (sx, sy, tx, ty) = getSourceAndDest(grid) val edgeMap = getEdgeMap(grid) return shortestPath(grid, edgeMap, sx, sy, tx, ty) } fun part2(input: List<String>): Int { val grid = input.map { it.toCharArray() }.toTypedArray() val (_, _, tx, ty) = getSourceAndDest(grid) val edgeMap = getEdgeMap(grid) var ans = Int.MAX_VALUE for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 'a') { ans = minOf(ans, shortestPath(grid, edgeMap, i, j, tx, ty)) } } } return ans } println(part1(readInput("data/Day12_test"))) println(part1(readInput("data/Day12"))) println(part2(readInput("data/Day12_test"))) println(part2(readInput("data/Day12"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
2,888
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/between_freedom_and_space/mono_backend/popular/service/model/PopularPeriod.kt
Between-Freedom-and-Space
453,797,438
false
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
package com.between_freedom_and_space.mono_backend.popular.service.model enum class PopularPeriod { HOUR, DAY, WEEK, MONTH; }
0
Kotlin
0
1
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
142
Mono-Backend
Apache License 2.0
My_Jetpack/app/src/main/java/com/laioffer/my_jetpack/lesson1_lifecycle/tools/Utils.kt
yuanuscfighton
557,023,117
false
null
package com.laioffer.my_jetpack.lesson1_lifecycle.tools import android.util.Log /** * @description lifecycle工具类 * @date 2022/10/31 10:54 下午 */ object Utils { private const val TAG = "[l1-lifecycle] " fun logMessage(tag: String, message: String) { Log.e(TAG, tag + message) } }
0
Kotlin
0
0
7b8e3cf83a0f815fdbe6412f8ed1d356fa1c8f3c
300
nice-android-job
MIT License
android/app/src/main/java/com/emergetools/hackernews/features/login/LoginScreen.kt
EmergeTools
682,684,464
false
{"Kotlin": 174590, "Swift": 30430, "Ruby": 5422}
package com.emergetools.hackernews.features.login import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Close import androidx.compose.material.icons.rounded.Warning import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import com.emergetools.hackernews.ui.preview.AppStoreSnapshot import com.emergetools.hackernews.ui.preview.SnapshotPreview import com.emergetools.hackernews.ui.theme.HackerNewsTheme import com.emergetools.hackernews.ui.theme.HackerRed import com.emergetools.snapshots.annotations.EmergeAppStoreSnapshot @Composable fun LoginScreen( state: LoginState, actions: (LoginAction) -> Unit, navigation: (LoginNavigation) -> Unit ) { LaunchedEffect(state.status) { if (state.status == LoginStatus.Success) { navigation(LoginNavigation.Dismiss) } } Box( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colorScheme.background) ) { IconButton( onClick = { navigation(LoginNavigation.Dismiss) } ) { Icon( imageVector = Icons.Rounded.Close, tint = MaterialTheme.colorScheme.onBackground, contentDescription = "Close" ) } Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy( space = 16.dp, alignment = Alignment.CenterVertically ), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Login", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground, ) TextField( value = state.username, shape = RoundedCornerShape(8.dp), colors = TextFieldDefaults.colors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next ), placeholder = { Text("Username") }, trailingIcon = { if (state.status == LoginStatus.Failed) { Icon( imageVector = Icons.Rounded.Warning, tint = HackerRed, contentDescription = "Failed" ) } }, onValueChange = { actions(LoginAction.UsernameUpdated(it)) } ) TextField( value = state.password, shape = RoundedCornerShape(8.dp), colors = TextFieldDefaults.colors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), placeholder = { Text("Password") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ), visualTransformation = PasswordVisualTransformation(), trailingIcon = { if (state.status == LoginStatus.Failed) { Icon( imageVector = Icons.Rounded.Warning, tint = HackerRed, contentDescription = "Failed" ) } }, onValueChange = { actions(LoginAction.PasswordUpdated(it)) } ) Button( colors = ButtonDefaults.buttonColors( contentColor = MaterialTheme.colorScheme.onBackground ), onClick = { actions(LoginAction.LoginSubmit) } ) { Text( text = "Submit", style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold ) } } } } @OptIn(EmergeAppStoreSnapshot::class) @SnapshotPreview @AppStoreSnapshot @Composable private fun LoginScreenPreview() { HackerNewsTheme { LoginScreen( state = LoginState(), actions = {}, navigation = {} ) } }
16
Kotlin
8
72
2cc224a3ee355f4b0044bbae74b20b6a3f820dd7
4,932
hackernews
MIT License
src/main/kotlin/days/Day06.kt
julia-kim
435,257,054
false
{"Kotlin": 15771}
package days import readInput fun main() { fun part1(input: List<String>): Long { val school = input[0].split(",").map { it.toInt() }.toMutableList() var iterator: MutableListIterator<Int> var days = 80 while (days > 0) { iterator = school.listIterator() while (iterator.hasNext()) { val lanternfish = iterator.next() if (lanternfish == 0) { iterator.set(6); iterator.add(8) } else { iterator.set(lanternfish - 1) } } days-- } return school.size.toLong() } fun part2(input: List<String>): Long { return 0L } val testInput = readInput("Day06_test") check(part1(testInput) == 5934L) // check(part2(testInput) == 26984457539L) val input = readInput("Day06") println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
5febe0d5b9464738f9a7523c0e1d21bd992b9302
954
advent-of-code-2021
Apache License 2.0
app/src/main/java/xyz/daijoubuteam/foodshoppingappadmin/ui/orders/adapter/OrderAdapter.kt
phuquang147
491,842,785
false
{"Kotlin": 121240}
package xyz.daijoubuteam.foodshoppingappadmin.ui.orders.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_order.view.* import xyz.daijoubuteam.foodshoppingappadmin.R import xyz.daijoubuteam.foodshoppingappadmin.databinding.ItemOrderBinding import xyz.daijoubuteam.foodshoppingappadmin.model.Order class OrderAdapter(private val onClickListener: OnClickListener) : ListAdapter<Order, OrderAdapter.OrderViewHolder>(DiffCallBack) { class OrderViewHolder(private var binding: ItemOrderBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(order: Order) { binding.order = order } } companion object DiffCallBack : DiffUtil.ItemCallback<Order>() { override fun areItemsTheSame(oldItem: Order, newItem: Order): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: Order, newItem: Order): Boolean { return oldItem.id == newItem.id } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderViewHolder { val binding = ItemOrderBinding.inflate(LayoutInflater.from(parent.context), parent, false) return OrderViewHolder(binding) } override fun onBindViewHolder(holder: OrderViewHolder, position: Int) { val orderItem = getItem(position) holder.itemView.setOnClickListener { onClickListener.onClick(orderItem) } when (orderItem.status) { "Preparing" -> holder.itemView.imageStatus.setImageResource(R.drawable.preparing) "Shipping" -> holder.itemView.imageStatus.setImageResource(R.drawable.shipping) "Completed" -> holder.itemView.imageStatus.setImageResource(R.drawable.completed) "Cancelled" -> holder.itemView.imageStatus.setImageResource(R.drawable.close_button) else -> holder.itemView.imageStatus.setImageResource(R.drawable.pending) } holder.bind(orderItem) } class OnClickListener(val clickListener: (order: Order) -> Unit) { fun onClick(order: Order) = clickListener(order) } }
0
Kotlin
0
0
cb429e624c42cfea866e4c4fc5f716e0da37ae3f
2,321
FoodShoppingAppAdmin
MIT License
Desktop/src/jvmMain/kotlin/io/nacular/doodle/theme/native/NativeSliderBehavior.kt
nacular
108,631,782
false
{"Kotlin": 3150677}
package io.nacular.doodle.theme.native import io.nacular.doodle.controls.range.Slider import io.nacular.doodle.controls.theme.range.SliderBehavior import io.nacular.doodle.core.View import io.nacular.doodle.drawing.Canvas import io.nacular.doodle.drawing.impl.CanvasImpl import io.nacular.doodle.event.PointerEvent import io.nacular.doodle.focus.FocusManager import io.nacular.doodle.geometry.Rectangle import io.nacular.doodle.geometry.Size import io.nacular.doodle.system.Cursor import io.nacular.doodle.system.Cursor.Companion.Default import io.nacular.doodle.theme.native.NativeTheme.WindowDiscovery import io.nacular.doodle.utils.Orientation import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.awt.Dimension import java.awt.event.FocusEvent import java.awt.event.FocusListener import java.awt.event.MouseEvent import java.awt.event.MouseEvent.MOUSE_DRAGGED import java.awt.event.MouseEvent.MOUSE_MOVED import javax.swing.BoundedRangeModel import javax.swing.JSlider import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener import kotlin.coroutines.CoroutineContext import kotlin.math.pow internal class NativeSliderBehavior<T>( private val appScope : CoroutineScope, private val uiDispatcher : CoroutineContext, private val window : WindowDiscovery, private val swingGraphicsFactory : SwingGraphicsFactory, private val focusManager : FocusManager?, private val nativePointerPreprocessor: NativePointerPreprocessor? ): SliderBehavior<T> where T: Number, T: Comparable<T> { private inner class ModelAdapter<T>( private val delegate: Slider<T>, precision: Int, private val setValue: (Slider<T>, Double) -> Unit, private val setRange: (Slider<T>, ClosedRange<Double>) -> Unit ): BoundedRangeModel where T: Number, T: Comparable<T> { private val listeners = mutableListOf<ChangeListener>() private val multiplier = 10.0.pow(precision.toDouble()) private var valueAdjusting = false fun notifyChanged() { val event = ChangeEvent(this) listeners.forEach { it.stateChanged(event) } } override fun getMinimum() = (delegate.range.start.toDouble() * multiplier).toInt() override fun setMinimum(newMinimum: Int) { setRange(delegate, newMinimum / multiplier .. delegate.range.endInclusive.toDouble()) } override fun getMaximum() = (delegate.range.endInclusive.toDouble() * multiplier).toInt() override fun setMaximum(newMaximum: Int) { setRange(delegate, delegate.range.start.toDouble() .. newMaximum / multiplier) } override fun getValue() = (delegate.value.toDouble() * multiplier).toInt() override fun setValue(newValue: Int) { setValue(delegate, newValue / multiplier) } override fun setValueIsAdjusting(b: Boolean) { valueAdjusting = b } override fun getValueIsAdjusting() = valueAdjusting override fun getExtent() = 0 override fun setExtent(newExtent: Int) { // no-op } override fun setRangeProperties(value: Int, extent: Int, min: Int, max: Int, adjusting: Boolean) { minimum = min maximum = max setValue (value ) setExtent(extent) valueAdjusting = adjusting } override fun addChangeListener(listener: ChangeListener) { listeners += listener } override fun removeChangeListener(listener: ChangeListener) { listeners -= listener } } private open inner class DoubleSlider<T>( slider: Slider<T>, precision: Int = 2, setValue: (Slider<T>, Double) -> Unit, setRange: (Slider<T>, ClosedRange<Double>) -> Unit, val model: ModelAdapter<T> = ModelAdapter(slider, precision, setValue, setRange) ): JSlider(model) where T: Number, T: Comparable<T> { init { this.orientation = when (slider.orientation) { Orientation.Vertical -> VERTICAL else -> HORIZONTAL } } fun notifyChange() { model.notifyChanged() } } private inner class JSliderPeer(slider: Slider<T>): DoubleSlider<T>(slider, setValue = { s,d -> s.set(d) }, setRange = { s,r -> s.set(r) }) { private val slider: Slider<T>? = slider init { focusTraversalKeysEnabled = false addFocusListener(object: FocusListener { override fun focusGained(e: FocusEvent?) { focusManager?.requestFocus(slider) } override fun focusLost(e: FocusEvent?) { focusManager?.clearFocus() } }) } override fun repaint(tm: Long, x: Int, y: Int, width: Int, height: Int) { slider?.rerender() } public fun handleMouseEvent(e: MouseEvent) = when (e.id) { MOUSE_MOVED, MOUSE_DRAGGED -> super.processMouseMotionEvent(e) else -> super.processMouseEvent(e) } } private lateinit var nativePeer : JSliderPeer private var oldCursor : Cursor? = null private var oldIdealSize : Size? = null private val focusChanged: (View, Boolean, Boolean) -> Unit = { _,_,new -> when (new) { true -> nativePeer.requestFocusInWindow() else -> nativePeer.transferFocus () } } private val enabledChanged: (View, Boolean, Boolean) -> Unit = { _,_,new -> nativePeer.isEnabled = new } private val focusableChanged: (View, Boolean, Boolean) -> Unit = { _,_,new -> nativePeer.isFocusable = new } private val boundsChanged: (View, Rectangle, Rectangle) -> Unit = { _,_,new -> nativePeer.size = new.size.run { Dimension(width.toInt(), height.toInt()) } } private val changeListener : (Slider<T>, T, T ) -> Unit = { _,_,_ -> nativePeer.notifyChange() } private val limitsChangeListener: (Slider<T>, ClosedRange<T>, ClosedRange<T>) -> Unit = { _,_,_ -> nativePeer.notifyChange() } override fun render(view: Slider<T>, canvas: Canvas) { nativePeer.paint(swingGraphicsFactory((canvas as CanvasImpl).skiaCanvas)) } override fun install(view: Slider<T>) { super.install(view) nativePeer = JSliderPeer(view) nativePointerPreprocessor?.set(view, object: NativePointerHandler { override fun invoke(event: PointerEvent) { if (event.source == view) { nativePeer.handleMouseEvent(event.toAwt(nativePeer)) } } }) view.apply { focusChanged += this@NativeSliderBehavior.focusChanged boundsChanged += this@NativeSliderBehavior.boundsChanged enabledChanged += this@NativeSliderBehavior.enabledChanged focusabilityChanged += this@NativeSliderBehavior.focusableChanged changed += this@NativeSliderBehavior.changeListener limitsChanged += this@NativeSliderBehavior.limitsChangeListener } appScope.launch(uiDispatcher) { nativePeer.size = view.size.run { Dimension(view.width.toInt(), view.height.toInt()) } view.apply { cursor = Default idealSize = nativePeer.preferredSize.run { Size(width, height) } } window.frameFor(view)?.add(nativePeer) if (view.hasFocus) { nativePeer.requestFocusInWindow() } } } override fun uninstall(view: Slider<T>) { super.uninstall(view) view.apply { cursor = oldCursor idealSize = oldIdealSize focusChanged -= this@NativeSliderBehavior.focusChanged boundsChanged -= this@NativeSliderBehavior.boundsChanged enabledChanged -= this@NativeSliderBehavior.enabledChanged focusabilityChanged -= this@NativeSliderBehavior.focusableChanged changed -= this@NativeSliderBehavior.changeListener limitsChanged -= this@NativeSliderBehavior.limitsChangeListener } appScope.launch(uiDispatcher) { window.frameFor(view)?.remove(nativePeer) } } }
5
Kotlin
26
613
f7414d4c30cdd7632992071234223653e52b978c
8,717
doodle
MIT License
tw-data/src/main/kotlin/com/github/ljufa/sma/tw/server/main.kt
ljufa
563,332,997
false
null
package com.github.ljufa.sma.tw.server import com.github.ljufa.sma.tw.server.api.TopTweetsService import com.github.ljufa.sma.tw.server.db.DataSource import com.github.ljufa.sma.tw.server.db.DbRepository import com.github.ljufa.sma.tw.server.incoming.MessageHandler import io.grpc.ServerBuilder import org.slf4j.LoggerFactory import kotlin.concurrent.thread private val log = LoggerFactory.getLogger("com.github.ljufa.sma.tw.server.MainKt") fun main() { val config = createConfig() log.debug("Staring application with configuration: {}", config) val kafkaConsumer = createKafkaConsumer(config) val messageHandler = MessageHandler(kafkaConsumer) val dataSource = DataSource(config) val dbRepository = DbRepository(dataSource) thread(name = "writer-thread") { if (dataSource.getDbPurged()) { messageHandler.seekOffsetToBeginning() } messageHandler.listenBatches { consumerRecords -> dbRepository.persistBatch(consumerRecords) } } val grpcServer = ServerBuilder .forPort(config.server.port) .addService(TopTweetsService(dbRepository)) .build() grpcServer.start() addShutdownHook { log.info("*** shutting down gRPC server since JVM is shutting down") grpcServer.shutdown() grpcServer.awaitTermination() log.info("*** server shut down") } addShutdownHook { log.info("*** shutting kafka message handler since JVM is shutting down") messageHandler.stop() log.info("*** message handler shut down") } grpcServer.awaitTermination() } fun addShutdownHook(hook: () -> Unit) { Runtime.getRuntime().addShutdownHook( Thread { hook() } ) }
0
Kotlin
0
0
9a3a398bd8169886569ff1c456226268d97653b2
1,766
sma
MIT License
app/src/main/java/me/artspb/android/kids/wall/clock/Util.kt
artspb
256,951,220
false
null
package me.artspb.android.kids.wall.clock import java.util.* internal fun combine(hours: Int, minutes: Int) = hours * 60 + minutes internal fun Int.split(): Pair<Int, Int> = Pair(this / 60, this % 60) internal fun Int.toDate(): Calendar { val (hours, minutes) = split() val date = Calendar.getInstance() date.set(Calendar.HOUR_OF_DAY, hours) date.set(Calendar.MINUTE, minutes) date.set(Calendar.SECOND, 0) return date } internal enum class Day { NIGHT, DAWN, DAY, DUSK } internal fun Calendar.toDay(start: Calendar, end: Calendar): Day { if (between(start, end)) { return Day.DAY } val startMinusHour = start.clone() as Calendar startMinusHour.add(Calendar.HOUR, -1) if (between(startMinusHour, start)) { return Day.DAWN } val endPlusHour = end.clone() as Calendar endPlusHour.add(Calendar.HOUR, 1) if (between(end, endPlusHour)) { return Day.DUSK } return Day.NIGHT } private fun Calendar.between(start: Calendar, end: Calendar) = after(start) && before(end)
0
Kotlin
0
0
11df4e21981080ff3fb7275eca31272ad9e27bfb
1,059
KidsWallClock
Apache License 2.0
app/src/main/java/ar/com/play2play/model/truco/message/TrucoActionMessage.kt
UTN-FRBA-Mobile
365,641,042
false
null
package ar.com.play2play.model.truco.message import com.fasterxml.jackson.annotation.JsonTypeName import ar.com.play2play.model.base.message.Message import ar.com.play2play.model.truco.TeamPlayer import ar.com.play2play.presentation.truco.actions.TrucoAction @JsonTypeName(value = TrucoActionMessage.TYPE) data class TrucoActionMessage(val action: TrucoAction, val teamPlayer: TeamPlayer) : Message(TYPE) { companion object { const val TYPE = "tr_action" } }
0
Kotlin
1
0
3212cb762824af2e12d3a7492ef66cc72326f3d0
477
Play2Play
MIT License
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/gcp.kt
fkorotkov
84,911,320
false
null
// GENERATED package com.fkorotkov.openshift import io.fabric8.openshift.api.model.GCPPlatformSpec as model_GCPPlatformSpec import io.fabric8.openshift.api.model.GCPPlatformStatus as model_GCPPlatformStatus import io.fabric8.openshift.api.model.PlatformSpec as model_PlatformSpec import io.fabric8.openshift.api.model.PlatformStatus as model_PlatformStatus fun model_PlatformSpec.`gcp`(block: model_GCPPlatformSpec.() -> Unit = {}) { if(this.`gcp` == null) { this.`gcp` = model_GCPPlatformSpec() } this.`gcp`.block() } fun model_PlatformStatus.`gcp`(block: model_GCPPlatformStatus.() -> Unit = {}) { if(this.`gcp` == null) { this.`gcp` = model_GCPPlatformStatus() } this.`gcp`.block() }
4
Kotlin
19
301
fa0b20b5a542cb332430fa85b1035456939a2ca6
717
k8s-kotlin-dsl
MIT License
app/src/main/java/dev/harshdalwadi/nasaapp/base/BaseRecyclerViewAdapter.kt
dalwadi2
533,047,238
false
null
package dev.harshdalwadi.nasaapp.base import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView abstract class BaseRecyclerViewAdapter<B : ViewDataBinding> : RecyclerView.Adapter<BaseRecyclerViewAdapter.ViewHolder<B>>() { lateinit var mContext: Context override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<B> { mContext = parent.context val mView = LayoutInflater.from(parent.context).inflate(setLayoutItem(), parent, false) return ViewHolder(mView) } override fun onBindViewHolder(holder: ViewHolder<B>, position: Int) { onViewReady(holder, position) } override fun getItemCount() = setCount() class ViewHolder<T : ViewDataBinding>(itemView: View) : RecyclerView.ViewHolder(itemView) { var mBinding = DataBindingUtil.bind<T>(itemView)!! } abstract fun setCount(): Int abstract fun setLayoutItem(): Int abstract fun onViewReady(holder: ViewHolder<B>, position: Int) }
0
Kotlin
0
0
6fd3348bc1034ee95e8e346388d74cc9e0c3a1d6
1,184
NasaApp
Apache License 2.0
src/main/kotlin/com/github/wenpiner/tron/block/data/transaction/contract/BeanAccountCreateContract.kt
Wenpiner
689,049,588
false
{"Kotlin": 46764}
package com.github.wenpiner.tron.block.data.transaction.contract import com.github.phish.tron.block.data.Address import com.github.phish.tron.block.enums.AccountType import com.github.phish.tron.block.serializer.StringToAddressAdapter import com.google.gson.annotations.JsonAdapter import com.google.gson.annotations.SerializedName data class BeanAccountCreateContract( @SerializedName("account_address") @JsonAdapter(value = StringToAddressAdapter::class) val accountAddress: Address, @SerializedName("type") val type: AccountType, ) : com.github.phish.tron.block.data.transaction.contract.BeanValue()
0
Kotlin
0
1
f717d4eba045cfb75a6b24dfa7a339040efa18e0
625
TronApi
MIT License
base/src/main/kotlin/com/tuanhv/mvvmarch/base/db/post/PostsLocalDataSource.kt
tuanhv-0226
295,288,304
false
{"Kotlin": 104121}
package com.tuanhv.mvvmarch.base.db.post import javax.inject.Inject import javax.inject.Singleton /** * Created by hoang.van.tuan on 2/2/18. */ @Singleton class PostsLocalDataSource @Inject constructor() { }
0
Kotlin
1
0
6e93d618e29eb2f9f607c746e305e79b662cc9ac
213
mvvm_arch_base
MIT License
src/main/kotlin/io/github/serpro69/kfaker/provider/StrangerThings.kt
jianfang-kso
204,592,729
true
{"Kotlin": 189205, "Groovy": 1142}
package io.github.serpro69.kfaker.provider import io.github.serpro69.kfaker.* import io.github.serpro69.kfaker.dictionary.* /** * [FakeDataProvider] implementation for [CategoryName.STRANGER_THINGS] category. */ class StrangerThings internal constructor(fakerService: FakerService) : AbstractFakeDataProvider(fakerService) { override val categoryName = CategoryName.STRANGER_THINGS val character = resolve { fakerService.resolve(Faker, it, "character") } val quote = resolve { fakerService.resolve(Faker, it, "quote") } }
0
Kotlin
0
0
36a77fb520f82a1a0b43cf6cd08c54c2c7b9d6d6
539
kotlin-faker
MIT License
app/src/main/java/com/app/jetpack/core/BundleContants.kt
ldk123456
648,167,522
false
null
package com.app.jetpack.core const val KEY_FEED_TYPE = "feedType" const val KEY_FEED = "key_feed" const val KEY_CATEGORY = "key_category" const val KEY_ITEM_ID = "key_item_id" const val KEY_PREVIEW_PATH = "key_preview_path" const val KEY_IS_VIDEO = "key_is_video" const val KEY_SHOW_ACTION_BTN = "key_show_action_btn" const val KEY_IS_LOCAL_FILE = "key_is_local_file" const val DATA_FROM_INTERACTION = "data_from_interaction" const val RESULT_FILE_PATH = "file_path" const val RESULT_FILE_WIDTH = "file_width" const val RESULT_FILE_HEIGHT = "file_height" const val RESULT_FILE_TYPE = "file_type"
0
Kotlin
0
0
5631f4b6d681374dc7d8fccc3574f9cca4795476
598
JetpackApp
Apache License 2.0
smartnotifications/src/main/java/com/kunalapk/smartnotifications/AppController.kt
Kunalapk
329,026,547
false
{"Kotlin": 22457, "JavaScript": 91}
package com.kunalapk.smartnotifications class AppController { }
0
Kotlin
0
3
483da289f7cb3d04568f00063127a9c366cd38de
64
SmartNotifications
Apache License 2.0
domain/src/main/java/com/ujizin/leafy/domain/usecase/alarm/implementation/UpdateAlarmImpl.kt
ujizin
442,024,281
false
{"Kotlin": 327053}
package com.ujizin.leafy.domain.usecase.alarm.implementation import com.ujizin.leafy.domain.model.Alarm import com.ujizin.leafy.domain.repository.AlarmRepository import com.ujizin.leafy.domain.usecase.alarm.UpdateAlarm class UpdateAlarmImpl( private val repository: AlarmRepository, ) : UpdateAlarm { override fun invoke(alarm: Alarm) = repository.updateAlarm(alarm) }
7
Kotlin
0
1
52cb750b08ecfc1f751f0171b110bbc26868caf4
380
Leafy
Apache License 2.0
src/main/kotlin/cn/inrhor/imipetcore/common/option/SkillOption.kt
inrhor
518,004,091
false
{"Kotlin": 201847}
package cn.inrhor.imipetcore.common.option /** * 技能配置 */ class SkillOption(var id: String = "null", val name: String = "null", val script: String = "", val tree: TreeSkillOption = TreeSkillOption(), val coolDown: String = "0", val icon: ItemElement = ItemElement()) /** * 技能树配置 */ class TreeSkillOption(val point: Int = 0, val select: List<String> = listOf()) /** * 技能图标配置 */ class IconOption(var id: String = "", val item: ItemElement = ItemElement())
3
Kotlin
3
9
3eb73fe92e5aaedfd907be4705ecaf0b379d8895
497
imipetCore
Creative Commons Zero v1.0 Universal
app/src/main/java/com/peruapps/christopher_elias/entity/User.kt
ChristopherME
189,524,605
false
null
package com.peruapps.christopher_elias.entity /** * Created by <NAME> on 29-may-2019 * <EMAIL> * Lima, Perú * Copyright (c) 2019 All rights reserved. */ data class User(val name: String = "", val email: String = "")
0
Kotlin
0
0
785b1e3938a69936b0c0732f82cb6b40fbfc8d0b
239
senior-test
Apache License 2.0
src/lox/ModuleInfo.kt
Pawel-Parma
803,926,420
false
{"XML": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 16, "Kotlin": 6}
package lox import lox.token.Token import lox.token.TokenType class ModuleInfo( val name: String, ) { @JvmField var hadError: Boolean = false @JvmField var hadRuntimeError: Boolean = false fun error(line: Int, message: String) { report(line, "", message) } fun error(token: Token, message: String) { if (token.type == TokenType.EOF) { report(token.line, " at end", message) } else { report(token.line, " at '" + token.lexeme + "'", message) } } private fun report(line: Int, where: String, message: String) { if (name == "__main__") { System.err.println("[line ${line}] Error${where}: ${message}") } else { System.err.println("In module '${name}' on [line ${line}] Error${where}: ${message}") } hadError = true } fun runtimeError(error: RuntimeError) { if (name == "__main__") { System.err.println("${error.message}\n[line ${error.token.line}]") } else { System.err.println("${error.message}\n[line ${error.token.line}] in module '${name}'") } hadRuntimeError = true } }
0
Java
0
0
e1b3d1e5e55e4c1691735b6784dcf2993508127b
1,189
lox-java
MIT License
lawnchair/src/app/lawnchair/allapps/SearchResultText.kt
LawnchairLauncher
83,799,439
false
null
package app.lawnchair.allapps import android.content.Context import android.provider.SearchRecentSuggestions import android.util.AttributeSet import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.core.view.ViewCompat import app.lawnchair.font.FontManager import app.lawnchair.launcher import app.lawnchair.search.HEADER_JUSTIFY import app.lawnchair.search.LawnchairRecentSuggestionProvider import app.lawnchair.search.SPACE import app.lawnchair.search.SPACE_MINI import app.lawnchair.search.SearchTargetCompat import app.lawnchair.search.data.SearchResultActionCallBack import app.lawnchair.theme.color.ColorTokens import com.android.launcher3.R class SearchResultText(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs), SearchResultView { private val launcher = context.launcher private lateinit var title: TextView private lateinit var clearHistory: Button override fun onFinishInflate() { super.onFinishInflate() onFocusChangeListener = launcher.focusHandler title = ViewCompat.requireViewById(this, R.id.title) title.setTextColor(ColorTokens.ColorAccent.resolveColor(context)) clearHistory = ViewCompat.requireViewById(this, R.id.clear_history) clearHistory.setTextColor(ColorTokens.ColorAccent.resolveColor(context)) clearHistory.visibility = GONE FontManager.INSTANCE.get(context).setCustomFont(title, R.id.font_heading) FontManager.INSTANCE.get(context).setCustomFont(clearHistory, R.id.font_heading) } override val isQuickLaunch: Boolean get() = false override val titleText: CharSequence? get() = title.text override fun launch(): Boolean = false override fun bind(target: SearchTargetCompat, shortcuts: List<SearchTargetCompat>, callBack: SearchResultActionCallBack?) { title.text = target.searchAction?.title val res = when (title.text) { SPACE -> resources.getDimensionPixelSize(R.dimen.space_layout_height) SPACE_MINI -> resources.getDimensionPixelSize(R.dimen.space_layout_mini_height) else -> resources.getDimensionPixelSize(R.dimen.search_result_text_height) } clearHistory.visibility = if (target.packageName == HEADER_JUSTIFY) VISIBLE else INVISIBLE if (target.packageName == HEADER_JUSTIFY) { clearHistory.setOnClickListener { val suggestionsRecent = SearchRecentSuggestions(launcher, LawnchairRecentSuggestionProvider.AUTHORITY, LawnchairRecentSuggestionProvider.MODE) suggestionsRecent.clearHistory() callBack?.action() } } val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, res) this.layoutParams = layoutParams } }
109
null
2
8,138
eeb901dc64186353a8f7fc44bf460432731f35e7
2,817
lawnchair
Apache License 2.0
lawnchair/src/app/lawnchair/allapps/SearchResultText.kt
LawnchairLauncher
83,799,439
false
null
package app.lawnchair.allapps import android.content.Context import android.provider.SearchRecentSuggestions import android.util.AttributeSet import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.core.view.ViewCompat import app.lawnchair.font.FontManager import app.lawnchair.launcher import app.lawnchair.search.HEADER_JUSTIFY import app.lawnchair.search.LawnchairRecentSuggestionProvider import app.lawnchair.search.SPACE import app.lawnchair.search.SPACE_MINI import app.lawnchair.search.SearchTargetCompat import app.lawnchair.search.data.SearchResultActionCallBack import app.lawnchair.theme.color.ColorTokens import com.android.launcher3.R class SearchResultText(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs), SearchResultView { private val launcher = context.launcher private lateinit var title: TextView private lateinit var clearHistory: Button override fun onFinishInflate() { super.onFinishInflate() onFocusChangeListener = launcher.focusHandler title = ViewCompat.requireViewById(this, R.id.title) title.setTextColor(ColorTokens.ColorAccent.resolveColor(context)) clearHistory = ViewCompat.requireViewById(this, R.id.clear_history) clearHistory.setTextColor(ColorTokens.ColorAccent.resolveColor(context)) clearHistory.visibility = GONE FontManager.INSTANCE.get(context).setCustomFont(title, R.id.font_heading) FontManager.INSTANCE.get(context).setCustomFont(clearHistory, R.id.font_heading) } override val isQuickLaunch: Boolean get() = false override val titleText: CharSequence? get() = title.text override fun launch(): Boolean = false override fun bind(target: SearchTargetCompat, shortcuts: List<SearchTargetCompat>, callBack: SearchResultActionCallBack?) { title.text = target.searchAction?.title val res = when (title.text) { SPACE -> resources.getDimensionPixelSize(R.dimen.space_layout_height) SPACE_MINI -> resources.getDimensionPixelSize(R.dimen.space_layout_mini_height) else -> resources.getDimensionPixelSize(R.dimen.search_result_text_height) } clearHistory.visibility = if (target.packageName == HEADER_JUSTIFY) VISIBLE else INVISIBLE if (target.packageName == HEADER_JUSTIFY) { clearHistory.setOnClickListener { val suggestionsRecent = SearchRecentSuggestions(launcher, LawnchairRecentSuggestionProvider.AUTHORITY, LawnchairRecentSuggestionProvider.MODE) suggestionsRecent.clearHistory() callBack?.action() } } val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, res) this.layoutParams = layoutParams } }
109
null
2
8,138
eeb901dc64186353a8f7fc44bf460432731f35e7
2,817
lawnchair
Apache License 2.0
NetClinet/src/main/java/com/mimimi/netclinet/net/download/GZipTask.kt
Aoyihala
414,897,860
false
{"Java": 124244, "Kotlin": 98641}
package com.mimimi.netclinet.net.download import android.content.Context import androidx.work.Worker import androidx.work.WorkerParameters import android.os.FileUtils import android.util.Log import androidx.work.Data import com.blankj.utilcode.util.ZipUtils import org.greenrobot.eventbus.EventBus import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream import java.lang.Exception import java.util.zip.ZipEntry import java.util.zip.ZipInputStream class GZipTask(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { override fun doWork(): Result { val aid = inputData.getString("aid") val vid = inputData.getString("vid") val zipPath = applicationContext.externalCacheDir?.path+"/"+aid + vid+".zip" val tempFileName = applicationContext.externalCacheDir?.path+"/"+aid+"/"+vid val file = ZipUtils.unzipFile(zipPath,tempFileName) if (file.size>0) { val data = Data.Builder() .putString("aid",aid) .putString("vid",vid) .putString("path",tempFileName) .build() return Result.success(data) } else { return Result.failure() } } }
1
null
1
1
1226d7b58fefbdf55569e232229785a4ce0f03b9
1,308
navoldemo
Apache License 2.0
clientes/android/app/src/main/java/com/lopez/guillen/dogfeeder/LoginActivity.kt
Sysop81
788,097,361
false
{"Text": 1, "Ignore List": 7, "Markdown": 1, "Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 24, "XML": 65, "Python": 2, "Maven POM": 1, "Java": 29, "SQL": 3}
package com.lopez.guillen.dogfeeder import android.app.Activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.lopez.guillen.dogfeeder.model.FragmentInteractionListener /** * Clase LoginActivity * Representa el Activity de entrada a la aplicación, sobre su frameLayout se montan los fragmentos para LOGIN,REGISTER y * RECOVERY. */ class LoginActivity : AppCompatActivity(), FragmentInteractionListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //Step 1. Se establece la pantalla de carga y espera 3 segundos antes de establecer el layout del activity installSplashScreen() Thread.sleep(3000) setContentView(R.layout.activity_login) // Step. 2. Se lealiza la carga del layout del login en el frame layout val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frameLayoutLogin, FragmentLogin()) fragmentTransaction.commit() } /** * Manejador de eventos onHandleRegisterUser * Se encarga de manejar el click sobre el boton de registro de un nuevo usuario. Simplemente, carga en el frameLayout * el layout correspondiente a la vista de registro de un nuevo usuario de la aplicación. */ override fun onHandleRegisterUser() { // Step 1. Instanciamos el objeto encargado de interactuar con los fragments val fragmentTransaction = supportFragmentManager.beginTransaction() // Step 2. Se realiza el reemplazo del fragment por el deseado y se crea una nueva instancia FragmentRegister asociado // al contexto de este activity. fragmentTransaction.replace(R.id.frameLayoutLogin, FragmentRegister()) // Step 3. Se maneja la pila de retroceso permitiendo volver al usuario al fragment anterior que siempre será loginFragment fragmentTransaction.addToBackStack(null) // Step 4. Se confirma la transacción y se aplican los cambios fragmentTransaction.commit() } /** * Manejador de eventos onHandleRecoveryPassword * Este método se encarga de manejar el click sobre el botón para la recuperación del password de usuario. Para ello carga en * el framelayout la vista de recuparación de password. */ override fun onHandleRecoveryPassword() { // Step 1. Instanciamos el objeto encargado de interactuar con los fragments val fragmentTransaction = supportFragmentManager.beginTransaction() // Step 2. Se realiza el reemplazo del fragment por el deseado y se crea una nueva instancia FragmentRecoveryPassword asociado // al contexto de este activity. fragmentTransaction.replace(R.id.frameLayoutLogin, FragmentRecoveryPassword()) // Step 3. Se maneja la pila de retroceso permitiendo volver al usuario al fragment anterior que siempre será loginFragment fragmentTransaction.addToBackStack(null) // Step 4. Se confirma la transacción y se aplican los cambios fragmentTransaction.commit() } /** * Método getLoginContext * Getter para el contexto del activity * @return this Contexto que representa al activity */ fun getLoginContext(): Activity { return this } }
0
Java
0
0
041a3e1e97d4b7caf967a4fa178fceddf2b41da3
3,404
PROYECTO_FINAL_DOGFEEDER
MIT License
buildSrc/src/main/kotlin/ReleaseSupportPlugin.kt
jebnix
565,612,684
true
{"Java Properties": 13, "Gradle Kotlin DSL": 75, "YAML": 66, "Shell": 4, "Text": 15, "EditorConfig": 2, "Markdown": 73, "Batchfile": 4, "Ignore List": 4, "Java": 972, "XML": 22, "reStructuredText": 36, "Python": 54, "INI": 6, "TOML": 2, "Makefile": 2, "Scala": 89, "CSS": 10, "SVG": 7, "HTML": 4, "JSON5": 1, "Kotlin": 5, "JSON": 9, "JSON with Comments": 1, "JavaScript": 15, "robots.txt": 1, "TSX": 28, "Jest Snapshot": 9, "OASv3-yaml": 2, "Protocol Buffer": 3, "Gradle": 2, "Maven POM": 1, "Smarty": 1, "ANTLR": 1}
/* * Copyright (C) 2022 Dremio * * 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. */ import java.nio.file.Path import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.options.Option import org.gradle.kotlin.dsl.register import org.gradle.work.DisableCachingByDefault /** Registers some tasks to manage the `version.txt` file. */ class ReleaseSupportPlugin : Plugin<Project> { override fun apply(project: Project) { project.tasks.register("showVersion") { group = "Release Support" description = "Show current version" doFirst { logger.lifecycle( "Current version is ${VersionTuple.fromFile(versionTxtFile(this.project))}." ) } } project.tasks.register<BumpVersionTask>("bumpVersion") { group = "Release Support" description = "Bumps the version to the next patch/minor/major version as a snapshot, see ' ./gradlew help --task :bumpVersion '." } } companion object { private fun versionTxtFile(project: Project): Path = project.rootDir.toPath().resolve("./version.txt") } @DisableCachingByDefault(because = "Version bumps cannot be cached") open class BumpVersionTask : DefaultTask() { @Option( option = "bumpToRelease", description = "Define whether to bump to a release version, defaults to snapshot release." ) @Internal var bumpToRelease: Boolean = false @Option( option = "bumpType", description = "Defines which part of the version should be bumped, defaults to 'none'." ) @Internal var bumpType: BumpType = BumpType.none @TaskAction fun bumpVersion() { val versionFile = versionTxtFile(project) val currentVersion = VersionTuple.fromFile(versionFile) logger.lifecycle("Current version is $currentVersion.") val nextVersion = when (bumpType) { BumpType.none -> currentVersion BumpType.patch -> currentVersion.bumpPatch() BumpType.minor -> currentVersion.bumpMinor() BumpType.major -> currentVersion.bumpMajor() } val finalVersion = if (bumpToRelease) nextVersion.asRelease() else nextVersion.asSnapshot() if (finalVersion < currentVersion) { throw GradleException( "New version $finalVersion would be lower than current version $currentVersion" ) } if (finalVersion != currentVersion) { finalVersion.writeToFile(versionFile) logger.lifecycle("New version is $finalVersion.") } else { throw GradleException("Bump version tasks results in no change.") } } } enum class BumpType { // lower-case, used as command line option values none, patch, minor, major } }
0
null
0
0
2f5274fc54804b35c550310413539b28b41741b5
3,430
nessie
Apache License 2.0
composeApp/src/commonMain/kotlin/io/github/taalaydev/doodleverse/ui/components/BrushPicker.kt
TaalayDev
870,037,542
false
{"Kotlin": 231243, "Swift": 621, "HTML": 337, "CSS": 102}
package io.github.taalaydev.doodleverse.ui.components import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material3.BottomSheetDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.PaintingStyle import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.unit.dp import io.github.taalaydev.doodleverse.core.DrawRenderer import io.github.taalaydev.doodleverse.data.models.BrushData import io.github.taalaydev.doodleverse.data.models.DrawingPath private fun createPreviewBrushPath(width: Float, height: Float): Path { val midWidth = width / 2 val midHeight = height / 2 val quarterWidth = width / 4 val quarterHeight = height / 4 val eighthWidth = width / 8 return Path().apply { moveTo(15f, midHeight) cubicTo( 15f, midHeight - quarterHeight, midWidth - eighthWidth, midHeight - quarterHeight, midWidth, midHeight ) cubicTo( midWidth + eighthWidth, midHeight + quarterHeight, width - 15f, midHeight + quarterHeight, width - 15f, midHeight ) moveTo(width - 15f, midHeight) close() } } private fun createPreviewShapePath(width: Float, height: Float): Path { return Path().apply { moveTo(15f, 15f) lineTo(width - 15f, 15f) lineTo(width - 15f, height - 15f) lineTo(15f, height - 15f) close() } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun BrushPicker( bottomSheetState: SheetState, selectedBrush: BrushData? = null, onSelected: (BrushData) -> Unit = {}, onDismiss: () -> Unit, ) { val brushes = BrushData.all() ModalBottomSheet( onDismissRequest = { onDismiss() }, sheetState = bottomSheetState, dragHandle = { BottomSheetDefaults.DragHandle() }, ) { Surface( modifier = Modifier .fillMaxWidth() .height(400.dp), color = MaterialTheme.colors.surface, ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { BrushGrid( brushes = brushes, selectedBrush = selectedBrush, onSelected = onSelected, ) } } } } @Composable fun BrushGrid( brushes: List<BrushData>, selectedBrush: BrushData? = null, onSelected: (BrushData) -> Unit = {}, ) { LazyVerticalGrid( columns = GridCells.Fixed(3), modifier = Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 16.dp, top = 16.dp, start = 16.dp, end = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { items(brushes.size) { index -> BrushPreview( brushes[index], isSelected = selectedBrush?.id == brushes[index].id, modifier = Modifier .clip(RoundedCornerShape(8.dp)) .clickable { onSelected(brushes[index]) }, ) } } } @Composable fun BrushPreview( brush: BrushData, isSelected: Boolean = false, modifier: Modifier = Modifier, ) { var bitmap by remember { mutableStateOf<ImageBitmap?>(null) } var imageCanvas by remember { mutableStateOf<Canvas?>(null) } var canvasSize by remember { mutableStateOf(Size.Zero) } val initialPath = remember(canvasSize) { val width = canvasSize.width.coerceAtLeast(1f) val height = canvasSize.height.coerceAtLeast(1f) DrawingPath( brush = brush, color = Color(0xFF333333), size = 10f, startPoint = Offset(10f, 10f), endPoint = Offset(width - 10f, height - 10f), path = if (brush.isShape) { createPreviewShapePath(width, height) } else { createPreviewBrushPath(width, height) }, ) } Column( modifier = modifier.fillMaxWidth(), ) { Box( modifier = Modifier .fillMaxWidth() .height(100.dp) .border( width = if (isSelected) 2.dp else 1.dp, color = if (isSelected) MaterialTheme.colors.primary else Color.LightGray, shape = RoundedCornerShape(8.dp) ) .clip(RoundedCornerShape(8.dp)) .background(Color.White) .padding(8.dp), ) { Canvas( modifier = Modifier.fillMaxSize(), ) { val canvasWidth = size.width.toInt().coerceAtLeast(1) val canvasHeight = size.height.toInt().coerceAtLeast(1) if (bitmap == null || bitmap?.width != canvasWidth || bitmap?.height != canvasHeight) { bitmap = ImageBitmap(canvasWidth, canvasHeight) imageCanvas = Canvas(bitmap!!) canvasSize = size } if (brush.brush != null) { DrawRenderer.drawBrushStampsBetweenPoints( imageCanvas!!, Offset(0f, 0f), Offset(size.width, size.height), DrawRenderer.pathPaint(initialPath), initialPath, ) } else { DrawRenderer.drawPath( canvas = imageCanvas!!, drawingPath = initialPath, paint = DrawRenderer.pathPaint(initialPath), size = size, ) } if (bitmap != null) { drawImage(bitmap!!, Offset(0f, 0f)) } } } Text(text = brush.name) } }
0
Kotlin
0
0
0bc6cd83b6fa9a9228f2da9b756e26e9da61ce81
7,664
DoodleVerse-ComposeMultiplatform
MIT License
sdk/src/main/kotlin/GetApp/Client/models/NewBugReportResDto.kt
getappsh
735,551,269
false
{"Kotlin": 788107, "Java": 8139, "Python": 589}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package GetApp.Client.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * * * @param bugId * @param uploadLogsUrl */ data class NewBugReportResDto ( @Json(name = "bugId") val bugId: java.math.BigDecimal, @Json(name = "uploadLogsUrl") val uploadLogsUrl: kotlin.String )
0
Kotlin
1
1
d9d3e9317175babb5f9726e568dc17ab1ce8187e
602
getmap-android-sdk
Apache License 2.0
src/test/kotlin/com/trankimtung/spring/data/jpa/filterable/repository/support/ValueResolverTest.kt
trankimtung
374,366,678
false
null
package com.trankimtung.spring.data.jpa.filterable.repository.support import com.trankimtung.spring.data.jpa.filterable.test.TestEnum import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.math.BigDecimal import java.time.* import java.util.* internal class ValueResolverTest { @Test fun string() { assertEquals("123.0", resolveValue(123.0, String::class)) assertEquals("123.0", resolveValue(123.0, CharSequence::class)) } @Test fun boolean() { assertEquals(true, resolveValue("true", Boolean::class)) assertEquals(false, resolveValue("false", Boolean::class)) } @Test fun number() { assertEquals(1.toByte(), resolveValue("1", Byte::class)) assertEquals(1234.toShort(), resolveValue("1234", Short::class)) assertEquals(123456, resolveValue("123456", Int::class)) assertEquals(123456789L, resolveValue("123456789", Long::class)) assertEquals(123.456.toFloat(), resolveValue(123.456, Float::class)) assertEquals(123.456789, resolveValue(123.456789, Double::class)) assertEquals("123.456789".toBigDecimal(), resolveValue(123.456789, BigDecimal::class)) } @Test fun enum() { assertEquals(TestEnum.VALUE1, resolveValue("VALUE1", TestEnum::class)) assertEquals(TestEnum.VALUE2, resolveValue("VALUE2", TestEnum::class)) } @Test fun `date & time`() { assertEquals( Date(ZonedDateTime.of(LocalDateTime.of(2021, 1, 1, 0, 0, 0), ZoneId.of("Z")).toInstant().toEpochMilli()), resolveValue("2021-01-01T00:00:00+00:00", Date::class) ) assertEquals(LocalDate.of(2021, 1, 1), resolveValue("2021-01-01", LocalDate::class)) assertEquals(LocalDateTime.of(2021, 1, 1, 0, 0, 0), resolveValue("2021-01-01T00:00:00", LocalDateTime::class)) assertEquals( ZonedDateTime.of(LocalDateTime.of(2021, 1, 1, 0, 0, 0), ZoneId.of("Z")), resolveValue("2021-01-01T00:00:00+00:00", ZonedDateTime::class) ) assertEquals( ZonedDateTime.of(LocalDateTime.of(2021, 1, 1, 0, 0, 0), ZoneId.of("Z")).toInstant(), resolveValue("2021-01-01T00:00:00Z", Instant::class) ) } }
0
Kotlin
0
1
f82180bd74e03016298752872e34aff3e08a4080
2,277
spring-data-jpa-filterable
MIT License
spoogle-backend/src/main/kotlin/no/nav/helse/spoogle/microsoft/AzureAd.kt
navikt
636,249,373
false
{"Kotlin": 93189, "TypeScript": 7882, "CSS": 693, "HTML": 358, "JavaScript": 310, "Dockerfile": 181}
package no.nav.helse.spoogle.microsoft import no.nav.security.token.support.v2.IssuerConfig class AzureAD private constructor(private val config: Config) { internal fun issuer(): String = "AAD" internal fun issuerConfig(): IssuerConfig = IssuerConfig( name = issuer(), discoveryUrl = config.discoveryUrl, acceptedAudience = listOf(config.clientId), ) private val requiredClaims = mapOf( "NAVident" to null, "preferred_username" to null, "name" to null, "azp" to config.clientId, "aud" to listOf(config.clientId), ) private val requiredGroups = config.validGroupId internal fun hasValidClaimValues(claimsAndValues: Map<String, Any>) = claimsAndValues.entries.fold(true) { _, (key, value) -> if (requiredClaims[key] == value) return@fold true false } internal fun hasValidClaims(claims: List<String>) = requiredClaims.keys.all { it in claims } internal fun hasValidGroups(groups: List<String>) = requiredGroups.any { it in groups } internal companion object { internal fun fromEnv(env: Map<String, String>): AzureAD { return AzureAD( Config( discoveryUrl = env.getValue("AZURE_APP_WELL_KNOWN_URL"), clientId = env.getValue("AZURE_APP_CLIENT_ID"), validGroupId = env.getValue("AZURE_VALID_GROUP_IDS").split(","), ), ) } } private class Config( val discoveryUrl: String, val clientId: String, val validGroupId: List<String>, ) }
2
Kotlin
0
0
fe48d3fd8abadd59ad7c13b4f56a363fe2535a5b
1,702
helse-spoogle
MIT License
src/main/kotlin/com/github/brainage04/togglesprint/gui/EntityTracker.kt
brainage04
703,531,886
false
{"Kotlin": 40434, "Java": 12667}
package com.github.brainage04.togglesprint.gui import com.github.brainage04.togglesprint.ToggleSprintMain import com.github.brainage04.togglesprint.gui.core.RenderGuiData import net.minecraft.client.Minecraft import net.minecraft.entity.EnumCreatureType object EntityTracker { private val guiElements get() = ToggleSprintMain.config.guiElements fun entityTracker() { if (!guiElements.entityTracker.coreSettings.isEnabled) return val theWorld = Minecraft.getMinecraft().theWorld ?: return val textArray = arrayListOf( "§f§b${theWorld.loadedEntityList.size} entities loaded" ) val players = theWorld.playerEntities val entities = theWorld.loadedEntityList var creaturesCount = 0 var waterCreaturesCount = 0 var ambientsCount = 0 var monstersCount = 0 for (entity in entities) { if (entity.isCreatureType(EnumCreatureType.CREATURE, false)) creaturesCount++ if (entity.isCreatureType(EnumCreatureType.WATER_CREATURE, false)) waterCreaturesCount++ if (entity.isCreatureType(EnumCreatureType.AMBIENT, false)) ambientsCount++ if (entity.isCreatureType(EnumCreatureType.MONSTER, false)) monstersCount++ } val allCategoriesCount = players.size + creaturesCount + waterCreaturesCount + ambientsCount + monstersCount if (guiElements.entityTracker.showPlayers) textArray.add("§fPlayers: ${players.size}") if (guiElements.entityTracker.showPlayerNames) for (player in players) textArray.add("§f${player.name}") if (guiElements.entityTracker.showCreatures) textArray.add("§fCreatures: $creaturesCount") if (guiElements.entityTracker.showWaterCreatures) textArray.add("§fWater Creatures: $waterCreaturesCount") if (guiElements.entityTracker.showAmbients) textArray.add("§fAmbients: $ambientsCount") if (guiElements.entityTracker.showMonsters) textArray.add("§fMonsters: $monstersCount") if (guiElements.entityTracker.showOthers) textArray.add("§f§b${entities.size - allCategoriesCount} other entities loaded") RenderGuiData.renderElement( guiElements.entityTracker.coreSettings.x, guiElements.entityTracker.coreSettings.y, guiElements.entityTracker.coreSettings.anchorCorner, textArray, ) } }
0
Kotlin
1
1
fa865fdd8cddbb98ef21ea11dde63eb5d34ce1e5
2,384
ToggleSprint
The Unlicense
app/src/main/java/com/example/testapp/di/module/ViewModelModule.kt
agesa3
499,420,513
false
{"Kotlin": 12646}
package com.example.testapp.di.module import com.example.testapp.ui.viewmodel.MainViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { viewModel { MainViewModel(get(), get()) } }
0
Kotlin
0
1
bb5519b00ece81317b93d9cc4030d6256a5132fc
261
Users
Apache License 2.0
src/commonTest/kotlin/io/github/hansanto/kault/auth/approle/payload/GenerateSecretIDPayloadTest.kt
Hansanto
712,104,593
false
{"Kotlin": 231989}
package io.github.hansanto.kault.auth.approle.payload import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe class GenerateSecretIDPayloadTest : FunSpec({ test("metadata from empty map") { val payload = GenerateSecretIDPayload() payload.metadata(emptyMap()) payload.metadata shouldBe "{}" } test("metadata from map with one entry") { val payload = GenerateSecretIDPayload() payload.metadata(mapOf("key" to "value")) payload.metadata shouldBe "{\"key\":\"value\"}" } test("metadata from map with multiple entries") { val payload = GenerateSecretIDPayload() payload.metadata(mapOf("key1" to "value1", "key2" to "value2")) payload.metadata shouldBe "{\"key1\":\"value1\",\"key2\":\"value2\"}" } })
2
Kotlin
0
0
2f94d0df208211ddd078e3c65e71e19b08b861dc
817
kault
Apache License 2.0
src/test/kotlin/no/nav/sokos/prosjektnavn/ApplicationTest.kt
navikt
509,000,535
false
null
package no.nav.sokos.prosjektnavn import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe class ApplicationTest : FunSpec ({ test("my first test") { 1 + 1 shouldBe 2 } test("my second test") { 2 + 2 shouldBe 4 } test("my third test") { 3 + 3 shouldBe 6 } })
1
Kotlin
0
0
abcfa5b7927128df8c502603a74a32d014ac0156
333
sokos-ktor-template
MIT License
AndroidLint-4.1.0/lint-checks/lintChecker/src/main/java/com/easelint/detector/ParseDetector.kt
Western-parotia
642,632,046
false
null
package com.easelint.detector import com.android.tools.lint.detector.api.* import com.intellij.psi.PsiMethod import com.easelint.utils.createWithMj import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UTryExpression import org.jetbrains.uast.getParentOfType class ParseDetector : Detector(), SourceCodeScanner { companion object { val ISSUE_PARSE_STRING = Issue.createWithMj<ParseDetector>( id = "ParseStringDetector", briefDescription = "调用parse方法必须捕获异常", explanation = "parseInt、parseLong、parseFloat、parseDouble需要加try catch,防止类型转换出错。", implementationScope = Scope.JAVA_FILE_SCOPE ) val ISSUE_PARSE_COLOR = Issue.createWithMj<ParseDetector>( id = "ParseColorDetector", briefDescription = "高风险API使用", explanation = "请避免使用android.graphics.Color.parseColor(),使用拓展方法进行替换," + "\n例如:string.toSafeColor(),或者使用try catch捕获异常(必须是Throwable或Exception)", implementationScope = Scope.JAVA_FILE_SCOPE ) } override fun getApplicableMethodNames(): List<String>? { return listOf( "parseInt", "parseLong", "parseFloat", "parseDouble", "toInt", "toLong", "toFloat", "toDouble", "valueOf", "parseColor" ) } override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { if (context.evaluator.isMemberInClass(method, "android.graphics.Color")) { //==========color=========== if (!hasTryCatch(context, node)) context.report( ISSUE_PARSE_COLOR, context.getLocation(node), ISSUE_PARSE_COLOR.getExplanation(TextFormat.TEXT) ) } else { //=========string=========== val isValueOf = "valueOf" == method.name val argumentType = node.valueArguments.firstOrNull()?.getExpressionType() val isString = context.evaluator.typeMatches(argumentType,"java.lang.String") //当前判断的方法是isValueOf(),且入参不是String类型,不需要检查此方法 if (isValueOf && !isString) return val methodName = when (method.containingClass?.qualifiedName) { "java.lang.Integer" -> if (isValueOf) "Integer.valueOf()" else "parseInt()" "java.lang.Long" -> if (isValueOf) "Long.valueOf()" else "parseLong()" "java.lang.Float" -> if (isValueOf) "Float.valueOf()" else "parseFloat()" "java.lang.Double" -> if (isValueOf) "Double.valueOf()" else "parseDouble()" "kotlin.text.StringsKt__StringNumberConversionsJVMKt" -> { when (method.name) { "toInt" -> "toInt()" "toLong" -> "toLong()" "toFloat" -> "toFloat()" "toDouble" -> "toDouble()" else -> "" } } else -> "" } //方法不是来自以上目标类直接返回 if (methodName.isEmpty()) return if (!hasTryCatch(context, node)) { val msg = "请避免使用${methodName}方法,使用拓展方法进行替换," + "\n例如:string.toSafeXX(),或者使用try catch捕获异常(必须是Throwable或Exception)" context.report(ISSUE_PARSE_STRING, node, context.getLocation(node), msg) } } } private fun hasTryCatch( context: JavaContext, node: UCallExpression ): Boolean { //判断方法的父节点是否为try-catch表达式 val tryExpression: UTryExpression = node.getParentOfType(UTryExpression::class.java, true) ?: return false //判断catch里是否是Throwable或者Exception tryExpression.catchClauses.firstOrNull { it.types.firstOrNull { type -> when (type.canonicalText) { "java.lang.Throwable", "java.lang.Exception", -> true else -> false } } != null } ?: return false //获取到try的行号 val start: Int = context.getLocation(tryExpression).start?.line ?: 0 //获取第一个catch的行号 val catchExpression = tryExpression.catchClauses[0] val end: Int = context.getLocation(catchExpression).start?.line ?: 0 //获取方法的行号 val target = context.getLocation(node).start?.line //方法的位置必须在try和第一个catch之间,在其它位置无效 return target in start..end } }
0
Kotlin
2
14
a9e3988f1b0d3399a8343bb72fecc14fd71db4fe
4,637
EaseLint
MIT License
AndroidLint-4.1.0/lint-checks/lintChecker/src/main/java/com/easelint/detector/ParseDetector.kt
Western-parotia
642,632,046
false
null
package com.easelint.detector import com.android.tools.lint.detector.api.* import com.intellij.psi.PsiMethod import com.easelint.utils.createWithMj import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UTryExpression import org.jetbrains.uast.getParentOfType class ParseDetector : Detector(), SourceCodeScanner { companion object { val ISSUE_PARSE_STRING = Issue.createWithMj<ParseDetector>( id = "ParseStringDetector", briefDescription = "调用parse方法必须捕获异常", explanation = "parseInt、parseLong、parseFloat、parseDouble需要加try catch,防止类型转换出错。", implementationScope = Scope.JAVA_FILE_SCOPE ) val ISSUE_PARSE_COLOR = Issue.createWithMj<ParseDetector>( id = "ParseColorDetector", briefDescription = "高风险API使用", explanation = "请避免使用android.graphics.Color.parseColor(),使用拓展方法进行替换," + "\n例如:string.toSafeColor(),或者使用try catch捕获异常(必须是Throwable或Exception)", implementationScope = Scope.JAVA_FILE_SCOPE ) } override fun getApplicableMethodNames(): List<String>? { return listOf( "parseInt", "parseLong", "parseFloat", "parseDouble", "toInt", "toLong", "toFloat", "toDouble", "valueOf", "parseColor" ) } override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { if (context.evaluator.isMemberInClass(method, "android.graphics.Color")) { //==========color=========== if (!hasTryCatch(context, node)) context.report( ISSUE_PARSE_COLOR, context.getLocation(node), ISSUE_PARSE_COLOR.getExplanation(TextFormat.TEXT) ) } else { //=========string=========== val isValueOf = "valueOf" == method.name val argumentType = node.valueArguments.firstOrNull()?.getExpressionType() val isString = context.evaluator.typeMatches(argumentType,"java.lang.String") //当前判断的方法是isValueOf(),且入参不是String类型,不需要检查此方法 if (isValueOf && !isString) return val methodName = when (method.containingClass?.qualifiedName) { "java.lang.Integer" -> if (isValueOf) "Integer.valueOf()" else "parseInt()" "java.lang.Long" -> if (isValueOf) "Long.valueOf()" else "parseLong()" "java.lang.Float" -> if (isValueOf) "Float.valueOf()" else "parseFloat()" "java.lang.Double" -> if (isValueOf) "Double.valueOf()" else "parseDouble()" "kotlin.text.StringsKt__StringNumberConversionsJVMKt" -> { when (method.name) { "toInt" -> "toInt()" "toLong" -> "toLong()" "toFloat" -> "toFloat()" "toDouble" -> "toDouble()" else -> "" } } else -> "" } //方法不是来自以上目标类直接返回 if (methodName.isEmpty()) return if (!hasTryCatch(context, node)) { val msg = "请避免使用${methodName}方法,使用拓展方法进行替换," + "\n例如:string.toSafeXX(),或者使用try catch捕获异常(必须是Throwable或Exception)" context.report(ISSUE_PARSE_STRING, node, context.getLocation(node), msg) } } } private fun hasTryCatch( context: JavaContext, node: UCallExpression ): Boolean { //判断方法的父节点是否为try-catch表达式 val tryExpression: UTryExpression = node.getParentOfType(UTryExpression::class.java, true) ?: return false //判断catch里是否是Throwable或者Exception tryExpression.catchClauses.firstOrNull { it.types.firstOrNull { type -> when (type.canonicalText) { "java.lang.Throwable", "java.lang.Exception", -> true else -> false } } != null } ?: return false //获取到try的行号 val start: Int = context.getLocation(tryExpression).start?.line ?: 0 //获取第一个catch的行号 val catchExpression = tryExpression.catchClauses[0] val end: Int = context.getLocation(catchExpression).start?.line ?: 0 //获取方法的行号 val target = context.getLocation(node).start?.line //方法的位置必须在try和第一个catch之间,在其它位置无效 return target in start..end } }
0
Kotlin
2
14
a9e3988f1b0d3399a8343bb72fecc14fd71db4fe
4,637
EaseLint
MIT License
core/common/src/main/kotlin/com/boswelja/smartwatchextensions/core/FeatureDataExt.kt
boswelja
103,805,743
false
{"Kotlin": 496889}
package com.boswelja.smartwatchextensions.core inline fun <T> FeatureData<T>?.fold( success: (T) -> Unit, error: (Throwable) -> Unit, disabled: () -> Unit, loading: () -> Unit ) { when (this) { is FeatureData.Success -> success(data) is FeatureData.Disabled -> disabled() is FeatureData.Error -> error(throwable) null -> loading() } }
11
Kotlin
0
25
ec7e9ad4c98e18a9a4b5c07f1d39f6c0b1fbfd65
392
SmartwatchExtensions
Apache License 2.0
app/src/main/java/com/github/iielse/imageviewer/demo/business/TestActivity.kt
HelloPeng
309,860,000
false
null
package com.github.iielse.imageviewer.demo.business import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.github.iielse.imageviewer.demo.R import com.github.iielse.imageviewer.demo.utils.toast import kotlinx.android.synthetic.main.activity_test.* class TestActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test) exoVideoView.setOnClickListener { toast("video click") } exoVideoView.setOnLongClickListener { toast("video long clicked") true } exoVideoView.prepare("https://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4") exoVideoView.resume() } override fun onDestroy() { super.onDestroy() exoVideoView.release() } }
0
Kotlin
2
1
c56a3e8b21fc3f71005dd721397bc6d6d1d6383e
911
ImageViewer
MIT License
domain/src/main/java/com/xquare/domain/usecase/schedules/FixSchedulesUseCase.kt
team-xquare
478,925,648
false
{"Kotlin": 447887}
package com.xquare.domain.usecase.schedules import com.xquare.domain.entity.schedules.FixSchedulesEntity import com.xquare.domain.repository.schedules.SchedulesRepository import com.xquare.domain.usecase.UseCase import javax.inject.Inject class FixSchedulesUseCase @Inject constructor( private val schedulesRepository: SchedulesRepository ): UseCase<FixSchedulesEntity, Unit>() { override suspend fun execute(data: FixSchedulesEntity) = schedulesRepository.fixSchedules(data) }
16
Kotlin
1
25
f9bc5d0bc3ed2957705dc6db53d0139f62827649
495
xquare-android
MIT License
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/model/Meeting.kt
yotkaz
56,866,821
false
null
package yotkaz.thimman.backend.model import yotkaz.thimman.backend.app.JPA_EMPTY_CONSTRUCTOR import java.time.LocalDateTime import java.util.* import javax.persistence.* @Entity data class Meeting( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long? = null, var subject: String, var description: String, var place: String, var startTime: LocalDateTime, var endTime: LocalDateTime, @OneToOne(fetch = FetchType.EAGER) var initiator: Person?, @ManyToMany(fetch = FetchType.EAGER) var persons: List<Person> ) { @Deprecated(JPA_EMPTY_CONSTRUCTOR) constructor() : this( subject = "", description = "", place = "", startTime = LocalDateTime.now(), endTime = LocalDateTime.now(), initiator = null, persons = ArrayList() ) }
0
Kotlin
0
3
743f56b675d24662d80f6a333185f93f1a3c6dce
934
thimman
Apache License 2.0
domain/src/main/java/com/depromeet/threedays/domain/entity/mate/Mate.kt
depromeet12th
548,194,728
false
null
package com.depromeet.threedays.domain.entity.mate import java.time.LocalDateTime data class Mate( val id: Long, val habitId: Long, val memberId: Long, val title: String, val createAt: LocalDateTime?, // TODO: null로 들어와서 임시 조치 val level: Int, val reward: Int, val rewardHistory: List<RewardHistory>?, val levelUpAt: LocalDateTime?, val characterType: MateType, val levelUpSection: List<Int>, val bubble: String, val status: String, ) { data class RewardHistory( val createAt: LocalDateTime?, ) }
0
Kotlin
1
15
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
566
three-days-android
MIT License
app/src/main/java/com/ar/musicplayer/screens/home/AdaptiveHomeScreen.kt
AjayDhattarwal
811,499,243
false
{"Kotlin": 742820}
@file:kotlin.OptIn(ExperimentalFoundationApi::class) package com.ar.musicplayer.screens.home import android.app.Activity import androidx.annotation.OptIn import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.media3.common.util.UnstableApi import com.ar.musicplayer.data.models.HomeListItem import com.ar.musicplayer.data.models.toInfoScreenModel import com.ar.musicplayer.screens.info.InfoScreen import com.ar.musicplayer.ui.theme.WindowInfoVM import com.ar.musicplayer.viewmodel.HomeViewModel import com.ar.musicplayer.viewmodel.MoreInfoViewModel import com.ar.musicplayer.viewmodel.PlayerViewModel import com.google.accompanist.adaptive.HorizontalTwoPaneStrategy import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.calculateDisplayFeatures @OptIn(UnstableApi::class, ) @Composable fun AdaptiveHomeScreen( windowInfoVM: WindowInfoVM, homeViewModel: HomeViewModel, playerViewModel: PlayerViewModel, moreInfoViewModel: MoreInfoViewModel, // listState: LazyListState, navigateSetting: () -> Unit, onItemClick: (Boolean, HomeListItem) -> Unit ) { val showPreviewScreen by windowInfoVM.showPreviewScreen.collectAsState() val selectedItem by windowInfoVM.selectedItem.collectAsState() val isPreviewVisible by windowInfoVM.isPreviewVisible.collectAsState() val context = LocalContext.current TwoPane( displayFeatures = calculateDisplayFeatures(context as Activity), first = { HomeScreen( homeViewModel = homeViewModel, // playerViewModel = playerViewModel, // listState = listState, navigateSetting = navigateSetting, onItemClick = remember { { isRadio, data -> windowInfoVM.onItemSelected(data.toInfoScreenModel()) onItemClick(isRadio, data) } } ) }, second = { if (isPreviewVisible && selectedItem != null && showPreviewScreen) { InfoScreen( moreInfoViewModel = moreInfoViewModel, data = selectedItem!!, onBackPressed = remember{ { windowInfoVM.closePreview() } } ) } }, strategy = HorizontalTwoPaneStrategy(if(isPreviewVisible && showPreviewScreen) 0.6f else 1f), ) }
0
Kotlin
0
0
5a549720e34d93b5cb588856d9d01f1d640fb045
2,711
MusicPlayer
MIT License
widgets/src/androidMain/kotlin/dev/icerock/moko/widgets/factory/DefaultLinearWidgetViewFactory.kt
MaTriXy
228,468,295
true
{"Kotlin": 311344}
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.widgets.factory import android.util.DisplayMetrics import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import dev.icerock.moko.widgets.LinearWidget import dev.icerock.moko.widgets.core.ViewBundle import dev.icerock.moko.widgets.core.ViewFactoryContext import dev.icerock.moko.widgets.style.applyStyle import dev.icerock.moko.widgets.style.ext.applyMargin import dev.icerock.moko.widgets.style.ext.toLinearLayoutOrientation import dev.icerock.moko.widgets.style.ext.toPlatformSize import dev.icerock.moko.widgets.style.view.SizeSpec import dev.icerock.moko.widgets.style.view.WidgetSize import dev.icerock.moko.widgets.view.AspectRatioFrameLayout actual class DefaultLinearWidgetViewFactory actual constructor( style: Style ) : DefaultLinearWidgetViewFactoryBase(style) { override fun <WS : WidgetSize> build( widget: LinearWidget<out WidgetSize>, size: WS, viewFactoryContext: ViewFactoryContext ): ViewBundle<WS> { val context = viewFactoryContext.context val dm = context.resources.displayMetrics val container = LinearLayout(context).apply { orientation = style.orientation.toLinearLayoutOrientation() applyStyle(style) } widget.children.forEach { child -> val viewBundle = child.buildView( ViewFactoryContext( context = context, lifecycleOwner = viewFactoryContext.lifecycleOwner, parent = container ) ) val (lp, view) = (viewBundle.size to viewBundle.view) .toLinearLayoutParams(dm) viewBundle.margins?.let { lp.applyMargin(dm, it) } container.addView(view, lp) } return ViewBundle( view = container, size = size, margins = style.margins ) } } fun Pair<WidgetSize, View>.toLinearLayoutParams( dm: DisplayMetrics ): Pair<LinearLayout.LayoutParams, View> { val widgetSize = this.first val view = this.second return when (widgetSize) { is WidgetSize.Const<out SizeSpec, out SizeSpec> -> { LinearLayout.LayoutParams( widgetSize.width.toPlatformSize(dm), widgetSize.height.toPlatformSize(dm) ) to view } is WidgetSize.AspectByWidth<out SizeSpec> -> { val lp = LinearLayout.LayoutParams( widgetSize.width.toPlatformSize(dm), ViewGroup.LayoutParams.WRAP_CONTENT ) lp to AspectRatioFrameLayout( context = view.context, aspectRatio = widgetSize.aspectRatio, aspectByWidth = true ).apply { addView( view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) } } is WidgetSize.AspectByHeight<out SizeSpec> -> { val lp = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, widgetSize.height.toPlatformSize(dm) ) lp to AspectRatioFrameLayout( context = view.context, aspectRatio = widgetSize.aspectRatio, aspectByWidth = false ).apply { addView( view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) } } } }
0
null
0
0
15318995f432351762def5ddc291b9696ac87516
3,761
moko-widgets
Apache License 2.0
src/main/kotlin/com/daveme/chocolateCakePHP/Settings.kt
dmeybohm
95,393,362
false
{"Kotlin": 366147, "Java": 17401, "PHP": 268, "HTML": 257}
package com.daveme.chocolateCakePHP import com.daveme.chocolateCakePHP.cake.PluginEntry import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.vfs.VirtualFile import java.io.File import java.lang.ref.WeakReference private const val DEFAULT_NAMESPACE = "\\App" private const val DEFAULT_APP_DIRECTORY = "src" private const val DEFAULT_CAKE3_TEMPLATE_EXTENSION = "ctp" data class SettingsState( var cakeTemplateExtension: String = DEFAULT_CAKE3_TEMPLATE_EXTENSION, var appDirectory: String = DEFAULT_APP_DIRECTORY, var appNamespace: String = DEFAULT_NAMESPACE, var pluginPath: String = "plugins", var cake2AppDirectory: String = "app", var cake2TemplateExtension: String = "ctp", var cake2PluginPath: String = "app/Plugin", var cake2Enabled: Boolean = false, var cake3Enabled: Boolean = true, var cake3ForceEnabled: Boolean = false, var pluginNamespaces: List<String> = arrayListOf("\\DebugKit"), var dataViewExtensions: List<String> = arrayListOf("json", "xml"), ) // For accessibility from Java, which doesn't support copy() with default args: fun copySettingsState(state: SettingsState): SettingsState = state.copy() data class CakeAutoDetectedValues( val cake3OrLaterPresent: Boolean = false, val namespace: String = DEFAULT_NAMESPACE, val appDirectory: String = DEFAULT_APP_DIRECTORY, ) @Service(Service.Level.PROJECT) class CakePhpAutoDetector(project: Project) { val projectRef = WeakReference(project) val autoDetectedValues by lazy { autodetectCakePhp() } private fun autodetectCakePhp(): CakeAutoDetectedValues { val project = projectRef.get() ?: return CakeAutoDetectedValues() val topDir = project.guessProjectDir() ?: return CakeAutoDetectedValues() val composerJson = topDir.findFileByRelativePath("composer.json") ?: return CakeAutoDetectedValues() val fullPath = composerJson.canonicalPath ?: return CakeAutoDetectedValues() val composerContents = File(fullPath).readText() val namespace = checkNamespaceInAppController(topDir) val (cake3OrLaterPresent: Boolean, appDirectory: String) = try { val composerJsonParsed = jsonParse(composerContents) as? Map<*, *> ?: throw Exception("Failed parsing") Pair( checkCakePhpInComposerJson(composerJsonParsed), extractAppDirFromComposerJson(composerJsonParsed, namespace) ) } catch (e: Exception) { Pair(false, DEFAULT_APP_DIRECTORY) } return CakeAutoDetectedValues( cake3OrLaterPresent = cake3OrLaterPresent, namespace = namespace, appDirectory = appDirectory, ) } private fun extractAppDirFromComposerJson( json: Map<*, *>, namespace: String ): String { val autoloadObj = json["autoload"] as? Map<*, *> ?: return DEFAULT_APP_DIRECTORY val psr4 = autoloadObj["psr-4"] as? Map<*, *> ?: return DEFAULT_APP_DIRECTORY val targetNamespace = "${namespace}\\".removeFromStart("\\") val directory = psr4[targetNamespace] as? String ?: return DEFAULT_APP_DIRECTORY return directory.removeFromEnd("/") } private fun checkCakePhpInComposerJson(composerParsed: Map<*, *>): Boolean { val required = composerParsed["require"] as? Map<*, *> ?: return false if (required["cakephp/cakephp"] != null) { return true } return false } private fun checkNamespaceInAppController(topDir: VirtualFile): String { val appController = topDir.findFileByRelativePath("src/Controller/AppController.php") ?: return DEFAULT_NAMESPACE val fullPath = appController.canonicalPath ?: return DEFAULT_APP_DIRECTORY val regex = Regex("^\\s*namespace\\s+([\\w\\\\]+);") val lines = File(fullPath).readLines() for (line in lines) { val namespace = regex.find(line)?.groupValues?.get(1) ?: continue return namespace.removeFromEnd("\\Controller").absoluteClassName() } return DEFAULT_NAMESPACE } } @Service(Service.Level.PROJECT) @State( name = "ChocolateCakePHPSettings", storages = [Storage( "ChocolateCakePHP.xml")] ) class Settings : PersistentStateComponent<SettingsState> { private var state = SettingsState() val cakeTemplateExtension get(): String { return if (state.cake3Enabled && !state.cake3ForceEnabled) { DEFAULT_CAKE3_TEMPLATE_EXTENSION } else { state.cakeTemplateExtension } } val appDirectory get(): String { return if (state.cake3Enabled && !state.cake3ForceEnabled) autoDetectedValues.appDirectory else state.appDirectory } val appNamespace get(): String { return if (state.cake3Enabled && !state.cake3ForceEnabled) autoDetectedValues.namespace else return state.appNamespace.absoluteClassName() } val pluginPath get() = state.pluginPath val cake2AppDirectory get() = state.cake2AppDirectory val cake2TemplateExtension get() = state.cake2TemplateExtension val cake2Enabled get() = state.cake2Enabled val cake3Enabled get() = cake3ForceEnabled || (state.cake3Enabled && autoDetectedValues.cake3OrLaterPresent) val cake3ForceEnabled get() = state.cake3ForceEnabled var autoDetectedValues = CakeAutoDetectedValues() val pluginEntries: List<PluginEntry> get() { return pluginEntryListFromNamespaceList(state.pluginNamespaces) } val dataViewExtensions: List<String> get() { return state.dataViewExtensions } val enabled: Boolean get() { return cake3Enabled || cake2Enabled } override fun equals(other: Any?): Boolean { return if (other is Settings) { this.state == other.state } else { false } } override fun hashCode(): Int { return state.hashCode() } override fun getState(): SettingsState { return this.state } override fun loadState(state: SettingsState) { this.state = state } companion object { @JvmStatic fun getInstance(project: Project): Settings { val settings = project.getService(Settings::class.java) if (settings.state.cake3Enabled && !settings.state.cake3ForceEnabled) { val autodetector = project.getService(CakePhpAutoDetector::class.java) settings.autoDetectedValues = autodetector.autoDetectedValues } return settings } @JvmStatic val defaults get() = Settings() @JvmStatic fun fromSettings(settings: Settings): Settings { val newState = settings.state.copy() val newSettings = Settings() newSettings.loadState(newState) return newSettings } @JvmStatic fun pluginEntryListFromNamespaceList(list: List<String>): List<PluginEntry> { val result = arrayListOf<PluginEntry>() list.forEach { result.add(PluginEntry(it)) } return result.toList() } @JvmStatic fun pluginNamespaceListFromEntryList(list: List<PluginEntry>): List<String> { val result = arrayListOf<String>() list.forEach { result.add(it.namespace) } return result } } }
15
Kotlin
0
16
5964682e85746d537870d81d1dbe2c531009c9b5
7,710
chocolate-cakephp
MIT License
src/main/kotlin/com/tuk/oriddle/global/message/StompMessage.kt
Team-Oriddle
731,663,342
false
{"Kotlin": 169575}
package com.tuk.oriddle.global.message interface StompMessage
0
Kotlin
1
0
cbca02a877b748d2ec4c8e872e4852c0248a4d8d
62
oriddle-backend
MIT License
src/main/java/space/impact/impact_compat/common/worldgen/CompatWorldGenSphere.kt
GT-IMPACT
658,419,880
false
null
package space.impact.impact_compat.common.worldgen import net.minecraft.block.Block import net.minecraft.util.MathHelper import net.minecraft.world.World import net.minecraft.world.chunk.IChunkProvider import space.impact.impact_compat.common.worldgen.WorldGenHelper.replaceableBlocks import java.util.* class CompatWorldGenSphere( name: String, isDefault: Boolean, block: Block, meta: Int, amount: Int, size: Int, minY: Int, maxY: Int, probability: Int, dimensionType: Int, biomeList: Collection<String> = emptyList(), allowGenVoid: Boolean = false, ) : CompatWorldGenBlocks(name, isDefault, block, meta, amount, size, minY, maxY, probability, dimensionType, biomeList, allowGenVoid) { override fun executeWorldGen( aWorld: World, aRandom: Random, aBiome: String, aDimensionType: Int, aChunkX: Int, aChunkZ: Int, aChunkGenerator: IChunkProvider, aChunkProvider: IChunkProvider ): Boolean { if ((isGenerationAllowed(aWorld, aDimensionType, dimensionType)) && ((biomeList.isEmpty()) || (biomeList.contains(aBiome))) && ((probability <= 1) || (aRandom.nextInt(probability) == 0)) ) { for (i in 0 until amount) { val tX = aChunkX + aRandom.nextInt(16) val tY: Int = minY + aRandom.nextInt(maxY - minY) val tZ = aChunkZ + aRandom.nextInt(16) if ((allowGenVoid) || (!aWorld.getBlock(tX, tY, tZ).isAir(aWorld, tX, tY, tZ))) { val math_pi = Math.PI.toFloat() val var6 = aRandom.nextFloat() * math_pi val var1d: Float = this.size / 8.0f val var2d = tX + 8 val var3d = tZ + 8 val var4d = tY - 2 val mh_s_0 = MathHelper.sin(var6) * var1d val mh_c_0 = MathHelper.cos(var6) * var1d val var7 = var2d + mh_s_0 val var11 = var3d + mh_c_0 val var15r = aRandom.nextInt(3) val var17r = aRandom.nextInt(3) val var15 = var4d + var15r val mh_n_4 = var17r - var15r val mh_n_0 = -2 * mh_s_0 val mh_n_1 = -2 * mh_c_0 for (var19 in 0..size) { val var5d: Float = (var19 / this.size).toFloat() val var20 = var7 + mh_n_0 * var5d val var22 = var15 + mh_n_4 * var5d val var24 = var11 + mh_n_1 * var5d val var6d: Float = var19 * math_pi / this.size val var26: Float = aRandom.nextFloat() * this.size / 16.0f val var28 = ((MathHelper.sin(var6d) + 1.0f) * var26 + 1.0f) / 2.0f val tMinX = MathHelper.floor_float(var20 - var28) val tMinY = MathHelper.floor_float(var22 - var28) val tMinZ = MathHelper.floor_float(var24 - var28) val tMaxX = MathHelper.floor_float(var20 + var28) val tMaxY = MathHelper.floor_float(var22 + var28) val tMaxZ = MathHelper.floor_float(var24 + var28) for (eX in tMinX..tMaxX) { val var39 = (eX + 0.5f - var20) / var28 val var10d = var39 * var39 if (var10d < 1.0f) { for (eY in tMinY..tMaxY) { val var42 = (eY + 0.5f - var22) / var28 val var12d = var10d + var42 * var42 if (var12d < 1.0f) { for (eZ in tMinZ..tMaxZ) { val var45 = (eZ + 0.5f - var24) / var28 if (var12d + var45 * var45 < 1.0f) { val tTargetedBlock = aWorld.getBlock(eX, eY, eZ) if (this.allowGenVoid && aWorld.getBlock(eX, eY, eZ).isAir(aWorld, eX, eY, eZ) || tTargetedBlock != null && tTargetedBlock.replaceableBlocks(aWorld, eX, eY, eZ)) { aWorld.setBlock(eX, eY, eZ, this.block, this.meta, 0) } } } } } } } } } } return true } return false } }
0
Kotlin
0
0
18ab2a6b7a88a76eb90a4edef9a8ce9db207f3c7
4,796
Impact-compat
MIT License
Kernl.Consumer/src/test/kotlin/associativememorycache/impl/SingleComplexParamPrimitiveReturnTest.kt
mattshoe
825,957,770
false
{"Kotlin": 344588, "Shell": 1045}
package associativememorycache.impl import org.mattshoe.shoebox.kernl.runtime.cache.associativecache.AssociativeCacheKernl import org.mattshoe.shoebox.kernl.models.ServiceRequest import kernl.org.mattshoe.shoebox.kernl.associativememorycache.SingleComplexParamPrimitiveReturnKernl import associativememorycache.AssociativeMemoryCacheScenariosTest class SingleComplexParamPrimitiveReturnTest : AssociativeMemoryCacheScenariosTest<SingleComplexParamPrimitiveReturnKernl.Params, Int>() { override fun repository(): AssociativeCacheKernl<SingleComplexParamPrimitiveReturnKernl.Params, Int> { return SingleComplexParamPrimitiveReturnKernl.Factory { id -> onFetch(SingleComplexParamPrimitiveReturnKernl.Params(id)) id.data.toInt() } } override val testData = mapOf( SingleComplexParamPrimitiveReturnKernl.Params(ServiceRequest("42")) to 42, SingleComplexParamPrimitiveReturnKernl.Params(ServiceRequest("96")) to 96, SingleComplexParamPrimitiveReturnKernl.Params(ServiceRequest("1")) to 1 ) }
10
Kotlin
1
9
9682fcafeb1dccd468443e1265eab55c05757e52
1,068
kernl
Apache License 2.0
app/src/main/kotlin/space/reul/ticketmasterchallenge/app/MainActivity.kt
reul
764,954,876
false
{"Kotlin": 53026}
package space.reul.ticketmasterchallenge.app import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.stringResource import dagger.hilt.android.AndroidEntryPoint import space.reul.ticketmasterchallenge.app.ui.composables.Events import space.reul.ticketmasterchallenge.app.ui.theme.TicketmasterChallengeTheme import space.reul.ticketmasterchallenge.app.ui.uistate.ScreenWrapper @AndroidEntryPoint class MainActivity : ComponentActivity() { private val viewModel: MainActivityViewModel by viewModels() @OptIn(ExperimentalMaterial3Api::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycle.addObserver(viewModel) setContent { TicketmasterChallengeTheme { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState()) val eventsFlow = viewModel.eventsFlow.collectAsState() val isConnectedFlow = viewModel.networkAvailableFlow.collectAsState() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { TopAppBar( title = { Text(text = stringResource(id = R.string.app_name)) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), scrollBehavior = scrollBehavior ) }, ) { innerPadding -> Surface( modifier = Modifier .padding(innerPadding) .background(MaterialTheme.colorScheme.secondaryContainer) .fillMaxSize() ) { // A surface container using the 'background' color from the theme ScreenWrapper( uiState = eventsFlow.value, showDisconnectedMessage = !isConnectedFlow.value ) { modifier, data -> Events(modifier, data) } } } } } } }
0
Kotlin
0
0
7ca0c967da83b3704894b19c27dad666cf440936
3,287
tiago-reul-ticketmaster-challenge
The Unlicense
imageclassifier_test/src/main/java/com/mozhimen/tfloader/imageclassifier/test/MainActivity.kt
mozhimen
504,380,742
false
{"Kotlin": 93845}
package com.mozhimen.tfloader.imageclassifier.test import android.view.View import com.mozhimen.kotlin.utilk.android.content.startContext import com.mozhimen.bindk.bases.viewbinding.activity.BaseActivityVB import com.mozhimen.tfloader.imageclassifier.test.databinding.ActivityMainBinding class MainActivity : BaseActivityVB<ActivityMainBinding>() { fun TFImageClassifier(view: View) { startContext<TFImageClassifierActivity>() } fun TFLiteImageClassifier(view: View) { startContext<TFLiteImageClassifierActivity>() } }
1
Kotlin
8
2
304a9bf6d7eb17f9d9f8b5fc329d78f9bcda08f8
554
ATFLiteLoader
Apache License 2.0
src/commonMain/kotlin/com.mfrancza.jwtrevocation/rules/conditions/DateTimeCondition.kt
mfrancza
585,426,278
false
null
package com.mfrancza.jwtrevocation.rules.conditions import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator @OptIn(ExperimentalSerializationApi::class) @Serializable @JsonClassDiscriminator("operation") sealed class DateTimeCondition : Condition<Long>
1
Kotlin
0
0
bae90e8b3abbf9f08071c70be3fd3ef05505e928
354
jwt-revocation-rules
Apache License 2.0
backend/src/main/kotlin/com/pwarss/api/UserController.kt
KhvanKonstantin
139,948,396
false
{"TypeScript": 43701, "Kotlin": 39875, "HTML": 1680}
// Created by <NAME> on 7/9/18 5:22 PM package com.pwarss.api import com.pwarss.model.User import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController /** * REST endpoint for login and logout commands */ @RestController @RequestMapping("/api") class UserController() { @GetMapping("/user") fun user(user: User): ResponseEntity<User> { return ResponseEntity.ok(user) } }
21
TypeScript
0
0
d3198fca4f955729c4ef7cbd3a3533ef419bb20a
565
pwarss
Apache License 2.0
settings-core/src/main/java/com/michaelflisar/settings/core/decorator/CardGroupDecorator.kt
MFlisar
256,263,996
false
null
package com.michaelflisar.settings.core.decorator import android.graphics.Canvas import android.graphics.Rect import android.util.Log import android.view.View import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import com.google.android.material.card.MaterialCardView import com.google.android.material.shape.CornerFamily import com.michaelflisar.settings.core.SettingsUtils import com.mikepenz.fastadapter.FastAdapter class CardGroupDecorator( private val cornerRadiusInDp: Int, private val topLevelStyle: Style, private val subLevelStyle: Style, private val groupTopLevelItemsWithoutGroups: Boolean, private val elevationInDp: Int, private val intentionMode: IntentionMode, private val intentInDp: Int, private val groupItemViewType: Int ) : ItemDecoration() { private val padding = SettingsUtils.dpToPx(cornerRadiusInDp) override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val childCount = parent.childCount Log.d("Decorator", "childCount = $childCount") for (i in 0 until childCount) { // ---------------------- // a) calculate variables // ---------------------- val childAbove = if (i > 0) parent.getChildAt(i - 1) else null val child = parent.getChildAt(i) val id = parent.getChildItemId(child) // val pos = parent.getChildAdapterPosition(child) // val viewType = getViewType(parent, pos) // following check is probably necessary because of a bug / sepcial behaviour in FastAdapter... val item = getSettingsItem(parent, id) ?: continue val isGroup = item.isCardGroupHeader() val parentSetting = item.getCardGroupParentItem() val hasParent = parentSetting != null val index = if (hasParent) parentSetting!!.getSubCardGroupItems().indexOf(item) else -1 // item.index ist ABSOLUTER Index ohne Filterung! val level = item.getLevel() //val setup = item.setup val isExpanded = item.isExpanded val currentIsHeader = isGroup // val currentIsFirstGroupItem = !isGroup && index == 0 // val currentIsLastGroupItem = hasParent && index == parentSetting!!.subItems.size - 1 val prevItem = getSettingsItemAt(parent, i - 1) val prevIsGroup = prevItem?.isCardGroupHeader() ?: false val prevLevel = prevItem?.getLevel() val prevItemOfSameGroup = if (hasParent && index > 0) parentSetting!!.getSubCardGroupItems()[index - 1] else null val prevItemOfSameGroupIsGroup = prevItemOfSameGroup?.isCardGroupHeader() ?: false val prevItemOfSameGroupIsExpandedSubGroup = prevItemOfSameGroupIsGroup && prevItemOfSameGroup?.isExpanded == true val nextItem = getSettingsItemAt(parent, i + 1) val nextIsGroup = nextItem?.isCardGroupHeader() ?: false // val prevIsSubGroup = prevItem?.item is BaseSettingsGroup // val nextIsSubGroup = nextItem?.item is BaseSettingsGroup val nextLevel = nextItem?.getLevel() // val prevIsExpandedSubGroup = prevIsSubGroup && prevItem!!.isExpanded val isFirstAndIsHeader = currentIsHeader && level == 0 val isNextATopGroup = nextIsGroup && nextLevel == 0 val isNextTopLevel = nextLevel == 0 val isTopLevelAndIsItem = !currentIsHeader && level == 0 val isLastItem = i == childCount - 1 val intention = calcIntentionInDp(intentionMode, intentInDp, level) val prevIntention = prevItem?.let { calcIntentionInDp(intentionMode, intentInDp, prevLevel!!) } val nextIntention = nextItem?.let { calcIntentionInDp(intentionMode, intentInDp, nextLevel!!) } // ---------------------- // b) calculate corners // ---------------------- val radius: Float = SettingsUtils.dpToPx(cornerRadiusInDp).toFloat() val cardStyle = CardStyle(radius) // 1) check if item has both corners at top // 1.1) Headers at top levels always have round corners at top // 1.2) Top level items may have round corners as well bases on flag if ((currentIsHeader && level == 0) || (!groupTopLevelItemsWithoutGroups && isTopLevelAndIsItem)) { cardStyle.setTopCorners() } // 2) check if item has both corners at bottom // 2.1) Headers at top levels have round corners if they are collapsed or do not have children // 2.2) Items before a new top level header have round corners // 2.3) Items inside a group that are before a top level item (last visible item of top group) have round corners // 2.4) Top level items may have round corners as well bases on flag // 2.5) Item inside a group that is the very last item has round corners if ((currentIsHeader && isTopLevelAndIsItem && (!isExpanded || item.getSubCardGroupItems().isEmpty())) || isNextATopGroup || isNextTopLevel || (!groupTopLevelItemsWithoutGroups && isTopLevelAndIsItem) || (!isTopLevelAndIsItem && isLastItem)) { cardStyle.setBottomCorners() } // 3) check if item has a coners at top/bottom because of intention if (prevIntention != null && prevIntention > intention) { cardStyle.setTopLeftCorner() } if (nextIntention != null && nextIntention > intention) { cardStyle.setBottomLeftCorner() } // ---------------------- // c) check style // ---------------------- // Cases: // Header => Item // Item => Header // Header => Header // Item => Item when (topLevelStyle) { Style.Flat -> { when (subLevelStyle) { Style.Flat, Style.CardsRect -> { cardStyle.setAll(false) } Style.CardsRounded -> { if (level == 0) { cardStyle.setAll(false) } else { if (!isGroup && prevIsGroup && level == 1) { cardStyle.setTopCorners() } } } } } Style.CardsRounded -> { when (subLevelStyle) { Style.Flat -> { if (level == 0) { cardStyle.setAll(true) } else { cardStyle.setAll(false) } } Style.CardsRect -> { if (level == 0) { cardStyle.setAll(true) } else { cardStyle.setAll(false) } if (isGroup && level == 0 && !nextIsGroup && nextLevel == 1) { cardStyle.setBottomCorners(false) } } Style.CardsRounded -> { // nothing to do } } } Style.CardsRect -> { when (subLevelStyle) { Style.Flat, Style.CardsRect -> { cardStyle.setAll(false) } Style.CardsRounded -> { if (level == 0) { cardStyle.setAll(false) } if (!isGroup && level == 1 && prevIsGroup && prevLevel == 0) { cardStyle.setTopCorners(false) } } } } } // ---------------------- // d) set corners // ---------------------- // Log.d("Decorator", "Index = $i | cardStyle: $cardStyle") val cardView = child as MaterialCardView cardStyle.apply(cardView) if (APPLY_CARD_STYLE_IN_DECORATOR) { val rootView = cardView.getChildAt(0) applyStyle(topLevelStyle, subLevelStyle, elevationInDp, cardView, rootView, level == 0) } } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val index = parent.getChildAdapterPosition(view) if (index == RecyclerView.NO_POSITION) { return } // ---------------------- // a) calculate variables // ---------------------- val item = (parent.adapter as FastAdapter<*>).getItem(index) as? ICardGroupItem ?: return val prevItem = index.takeIf { it > 0 }?.let { (parent.adapter as FastAdapter<*>).getItem(it - 1) as? ICardGroupItem } val childCount = (parent.adapter as FastAdapter<*>).itemCount val isLastIndex = index == childCount - 1 val type = getViewType(parent, index) val typePrev = if (index == 0) null else getViewType(parent, index - 1) // val typeNext = if (index + 1 == childCount) null else getViewType(parent, index + 1) val level = item.getLevel() // val setup = item.setup val isGroup = type == groupItemViewType val prevIsGroup = typePrev == groupItemViewType val prevLevel = prevItem?.getLevel() val isTopLevel = level == 0 val isFirstItem = index == 0 val isFirstItemAndIsNotAGroup = !isGroup && index == 0 val isItemUnderneathAGroup = !isGroup && prevIsGroup val isItemUnderneathNotTopLevelItem = !isGroup && prevLevel != null && prevLevel > 0 val isGroupAndNotFirstItem = index > 0 && isGroup // ---------------------- // b) calculate paddings // ---------------------- var hasTopPadding = isTopLevel && (isFirstItem /*isFirstItemAndIsNotAGroup*/ || isItemUnderneathAGroup || isItemUnderneathNotTopLevelItem || isGroupAndNotFirstItem) if (!groupTopLevelItemsWithoutGroups) { hasTopPadding = hasTopPadding || (isTopLevel && !isGroup) } val hasBottomPadding = isLastIndex val paddingLeft = SettingsUtils.dpToPx(calcIntentionInDp(intentionMode, intentInDp, level)) // ---------------------- // c) check style // ---------------------- // TODO: handle all cases.. if (topLevelStyle == Style.Flat && subLevelStyle == Style.Flat) { hasTopPadding = false } // ---------------------- // d) set paddings // ---------------------- outRect.top = if (hasTopPadding) padding else 0 outRect.bottom = if (hasBottomPadding) padding else 0 outRect.left = paddingLeft outRect.right = 0 } // ----------------- // helper functions // ----------------- companion object { val APPLY_CARD_STYLE_IN_DECORATOR = false // leads to flicker because this is happening too late fun applyStyle(topLevelStyle: Style, subLevelStyle: Style, elevationInDp: Int, cardView: MaterialCardView, contentView: View, isTopLevel: Boolean) { val style = if (isTopLevel) topLevelStyle else subLevelStyle val dp1 = SettingsUtils.dpToPx(1) // Padding vs Margin: // we change this so that both styles do look the same but only their touch feedback will look different depending on the style val elevation = if (style == Style.Flat) 0f else (dp1 * elevationInDp).toFloat() val useMargin = style == Style.CardsRounded val margin = if (useMargin) (dp1 * 16) else 0 val paddingHorizontal = if (useMargin) (dp1 * 8) else (dp1 * 16) cardView.cardElevation = elevation contentView.setPadding(paddingHorizontal, dp1 * 8, paddingHorizontal, dp1 * 8) // cardView.setContentPadding(paddingHorizontal, 0, paddingHorizontal, 0) (cardView.layoutParams as? ViewGroup.MarginLayoutParams)?.apply { leftMargin = margin rightMargin = margin } } } private fun getViewType(parent: RecyclerView, viewPosition: Int): Int { return parent.adapter!!.getItemViewType(viewPosition) } private fun getSettingsItem(parent: RecyclerView, id: Long): ICardGroupItem? { return (parent.adapter as FastAdapter<*>).getItemById(id)?.first as? ICardGroupItem } private fun getSettingsItemAt(parent: RecyclerView, pos: Int): ICardGroupItem? { if (pos < 0 || pos >= parent.childCount) { return null } val child = parent.getChildAt(pos) val id = parent.getChildItemId(child) return getSettingsItem(parent, id) } private fun calcIntentionInDp(intentionMode: IntentionMode, intentInDp: Int, level: Int): Int { return when (intentionMode) { IntentionMode.None -> 0 IntentionMode.AllSubItems -> intentInDp * level IntentionMode.SubGroups -> if (level == 0) 0 else (intentInDp * (level - 1)) } } private data class CardStyle( private val radius: Float, private var cornerTopLeft: Float = 0f, private var cornerTopRight: Float = 0f, private var cornerBottomRight: Float = 0f, private var cornerBottomLeft: Float = 0f ) { fun setAll(enabled: Boolean = true) { (if (enabled) radius else 0f).let { cornerTopLeft = it cornerTopRight = it cornerBottomRight = it cornerBottomLeft = it } } fun setTopLeftCorner(enabled: Boolean = true) { (if (enabled) radius else 0f).let { cornerTopLeft = it } } fun setBottomLeftCorner(enabled: Boolean = true) { (if (enabled) radius else 0f).let { cornerBottomLeft = it } } fun setTopCorners(enabled: Boolean = true) { (if (enabled) radius else 0f).let { cornerTopLeft = it cornerTopRight = it } } fun setBottomCorners(enabled: Boolean = true) { (if (enabled) radius else 0f).let { cornerBottomLeft = it cornerBottomRight = it } } fun apply(cardView: MaterialCardView) { cardView.shapeAppearanceModel = cardView.shapeAppearanceModel .toBuilder() .setTopLeftCorner(CornerFamily.ROUNDED, cornerTopLeft) .setTopRightCorner(CornerFamily.ROUNDED, cornerTopRight) .setBottomRightCorner(CornerFamily.ROUNDED, cornerBottomRight) .setBottomLeftCorner(CornerFamily.ROUNDED, cornerBottomLeft) .build() } } }
0
Kotlin
0
2
5fc5264a9b2bfc108aab03e8925244d665c6a9d4
15,800
Settings
Apache License 2.0
Hilt/app/src/main/java/com/example/hilt/MainActivity4.kt
fairoozp
356,848,633
false
null
package com.example.hilt import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.activity.viewModels import androidx.core.widget.doOnTextChanged import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController class MainActivity4 : AppCompatActivity() { private val viewModel: MyViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main4) val f1_next_button: Button = findViewById(R.id.a1_next_button) val et_f1_share: EditText = findViewById(R.id.et_a1_share) val imageView: ImageView = findViewById(R.id.imageView) imageView.setOnClickListener { observe() } f1_next_button.setOnClickListener { viewModel.setShared(et_f1_share.text.toString()) startActivity(Intent(this, MainActivity5::class.java)) } } private fun observe() { val tv_f1_share: TextView = findViewById(R.id.tv_a1_share) viewModel.shared.observeForever { tv_f1_share.text = it } } }
0
Kotlin
0
1
09bfb87ce91f6ccb6f8b08534b127f77116a5179
1,337
Android_Kotlin_projects
MIT License
runtime/src/main/java/com/edgeverse/wallet/runtime/multiNetwork/chain/remote/model/ChainRemote.kt
finn-exchange
512,140,809
false
null
package com.edgeverse.wallet.runtime.multiNetwork.chain.remote.model data class ChainRemote( val chainId: String, val name: String, val color: String?, val assets: List<ChainAssetRemote>, val nodes: List<ChainNodeRemote>, val explorers: List<ChainExplorerRemote>?, val externalApi: ChainExternalApiRemote?, val icon: String, val addressPrefix: Int, val types: ChainTypesInfo?, val options: List<String>?, val parentId: String?, val additional: Map<String, Any?>?, )
0
Kotlin
1
0
6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d
519
edgeverse-wallet
Apache License 2.0
VehicleUI/src/main/java/com/drivequant/drivekit/vehicle/ui/vehicledetail/common/VehicleCustomImageHelper.kt
DriveQuantPublic
216,339,559
false
{"Kotlin": 1646497, "Java": 8753}
package com.drivequant.drivekit.vehicle.ui.vehicledetail.common import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat.startActivityForResult import androidx.core.content.FileProvider import androidx.core.net.toUri import androidx.exifinterface.media.ExifInterface import com.drivequant.drivekit.common.ui.utils.convertDpToPx import com.drivequant.drivekit.core.DriveKit import com.drivequant.drivekit.core.DriveKitLog import com.drivequant.drivekit.vehicle.ui.DriveKitVehicleUI import com.drivequant.drivekit.vehicle.ui.R import com.drivequant.drivekit.vehicle.ui.listener.OnCameraPictureTakenCallback import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream /** * Created by steven on 26/07/2019. */ internal object VehicleCustomImageHelper { const val REQUEST_CAMERA = 11 fun getVehicleFileName(vehicleId: String) = "$vehicleId.png" fun openPhotoPicker(pickMedia: ActivityResultLauncher<PickVisualMediaRequest>) { pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } fun getImageUri(vehicleId: String): Uri? { val file = File(buildVehicleDirectory(), getVehicleFileName(vehicleId)) return if (file.exists() && file.canRead()) { return file.toUri() } else { null } } suspend fun saveImage(context: Context, filename: String, uri: Uri): Boolean = withContext(Dispatchers.IO) { val directory = buildVehicleDirectory() if (!directory.exists()) { val success = directory.mkdirs() if (!success) { DriveKitLog.e(DriveKitVehicleUI.TAG, "Couldn't create directory") return@withContext false } } val stream = context.contentResolver.openInputStream(uri) val originalBitmap = BitmapFactory.decodeStream(stream) originalBitmap.density = Bitmap.DENSITY_NONE val matrix = buildMatrixOrientation(context, uri) val computedImageSize = Pair(originalBitmap.width, originalBitmap.height).computeNewImageSize(context) val bitmap = Bitmap.createBitmap(originalBitmap, 0, 0, computedImageSize.first, computedImageSize.second, matrix, true) try { val file = File(directory, filename) FileOutputStream(file).use { out -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) return@withContext true } } catch (e: IOException) { DriveKitLog.e(DriveKitVehicleUI.TAG, "Couldn't create vehicle file: $e") return@withContext false } finally { stream?.close() } } private fun buildVehicleDirectory(): File { val filesDir: File = DriveKit.applicationContext.filesDir val directory = "DriveKitVehicleUI" return File(filesDir, directory) } fun openCamera(activity: Activity, outputFilename: String, cameraCallback: OnCameraPictureTakenCallback) { try { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val file = createImageFile(activity, outputFilename) val uri: Uri = FileProvider.getUriForFile(activity, activity.packageName + ".provider", file) intent.putExtra(MediaStore.EXTRA_OUTPUT, uri) val filePath = "file://" + file.absolutePath cameraCallback.onFilePathReady(filePath) startActivityForResult(activity, intent, REQUEST_CAMERA, null) } catch (e: Exception) { DriveKitLog.e(DriveKitVehicleUI.TAG, "Could not open camera: $e") } } @Throws(IOException::class) private fun createImageFile(activity: Activity, filename: String): File { // taken from https://developer.android.com/training/camera/photobasics val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile(filename, ".jpg", storageDir) } private fun buildMatrixOrientation(context: Context, uri: Uri): Matrix? = getImageOrientation(context, uri)?.let { val matrix = Matrix() matrix.setRotate(it.toFloat()) return matrix } ?: run { null } private fun getImageOrientation(context: Context, uri: Uri): Int? { var stream: InputStream? = null try { stream = context.contentResolver.openInputStream(uri) val exifInterface = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && stream != null) { ExifInterface(stream) } else { null // DriveKit will no longer support Android 6.0 and 7.0 in Q4 2024. } exifInterface?.let { val orientation = it.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) return when (orientation) { ExifInterface.ORIENTATION_ROTATE_270 -> 270 ExifInterface.ORIENTATION_ROTATE_180 -> 180 ExifInterface.ORIENTATION_ROTATE_90 -> 90 else -> null } } } catch (e: Exception) { DriveKitLog.e(DriveKitVehicleUI.TAG, "Couldn't get image orientation: $e") } finally { stream?.close() } return null } private fun Pair<Int, Int>.computeNewImageSize(context: Context): Pair<Int, Int> { val originalWidth = this.first val originalHeight = this.second val deviceScreenWidth = (context.resources.displayMetrics.widthPixels * context.resources.displayMetrics.density).toInt() val imageViewHeight = context.resources.getDimension(R.dimen.dk_vehicle_image_height).convertDpToPx() if (originalWidth > deviceScreenWidth && originalHeight > imageViewHeight) { val ratioWidth = originalWidth.toFloat() / deviceScreenWidth.toFloat() val newHeight = (originalHeight / ratioWidth).toInt() if (newHeight < imageViewHeight) { val ratioHeight = originalHeight.toFloat() / imageViewHeight.toFloat() val newWidth = (originalWidth / ratioHeight).toInt() return Pair(newWidth, imageViewHeight) } else { return Pair(deviceScreenWidth, newHeight) } } else { return this } } internal fun reset() { try { val files = buildVehicleDirectory().listFiles() var count = 0 if (files != null) { files.forEach { if (it.exists()) { count++ it.delete() } } DriveKitLog.i(DriveKitVehicleUI.TAG, "$count vehicle file(s) deleted") } } catch (e: Exception) { DriveKitLog.e(DriveKitVehicleUI.TAG, "An error occured during vehicle image deletion: $e") } } }
0
Kotlin
3
9
5e67fbaf3a815e59cff3138bfbad56db04648044
7,702
drivekit-ui-android
Apache License 2.0
TierWhere/app/src/main/java/site/yoonsang/tierwhere/src/main/search/favorite/FavoriteRetrofitInterface.kt
yoonsangkwak
357,787,150
false
null
package site.yoonsang.tierwhere.src.main.search.favorite import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import site.yoonsang.tierwhere.src.main.search.favorite.model.FavoriteSummoner interface FavoriteRetrofitInterface { @GET("/lol/summoner/v4/summoners/by-name/{summonerName}") fun getSummoner( @Path("summonerName") summonerName: String ): Call<FavoriteSummoner> }
0
Kotlin
1
0
2e7cf8827c4dc3dbede448751ce0844a6c29b1f0
417
TierWhere
MIT License
kotlin/src/main/kotlin/AoC_Day17.kt
sviams
115,921,582
false
null
object AoC_Day17 { fun solvePt1(input: Int) : Int { val endState = generateSequence(Pair(0,arrayOf(0))) { val newPos = (it.first + input) % it.second.size + 1 Pair(newPos, (it.second.sliceArray(0..(newPos-1)) + it.second.size + it.second.sliceArray((newPos) until it.second.size))) }.take(2018).last() return endState.second[endState.first + 1] } fun solvePt2(input: Int) : Int = generateSequence(Triple(0, 1, emptyArray<Int>())) { val newPos = (it.first + input) % it.second + 1 if (newPos == 1) Triple(newPos, it.second + 1, it.third + it.second) else Triple(newPos, it.second + 1, it.third) }.take(50000000).last().third.last() }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
746
aoc17
MIT License
src/main/kotlin/tokyo/aieuo/mineflow/flowItem/action/player/AddXpProgress.kt
aieuo
364,472,156
false
null
package tokyo.aieuo.mineflow.flowItem.action.player import tokyo.aieuo.mineflow.flowItem.FlowItem import tokyo.aieuo.mineflow.flowItem.FlowItemExecutor import tokyo.aieuo.mineflow.flowItem.FlowItemIds import tokyo.aieuo.mineflow.flowItem.base.PlayerFlowItem import tokyo.aieuo.mineflow.formAPI.element.Element import tokyo.aieuo.mineflow.formAPI.element.mineflow.ExampleNumberInput import tokyo.aieuo.mineflow.formAPI.element.mineflow.PlayerVariableDropdown import tokyo.aieuo.mineflow.formAPI.response.CustomFormResponseList import tokyo.aieuo.mineflow.utils.Category import tokyo.aieuo.mineflow.utils.DummyVariableMap import tokyo.aieuo.mineflow.utils.Language @Suppress("LeakingThis") open class AddXpProgress(player: String = "", var xp: String = "") : FlowItem(), PlayerFlowItem { override val id = FlowItemIds.ADD_XP_PROGRESS override val nameTranslationKey = "action.addXp.name" override val detailTranslationKey = "action.addXp.detail" override val detailDefaultReplaces = listOf("player", "value") override val category = Category.PLAYER override var playerVariableNames: MutableMap<String, String> = mutableMapOf() init { setPlayerVariableName(player) } override fun isDataValid(): Boolean { return xp != "" } override fun getDetail(): String { if (!isDataValid()) return getName() return Language.get(detailTranslationKey, listOf(getPlayerVariableName(), xp)) } override fun execute(source: FlowItemExecutor) = sequence { throwIfCannotExecute() val xpStr = source.replaceVariables(xp) throwIfInvalidNumber(xp) var xp = xpStr.toInt() val player = getPlayer(source) throwIfInvalidPlayer(player) val new = player.experience + xp if (new < 0) xp = -player.experience player.addExperience(xp) yield(FlowItemExecutor.Result.CONTINUE) } override fun getEditFormElements(variables: DummyVariableMap): List<Element> { return listOf( PlayerVariableDropdown(variables, getPlayerVariableName()), ExampleNumberInput("@action.addXp.form.xp", "10", xp, true), ) } override fun loadSaveData(contents: CustomFormResponseList) = apply { setPlayerVariableName(contents.getString(0)) xp = contents.getString(1) } override fun serializeContents(): List<Any> { return listOf(getPlayerVariableName(), xp) } override fun clone(): AddXpProgress { val item = super.clone() as AddXpProgress item.playerVariableNames = playerVariableNames.toMutableMap() return item } }
0
Kotlin
0
0
9c2ef7133d84c5d9b6f4336463d9e1d56442924a
2,657
Mineflow-Kotlin
MIT License
app/src/main/java/soy/gabimoreno/movies/di/DataModule.kt
soygabimoreno
238,377,569
false
{"Kotlin": 61734}
package soy.gabimoreno.movies.di import dagger.Module import dagger.Provides import soy.gabimoreno.movies.data.PermissionChecker import soy.gabimoreno.movies.data.repository.MoviesRepository import soy.gabimoreno.movies.data.repository.RegionRepository import soy.gabimoreno.movies.data.source.LocalDataSource import soy.gabimoreno.movies.data.source.LocationDataSource import soy.gabimoreno.movies.data.source.RemoteDataSource import soy.gabimoreno.movies.domain.Keys import javax.inject.Named @Module class DataModule { @Provides fun regionRepositoryProvider( locationDataSource: LocationDataSource, permissionChecker: PermissionChecker ) = RegionRepository( locationDataSource, permissionChecker ) @Provides fun moviesRepositoryProvider( localDataSource: LocalDataSource, remoteDataSource: RemoteDataSource, regionRepository: RegionRepository, @Named(Keys.API_KEY) apiKey: String ) = MoviesRepository( localDataSource, remoteDataSource, regionRepository, apiKey ) }
0
Kotlin
0
0
ea1621da6d6840802770e2cef426019bd572f362
1,101
Movies
Apache License 2.0
src/main/kotlin/com/github/oduig/kotlin/springboot/starter/config/properties/StarterConfigProperties.kt
Oduig
170,754,806
false
null
package com.github.oduig.kotlin.springboot.starter.config.properties import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties(prefix = "starter") data class StarterConfigProperties( // These need to be nullable so Spring Boot can load them var slothDelayMs: Long? = null, var cors: CorsConfigProperties? = CorsConfigProperties(), var webClient: WebClientConfigProperties? = WebClientConfigProperties() )
0
Kotlin
0
1
b1c23a31089856e461daed373572475e337454ea
465
kotlin-springboot-starter
MIT License