path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/ink/ptms/chemdah/core/quest/objective/bukkit/IEntityInteract.kt
TabooLib
338,114,548
false
null
package ink.ptms.chemdah.core.quest.objective.bukkit import ink.ptms.chemdah.core.quest.objective.Dependency import ink.ptms.chemdah.core.quest.objective.ObjectiveCountableI import org.bukkit.event.player.PlayerInteractAtEntityEvent /** * Chemdah * ink.ptms.chemdah.core.quest.objective.bukkit.IEntityInteract * * @author sky * @since 2021/3/2 5:09 下午 */ @Dependency("minecraft") object IEntityInteract : ObjectiveCountableI<PlayerInteractAtEntityEvent>() { override val name = "entity interact" override val event = PlayerInteractAtEntityEvent::class.java init { handler { it.player } addSimpleCondition("position") { data, e -> data.toPosition().inside(e.rightClicked.location) } addSimpleCondition("position:clicked") { data, e -> data.toVector().inside(e.clickedPosition) } addSimpleCondition("entity") { data, e -> data.toInferEntity().isEntity(e.rightClicked) } addSimpleCondition("hand") { data, e -> data.asList().any { it.equals(e.hand.name, true) } } addSimpleCondition("item") { data, e -> data.toInferItem().isItem(e.player.equipment!!.getItem(e.hand)) } } }
6
Kotlin
44
55
cac7ab72556538dfcfe53b2169c93687c69b3f31
1,264
chemdah
MIT License
app/src/main/java/com/gaugustini/shiny/presentation/result/ResultScreen.kt
gaugustini
695,659,583
false
{"Kotlin": 30639}
package com.gaugustini.shiny.presentation.result import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.hilt.navigation.compose.hiltViewModel import com.gaugustini.shiny.domain.model.Result import com.gaugustini.shiny.presentation.theme.ShinyTheme @Composable fun ResultScreen( viewModel: ResultViewModel = hiltViewModel() ) { val state = viewModel.resultState Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ResultScreenContent(state) } } @Composable fun ResultScreenContent( state: ResultState ) { LazyColumn { items(state.results) {result -> Text(text = result.head) Text(text = result.body) Text(text = result.arms) Text(text = result.waist) Text(text = result.legs) result.decorations.forEach { (decorations, amount) -> Text(text = "$decorations x $amount") } } } } @Preview(name = "Light Mode") //@Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun SearchScreenPreview( @PreviewParameter(ResultScreenPreviewParamProvider::class) state: ResultState ) { ShinyTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ResultScreenContent(state) } } } private class ResultScreenPreviewParamProvider : PreviewParameterProvider<ResultState> { val result = Result("Head", "Body", "Arms", "Waist", "Legs", mapOf("Decoration A" to 1, "Decoration B" to 2, "Decoration C" to 3)) override val values: Sequence<ResultState> = sequenceOf( ResultState(results = listOf(result, result, result, result, result, result)) ) }
0
Kotlin
0
0
c28b1ee6932cf69bdab5038e62ae7113e0a90b6b
2,322
shiny
MIT License
lib/src/main/kotlin/treelib/abstractTree/balanced/BalancerNoParent.kt
spbu-coding-2022
616,414,890
false
null
package treelib.abstractTree.balanced import treelib.abstractTree.Node import treelib.abstractTree.StateContainer import treelib.singleObjects.exceptions.IllegalNodeStateException abstract class BalancerNoParent<Pack : Comparable<Pack>, NodeType : Node<Pack, NodeType>, StateContainerType : StateContainer<Pack, NodeType>> : Balancer<Pack, NodeType, StateContainerType> { override fun rightRotate(currentNode: NodeType): NodeType { val leftSon = currentNode.left ?: throw IllegalNodeStateException() currentNode.left = leftSon.right leftSon.right = currentNode return leftSon } override fun leftRotate(currentNode: NodeType): NodeType { val rightSon = currentNode.right ?: throw IllegalNodeStateException() currentNode.right = rightSon.left rightSon.left = currentNode return rightSon } }
9
Kotlin
2
4
8abae618ab4f5b6d329046b897d1e62f60e1f8f0
876
trees-1
Apache License 2.0
subprojects/android-test/test-report/src/main/kotlin/com/avito/android/test/report/TestCaseAssertion.kt
StanlyT
344,157,673
true
{"Kotlin": 2773538, "HTML": 121161, "Shell": 17522, "Python": 14168, "Makefile": 7187, "Dockerfile": 7134}
package com.avito.android.test.report interface TestCaseAssertion { fun assertion(assertionMessage: String, action: () -> Unit) }
0
Kotlin
0
0
96463f7714c0550e331d2a37fb32ad98fac9d62d
135
avito-android
MIT License
src/main/kotlin/com/informalware/footylens/routes/Match.kt
informalware
770,996,595
false
{"Kotlin": 45742, "Shell": 5660, "Dockerfile": 96}
package com.informalware.footylens.routes import com.informalware.footylens.data.Matches import com.informalware.footylens.data.Match import com.informalware.footylens.data.Events import com.informalware.footylens.data.MatchRegistryRequest import com.informalware.footylens.plugins.validateMatchById import com.informalware.footylens.plugins.connectFooty import com.informalware.footylens.plugins.matches import com.informalware.footylens.plugins.events import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.ktorm.database.Database import org.ktorm.dsl.* import org.ktorm.entity.* /** * Define as rotas de GET para as partidas * */ fun Application.matchGetRoutes() { routing { // Obtém uma série de partidas get("/matches") { val database = connectFooty() when (val reqs = call.receive<Map<String, List<Int>>>()["matches"]) { null -> call.respond(HttpStatusCode.BadRequest, mapOf("error" to "Missing `matches` field with a list of requested matches")) else -> { val invalid = reqs.filter { !database.validateMatchById(it) } if (invalid.isNotEmpty()) { call.respond(HttpStatusCode.NotFound, mapOf("error" to "Matches not found: $invalid")) } else { val matches = database.matches.filter { Matches.id inList reqs }.toList() call.respond(mapOf("matches" to matches)) } } } } // Obtém dados da partida get("/matches/{id}") { val database = connectFooty() call.parameters["id"]?.let {id -> val query = database.matches.find { Matches.id eq (id.toInt()) } if (query == null) { call.respond(HttpStatusCode.NotFound, mapOf("error" to "$id is not a registered match")) } else { val req = call.receive<Map<String, List<String>>>() val match = (query as Match) call.respond(Match) } } } // Obtém mais detalhes de uma partida get("/matches/{id}/details") { val database = connectFooty() call.parameters["id"]?.let {id -> val query = database.matches.find { Matches.id eq (id.toInt()) } if (query == null) { call.respond(HttpStatusCode.NotFound, mapOf("error" to "$id is not a registered match")) } else { val events = database.events .filter { Events.matchId eq id.toInt() } .map { it.id } call.respond(mapOf("events" to events)) } } } // Obtém reviews de uma partida get("/matches/{id}/reviews") { val database = connectFooty() call.parameters["id"]?.let {id -> val query = database.matches.find { Matches.id eq (id.toInt()) } if (query == null) { call.respond(HttpStatusCode.NotFound, mapOf("error" to "$id is not a registered match")) } else { val reviews = database.matches .filter { Matches.id eq id.toInt() } .map { it.id } call.respond(mapOf("reviews" to reviews)) } } } } } /** * Define as rotas de POST para as partidas * */ fun Application.matchPostRoutes() { routing { // Registra uma nova partida post("/matches") { val database = connectFooty() val req = call.receive<MatchRegistryRequest>() database.insert(Matches) { set(it.home, req.home) set(it.away, req.away) set(it.home_scoreboard, req.scoreboard.first) set(it.away_scoreboard, req.scoreboard.second) } call.respond(HttpStatusCode.Created, mapOf("ok" to true)) } } }
0
Kotlin
0
0
b69ffdc9296fe450d4b1e131aeebb961d904eff2
4,246
footylens-server
MIT License
src/main/kotlin/com/rmarioo/checkout/events/EventHandler.kt
rmarioo
303,830,669
false
null
package com.rmarioo.checkout.events import com.rmarioo.checkout.CheckoutStatus import com.rmarioo.checkout.events.Event.DELIVERED import com.rmarioo.checkout.events.Event.NOTIFICATION_CREATED import com.rmarioo.checkout.events.Event.NOTIFICATION_SENT import com.rmarioo.checkout.events.Event.PAID import com.rmarioo.checkout.events.Event.PURCHASED class EventHandler { fun retrieveCurrentState(eventStore: EventStore): CheckoutStatus { val events = eventStore.readEvents() val status: CheckoutStatus = events.fold(CheckoutStatus.WISH_LIST,::onEvent) return status } private fun onEvent(currentStatus: CheckoutStatus, event: Event): CheckoutStatus { return when(event) { is PAID -> when (currentStatus) { is CheckoutStatus.WISH_LIST -> CheckoutStatus.ORDER(event.payment) else -> logErrorAndReturn(event, currentStatus, "PAID") } is PURCHASED -> CheckoutStatus.BOOKING(event.pricedProduct) is DELIVERED -> CheckoutStatus.DELIVERED(event.deliveryInfo) is NOTIFICATION_CREATED -> CheckoutStatus.NOTIFICATION_CREATED(event.receipt) is NOTIFICATION_SENT -> CheckoutStatus.BOOKING_COMPLETED } } private fun logErrorAndReturn( event: Event, currentStatus: CheckoutStatus, expectedEvent: String ): CheckoutStatus { System.err.println("error received event ${event} but not $expectedEvent "); return currentStatus } }
0
Kotlin
1
2
05c25808b4495a43129b2d56ad6b2d0ecc73e5e8
1,535
checkout-event-sourcing
MIT License
src/main/kotlin/me/nepnep/lambdaauth/AuthModule.kt
NepNep21
376,793,261
false
null
package me.nepnep.lambdaauth import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonObject import com.lambda.client.event.events.GuiEvent import com.lambda.client.mixin.extension.message import com.lambda.client.module.Category import com.lambda.client.plugin.api.PluginModule import com.lambda.client.event.listener.listener import com.mojang.authlib.Agent import com.mojang.authlib.UserType import com.mojang.authlib.exceptions.AuthenticationException import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService import com.mojang.util.UUIDTypeAdapter import net.minecraft.client.gui.GuiDisconnected import net.minecraft.client.multiplayer.GuiConnecting import net.minecraft.client.resources.I18n import net.minecraft.util.Session import org.apache.http.client.methods.CloseableHttpResponse import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.entity.StringEntity import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients import org.apache.http.util.EntityUtils import java.util.* internal object AuthModule : PluginModule( name = "LambdaAuth", category = Category.MISC, description = "Automatically fixes the invalid session error", pluginMain = LambdaAuth ) { private val type by setting("Type", Type.MOJANG) private val email by setting("Email", "", { type == Type.MOJANG }) private val password by setting("Password", "", { type == Type.MOJANG }) internal val msaUsername by setting("Microsoft email", "", { type == Type.MICROSOFT }) private enum class Type { MOJANG, MICROSOFT } private val gson = Gson() private val jsonClass = JsonObject::class.java init { listener<GuiEvent.Displayed> { event -> val message = I18n.format("disconnect.loginFailed") + ": " + I18n.format("disconnect.loginFailedInfo.invalidSession") if (event.screen is GuiDisconnected && (event.screen as GuiDisconnected).message.unformattedText == message) { var session: Session? = null if (type == Type.MOJANG) { val authenticationService = YggdrasilAuthenticationService(mc.proxy, UUID.randomUUID().toString()) val userAuthentication = authenticationService.createUserAuthentication(Agent.MINECRAFT) userAuthentication.setUsername(email) userAuthentication.setPassword(<PASSWORD>) try { userAuthentication.logIn() session = Session( userAuthentication.selectedProfile.name, UUIDTypeAdapter.fromUUID(userAuthentication.selectedProfile.id), userAuthentication.authenticatedToken, userAuthentication.userType.name ) userAuthentication.logOut() } catch (e: AuthenticationException) { LambdaAuth.logger.error("Failed to authenticate with mojang", e) } } else { AuthCommand.authResult?.accessToken()?.let { token -> HttpClients.createDefault().use { client -> xblAuth(client, token).use { response -> val responseBody = gson.fromJson(EntityUtils.toString(response.entity), jsonClass) val xblToken = responseBody["Token"].asString val userHash = responseBody["DisplayClaims"] .asJsonObject["xui"] .asJsonArray[0] .asJsonObject["uhs"] .asString xstsAuth(client, xblToken).use { xstsResponse -> val xstsResponseBody = gson.fromJson(EntityUtils.toString(xstsResponse.entity), jsonClass) if (xstsResponse.statusLine.statusCode == 401) { LambdaAuth.logger.error("XSTS auth returned 401 with XErr ${xstsResponseBody["XErr"].asLong}") return@listener } val xstsToken = xstsResponseBody["Token"].asString minecraftAuth(client, xstsToken, userHash).use { mcResponse -> val mcToken = gson.fromJson(EntityUtils.toString(mcResponse.entity), jsonClass)["access_token"] .asString getProfile(client, mcToken).use { profile -> val status = profile.statusLine.statusCode if (status != 200) { LambdaAuth.logger.error("Error while fetching profile $status") return@listener } val profileBody = gson.fromJson(EntityUtils.toString(profile.entity), jsonClass) val uuid = profileBody["id"].asString val name = profileBody["name"].asString session = Session( name, uuid, mcToken, UserType.MOJANG.name ) } } } } } } } session?.let { nonNullSession -> LambdaAuth.changeSession(nonNullSession) mc.currentServerData?.let { mc.displayGuiScreen(GuiConnecting(event.screen!!, mc, it)) } } } } } private fun xblAuth(client: CloseableHttpClient, token: String): CloseableHttpResponse { val innerObject = JsonObject() innerObject.addProperty("AuthMethod", "RPS") innerObject.addProperty("SiteName", "user.auth.xboxlive.com") innerObject.addProperty("RpsTicket", "d=$token") val bodyObject = JsonObject() bodyObject.add("Properties", innerObject) bodyObject.addProperty("RelyingParty", "http://auth.xboxlive.com") bodyObject.addProperty("TokenType", "JWT") val request = HttpPost("https://user.auth.xboxlive.com/user/authenticate") request.entity = StringEntity(bodyObject.toString()) request.setHeader("Content-Type", "application/json") request.setHeader("Accept", "application/json") return client.execute(request) } private fun xstsAuth(client: CloseableHttpClient, token: String): CloseableHttpResponse { val innerObject = JsonObject() innerObject.addProperty("SandboxId", "RETAIL") val tokenArray = JsonArray() tokenArray.add(token) innerObject.add("UserTokens", tokenArray) val bodyObject = JsonObject() bodyObject.add("Properties", innerObject) bodyObject.addProperty("RelyingParty", "rp://api.minecraftservices.com/") bodyObject.addProperty("TokenType", "JWT") val request = HttpPost("https://xsts.auth.xboxlive.com/xsts/authorize") request.entity = StringEntity(bodyObject.toString()) request.setHeader("Content-Type", "application/json") request.setHeader("Accept", "application/json") return client.execute(request) } private fun minecraftAuth(client: CloseableHttpClient, token: String, userHash: String): CloseableHttpResponse { val bodyObject = JsonObject() bodyObject.addProperty("identityToken", "<PASSWORD> x=$userHash;$token") val request = HttpPost("https://api.minecraftservices.com/authentication/login_with_xbox") request.entity = StringEntity(bodyObject.toString()) // Maybe not necessary? request.setHeader("Content-Type", "application/json") request.setHeader("Accept", "application/json") return client.execute(request) } private fun getProfile(client: CloseableHttpClient, token: String): CloseableHttpResponse { val request = HttpGet("https://api.minecraftservices.com/minecraft/profile") request.setHeader("Authorization", "Bearer $token") return client.execute(request) } }
0
Kotlin
0
1
88ddb83d2fbac899b256bb741d64a1e91e2c3024
8,972
lambda-auth
MIT License
src/test/kotlin/biokotlin/genome/TravisTest.kt
maize-genetics
281,224,272
false
{"Kotlin": 921743, "Jupyter Notebook": 222698, "Nu": 8928, "QMake": 1381, "Prolog": 401}
package biokotlin.genome import biokotlin.seq.NucSeq fun main() { /* val gcSame: (NucSeq, NucSeq) -> Boolean = { a, b -> (a.gc() / a.size() == b.gc() / b.size()) } val repeatOverlapSame: (SRange, SRange, SRange) -> Boolean = { a, b, r -> (a.overlapPerc(r) == b.overlapPerc(r)) } val compFunc: (SRange, SRange, SRange) -> Boolean = { a, b, r -> gcSame(a.seq(), b.seq()) and repeatOverlapSame(a, b, r) } val aSeq = NucSeq("ACGTCCTG") val positivePeaks: SRangeSet = bedfileToSRangeSet("peaks.bed") var negativePeaks = overlappingSetOf(SeqPositionRangeComparator.sprComparator, listOf()) for (positivePeak in positivePeaks) { val searchSpace = positivePeak .flankBoth(30000) .toSet() .subtract( positivePeaks.union(negativePeaks) ) val pairedIntervals = aSeq.pairedIntervals(positivePeak, searchSpace, gcSame, n = 5) negativePeaks = negativePeaks.union(pairedIntervals) } negativePeaks.toBedFile("peaks.neg.bed") */ }
2
Kotlin
1
6
50c26a6e279e36450175b9a00fd30d4f94040f9f
1,085
BioKotlin
Apache License 2.0
compiler/testData/diagnostics/tests/override/MultipleDefaultsInSupertypesNoExplicitOverride.fir.kt
JetBrains
3,432,266
false
null
interface X { fun foo(a : Int = 1) } interface Y { fun foo(a : Int = 1) } <!ABSTRACT_MEMBER_NOT_IMPLEMENTED!>class Z1<!> : X, Y {} // BUG <!ABSTRACT_MEMBER_NOT_IMPLEMENTED!>object Z1O<!> : X, Y {} // BUG
154
Kotlin
5566
45,025
8a69904d02dd3e40fae5f2a1be4093d44a227788
214
kotlin
Apache License 2.0
testing/core-test-utils/src/main/kotlin/net/corda/coretesting/internal/performance/Rate.kt
corda
70,137,417
false
null
package net.corda.testing.internal.performance import java.time.Duration import java.time.temporal.ChronoUnit import java.util.concurrent.TimeUnit /** * [Rate] holds a quantity denoting the frequency of some event e.g. 100 times per second or 2 times per day. */ data class Rate( val numberOfEvents: Long, val perTimeUnit: TimeUnit ) { /** * Returns the interval between two subsequent events. */ fun toInterval(): Duration { return Duration.of(TimeUnit.NANOSECONDS.convert(1, perTimeUnit) / numberOfEvents, ChronoUnit.NANOS) } /** * Converts the number of events to the given unit. */ operator fun times(inUnit: TimeUnit): Long = inUnit.convert(numberOfEvents, perTimeUnit) override fun toString(): String = "$numberOfEvents / ${perTimeUnit.name.dropLast(1).toLowerCase()}" // drop the "s" at the end } operator fun Long.div(timeUnit: TimeUnit) = Rate(this, timeUnit)
62
null
1087
3,989
d27aa0e6850d3804d0982024054376d452e7073a
945
corda
Apache License 2.0
app/src/main/kotlin/com/citrus/theme/ThemeFunctions.kt
Citrus-CAF
99,509,439
false
null
package substratum.theme.template import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.Signature import android.net.Uri import android.os.RemoteException import android.widget.Toast import substratum.theme.template.Constants.BLACKLISTED_APPLICATIONS import substratum.theme.template.Constants.ENABLE_KNOWN_THIRD_PARTY_THEME_MANAGERS import substratum.theme.template.Constants.MINIMUM_SUBSTRATUM_VERSION import substratum.theme.template.Constants.OTHER_THEME_SYSTEMS @Suppress("ConstantConditionIf") // This needs to be defined by the themer, so suppress! object ThemeFunctions { val SUBSTRATUM_PACKAGE_NAME = "projekt.substratum" fun isPackageInstalled(context: Context, package_name: String): Boolean { return try { val pm = context.packageManager val ai = context.packageManager.getApplicationInfo(package_name, 0) pm.getPackageInfo(package_name, PackageManager.GET_ACTIVITIES) ai.enabled } catch (e: Exception) { false } } @SuppressLint("PackageManagerGetSignatures") private fun checkSubstratumIntegrity(context: Context, packageName: String?): Boolean { return try { val pm = context.packageManager val pi = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) if (pi.signatures != null && pi.signatures.size == 1 && ((SIGNATURES[0] == pi.signatures[0]) || (SIGNATURES[1] == pi.signatures[0]))) { return true } false } catch (e: RemoteException) { false } } fun getSubstratumFromPlayStore(activity: Activity) { val playURL = "https://play.google.com/store/apps/details?id=projekt.substratum" val i = Intent(Intent.ACTION_VIEW) Toast.makeText( activity, activity.getString(R.string.toast_substratum), Toast.LENGTH_SHORT ).show() i.data = Uri.parse(playURL) activity.startActivity(i) activity.finishAffinity() } fun hasOtherThemeSystem(context: Context): Boolean { try { val pm = context.packageManager for (s: String in OTHER_THEME_SYSTEMS) { val ai = pm.getApplicationInfo(s, 0) pm.getPackageInfo(s, PackageManager.GET_ACTIVITIES) return ai.enabled } } catch (e: Exception) { } return false } fun getSubstratumUpdatedResponse(context: Context): Boolean { try { val packageInfo = context.applicationContext.packageManager .getPackageInfo(SUBSTRATUM_PACKAGE_NAME, 0) if (packageInfo.versionCode >= MINIMUM_SUBSTRATUM_VERSION) { return true } } catch (e: Exception) { // Suppress warning } return false } fun getSelfVerifiedIntentResponse(context: Context): Int? { return if (ENABLE_KNOWN_THIRD_PARTY_THEME_MANAGERS) { getSelfSignature(context) } else { getSubstratumSignature(context) } } fun getSelfVerifiedPirateTools(context: Context): Boolean { BLACKLISTED_APPLICATIONS .filter { isPackageInstalled(context, it) } .forEach { return true } return false } fun checkSubstratumIntegrity(context: Context): Boolean { SIGNATURES .filter { checkSubstratumIntegrity(context, SUBSTRATUM_PACKAGE_NAME) } .forEach { return true } return false } fun getSelfVerifiedThemeEngines(context: Context): Boolean? { val isPermitted: Boolean? = OTHER_THEME_SYSTEMS.any { isPackageInstalled(context, it) } if (ENABLE_KNOWN_THIRD_PARTY_THEME_MANAGERS) { return isPermitted } else if (isPackageInstalled(context, SUBSTRATUM_PACKAGE_NAME)) { return (!isPermitted!!) } return false } fun isCallingPackageAllowed(packageId: String): Boolean { if (packageId == SUBSTRATUM_PACKAGE_NAME) return true if (ENABLE_KNOWN_THIRD_PARTY_THEME_MANAGERS) { OTHER_THEME_SYSTEMS.filter { packageId == it }.forEach { return true } } return false } @SuppressLint("PackageManagerGetSignatures") private fun getSubstratumSignature(context: Context): Int { val sigs: Array<Signature> try { sigs = context.packageManager.getPackageInfo( SUBSTRATUM_PACKAGE_NAME, PackageManager.GET_SIGNATURES ).signatures return sigs[0].hashCode() } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } @SuppressLint("PackageManagerGetSignatures") fun getSelfSignature(context: Context): Int { val sigs: Array<Signature> try { sigs = context.packageManager.getPackageInfo( context.packageName, PackageManager.GET_SIGNATURES ).signatures return sigs[0].hashCode() } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } // Enforce a way to get official support from the team, by ensuring that only private val SUBSTRATUM_SIGNATURE = Signature("" + "308202eb308201d3a003020102020411c02f2f300d06092a864886f70d01010b050030263124302206" + "03550403131b5375627374726174756d20446576656c6f706d656e74205465616d301e170d31363037" + "30333032333335385a170d3431303632373032333335385a3026312430220603550403131b53756273" + "74726174756d20446576656c6f706d656e74205465616d30820122300d06092a864886f70d01010105" + "000382010f003082010a02820101008855626336f645a335aa5d40938f15db911556385f72f72b5f8b" + "ad01339aaf82ae2d30302d3f2bba26126e8da8e76a834e9da200cdf66d1d5977c90a4e4172ce455704" + "a22bbe4a01b08478673b37d23c34c8ade3ec040a704da8570d0a17fce3c7397ea63ebcde3a2a3c7c5f" + "983a163e4cd5a1fc80c735808d014df54120e2e5708874739e22e5a22d50e1c454b2ae310b480825ab" + "3d877f675d6ac1293222602a53080f94e4a7f0692b627905f69d4f0bb1dfd647e281cc0695e0733fa3" + "efc57d88706d4426c4969aff7a177ac2d9634401913bb20a93b6efe60e790e06dad3493776c2c0878c" + "e82caababa183b494120edde3d823333efd464c8aea1f51f330203010001a321301f301d0603551d0e" + "04160414203ec8b075d1c9eb9d600100281c3924a831a46c300d06092a864886f70d01010b05000382" + "01010042d4bd26d535ce2bf0375446615ef5bf25973f61ecf955bdb543e4b6e6b5d026fdcab09fec09" + "c747fb26633c221df8e3d3d0fe39ce30ca0a31547e9ec693a0f2d83e26d231386ff45f8e4fd5c06095" + "8681f9d3bd6db5e940b1e4a0b424f5c463c79c5748a14a3a38da4dd7a5499dcc14a70ba82a50be5fe0" + "82890c89a27e56067d2eae952e0bcba4d6beb5359520845f1fdb7df99868786055555187ba46c69ee6" + "7fa2d2c79e74a364a8b3544997dc29cc625395e2f45bf8bdb2c9d8df0d5af1a59a58ad08b32cdbec38" + "19fa49201bb5b5aadeee8f2f096ac029055713b77054e8af07cd61fe97f7365d0aa92d570be98acb89" + "41b8a2b0053b54f18bfde092eb") // Also allow our CI builds private val SUBSTRATUM_CI_SIGNATURE = Signature("" + "308201dd30820146020101300d06092a864886f70d010105050030373116301406035504030c0d416e" + "64726f69642044656275673110300e060355040a0c07416e64726f6964310b30090603550406130255" + "53301e170d3137303232333036303730325a170d3437303231363036303730325a3037311630140603" + "5504030c0d416e64726f69642044656275673110300e060355040a0c07416e64726f6964310b300906" + "035504061302555330819f300d06092a864886f70d010101050003818d00308189028181008aa6cf56" + "e3ba4d0921da3baf527529205efbe440e1f351c40603afa5e6966e6a6ef2def780c8be80d189dc6101" + "935e6f8340e61dc699cfd34d50e37d69bf66fbb58619d0ebf66f22db5dbe240b6087719aa3ceb1c68f" + "3fa277b8846f1326763634687cc286b0760e51d1b791689fa2d948ae5f31cb8e807e00bd1eb72788b2" + "330203010001300d06092a864886f70d0101050500038181007b2b7e432bff612367fbb6fdf8ed0ad1" + "a19b969e4c4ddd8837d71ae2ec0c35f52fe7c8129ccdcdc41325f0bcbc90c38a0ad6fc0c604a737209" + "17d37421955c47f9104ea56ad05031b90c748b94831969a266fa7c55bc083e20899a13089402be49a5" + "edc769811adc2b0496a8a066924af9eeb33f8d57d625a5fa150f7bc18e55") // Whitelisted signatures private val SIGNATURES = arrayOf( SUBSTRATUM_SIGNATURE, SUBSTRATUM_CI_SIGNATURE ) }
5
null
7
8
c1a7f5487ae4b22b0658e4b4368f34c0709b0013
8,905
packages_apps_Margarita
Apache License 2.0
feature_emi/src/main/kotlin/com/allutils/feature_emi/EmiKoinModule.kt
donchakkappan
811,182,787
false
{"Kotlin": 114972}
package com.allutils.feature_emi import com.allutils.feature_emi.di.dataModule import com.allutils.feature_emi.di.domainModule import com.allutils.feature_emi.di.presentationModule val emiModules = listOf( presentationModule, domainModule, dataModule, )
0
Kotlin
0
0
72a99d8dcb480f4247256909e30c76448afcade7
268
Convert
MIT License
runtime/jsMain/src/kotlinx/benchmark/js/JsBenchmarkExecutor.kt
Kotlin
162,275,279
false
null
package kotlinx.benchmark.js import kotlinx.benchmark.* import kotlinx.benchmark.internal.KotlinxBenchmarkRuntimeInternalApi import kotlin.js.Promise @KotlinxBenchmarkRuntimeInternalApi class JsBenchmarkExecutor(name: String, @Suppress("UNUSED_PARAMETER") dummy_args: Array<out String>) : SuiteExecutor(name, jsEngineSupport.arguments()[0]) { init { check(!isD8) { "${JsBenchmarkExecutor::class.simpleName} does not support d8 engine" } } private val benchmarkJs: dynamic = require("benchmark") override fun run( runnerConfiguration: RunnerConfiguration, benchmarks: List<BenchmarkDescriptor<Any?>>, start: () -> Unit, complete: () -> Unit ) { start() val jsSuite: dynamic = benchmarkJs.Suite() jsSuite.on("complete") { complete() } benchmarks.forEach { benchmark -> val suite = benchmark.suite val config = BenchmarkConfiguration(runnerConfiguration, suite) val isAsync = benchmark.isAsync runWithParameters(suite.parameters, runnerConfiguration.params, suite.defaultParameters) { params -> val id = id(benchmark.name, params) val instance = suite.factory() // TODO: should we create instance per bench or per suite? suite.parametrize(instance, params) val asynchronous = if (isAsync) { when(benchmark) { // Mind asDynamic: this is **not** a regular promise is JsBenchmarkDescriptorWithNoBlackholeParameter -> { @Suppress("UNCHECKED_CAST") val promiseFunction = benchmark.function as Any?.() -> Promise<*> jsSuite.add(benchmark.name) { deferred: Promise<Unit> -> instance.promiseFunction().then { (deferred.asDynamic()).resolve() } } } is JsBenchmarkDescriptorWithBlackholeParameter -> { @Suppress("UNCHECKED_CAST") val promiseFunction = benchmark.function as Any?.(Blackhole) -> Promise<*> jsSuite.add(benchmark.name) { deferred: Promise<Unit> -> instance.promiseFunction(benchmark.blackhole).then { (deferred.asDynamic()).resolve() } } } else -> error("Unexpected ${benchmark::class.simpleName}") } true } else { when(benchmark) { is JsBenchmarkDescriptorWithNoBlackholeParameter -> { val function = benchmark.function jsSuite.add(benchmark.name) { instance.function() } } is JsBenchmarkDescriptorWithBlackholeParameter -> { val function = benchmark.function jsSuite.add(benchmark.name) { instance.function(benchmark.blackhole) } } else -> error("Unexpected ${benchmark::class.simpleName}") } false } val jsBenchmark = jsSuite[jsSuite.length - 1] // take back last added benchmark and subscribe to events // TODO: Configure properly // initCount: The default number of times to execute a test on a benchmark’s first cycle // minTime: The time needed to reduce the percent uncertainty of measurement to 1% (secs). // maxTime: The maximum time a benchmark is allowed to run before finishing (secs). jsBenchmark.options.initCount = config.warmups jsBenchmark.options.minSamples = config.iterations val iterationSeconds = config.iterationTime * config.iterationTimeUnit.toSecondsMultiplier() jsBenchmark.options.minTime = iterationSeconds jsBenchmark.options.maxTime = iterationSeconds jsBenchmark.options.async = asynchronous jsBenchmark.options.defer = asynchronous jsBenchmark.on("start") { _ -> reporter.startBenchmark(executionName, id) suite.setup(instance) } var iteration = 0 jsBenchmark.on("cycle") { event -> val target = event.target val nanos = (target.times.period as Double) * BenchmarkTimeUnit.SECONDS.toMultiplier() val sample = nanos.nanosToText(config.mode, config.outputTimeUnit) // (${target.cycles} × ${target.count} calls) -- TODO: what's this? reporter.output( executionName, id, "Iteration #${iteration++}: $sample" ) } jsBenchmark.on("complete") { event -> suite.teardown(instance) benchmark.blackhole.flush() val stats = event.target.stats val samples = stats.sample .unsafeCast<DoubleArray>() .map { val nanos = it * BenchmarkTimeUnit.SECONDS.toMultiplier() nanos.nanosToSample(config.mode, config.outputTimeUnit) } .toDoubleArray() val result = ReportBenchmarksStatistics.createResult(benchmark, params, config, samples) val message = with(result) { " ~ ${score.sampleToText( config.mode, config.outputTimeUnit )} ±${(error / score * 100).formatSignificant(2)}%" } val error = event.target.error if (error == null) { reporter.endBenchmark( executionName, id, BenchmarkProgress.FinishStatus.Success, message ) result(result) } else { val stacktrace = error.stack reporter.endBenchmarkException( executionName, id, error.toString(), stacktrace.toString() ) } } Unit } } jsSuite.run() } }
61
null
36
469
7950a879c92b765d8df43feb9c667efc2d5fd75d
6,898
kotlinx-benchmark
Apache License 2.0
mobile_app1/module753/src/main/java/module753packageKt0/Foo41.kt
uber-common
294,831,672
false
null
package module753packageKt0; annotation class Foo41Fancy @Foo41Fancy class Foo41 { fun foo0(){ module753packageKt0.Foo40().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
233
android-build-eval
Apache License 2.0
mobile_app1/module753/src/main/java/module753packageKt0/Foo41.kt
uber-common
294,831,672
false
null
package module753packageKt0; annotation class Foo41Fancy @Foo41Fancy class Foo41 { fun foo0(){ module753packageKt0.Foo40().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
233
android-build-eval
Apache License 2.0
app/src/test/java/com/rafaelfelipeac/marvelapp/features/details/data/model/DetailInfoDtoMapperTest.kt
rafaelfelipeac
329,159,954
false
null
package com.rafaelfelipeac.marvelapp.features.details.data.model import com.rafaelfelipeac.marvelapp.base.DataProviderTest.createDetailInfo import com.rafaelfelipeac.marvelapp.base.DataProviderTest.createDetailInfoDto import com.rafaelfelipeac.marvelapp.base.equalTo import org.junit.Test class DetailInfoDtoMapperTest { private val detailInfoDtoMapper = DetailInfoDtoMapper() @Test fun `GIVEN DetailInfoDto WHEN map is called THEN DetailInfo is returned`() { // given val detailInfoDto = createDetailInfoDto() // when val result = detailInfoDtoMapper.map(detailInfoDto) // then result equalTo createDetailInfo() } @Test fun `GIVEN DetailInfo WHEN mapReverse is called THEN DetailInfoDto is returned`() { // given val detailInfo = createDetailInfo() // when val result = detailInfoDtoMapper.mapReverse(detailInfo) // then result equalTo createDetailInfoDto() } }
0
Kotlin
0
0
645da550990292d44e81cf9412475c7836ec11d0
996
MarvelApp
Apache License 2.0
tiny-event-sourcing-lib/src/main/kotlin/ru/quipy/streams/BufferedAggregateEventStream.kt
andrsuh
498,475,206
false
null
package ru.quipy.streams import kotlinx.coroutines.* import org.slf4j.LoggerFactory import ru.quipy.domain.Aggregate import ru.quipy.domain.EventRecord import ru.quipy.streams.annotation.RetryConf import ru.quipy.streams.annotation.RetryFailedStrategy import java.util.concurrent.atomic.AtomicBoolean class BufferedAggregateEventStream<A : Aggregate>( override val streamName: String, private val streamReadPeriod: Long, // todo sukhoa wrong naming private val streamBatchSize: Int, private val eventsChannel: EventsChannel, private val eventReader: EventReader, private val retryConfig: RetryConf, private val eventStreamNotifier: EventStreamNotifier, private val dispatcher: CoroutineDispatcher ) : AggregateEventStream<A> { companion object { private val logger = LoggerFactory.getLogger(BufferedAggregateEventStream::class.java) } private var active = AtomicBoolean(true) private var suspended = AtomicBoolean(false) private val eventStreamCompletionHandler: CompletionHandler = { th: Throwable? -> if (active.get()) { logger.error( "Unexpected error in aggregate event stream ${streamName}. Relaunching...", th ) eventStreamJob = launchJob() } else { logger.warn("Stopped event stream $streamName coroutine") } } @Volatile private var eventStreamJob: Job = launchJob() private fun launchJob() = CoroutineScope(CoroutineName("reading-$streamName-coroutine") + dispatcher).launch { // initial delay delay(5_000) eventStreamNotifier.onStreamLaunched(streamName) while (active.get()) { while (suspended.get()) { logger.debug("Suspending stream $streamName...") delay(500) } val startTs = System.currentTimeMillis() val eventsBatch = eventReader.read(streamBatchSize) if (eventsBatch.isEmpty()) { delay(streamReadPeriod) continue } eventsBatch.forEach { eventRecord -> logger.trace("Processing event from batch: $eventRecord.") feedToHandling(eventRecord) { eventStreamNotifier.onRecordHandledSuccessfully(streamName, eventRecord.eventTitle) eventReader.acknowledgeRecord(eventRecord) } } val executionTime = System.currentTimeMillis() - startTs if (executionTime < streamReadPeriod) { delay(streamReadPeriod - executionTime) } } }.also { it.invokeOnCompletion(eventStreamCompletionHandler) } override suspend fun handleNextRecord(eventProcessingFunction: suspend (EventRecord) -> Boolean) { val receivedRecord = eventsChannel.receiveEvent() logger.trace("Event $receivedRecord was received for handling") try { eventProcessingFunction(receivedRecord).also { if (!it) logger.info("Processing function return false for event record: $receivedRecord") logger.trace("Sending confirmation on receiving event $receivedRecord") eventsChannel.sendConfirmation(isConfirmed = it) } } catch (e: Exception) { logger.error( "Error while invoking event handling function. Stream: ${streamName}. Event record: $receivedRecord", e ) eventsChannel.sendConfirmation(isConfirmed = false) } } override fun stopAndDestroy() { if (!active.compareAndSet(true, false)) return // todo sukhoa think of committing last read index eventReader.stop() if (eventStreamJob.isActive) { eventStreamJob.cancel() } } override fun suspend() { suspended.set(true) eventReader.stop() } override fun resume() { logger.info("Resuming stream $streamName...") suspended.set(false) eventReader.resume() } override fun isSuspended() = suspended.get() private suspend fun feedToHandling(event: EventRecord, beforeNextPerform: () -> Unit) { for (attemptNum in 1..retryConfig.maxAttempts) { // todo sukhoa BUG eventsChannel.sendEvent(event) if (eventsChannel.receiveConfirmation()) { beforeNextPerform() return } if (attemptNum == retryConfig.maxAttempts) { when (retryConfig.lastAttemptFailedStrategy) { RetryFailedStrategy.SKIP_EVENT -> { logger.error("Event stream: $streamName. Retry attempts failed $attemptNum times. SKIPPING...") beforeNextPerform() return } RetryFailedStrategy.SUSPEND -> { logger.error("Event stream: $streamName. Retry attempts failed $attemptNum times. SUSPENDING THE HOLE STREAM...") eventStreamNotifier.onRecordSkipped(streamName, event.eventTitle, attemptNum) delay(Long.MAX_VALUE) // todo sukhoa find the way better } } } eventStreamNotifier.onRecordHandlingRetry(streamName, event.eventTitle, attemptNum) } } }
14
null
18
31
0ef623b888458ab2919937653d79f09da23f66ef
5,743
tiny-event-sourcing
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/ClockArrowDownload.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.ClockArrowDownload: ImageVector get() { if (_clockArrowDownload != null) { return _clockArrowDownload!! } _clockArrowDownload = fluentIcon(name = "Filled.ClockArrowDownload") { fluentPath { moveTo(22.0f, 12.0f) arcToRelative(10.0f, 10.0f, 0.0f, true, false, -19.97f, 0.78f) arcToRelative(6.48f, 6.48f, 0.0f, false, true, 8.97f, 0.03f) lineTo(11.0f, 6.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.5f, -0.1f) lineTo(12.5f, 12.0f) horizontalLineToRelative(3.25f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) horizontalLineToRelative(-4.1f) lineToRelative(-0.14f, -0.01f) arcToRelative(6.47f, 6.47f, 0.0f, false, true, -0.4f, 8.48f) lineTo(12.0f, 22.0f) arcToRelative(10.0f, 10.0f, 0.0f, false, false, 10.0f, -10.0f) close() moveTo(1.0f, 17.5f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, 5.0f, -5.48f) verticalLineToRelative(5.77f) lineToRelative(-1.65f, -1.64f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, 0.7f) lineToRelative(2.5f, 2.5f) curveToRelative(0.2f, 0.2f, 0.5f, 0.2f, 0.7f, 0.0f) lineToRelative(2.5f, -2.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, -0.7f) lineTo(7.0f, 17.79f) verticalLineToRelative(-5.77f) arcToRelative(5.5f, 5.5f, 0.0f, true, true, -6.0f, 5.48f) close() moveTo(3.5f, 20.5f) curveToRelative(0.0f, 0.28f, 0.22f, 0.5f, 0.5f, 0.5f) horizontalLineToRelative(5.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f) lineTo(4.0f, 20.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.5f, 0.5f) close() } } return _clockArrowDownload!! } private var _clockArrowDownload: ImageVector? = null
0
Kotlin
0
24
336c85b59b6a6ad97a522a25a0042cd8e0750474
2,443
compose-fluent-ui
Apache License 2.0
data/src/main/java/com/vinners/cube_vishwakarma/data/models/profile/UserProfile.kt
Mansoori999
412,034,929
false
null
package com.vinners.cube_vishwakarma.data.models.profile import com.google.gson.annotations.SerializedName data class UserProfile( @SerializedName("jobcCompleted") val jobCompleted: Int, @SerializedName("moneyEarned") val moneyEarned: Int, @SerializedName("rating") val rateing: String? = null ) { }
1
null
1
1
522bae5017a74f33fbb9bd7aff9af5ccd60a8b39
328
cube-vishwakarma
MIT License
language-actionscript/src/main/kotlin/com/blacksquircle/ui/language/actionscript/lexer/ActionScriptToken.kt
massivemadness
608,535,719
false
null
/* * Copyright 2023 Squircle CE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blacksquircle.ui.language.actionscript.lexer enum class ActionScriptToken { LONG_LITERAL, INTEGER_LITERAL, FLOAT_LITERAL, DOUBLE_LITERAL, BREAK, CASE, CONTINUE, DEFAULT, DO, WHILE, ELSE, FOR, IN, EACH, IF, LABEL, RETURN, SUPER, SWITCH, THROW, TRY, CATCH, FINALLY, WITH, DYNAMIC, FINAL, INTERNAL, NATIVE, OVERRIDE, PRIVATE, PROTECTED, PUBLIC, STATIC, PARAMETER, CLASS, CONST, EXTENDS, FUNCTION, GET, IMPLEMENTS, INTERFACE, NAMESPACE, PACKAGE, TYPEOF, SET, THIS, INCLUDE, INSTANCEOF, IMPORT, USE, AS, NEW, VAR, ARRAY, OBJECT, BOOLEAN, NUMBER, STRING, VOID, VECTOR, INT, UINT, TRUE, FALSE, NULL, UNDEFINED, NAN, // Arithmetic PLUS, MINUSMINUS, DIV, PLUSPLUS, MOD, MULT, MINUS, // Arithmetic compound assignment PLUSEQ, DIVEQ, MODEQ, MULTEQ, MINUSEQ, // Assignment EQ, // Bitwise AND, LTLT, TILDE, OR, GTGT, GTGTGT, XOR, // Bitwise compound assignment ANDEQ, LTLTEQ, OREQ, GTGTEQ, GTGTGTEQ, XOREQ, // Comparison EQEQ, GT, GTEQ, NOTEQ, LT, LTEQ, EQEQEQ, NOTEQEQ, // Logical ANDAND, ANDANDEQ, NOT, OROR, OROREQ, // Other LPAREN, RPAREN, LBRACE, RBRACE, LBRACK, RBRACK, SEMICOLON, COMMA, DOT, QUEST, COLON, PREPROCESSOR, DOUBLE_QUOTED_STRING, SINGLE_QUOTED_STRING, LINE_COMMENT, BLOCK_COMMENT, IDENTIFIER, WHITESPACE, BAD_CHARACTER, EOF }
45
null
46
5
bbf3b9ea8316fe6831ac40a75f0a1076c2e31663
2,404
EditorKit
Apache License 2.0
app/src/main/java/com/example/tobechain/ui/component/ModalNavigationDrawer.kt
imchic
569,119,742
false
{"Kotlin": 97397}
package com.example.tobechain.ui.component import android.util.Log import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import com.carto.core.MapPos import com.carto.core.MapRange import com.carto.projections.Projection import com.carto.ui.MapView import com.example.tobechain.map.BaseMap import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun setDrawerLayoutMaterial3( drawerState: DrawerState, scope: CoroutineScope, items: List<ImageVector>, menuItems: List<String>, selectedItem: MutableState<ImageVector>, paddingValues: PaddingValues ) { lateinit var projection: Projection ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet(Modifier.width(240.dp)) { Spacer(Modifier.height(100.dp)) items.forEachIndexed { index, item -> NavigationDrawerItem( icon = { Icon(item, contentDescription = null) }, label = { Text(menuItems[index]) }, selected = item == selectedItem.value, onClick = { scope.launch { drawerState.close() Log.d("carto", menuItems[index]) } selectedItem.value = item }, modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding) ) } } }, content = { // Box ( // modifier = Modifier // .fillMaxSize() // .padding(paddingValues), // contentAlignment = Alignment.Center, // content = { // showIntroLottieAnimation() // } // ) Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { setListItem() // AndroidView( // factory = { context -> // val mapView = MapView(context) // mapView // }, // modifier = Modifier.fillMaxSize().padding(paddingValues), // update = { view -> // view.apply { // // val mapOpt = options // projection = mapOpt.baseProjection // // mapOpt.apply { // watermarkScale = 0.0f // tiltRange = MapRange(90f, 90f) // isRotatable = false // setZoom(14f, 0.0f) // setFocusPos(projection.fromWgs84(MapPos(24.643076, 59.420502)), 0.5F) // } // // //BaseMap.addMarker(projection, view) // //BaseMap.addPoint(projection, view) // //BaseMap.addLine(projection, view) // BaseMap.addPolygon(projection, view) // //BaseMap.addText(projection, view) // // } // } // ) } } ) }
0
Kotlin
0
0
3215c509a38b66c2c2e94051ea3cc91d22a1370d
3,812
JetPackSample
Apache License 2.0
features/settings/faq/src/main/kotlin/com/egoriku/grodnoroads/settings/faq/domain/model/FAQ.kt
egorikftp
485,026,420
false
null
package com.egoriku.grodnoroads.settings.faq.domain.model data class FAQ( val question: String, val answer: String )
2
Kotlin
1
6
4c13949a65f68379426b54b3fe2561f9698ec214
125
GrodnoRoads
Apache License 2.0
feature/screencapture/src/main/java/com/lingshot/screencapture/util/ServiceUtil.kt
CharlesMoreira1
618,817,135
false
{"Kotlin": 311024, "Ruby": 301}
/* * Copyright 2023 Lingshot * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lingshot.screencapture.util import android.app.ActivityManager import android.content.Context import com.lingshot.screencapture.service.ScreenShotService @Suppress("DEPRECATION") fun isServiceRunning(context: Context): Boolean { val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val services = manager.getRunningServices(Integer.MAX_VALUE) for (service in services) { if (ScreenShotService::class.java.name == service.service.className) { return true } } return false }
12
Kotlin
7
80
d7e5bc6580cd3ffca390916c37a0a0e60fdb6a91
1,159
lingshot
Apache License 2.0
SubShop/app/src/main/java/com/diekvoss/subshop/screens/history/OrderHistoryViewModel.kt
ToyVo
231,263,116
false
{"Kotlin": 139741}
package com.diekvoss.subshop.screens.history import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import com.diekvoss.subshop.OrderEntity import com.diekvoss.subshop.OrderRepository /** * @property repository local database * @property allOrders all orders from the repository */ class OrderHistoryViewModel(application: Application) : AndroidViewModel(application) { private val repository: OrderRepository = OrderRepository(application) val allOrders: LiveData<List<OrderEntity>> = repository.allOrders /** * pass through for repository insert */ fun insertOrder(order: OrderEntity) { repository.insertOrder(order) } }
0
Kotlin
0
0
ea17b954729a0fba2dd5a69684021fe9d3042fcc
722
AndroidStout
Apache License 2.0
.teamcity/src/subprojects/release/ProjectRelease.kt
ktorio
300,262,534
false
null
package subprojects.release import jetbrains.buildServer.configs.kotlin.v2019_2.* import subprojects.SIGN_KEY_PUBLIC import subprojects.build.* import subprojects.release.apidocs.ProjectReleaseAPIDocs import subprojects.release.generator.ProjectReleaseGeneratorWebsite import subprojects.release.publishing.* import java.io.* object ProjectRelease : Project({ id("ProjectKtorRelease") name = "Release Ktor" description = " The Full Monty! - Release Ktor framework, update docs, site, etc." subProject(ProjectReleaseAPIDocs) subProject(ProjectReleaseGeneratorWebsite) subProject(ProjectPublishing) buildType(ReleaseBuild) params { defaultTimeouts() param("env.SIGN_KEY_ID", value = "<KEY>") // Inherited from parent project. The reason for this is that security tokens seem to mess up with multiline values // So we set this in the parent project and read from there. That way, we don't need to make our project editable. password("env.SIGN_KEY_PASSPHRASE", value = "%sign.key.passphrase%") password("env.SIGN_KEY_PRIVATE", value = "%sign.key.private%") password("env.PUBLISHING_USER", value = "%sonatype.username%") password("env.PUBLISHING_PASSWORD", value = "%sonatype.password%") param("env.PUBLISHING_URL", value = "%sonatype.url%") param("env.SIGN_KEY_LOCATION", value = File("%teamcity.build.checkoutDir%").invariantSeparatorsPath) param("env.SIGN_KEY_PUBLIC", value = SIGN_KEY_PUBLIC) } }) fun ParametrizedWithType.configureReleaseVersion() { text("releaseVersion", "", display = ParameterDisplay.PROMPT, allowEmpty = false) }
1
Kotlin
2
9
d1cd27b232778d48977a5e152eaadf821ab56a1c
1,669
ktor-build
Apache License 2.0
core/ui/src/androidMain/kotlin/ru/kyamshanov/mission/core/ui/extensions/applyImePadding.kt
KYamshanov
656,042,097
false
null
package ru.kyamshanov.mission.core.ui.extensions import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.ViewConfiguration actual fun Modifier.imePadding(): Modifier = imePadding() actual fun Modifier.navigationBarsPadding(): Modifier = navigationBarsPadding() @Composable actual fun ViewConfiguration.getOrientation(): Int = LocalConfiguration.current.orientation @Composable actual fun WindowInsets.Companion.getStatusBars(): WindowInsets = WindowInsets.statusBars actual fun Modifier.systemBarsPadding(): Modifier = systemBarsPadding() @Composable actual fun isSingleLineSupported(): Boolean = true
7
null
0
1
11b2f6c17bf59fd3ef027536a0c1033f61b49684
1,005
Mission-app
Apache License 2.0
kmath-coroutines/src/commonMain/kotlin/space/kscience/kmath/streaming/RingBuffer.kt
SciProgCentre
129,486,382
false
null
package space.kscience.kmath.streaming import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.MutableBuffer import space.kscience.kmath.structures.VirtualBuffer /** * Thread-safe ring buffer */ @Suppress("UNCHECKED_CAST") public class RingBuffer<T>( private val buffer: MutableBuffer<T?>, private var startIndex: Int = 0, size: Int = 0 ) : Buffer<T> { private val mutex: Mutex = Mutex() public override var size: Int = size private set public override operator fun get(index: Int): T { require(index >= 0) { "Index must be positive" } require(index < size) { "Index $index is out of circular buffer size $size" } return buffer[startIndex.forward(index)] as T } public fun isFull(): Boolean = size == buffer.size /** * Iterator could provide wrong results if buffer is changed in initialization (iteration is safe) */ public override operator fun iterator(): Iterator<T> = object : AbstractIterator<T>() { private var count = size private var index = startIndex val copy = buffer.copy() override fun computeNext() { if (count == 0) done() else { setNext(copy[index] as T) index = index.forward(1) count-- } } } /** * A safe snapshot operation */ public suspend fun snapshot(): Buffer<T> { mutex.withLock { val copy = buffer.copy() return VirtualBuffer(size) { i -> copy[startIndex.forward(i)] as T } } } public suspend fun push(element: T) { mutex.withLock { buffer[startIndex.forward(size)] = element if (isFull()) startIndex++ else size++ } } @Suppress("NOTHING_TO_INLINE") private inline fun Int.forward(n: Int): Int = (this + n) % (buffer.size) public companion object { public inline fun <reified T : Any> build(size: Int, empty: T): RingBuffer<T> { val buffer = MutableBuffer.auto(size) { empty } as MutableBuffer<T?> return RingBuffer(buffer) } /** * Slow yet universal buffer */ public fun <T> boxing(size: Int): RingBuffer<T> { val buffer: MutableBuffer<T?> = MutableBuffer.boxing(size) { null } return RingBuffer(buffer) } } }
91
null
52
600
83d9e1f0afb3024101a2f90a99b54f2a8b6e4212
2,488
kmath
Apache License 2.0
arrow-libs/core/arrow-core/src/jvmTest/kotlin/examples/example-iterable-10.kt
lukaszkalnik
427,116,886
true
{"Kotlin": 1928099, "SCSS": 99659, "JavaScript": 83153, "HTML": 25306, "Java": 7691, "Ruby": 917, "Shell": 98}
// This file was automatically generated from Iterable.kt by Knit tool. Do not edit. package arrow.core.examples.exampleIterable10 import arrow.core.* fun main(args: Array<String>) { //sampleStart val result = listOf("A:1", "B:2", "C:3").unzip { e -> e.split(":").let { it.first() to it.last() } } //sampleEnd println(result) }
0
Kotlin
0
1
73fa3847df1f04e634a02bba527917389b59d7df
361
arrow
Apache License 2.0
app/src/main/java/com/drewbitt/trntlist/dagger/scopes/MainScope.kt
drewbitt
185,934,336
false
null
package com.drewbitt.trntlist.dagger.scopes import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class AppScope
0
Kotlin
0
0
0f289e65be623c33d3eb4dc57be8b3dcdcad3869
145
TrntList
Apache License 2.0
src/main/kotlin/browser/tabs/Extras.kt
rivasdiaz
114,281,782
false
null
package chrome.tabs const val MUTED_INFO_REASON__USER = "user" const val MUTED_INFO_REASON__CAPTURE = "capture" const val MUTED_INFO_REASON__EXTENSION = "extension" const val RUN_AT__DOCUMENT_START = "document_start" const val RUN_AT__DOCUMENT_END = "document_end" const val RUN_AT__DOCUMENT_IDLE = "document_idle" const val TAB_STATUS__LOADING = "loading" const val TAB_STATUS__COMPLETE = "complete" const val WINDOW_TYPE__NORMAL = "normal" const val WINDOW_TYPE__POPUP = "popup" const val WINDOW_TYPE__PANEL = "panel" const val WINDOW_TYPE__APP = "app" const val WINDOW_TYPE__DEVTOOLS = "devtools" @Suppress("UNCHECKED_CAST_TO_NATIVE_INTERFACE") inline fun QueryInfo(block: QueryInfo.() -> Unit) = (js("{}") as QueryInfo).apply(block) @Suppress("UNCHECKED_CAST_TO_NATIVE_INTERFACE") inline fun ExecuteScriptDetails(block: ExecuteScriptDetails.() -> Unit) = (js("{}") as ExecuteScriptDetails).apply(block)
3
null
8
30
6496af8ba4411c973d7be3c18b83377cb535de82
929
helloworld-chrome-extension-kotlin
Apache License 2.0
quadtree/d2v-quadtree-common/src/test/kotlin/io/data2viz/quadtree/QuadtreeAccessorsTests.kt
yijunwu
207,939,886
true
{"Kotlin": 1455567, "HTML": 45831, "JavaScript": 9282}
package io.data2viz.quadtree import io.data2viz.geom.Point import io.data2viz.test.JsName import io.data2viz.test.TestBase import kotlin.test.Test class QuadtreeAccessorsTests : TestBase() { @Test @JsName("quadtree_accessor_1") fun `quadtree sets the accessors used by quadtree add`() { val quadtree = Quadtree<Point>({ point -> point.x }, { point -> point.y }) quadtree.add(Point(1.0, 2.0)) quadtree.extent.toArray() shouldBe arrayOf(1.0, 2.0, 2.0, 3.0) (quadtree.root as LeafNode).data shouldBe Point(1.0, 2.0) } @Test @JsName("quadtree_accessor_2") fun `quadtree sets the accessors used by quadtree addAll`() { val quadtree = Quadtree<Point>({ point -> point.x }, { point -> point.y }) quadtree.addAll(listOf(Point(1.0, 2.0))) quadtree.extent.toArray() shouldBe arrayOf(1.0, 2.0, 2.0, 3.0) (quadtree.root as LeafNode).data shouldBe Point(1.0, 2.0) } @Test @JsName("quadtree_accessor_3") fun `quadtree sets the accessors used by quadtree remove`() { val p0 = Point(.0, 1.0) val p1 = Point(1.0, 2.0) val quadtree = Quadtree<Point>({ point -> point.x }, { point -> point.y }) quadtree.add(p0) (quadtree.root as LeafNode).data shouldBe Point(.0, 1.0) quadtree.add(p1) ((quadtree.root as InternalNode).NE_0 as LeafNode).data shouldBe p0 (quadtree.root as InternalNode).NW_1 shouldBe null (quadtree.root as InternalNode).SE_2 shouldBe null ((quadtree.root as InternalNode).SW_3 as LeafNode).data shouldBe p1 quadtree.remove(p1) (quadtree.root as LeafNode).data shouldBe Point(.0, 1.0) quadtree.remove(p0) quadtree.root shouldBe null } }
0
Kotlin
0
0
733f9ac458755ab065becd16d7f001be21080f59
1,769
data2viz
Apache License 2.0
core/src/commonMain/kotlin/com/littlekt/graphics/webgpu/enums.kt
littlektframework
442,309,478
false
{"Kotlin": 2170511, "Java": 1717152, "C": 111391}
package com.littlekt.graphics.webgpu import kotlin.jvm.JvmInline /** Primitive type the input mesh is composed of. */ enum class PrimitiveTopology { /** Vertex data is a list of points. Each vertex is a new point. */ POINT_LIST, /** * Vertex data is a list of lines. Each pair of vertices composes a new line. * * Vertices `0 1 2 3` create two lines `0 1` and `2 3`. */ LINE_LIST, /** * Vertex data is a strip of lines. Each set of two adjacent vertices form a line. * * Vertices `0 1 2 3` create three lines `0 1`, `1 2`, and `2 3`. */ LINE_STRIP, /** * Vertex data is a list of triangles. Each set of 3 vertices composes a new triangle. * * Vertices `0 1 2 3 4 5` create two triangles `0 1 2` and `3 4 5`. */ TRIANGLE_LIST, /** * Vertex data is a triangle strip. Each set of three adjacent vertices form a triangle. * * Vertices `0 1 2 3 4 5` create four triangles `0 1 2`, `2 1 3`, `2 3 4`, and `4 3 5`. */ TRIANGLE_STRIP } /** Vertex winding order which classifies the "front" face of a triangle. */ enum class FrontFace { /** * Triangles with vertices in counter-clockwise order are considered the front face. * * This is the default with right-handed coordinate spaces. */ CCW, /** * Triangles with vertices in clockwise order are considered the front face. * * This is the default with left-handed coordinate spaces. */ CW } /** Face of a vertex. */ enum class CullMode { /** Neither used. */ NONE, /** Front face. */ FRONT, /** Back face. */ BACK } /** * The usages determine what kind of memory the texture is allocated from and what actions the * texture can partake in. */ @JvmInline value class TextureUsage(val usageFlag: Int) { infix fun or(other: TextureUsage): TextureUsage = TextureUsage(usageFlag or other.usageFlag) infix fun and(other: TextureUsage): TextureUsage = TextureUsage(usageFlag and other.usageFlag) companion object { /** Allows a texture to be the source in a copy operation */ val COPY_SRC: TextureUsage = TextureUsage(0x01) /** * Allows a texture to be the destination of a copy operation such as * [CommandEncoder.copyBufferToTexture] */ val COPY_DST: TextureUsage = TextureUsage(0x02) /** Allows a texture to be a sampled texture in a bind group */ val TEXTURE: TextureUsage = TextureUsage(0x04) /** Allows a texture to be a storage texture in a bind group */ val STORAGE: TextureUsage = TextureUsage(0x08) /** Allows a texture to be an output attachment of a render pass */ val RENDER_ATTACHMENT: TextureUsage = TextureUsage(0x10) } } /** Dimensions of a particular texture view. */ enum class TextureViewDimension { /** A one dimensional texture. */ D1, /** A two-dimensional texture. */ D2, /** A two-dimensional array texture. */ D2_ARRAY, /** A cubemap texture. */ CUBE, /** A cubemap array texture. */ CUBE_ARRAY, /** A three-dimensional texture. */ D3 } /** Type of data the texture holds. */ enum class TextureAspect { /** Depth, stecil, and color. */ ALL, /** Stencil only. */ STENCIL_ONLY, /** Depth only. */ DEPTH_ONLY } /** Dimensionality of a texture. */ enum class TextureDimension { /** 1D texture. */ D1, /** 2D texture. */ D2, /** 3D texture. */ D3 } /** * The underlying texture data format. * * If there is a conversion in the format (such as srgb -> linear), the conversion listed here is * for loading from texture in a shader. When writing to the texture, the opposite conversion takes * place. * * @param bytes the number of bytes each format requires * @param srgb if this format is an SRGB format and expects linear colors. */ enum class TextureFormat(val bytes: Int, val srgb: Boolean = false) { /** 8 Bit Red channel only. `[0, 255]` converted to/from float `[0, 1]` in shader. */ R8_UNORM(1), /** 8 Bit Red channel only. `[-127, 127]` converted to/from float `[-1, 1]` in shader. */ R8_SNORM(1), /** Red channel only. 8 bit integer per channel. Unsigned in shader. */ R8_UINT(1), /** Red channel only. 8 bit integer per channel. Signed in shader. */ R8_SINT(1), /** Red channel only. 16 bit integer per channel. Unsigned in shader. */ R16_UINT(2), /** Red channel only. 16 bit integer per channel. Signed in shader. */ R16_SINT(2), /** Red channel only. 16 bit float per channel. Float in shader. */ R16_FLOAT(2), /** * Red and green channels. 8 bit integer per channel. `[0, 255]` converted to/from float `[0, * 1]` in shader. */ RG8_UNORM(2), /** * Red and green channels. 8 bit integer per channel. `[-127, 127]` converted to/from float * `[-1, 1]` in shader. */ RG8_SNORM(2), /** Red and green channels. 8 bit integer per channel. Unsigned in shader. */ RG8_UINT(2), /** Red and green channel s. 8 bit integer per channel. Signed in shader. */ RG8_SINT(2), /** Red channel only. 32 bit integer per channel. Unsigned in shader. */ R32_UINT(4), /** Red channel only. 32 bit integer per channel. Signed in shader. */ R32_SINT(4), /** Red channel only. 32 bit float per channel. Float in shader. */ R32_FLOAT(4), /** Red and green channels. 16 bit integer per channel. Unsigned in shader. */ RG16_UINT(4), /** Red and green channels. 16 bit integer per channel. Signed in shader. */ RG16_SINT(4), /** Red and green channels. 16 bit float per channel. Float in shader. */ RG16_FLOAT(4), /** * Red, green, blue, and alpha channels. 8 bit integer per channel. `[0, 255]` converted to/from * float `[0, 1]` in shader. */ RGBA8_UNORM(4), /** * Red, green, blue, and alpha channels. 8 bit integer per channel. Srgb-color `[0, 255]` * converted to/from linear-color float `[0, 1]` in shader. */ RGBA8_UNORM_SRGB(4, true), /** * Red, green, blue, and alpha channels. 8 bit integer per channel. `[-127, 127]` converted * to/from float `[-1, 1]` in shader. */ RGBA8_SNORM(4), /** Red, green, blue, and alpha channels. 8 bit integer per channel. Unsigned in shader. */ RGBA8_UINT(4), /** Red, green, blue, and alpha channels. 8 bit integer per channel. Signed in shader. */ RGBA8_SINT(4), /** * Blue, green, red, and alpha channels. 8 bit integer per channel. `[0, 255]` converted to/from * float `[0, 1]` in shader. */ BGRA8_UNORM(4), /** * Blue, green, red, and alpha channels. 8 bit integer per channel. Srgb-color `[0, 255]` * converted to/from linear-color float `[0, 1]` in shader. */ BGRA8_UNORM_SRGB(4, true), /** * Red, green, blue, and alpha channels. 10 bit integer for RGB channels, 2 bit integer for * alpha channel. `[0, 1023]` (`[0, 3]` for alpha) converted to/from float `[0, 1]` in shader. */ RGB10A2_UNORM(4), /** * Red, green, and blue channels. 11 bit float with no sign bit for RG channels. 10 bit float * with no sign bit for blue channel. Float in shader. */ RG11B10_FLOAT(4), /** Red and green channels. 32 bit integer per channel. Unsigned in shader. */ RG32_UINT(8), /** Red and green channels. 32 bit integer per channel. Signed in shader. */ RG32_SINT(8), /** Red and green channels. 32 bit float per channel. Float in shader. */ RG32_FLOAT(8), /** Red, green, blue, and alpha channels. 16 bit integer per channel. Unsigned in shader. */ RGBA16_UINT(8), /** Red, green, blue, and alpha channels. 16 bit integer per channel. Signed in shader. */ RGBA16_SINT(8), /** Red, green, blue, and alpha channels. 16 bit float per channel. Float in shader. */ RGBA16_FLOAT(8), /** Red, green, blue, and alpha channels. 32 bit integer per channel. Unsigned in shader. */ RGBA32_UINT(16), /** Red, green, blue, and alpha channels. 32 bit integer per channel. Signed in shader. */ RGBA32_SINT(16), /** Red, green, blue, and alpha channels. 32 bit float per channel. Float in shader. */ RGBA32_FLOAT(16), /** Special depth format with 32 bit floating point depth. */ DEPTH32_FLOAT(4), /** Special depth format with at least 24 bit integer depth. */ DEPTH24_PLUS(3), /** * Special depth/stencil format with at least 24 bit integer depth and 8 bits integer stencil. */ DEPTH24_PLUS_STENCIL8(4); companion object } /** Alpha blend operation. */ enum class BlendOperation { /** Src + Dst */ ADD, /** Src - Dst */ SUBTRACT, /** Dst - Src */ REVERSE_SUBTRACT, /** min(Src, Dst) */ MIN, /** max(Src, Dst) */ MAX } /** Operation to perform on the stencil value. */ enum class StencilOperation { /** Keep stencil value unchanged. */ KEEP, /** Set stencil value to zero. */ ZERO, /** * Replace stencil value with value provided in most recent call to * [RenderPassEncoder.setStencilReference]. */ REPLACE, /** Bitwise inverts stencil value. */ INVERT, /** Increments stencil value by one, clamping on overflow. */ INCREMENT_CLAMP, /** Decrements stencil value by one, clamping on underflow. */ DECREMENT_CLAMP, /** Increments stencil value by one, wrapping on overflow. */ INCREMENT_WRAP, /** Decrements stencil value by one, wrapping on underflow. */ DECREMENT_WRAP } /** Alpha blend factor. */ enum class BlendFactor { /** 0.0 */ ZERO, /** 1.0 */ ONE, /** S.component */ SRC_COLOR, /** 1.0 - S.component */ ONE_MINUS_SRC_COLOR, /** S.alpha */ SRC_ALPHA, /** 1.0 - S.alpha */ ONE_MINUS_SRC_ALPHA, /** D.component */ DST_COLOR, /** 1.0 - D.component */ ONE_MINUS_DST_COLOR, /** D.alpha */ DST_ALPHA, /** 1.0 - D.alpha */ ONE_MINUS_DST_ALPHA, /** min(S.alpha, 1.0 - D.alpha) */ SRC_ALPHA_SATURATED, /** Constant */ CONSTANT_COLOR, /** 1.0 - Constant */ ONE_MINUS_CONSTANT_COLOR } /** Format of indices used with pipeline. */ enum class IndexFormat { /** Indices are 16 bit unsigned integers. */ UINT16, /** Indices are 32 bit unsigned integers. */ UINT32, } /** Vertex format for a [WebGPUVertexAttribute] (input). */ enum class VertexFormat( /** The number of components of the format. */ val components: Int, /** The byte size of the format. */ val bytes: Int, /** If the format uses integer or float. */ val isInt: Boolean = false ) { /** Two unsigned bytes. uvec2 in shaders */ UINT8x2(2, 2, true), /** Four unsigned bytes. uvec4 in shaders */ UINT8x4(4, 4, true), /** Two signed bytes. ivec2 in shaders */ SINT8x2(2, 2, true), /** Four signed bytes. ivec4 in shaders */ SINT8x4(4, 4, true), /** Two unsigned bytes `[0, 255]` converted to floats `[0, 1]`. vec2 in shaders */ UNORM8x2(2, 2), /** Four unsigned bytes `[0, 255]` converted to floats `[0, 1]`. vec4 in shaders */ UNORM8x4(4, 4), /** two signed bytes converted to float `[-1,1]`. vec2 in shaders */ SNORM8x2(2, 2), /** two signed bytes converted to float `[-1,1]`. vec2 in shaders */ SNORM8x4(4, 4), /** two unsigned shorts. uvec2 in shaders */ UINT16x2(2, 4, true), /** four unsigned shorts. uvec4 in shaders */ UINT16x4(4, 8, true), /** two signed shorts. ivec2 in shaders */ SINT16x2(2, 4, true), /** four signed shorts. ivec4 in shaders */ SINT16x4(4, 8, true), /** two unsigned shorts `[0, 65525]` converted to float `[0, 1]`. vec2 in shaders */ UNORM16x2(2, 4), /** four unsigned shorts `[0, 65525]` converted to float `[0, 1]`. vec4 in shaders */ UNORM16x4(4, 8), /** two signed shorts `[-32767, 32767]` converted to float `[-1, 1]`. vec2 in shaders */ SNORM16x2(2, 4), /** two signed shorts `[-32767, 32767]` converted to float `[-1, 1]`. vec4 in shaders */ SNORM16x4(4, 8), /** two half precision floats. vec2 in shaders */ FLOAT16x2(2, 4), /** four half precision floats. vec4 in shaders */ FLOAT16x4(4, 8), /** one float. float in shaders */ FLOAT32(1, 4), /** two floats. vec2 in shaders */ FLOAT32x2(2, 8), /** three floats. vec3 in shaders */ FLOAT32x3(3, 12), /** four floats. vec4 in shaders */ FLOAT32x4(4, 16), /** one unsigned int. uint in shaders */ UINT32(1, 4, true), /** two unsigned ints. uvec2 in shaders */ UINT32x2(2, 8, true), /** three unsigned ints. uvec3 in shaders */ UINT32x3(3, 12, true), /** four unsigned ints. uvec4 in shaders */ UINT32x4(4, 16, true), /** one signed int. int in shaders */ SINT32(1, 4, true), /** two signed ints. ivec2 in shaders */ SINT32x2(2, 8, true), /** three signed ints. ivec2 in shaders */ SINT32x3(3, 12, true), /** four signed ints. ivec2 in shaders */ SINT32x4(4, 16, true) } /** Whether a vertex buffer is indexed by vertex or by instance. */ enum class VertexStepMode { /** Vertex data is advanced every vertex. */ VERTEX, /** Vertex data is advanced every instance. */ INSTANCE } /** Operation to perform to the output attachment at the start of a render pass. */ enum class LoadOp { /** * Loads the specified value for this attachment into the render pass. * * On some GPU hardware (primarily mobile), “clear” is significantly cheaper because it avoids * loading data from main memory into tile-local memory. * * On other GPU hardware, there isn’t a significant difference. * * As a result, it is recommended to use “clear” rather than “load” in cases where the initial * value doesn’t matter (e.g. the render target will be cleared using a skybox). */ CLEAR, /** Loads the existing value for this attachment into the render pass. */ LOAD } /** Operation to perform to the output attachment at the end of a render pass. */ enum class StoreOp { /** * Discards the resulting value of the render pass for this attachment. * * The attachment will be treated as uninitialized afterwards. (If only either Depth or Stencil * texture-aspects is set to Discard, the respective other texture-aspect will be preserved.) * * This can be significantly faster on tile-based render hardware. * * Prefer this if the attachment is not read by subsequent passes. */ DISCARD, /** Stores the resulting value of the render pass for this attachment. */ STORE } /** Specific type of a buffer binding. */ enum class BufferBindingType { /** * A buffer for uniform values. * * ```wgsl * struct Globals { * a_uniform: vec2<f32>, * another_uniform: vec2<f32>, * } * @group(0) @binding(0) * var<uniform> globals: Globals; * ``` */ UNIFORM, /** * A storage buffer. * * ```wgsl * @group(0) @binding(0) * var<storage, read_write> my_element: array<vec4<f32>>; * ``` */ STORAGE, /** * A read only storage buffer. The buffer can only be read in the shader. * * ```wgsl * @group(0) @binding(0) * var<storage, read> my_element: array<vec4<f32>>; * ``` */ READ_ONLY_STORAGE } enum class AddressMode { CLAMP_TO_EDGE, REPEAT, MIRROR_REPEAT } enum class FilterMode { NEAREST, LINEAR } /** Comparison function used for depth and stencil operations. */ enum class CompareFunction { /** Function never passes. */ NEVER, /** Function passes if new value less than existing value. */ LESS, /** * Function passes if new value is equal to existing value. When using this compare function, * make sure to mark your Vertex shader's `@builtin(position)` output as `@invariant` to prevent * artifacting. */ EQUAL, /** Function passes if new value is less than or equal to existing value. */ LESS_EQUAL, /** Function passes if new value is greater than existing value. */ GREATER, /** * Function passes if new value is not equal to existing value. When using this compare * function, make sure to mark your Vertex shader's `@builtin(position)` output as `@invariant` * to prevent artifacting. */ NOT_EQUAL, /** Function passes if new value is greater than or equal existing value. */ GREATER_EQUAL, /** Function always passes. */ ALWAYS } /** Specific type of a sample in a texture binding. */ enum class TextureSampleType { /** * Sampling returns floats. * * ```wgsl * @group(0) @binding(0) * var t: texture_2d<f32>; * ``` */ FLOAT, /** * Sampling does the depth reference comparison. This is also compatible with a non-filtering * sampler. * * ```wgsl * @group(0) @binding(0) * var t: texture_depth_2d; * ``` */ DEPTH, /** * Sampling returns signed integers. * * ```wgsl * @group(0) @binding(0) * var t: texture_2d<i32>; * ``` */ SINT, /** * Sampleing returns unsigned integers. * * ```wgsl * @group(0) @binding(0) * var t: texture_2d<u32>; * ``` */ UINT } /** Specific type of a sampler binding. */ enum class SamplerBindingType { /** * The sampling result is produced based on more than a single color sample from a texture, e.g. * when bilinear interpolation is enabled. */ FILTERING, /** The sampling result is produced based on a single color sample from a texture. */ NON_FILTERING, /** * Use as a comparison sampler instead of a normal sampler. For more info take a look at the * analogous functionality in * [OpenGL](https://www.khronos.org/opengl/wiki/Sampler_Object#Comparison_mode). */ COMPARISON } /** A color write mask. Disabled color channels will not be written to. */ @JvmInline value class ColorWriteMask(val usageFlag: Int) { infix fun or(other: ColorWriteMask): ColorWriteMask = ColorWriteMask(usageFlag or other.usageFlag) infix fun and(other: ColorWriteMask): ColorWriteMask = ColorWriteMask(usageFlag and other.usageFlag) companion object { /** Disable writes to all channels. */ val NONE: ColorWriteMask = ColorWriteMask(0x0) /** Enable red channel writes. */ val RED: ColorWriteMask = ColorWriteMask(0x1) /** Enable green channel writes. */ val GREEN: ColorWriteMask = ColorWriteMask(0x2) /** Enable blue channel writes. */ val BLUE: ColorWriteMask = ColorWriteMask(0x4) /** Enable alpha channel writes. */ val ALPHA: ColorWriteMask = ColorWriteMask(0x8) /** Enable writes to all channels. */ val ALL: ColorWriteMask = ColorWriteMask(0xF) } } /** Specifies how the alpha channel of the texture should be handled during compositing. */ enum class AlphaMode { /** * Chooses either [Opaque] or [Inherit] automatically,depending on the `alphaMode` that the * current surface can support. */ AUTO, /** * The alpha channel, if it exists, of the textures is ignored in the compositing process. * Instead, the textures is treated as if it has a constant alpha of 1.0. */ OPAQUE, /** * The alpha channel, if it exists, of the textures is respected in the compositing process. The * non-alpha channels of the textures are expected to already be multiplied by the alpha channel * by the application. */ PREMULTIPLIED, /** * The alpha channel, if it exists, of the textures is respected in the compositing process. The * non-alpha channels of the textures are not expected to already be multiplied by the alpha * channel by the application; instead, the compositor will multiply the non-alpha channels of * the texture by the alpha channel during compositing. */ UNPREMULTIPLIED, /** * The alpha channel, if it exists, of the textures is unknown for processing during * compositing. Instead, the application is responsible for setting the composite alpha blending * mode using native WSI command. If not set, then a platform-specific default will be used. */ INHERIT; companion object } /** Behavior of the presentation engine based on frame rate. */ enum class PresentMode { /** * Presentation frames are kept in a First-In-First-Out queue approximately 3 frames long. Every * vertical blanking period, the presentation engine will pop a frame off the queue to display. * If there is no frame to display, it will present the same frame again until the next vblank. * * When a present command is executed on the gpu, the presented image is added on the queue. * * No tearing will be observed. * * Calls to `getCurrentTexture` will block until there is a spot in the queue. * * Supported on all platforms. * * If you don’t know what mode to choose, choose this mode. This is traditionally called “Vsync * On”. */ FIFO, /** * Presentation frames are kept in a First-In-First-Out queue approximately 3 frames long. Every * vertical blanking period, the presentation engine will pop a frame off the queue to display. * If there is no frame to display, it will present the same frame until there is a frame in the * queue. The moment there is a frame in the queue, it will immediately pop the frame off the * queue. * * When a present command is executed on the gpu, the presented image is added on the queue. * * Tearing will be observed if frames last more than one vblank as the front buffer. * * Calls to `getCurrentTexture` will block until there is a spot in the queue. * * Supported on AMD on Vulkan. * * This is traditionally called “Adaptive Vsync” */ FIFO_RELAXED, /** * Presentation frames are not queued at all. The moment a present command is executed on the * GPU, the presented image is swapped onto the front buffer immediately. * * Tearing can be observed. * * Supported on most platforms except older DX12 and Wayland. * * This is traditionally called “Vsync Off”. */ IMMEDIATE, /** * Presentation frames are kept in a single-frame queue. Every vertical blanking period, the * presentation engine will pop a frame from the queue. If there is no frame to display, it will * present the same frame again until the next vblank. * * When a present command is executed on the gpu, the frame will be put into the queue. If there * was already a frame in the queue, the new frame will replace the old frame on the queue. * * No tearing will be observed. * * Supported on DX12 on Windows 10, NVidia on Vulkan and Wayland on Vulkan. * * This is traditionally called “Fast Vsync” */ MAILBOX } /** Status of the received surface texture. */ enum class TextureStatus { /** No issues. */ SUCCESS, /** Unable to get the next frame, timed out. */ TIMEOUT, /** The surface under the swap chain has changed. */ OUTDATED, /** The surface under the swap chain is lost */ LOST, /** The surface under the swap chain has ran out of memory. */ OUT_OF_MEMORY, /** The surface under the swap chain lost the device. */ DEVICE_LOST; companion object } /** * The usages determine what kind of memory the buffer is allocated from and what actions the buffer * can partake in. */ @JvmInline value class BufferUsage(val usageFlag: Int) { infix fun or(other: BufferUsage): BufferUsage = BufferUsage(usageFlag or other.usageFlag) infix fun and(other: BufferUsage): BufferUsage = BufferUsage(usageFlag and other.usageFlag) companion object { /** * Allow a buffer to be mapped for reading. Does not need to be enabled for * mapped_at_creation. */ val MAP_READ: BufferUsage = BufferUsage(0x0001) /** * Allow a buffer to be mapped for writing. Does not need to be enabled for * mapped_at_creation. */ val MAP_WRITE: BufferUsage = BufferUsage(0x0002) /** * Allow a buffer to be the source buffer for [CommandEncoder.copyBufferToBuffer] or * [CommandEncoder.copyBufferToTexture] */ val COPY_SRC: BufferUsage = BufferUsage(0x0004) /** Allow a buffer to be the destination buffer for [CommandEncoder.copyBufferToBuffer] */ val COPY_DST: BufferUsage = BufferUsage(0x0008) /** Allow a buffer to be used as index buffer for draw calls */ val INDEX: BufferUsage = BufferUsage(0x0010) /** Allow a buffer to be used as vertex buffer for draw calls */ val VERTEX: BufferUsage = BufferUsage(0x0020) /** Allow a buffer to be used as uniform buffer */ val UNIFORM: BufferUsage = BufferUsage(0x0040) /** Allows a buffer to be used as a storage buffer */ val STORAGE: BufferUsage = BufferUsage(0x0080) /** Allow a buffer to be the indirect buffer in an indirect draw call. */ val INDIRECT: BufferUsage = BufferUsage(0x0100) /** * Allow a buffer to be the destination buffer for a [CommandEncoder.resolveQuerySet] * operation. */ val QUERY_RESOLVE: BufferUsage = BufferUsage(0x0200) } } /** Type of buffer mapping. */ @JvmInline value class MapMode(val usageFlag: Int) { infix fun or(other: MapMode): MapMode = MapMode(usageFlag or other.usageFlag) infix fun and(other: MapMode): MapMode = MapMode(usageFlag and other.usageFlag) companion object { /** Map only for reading. */ val READ: MapMode = MapMode(0x0001) /** Map only for writing. */ val WRITE: MapMode = MapMode(0x0002) } } /** * Describes the shader stages that a binding will be visible from. These can be combined so that * something is visible from both vertex and fragment shaders: * * `ShaderStage.VERTEX or ShaderStage.FRAGMENT` */ @JvmInline value class ShaderStage(val usageFlag: Int) { infix fun or(other: ShaderStage): ShaderStage = ShaderStage(usageFlag or other.usageFlag) infix fun and(other: ShaderStage): ShaderStage = ShaderStage(usageFlag and other.usageFlag) companion object { /** Binding visible from the vertex shader of a render pipeline. */ val VERTEX: ShaderStage = ShaderStage(0x1) /** Binding visible from the fragment shader of a render pipeline. */ val FRAGMENT: ShaderStage = ShaderStage(0x2) /** Binding visible from the compute shader of a compute pipeline. */ val COMPUTE: ShaderStage = ShaderStage(0x4) } } /** * Each Feature identifies a set of functionality which, if available, allows additional usages of * WebGPU that would have otherwise been invalid. */ enum class Feature { /** Allows depth clipping to be disabled. */ DEPTH_CLIP_CONTROL, /** Allows for explicit creation of textures of format "depth32float-stencil8". */ DEPTH32FLOAT_STENCIL18, /** * Allows for explicit creation of textures of BC compressed formats. Supports both 2D and 3D * textures. */ TEXTURE_COMPRESSION_BC, /** * Allows for explicit creation of textures of ETC2 compressed formats. Only supports 2D * textures. */ TEXTURE_COMPRESSION_ETC2, /** * Allows for explicit creation of textures of ASTC compressed formats. Only supports 2D * textures. */ TEXTURE_COMPRESSION_ASTC, /** Adds the ability to query timestamps from GPU command buffers. */ TIMESTAMP_QUERY, /** * Allows the use of non-zero firstInstance values in indirect draw parameters and indirect * drawIndexed parameters. */ INDIRECT_FIRST_INSTANCE, /** Allows the use of the half-precision floating-point type f16 in WGSL. */ SHADER_F16, /** * Allows the RENDER_ATTACHMENT usage on textures with format "rg11b10ufloat", and also allows * textures of that format to be blended and multisampled. */ RG11B10UFLOAT_RENDERABLE, /** Allows the STORAGE_BINDING usage on textures with format "bgra8unorm". */ BGRA8UNORM_STORAGE, /** Makes textures with formats "r32float", "rg32float", and "rgba32float" filterable. */ FLOAT32_FILTERABLE, /** Allows the use of clip_distances in WGSL. */ CLIP_DISTANCES, /** * Allows the use of blend_src in WGSL and simultaneously using both pixel shader outputs * (@blend_src(0) and @blend_src(1)) as inputs to a blending operation with the single color * attachment at location 0. */ DUAL_SOURCE_BLENDING }
14
Kotlin
12
316
100c37feefcfd65038a9cba4886aeb4a7d5632dc
29,266
littlekt
Apache License 2.0
adaptive-core/src/commonMain/kotlin/hu/simplexion/adaptive/service/model/RequestEnvelope.kt
spxbhuhb
788,711,010
false
{"Kotlin": 963434, "CSS": 47382, "Java": 16814, "HTML": 2759, "JavaScript": 896}
/* * Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.adaptive.service.model import hu.simplexion.adaptive.utility.UUID import hu.simplexion.adaptive.wireformat.Wire import hu.simplexion.adaptive.wireformat.WireFormat import hu.simplexion.adaptive.wireformat.WireFormatDecoder import hu.simplexion.adaptive.wireformat.WireFormatEncoder @Wire class RequestEnvelope( val callId: UUID<RequestEnvelope>, val serviceName: String, val funName: String, val payload: ByteArray ) { companion object : WireFormat<RequestEnvelope> { override val wireFormatName: String get() = "hu.simplexion.adaptive.service.model.RequestEnvelope" override fun wireFormatEncode(encoder: WireFormatEncoder, value: RequestEnvelope): WireFormatEncoder = encoder .uuid(1, "callId", value.callId) .string(2, "serviceName", value.serviceName) .string(3, "funName", value.funName) .byteArray(4, "payload", value.payload) override fun <ST> wireFormatDecode(source: ST, decoder: WireFormatDecoder<ST>?): RequestEnvelope { requireNotNull(decoder) return RequestEnvelope( decoder.uuid(1, "callId"), decoder.string(2, "serviceName"), decoder.string(3, "funName"), decoder.byteArray(4, "payload") ) } } }
23
Kotlin
0
0
f3550c330c1b66014e922b30c8a8586d6e9d31d8
1,518
adaptive
Apache License 2.0
app/src/main/kotlin/io/xps/playground/ui/feature/liquidWidget/LiquidWidgetFragment.kt
serhii-petrenko-dev
593,936,096
false
{"Kotlin": 226184, "Java": 6274}
package io.xps.playground.ui.feature.liquidWidget import android.graphics.ColorMatrix import android.graphics.ColorMatrixColorFilter import android.graphics.RenderEffect import android.graphics.Shader import android.os.Build import android.os.Bundle import android.view.View import androidx.annotation.RequiresApi import androidx.compose.animation.core.Easing import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.CalendarToday import androidx.compose.material.icons.filled.Group import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.ShoppingCart import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme 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.paint import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asComposeRenderEffect import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.fragment.app.Fragment import dagger.hilt.android.AndroidEntryPoint import io.xps.playground.R import io.xps.playground.databinding.FragmentComposeBinding import io.xps.playground.tools.viewBinding import io.xps.playground.ui.theme.PlaygroundTheme import io.xps.playground.ui.theme.Purple900 import kotlin.math.PI import kotlin.math.sin import androidx.compose.ui.graphics.RenderEffect as ComposeRenderEffect const val DEFAULT_PADDING = 44 @AndroidEntryPoint class LiquidWidgetFragment : Fragment(R.layout.fragment_compose) { private val binding by viewBinding(FragmentComposeBinding::bind) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.containerCompose.setViewCompositionStrategy( ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed ) binding.containerCompose.setContent { PlaygroundTheme { LiquidScreen() } } } @Composable fun LiquidScreen() { val renderEffect = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { getRenderEffect().asComposeRenderEffect() } else { null } var isMenuExtended by remember { mutableStateOf(false) } val fabAnimationProgress by animateFloatAsState( targetValue = if (isMenuExtended) 1f else 0f, label = "", animationSpec = tween( durationMillis = 1000, easing = LinearEasing ) ) val clickAnimationProgress by animateFloatAsState( targetValue = if (isMenuExtended) 1f else 0f, label = "", animationSpec = tween( durationMillis = 400, easing = LinearEasing ) ) LiquidScreen( renderEffect = renderEffect, fabAnimationProgress = fabAnimationProgress, clickAnimationProgress = clickAnimationProgress, toggleAnimation = { isMenuExtended = !isMenuExtended } ) } @Composable fun LiquidScreen( renderEffect: ComposeRenderEffect?, fabAnimationProgress: Float = 0f, clickAnimationProgress: Float = 0f, toggleAnimation: () -> Unit = { } ) { Box( modifier = Modifier .fillMaxSize() .background(Purple900) .navigationBarsPadding(), contentAlignment = Alignment.BottomCenter ) { CustomBottomNavigation() Circle( color = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f), animationProgress = 0.5f ) FabGroup( renderEffect = renderEffect, animationProgress = fabAnimationProgress, toggleAnimation = toggleAnimation ) FabGroup( renderEffect = null, animationProgress = fabAnimationProgress, toggleAnimation = toggleAnimation ) Circle( color = Color.White, animationProgress = clickAnimationProgress ) } } @Composable fun Circle(color: Color, animationProgress: Float) { val animationValue = sin(PI * animationProgress).toFloat() Box( modifier = Modifier .padding(DEFAULT_PADDING.dp) .size(56.dp) .scale(2 - animationValue) .border( width = 2.dp, color = color.copy(alpha = color.alpha * animationValue), shape = CircleShape ) ) } @Composable fun CustomBottomNavigation() { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .height(80.dp) .paint( painter = painterResource(R.drawable.bottom_navigation), contentScale = ContentScale.FillHeight ) .padding(horizontal = 40.dp) ) { listOf(Icons.Filled.CalendarToday, Icons.Filled.Group).map { image -> IconButton(onClick = { }) { Icon(imageVector = image, contentDescription = null, tint = Color.White) } } } } @Composable fun FabGroup( animationProgress: Float = 0f, renderEffect: ComposeRenderEffect? = null, toggleAnimation: () -> Unit = { } ) { Box( Modifier .fillMaxSize() .graphicsLayer { this.renderEffect = renderEffect } .padding(bottom = DEFAULT_PADDING.dp), contentAlignment = Alignment.BottomCenter ) { AnimatedFab( icon = Icons.Default.PhotoCamera, modifier = Modifier .padding( PaddingValues( bottom = 72.dp, end = 210.dp ) * FastOutSlowInEasing.transform(0f, 0.8f, animationProgress) ), opacity = LinearEasing.transform(0.2f, 0.7f, animationProgress) ) AnimatedFab( icon = Icons.Default.Settings, modifier = Modifier.padding( PaddingValues( bottom = 88.dp ) * FastOutSlowInEasing.transform(0.1f, 0.9f, animationProgress) ), opacity = LinearEasing.transform(0.3f, 0.8f, animationProgress) ) AnimatedFab( icon = Icons.Default.ShoppingCart, modifier = Modifier.padding( PaddingValues( bottom = 72.dp, start = 210.dp ) * FastOutSlowInEasing.transform(0.2f, 1.0f, animationProgress) ), opacity = LinearEasing.transform(0.4f, 0.9f, animationProgress) ) AnimatedFab( modifier = Modifier .scale(1f - LinearEasing.transform(0.5f, 0.85f, animationProgress)) ) AnimatedFab( icon = Icons.Default.Add, modifier = Modifier .rotate( 225 * FastOutSlowInEasing .transform(0.35f, 0.65f, animationProgress) ), onClick = toggleAnimation, backgroundColor = Color.Transparent ) } } @Composable fun AnimatedFab( modifier: Modifier, icon: ImageVector? = null, opacity: Float = 1f, backgroundColor: Color = Color(0xFFF373C4), onClick: () -> Unit = {} ) { FloatingActionButton( onClick = onClick, elevation = FloatingActionButtonDefaults.elevation(0.dp, 0.dp, 0.dp, 0.dp), containerColor = backgroundColor, shape = CircleShape, modifier = modifier.scale(1.25f) ) { icon?.let { Icon( imageVector = it, contentDescription = null, tint = Color.White.copy(alpha = opacity) ) } } } @RequiresApi(Build.VERSION_CODES.S) private fun getRenderEffect(): RenderEffect { val blurEffect = RenderEffect.createBlurEffect( 80f, 80f, Shader.TileMode.MIRROR ) val alphaMatrix = RenderEffect.createColorFilterEffect( ColorMatrixColorFilter( ColorMatrix( floatArrayOf( 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 50f, -5000f ) ) ) ) return RenderEffect.createChainEffect(alphaMatrix, blurEffect) } private fun Easing.transform(from: Float, to: Float, value: Float): Float { return transform(((value - from) * (1f / (to - from))).coerceIn(0f, 1f)) } operator fun PaddingValues.times(value: Float): PaddingValues = PaddingValues( top = calculateTopPadding() * value, bottom = calculateBottomPadding() * value, start = calculateStartPadding(LayoutDirection.Ltr) * value, end = calculateEndPadding(LayoutDirection.Ltr) * value ) }
0
Kotlin
0
0
bc0277d1200aa5078c8943c67aa8fa9dfe37b8ce
11,584
playground
MIT License
src/main/kotlin/com/krillsson/sysapi/graphql/domain/MonitorEvent.kt
Krillsson
40,235,586
false
{"Kotlin": 454985, "Shell": 10836, "Batchfile": 734, "Dockerfile": 274}
package com.krillsson.sysapi.graphql.domain import com.krillsson.sysapi.core.monitoring.Monitor import java.time.OffsetDateTime import java.util.* class MonitorEvent( val id: UUID, val monitorId: UUID, val time: OffsetDateTime, val monitorType: Monitor.Type, val threshold: Double, val value: Double )
9
Kotlin
3
97
08d2205b06687f67a24e64a9ed9fc9cf36ff91a4
351
sys-API
Apache License 2.0
src/main/kotlin/com/epam/brn/controller/advice/ExceptionControllerAdvice.kt
Reset256
233,861,917
true
{"Kotlin": 152983, "JavaScript": 101723, "TypeScript": 24564, "HTML": 17191, "CSS": 8735, "RAML": 4123, "Makefile": 467, "Shell": 405, "TSQL": 191, "Dockerfile": 185, "Java": 128}
package com.epam.brn.controller.advice import com.epam.brn.dto.BaseResponseDto import com.epam.brn.dto.ErrorResponse import com.epam.brn.exception.EntityNotFoundException import com.epam.brn.exception.FileFormatException import com.epam.brn.exception.NoDataFoundException import org.apache.logging.log4j.kotlin.logger import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @ControllerAdvice class ExceptionControllerAdvice { private val logger = logger() @ExceptionHandler(NoDataFoundException::class) fun handleNoDataFoundException(e: NoDataFoundException): ResponseEntity<BaseResponseDto> { logger.error("Data was not found. ${e.message}", e) return ResponseEntity .status(HttpStatus.NOT_FOUND) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BaseResponseDto(errors = listOf(e.message.toString()))) } @ExceptionHandler(Throwable::class) fun handleException(e: Throwable): ResponseEntity<BaseResponseDto> { logger.error("Internal exception: ${e.message}", e) return makeInternalServerErrorResponseEntity(e) } @ExceptionHandler(FileFormatException::class) fun handleFileFormatException(e: FileFormatException): ResponseEntity<ErrorResponse> { logger.error("File format exception: ${e.message}", e) return ResponseEntity .status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(ErrorResponse(e.message)) } @ExceptionHandler(EntityNotFoundException::class) fun handleEntityNotFoundException(e: EntityNotFoundException): ResponseEntity<ErrorResponse> { logger.error("Entity not found exception: ${e.message}", e) return ResponseEntity .status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(ErrorResponse(e.message)) } fun makeInternalServerErrorResponseEntity(e: Throwable) = ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BaseResponseDto(errors = listOf(e.message.toString()))) }
0
null
0
0
f160a881865680365e87755dec6b2e0d93d84e10
2,367
brn
MIT License
src/client/kotlin/tech/thatgravyboat/skyblockapi/helpers/McClient.kt
SkyblockAPI
861,984,504
false
{"Kotlin": 300649, "Java": 24588}
package tech.thatgravyboat.skyblockapi.helpers import com.mojang.blaze3d.platform.Window import com.mojang.brigadier.CommandDispatcher import net.fabricmc.loader.api.FabricLoader import net.minecraft.client.Minecraft import net.minecraft.client.gui.components.ChatComponent import net.minecraft.client.gui.components.toasts.ToastComponent import net.minecraft.client.gui.screens.ChatScreen import net.minecraft.client.gui.screens.Screen import net.minecraft.client.multiplayer.PlayerInfo import net.minecraft.commands.SharedSuggestionProvider import net.minecraft.network.chat.Component import net.minecraft.world.level.GameType import net.minecraft.world.scores.DisplaySlot object McClient { private val tabListComparator: Comparator<PlayerInfo> = compareBy( { it.gameMode == GameType.SPECTATOR }, { it.team?.name ?: "" }, { it.profile.name.lowercase() }, ) val isDev = FabricLoader.getInstance().isDevelopmentEnvironment val self: Minecraft get() = Minecraft.getInstance() val window: Window get() = self.window var clipboard: String? get() = self.keyboardHandler?.clipboard set(value) { self.keyboardHandler?.clipboard = value } val mouse: Pair<Double, Double> get() = Pair( self.mouseHandler.xpos() * (window.guiScaledWidth / window.screenWidth.coerceAtLeast(1).toDouble()), self.mouseHandler.ypos() * (window.guiScaledHeight / window.screenHeight.coerceAtLeast(1).toDouble()) ) val tablist: List<PlayerInfo> get() = self.connection ?.listedOnlinePlayers ?.sortedWith(tabListComparator) ?: emptyList() val players: List<PlayerInfo> get() = tablist.filter { it.profile.id.version() == 4 } val scoreboard: Collection<Component> get() { val scoreboard = self.level?.scoreboard ?: return emptyList() val objective = scoreboard.getDisplayObjective(DisplaySlot.SIDEBAR) ?: return emptyList() return scoreboard.listPlayerScores(objective) .sortedBy { -it.value } .map { val team = scoreboard.getPlayersTeam(it.owner) Component.empty().also { main -> team?.playerPrefix?.apply { siblings.forEach { sibling -> main.append(sibling) } } team?.playerSuffix?.apply { siblings.forEach { sibling -> main.append(sibling) } } } } } val scoreboardTitle get() = self.level?.scoreboard?.getDisplayObjective(DisplaySlot.SIDEBAR)?.displayName val toasts: ToastComponent get() = self.toasts val serverCommands: CommandDispatcher<SharedSuggestionProvider>? get() = self.connection?.commands val chat: ChatComponent get() = self.gui.chat fun tell(action: () -> Unit) { self.tell(action) } fun setScreen(screen: Screen?) { if (self.screen is ChatScreen) { tell { self.setScreen(screen) } } else { self.setScreen(screen) } } fun sendCommand(command: String) { self.connection?.sendCommand(command.removePrefix("/")) } }
3
Kotlin
3
3
8948d699bf0fc3df88de59d8ec79d162fb922ace
3,253
SkyblockAPI
MIT License
servers/graphql-kotlin-spring-server/src/test/kotlin/com/expediagroup/graphql/server/spring/context/GraphQLContextFactoryIT.kt
webdeveloper0012
338,369,606
true
{"Kotlin": 1448590, "HTML": 8758, "JavaScript": 8746, "CSS": 297}
/* * Copyright 2020 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.server.spring.context import com.expediagroup.graphql.generator.execution.GraphQLContext import com.expediagroup.graphql.server.spring.execution.SpringGraphQLContextFactory import com.expediagroup.graphql.types.GraphQLRequest import com.expediagroup.graphql.types.operations.Query import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.MediaType import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.reactive.function.server.ServerRequest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["graphql.packages=com.expediagroup.graphql.server.spring.context"]) @EnableAutoConfiguration class GraphQLContextFactoryIT(@Autowired private val testClient: WebTestClient) { @Test fun `verify context is generated and available to the GraphQL execution`() { testClient.post() .uri("/graphql") .header("X-First-Header", "JUNIT_FIRST") .header("X-Second-Header", "JUNIT_SECOND") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .bodyValue(GraphQLRequest("query { context { first second } }")) .exchange() .expectBody() .jsonPath("$.data.context").exists() .jsonPath("$.data.context.first").isEqualTo("JUNIT_FIRST") .jsonPath("$.data.context.second").isEqualTo("JUNIT_SECOND") .jsonPath("$.errors").doesNotExist() .jsonPath("$.extensions").doesNotExist() } @Configuration class GraphQLContextFactoryConfiguration { @Bean fun query(): Query = ContextualQuery() @Bean @ExperimentalCoroutinesApi fun customContextFactory(): SpringGraphQLContextFactory<CustomContext> = object : SpringGraphQLContextFactory<CustomContext>() { override suspend fun generateContext(request: ServerRequest): CustomContext { return CustomContext( first = request.headers().firstHeader("X-First-Header") ?: "DEFAULT_FIRST", second = request.headers().firstHeader("X-Second-Header") ?: "DEFAULT_SECOND" ) } } } class ContextualQuery : Query { fun context(ctx: CustomContext): CustomContext = ctx } data class CustomContext(val first: String?, val second: String?) : GraphQLContext }
0
null
0
0
5294aa549d00bfd2c0dec2e9588662ce0d8920d1
3,410
graphql-kotlin
Apache License 2.0
core/src/commonMain/kotlin/com/xebia/functional/xef/llm/models/chat/ChatCompletionResponseWithFunctions.kt
xebia-functional
629,411,216
false
null
package com.xebia.functional.xef.llm.models.chat import com.xebia.functional.xef.llm.models.usage.Usage data class ChatCompletionResponseWithFunctions( val id: String, val `object`: String, val created: Int, val model: String, val usage: Usage, val choices: List<ChoiceWithFunctions> )
10
Kotlin
8
89
a762a968c31778f0a314a204f6b10340cec38336
300
xef
Apache License 2.0
src/test/kotlin/pubg/radar/getRouteTable.kt
whitewingz2017
129,306,460
false
null
package pubg.radar import pubg.radar.sniffer.Sniffer.Companion.targetAddr import java.io.BufferedReader import java.io.InputStreamReader import java.net.Inet4Address fun main(args: Array<String>) { val proc = Runtime.getRuntime().exec("route print -4") val input = BufferedReader(InputStreamReader(proc.inputStream)) val result = input.readText() val regex = Regex("\\s*On-link\\s*([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)\\s*") val ips = HashMap<String, Int>() for (matchResult in regex.findAll(result)) { val ip = matchResult.groups[1]!!.value ips.compute(ip) { _, count -> (count ?: 0) + 1 } } ips.remove(targetAddr.hostAddress) ips.remove("127.0.0.1") val maxIp = ips.maxBy { it.value } if (maxIp != null) { val routeIpAddr = Inet4Address.getByName(maxIp.key) as Inet4Address } else { System.exit(0) } }
2
null
67
7
0810899b85ac5bea69cb558c24c8241d5cc29ff3
908
Gdar
The Unlicense
src/main/kotlin/me/rafaelka/cmdportals/command/Commands.kt
Angelo4ekUwU
676,237,886
false
null
package me.rafaelka.cmdportals.command import com.mojang.brigadier.arguments.IntegerArgumentType.getInteger import com.mojang.brigadier.arguments.IntegerArgumentType.integer import com.mojang.brigadier.arguments.StringArgumentType.getString import com.mojang.brigadier.arguments.StringArgumentType.greedyString import com.mojang.brigadier.arguments.StringArgumentType.word import com.mojang.brigadier.builder.LiteralArgumentBuilder import com.mojang.brigadier.builder.LiteralArgumentBuilder.literal import com.mojang.brigadier.builder.RequiredArgumentBuilder.argument import io.papermc.paper.adventure.PaperAdventure import me.rafaelka.cmdportals.config.messages import me.rafaelka.cmdportals.config.portals import me.rafaelka.cmdportals.config.settings import me.rafaelka.cmdportals.playerListener import me.rafaelka.cmdportals.plugin import me.rafaelka.cmdportals.portal.Portal import me.rafaelka.cmdportals.util.Permissions import net.kyori.adventure.text.minimessage.MiniMessage import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver import net.minecraft.commands.CommandSourceStack import net.minecraft.network.chat.Component import org.bukkit.Bukkit import org.bukkit.craftbukkit.v1_20_R1.CraftServer import org.bukkit.entity.Player fun registerCommands() { val dispatcher = (Bukkit.getServer() as CraftServer).server.commands.dispatcher dispatcher.register(portalCommand()) } private fun portalCommand(): LiteralArgumentBuilder<CommandSourceStack> = literal<CommandSourceStack?>("portal") .then(literal<CommandSourceStack?>("reload") .requires { it.hasPermission(2, Permissions.RELOAD) } .executes { ctx -> plugin.reload() ctx.source.sendSystemMessage(vanilla(messages.commands.reload)) 1 } ) .then(literal<CommandSourceStack?>("wand") .requires { it.hasPermission(2, Permissions.WAND) } .executes { ctx -> val sender = ctx.source.bukkitSender if (sender is Player) { sender.inventory.addItem(settings.wand) ctx.source.sendSystemMessage(vanilla(messages.commands.wand)) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.onlyForPlayers)) } 1 } ) .then(literal<CommandSourceStack?>("create") .requires { it.hasPermission(2, Permissions.CREATE) } .then(argument<CommandSourceStack?, String?>("portal_id", word()) .executes { ctx -> val sender = ctx.source.bukkitSender if (sender is Player) { val selection = playerListener.selections[sender.uniqueId] if (selection != null && selection.isComplete()) { val id = getString(ctx, "portal_id") val portal = Portal(id, selection.pos1!!, selection.pos2!!) portals.portals.add(portal) portals.save() ctx.source.sendSystemMessage(vanilla(messages.commands.create, Placeholder.unparsed("portal_id", id))) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.noSelection)) } } else { ctx.source.sendSystemMessage(vanilla(messages.errors.onlyForPlayers)) } 1 } ) ) .then(literal<CommandSourceStack?>("delete") .requires { it.hasPermission(2, Permissions.DELETE) } .then(argument<CommandSourceStack?, String?>("portal_id", word()) .executes { ctx -> val sender = ctx.source.bukkitSender if (sender is Player) { val id = getString(ctx, "portal_id") portals.portals.removeIf { it.id == id } portals.save() ctx.source.sendSystemMessage(vanilla(messages.commands.delete, Placeholder.unparsed("portal_id", id))) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.onlyForPlayers)) } 1 } .suggests { ctx, builder -> try { val arg = ctx.getArgument("portal_id", String::class.java).lowercase() portals.portals.forEach { if (it.id.startsWith(arg)) builder.suggest(it.id) } } catch (ex: IllegalArgumentException) { portals.portals.stream().map(Portal::id).forEach(builder::suggest) } builder.buildFuture() } ) ) .then(literal<CommandSourceStack?>("actions") .then(argument<CommandSourceStack?, String?>("portal_id", word()) .then(literal<CommandSourceStack?>("add") .requires { it.hasPermission(2, Permissions.ACTIONS_ADD) } .then(argument<CommandSourceStack?, String?>("action", greedyString()) .executes { ctx -> val portalId = getString(ctx, "portal_id") val portal = portals.portals.stream().filter { it.id == portalId }.findFirst().orElse(null) if (portal != null) { val action = getString(ctx, "action") portals.portals.remove(portal) portal.actions[portal.actions.size] = action portals.portals.add(portal) portals.save() ctx.source.sendSystemMessage( vanilla( messages.commands.actions.add, Placeholder.unparsed("action", action), Placeholder.unparsed("action_id", (portal.actions.size - 1).toString()), Placeholder.unparsed("portal_id", portalId), ) ) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.portalNotFound)) } 1 } ) ) .then(literal<CommandSourceStack?>("remove") .requires { it.hasPermission(2, Permissions.ACTIONS_REMOVE) } .then(argument<CommandSourceStack?, Int?>("action_id", integer()) .executes { ctx -> val portalId = getString(ctx, "portal_id") val portal = portals.portals.stream().filter { it.id == portalId }.findFirst().orElse(null) if (portal != null) { val actionId = getInteger(ctx, "action_id") if (portal.actions.containsKey(actionId)) { portals.portals.remove(portal) portal.actions.remove(actionId) portals.portals.add(portal) portals.save() ctx.source.sendSystemMessage( vanilla( messages.commands.actions.remove, Placeholder.unparsed("portal_id", portalId), Placeholder.unparsed("action_id", portal.actions.size.toString()) ) ) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.actionNotFound)) } } else { ctx.source.sendSystemMessage(vanilla(messages.errors.portalNotFound)) } 1 } ) ) .then(literal<CommandSourceStack?>("clear") .requires { it.hasPermission(2, Permissions.ACTIONS_CLEAR) } .executes { ctx -> val portalId = getString(ctx, "portal_id") val portal = portals.portals.stream().filter { it.id == portalId }.findFirst().orElse(null) if (portal != null) { if (portal.actions.isNotEmpty()) { portals.portals.remove(portal) portal.actions.clear() portals.portals.add(portal) portals.save() ctx.source.sendSystemMessage(vanilla(messages.commands.actions.clear)) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.noActions)) } } else { ctx.source.sendSystemMessage(vanilla(messages.errors.portalNotFound)) } 1 } ) .then(literal<CommandSourceStack?>("list") .requires { it.hasPermission(2, Permissions.ACTIONS_LIST) } .executes { ctx -> val portalId = getString(ctx, "portal_id") val portal = portals.portals.stream().filter { it.id == portalId }.findFirst().orElse(null) if (portal != null) { if (portal.actions.isNotEmpty()) { val msg = vanilla( messages.commands.actions.listHeader, Placeholder.unparsed("portal_id", portalId) ).copy() portal.actions.forEach { id, action -> msg.append( vanilla( messages.commands.actions.listEntry, Placeholder.unparsed("action_id", id.toString()), Placeholder.unparsed("action", action) ) ) } ctx.source.sendSystemMessage(msg) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.noActions)) } } else { ctx.source.sendSystemMessage(vanilla(messages.errors.portalNotFound)) } 1 } ) .suggests { ctx, builder -> try { val arg = ctx.getArgument("portal_id", String::class.java).lowercase() portals.portals.forEach { if (it.id.startsWith(arg)) builder.suggest(it.id) } } catch (ex: IllegalArgumentException) { portals.portals.stream().map(Portal::id).forEach(builder::suggest) } builder.buildFuture() } ) ) .then(literal<CommandSourceStack?>("permission") .then(argument<CommandSourceStack?, String?>("portal_id", word()) .then(literal<CommandSourceStack?>("set") .requires { it.hasPermission(2, Permissions.PERMISSION_SET) } .then(argument<CommandSourceStack?, String?>("permission", word()) .executes { ctx -> val portalId = getString(ctx, "portal_id") val portal = portals.portals.stream().filter { it.id == portalId }.findFirst().orElse(null) if (portal != null) { val permission = getString(ctx, "permission") portals.portals.remove(portal) portal.permission = permission portals.portals.add(portal) portals.save() ctx.source.sendSystemMessage( vanilla( messages.commands.permission.set, Placeholder.unparsed("permission", permission), Placeholder.unparsed("portal_id", portalId) ) ) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.portalNotFound)) } 1 } ) ) .then(literal<CommandSourceStack?>("remove") .requires { it.hasPermission(2, Permissions.PERMISSION_REMOVE) } .executes { ctx -> val portalId = getString(ctx, "portal_id") val portal = portals.portals.stream().filter { it.id == portalId }.findFirst().orElse(null) if (portal != null) { portals.portals.remove(portal) portal.permission = null portals.portals.add(portal) portals.save() ctx.source.sendSystemMessage( vanilla( messages.commands.permission.remove, Placeholder.unparsed("portal_id", portalId) ) ) } else { ctx.source.sendSystemMessage(vanilla(messages.errors.portalNotFound)) } 1 } ) .suggests { ctx, builder -> try { val arg = ctx.getArgument("portal_id", String::class.java).lowercase() portals.portals.forEach { if (it.id.startsWith(arg)) builder.suggest(it.id) } } catch (ex: IllegalArgumentException) { portals.portals.stream().map(Portal::id).forEach(builder::suggest) } builder.buildFuture() } ) ) private fun vanilla(string: String, vararg tags: TagResolver): Component = PaperAdventure.asVanilla(MiniMessage.miniMessage().deserialize(string, *tags))
0
Kotlin
0
0
4ffdf454c3cf303f9318c2b6511bee06ecc05417
14,650
CommandPortals
Creative Commons Zero v1.0 Universal
MzaziConnectApplication/app/src/main/java/sakigake/mzaziconnect/mzaziconnectapplication/ui/teacher/EditAssignmentActivity.kt
Florence-nyokabi
721,515,801
false
{"Kotlin": 130912}
package sakigake.mzaziconnect.mzaziconnectapplication.ui.teacher import android.app.DatePickerDialog import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import sakigake.mzaziconnect.mzaziconnectapplication.databinding.ActivityEditAssignmentBinding import java.util.Calendar import java.util.Locale import android.widget.Toast import androidx.activity.viewModels import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import sakigake.mzaziconnect.mzaziconnectapplication.model.AssignmentsData import sakigake.mzaziconnect.mzaziconnectapplication.model.ShopData import sakigake.mzaziconnect.mzaziconnectapplication.model.SubjectData import sakigake.mzaziconnect.mzaziconnectapplication.repository.AssignmentRepo import sakigake.mzaziconnect.mzaziconnectapplication.viewmodel.ShopViewModel import sakigake.mzaziconnect.mzaziconnectapplication.viewmodel.SubjectViewModel import java.time.LocalDateTime import java.time.format.DateTimeFormatter class EditAssignmentActivity : AppCompatActivity() { lateinit var binding: ActivityEditAssignmentBinding private lateinit var editTextDate: EditText private val calendar = Calendar.getInstance() lateinit var postrepo: AssignmentRepo private lateinit var subjectSpinner: Spinner private lateinit var shopSpinner:Spinner val subjectViewModel: SubjectViewModel by viewModels() val shopViewModel: ShopViewModel by viewModels() private lateinit var adapter: ArrayAdapter<SubjectData> private lateinit var shopAdapter:ArrayAdapter<ShopData> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityEditAssignmentBinding.inflate(layoutInflater) setContentView(binding.root) subjectSpinner = binding.spinnerSubject shopSpinner = binding.spinnercategories postrepo=AssignmentRepo() } override fun onResume() { super.onResume() clearErrors() fun showToast() { Toast.makeText(applicationContext, "Assignment posted", Toast.LENGTH_SHORT).show() } binding.btnPostAssignment.setOnClickListener { postAsignment() showToast() val intent = Intent(this, SubjectAssignmentActivity::class.java) startActivity(intent) } binding.ivcancel.setOnClickListener { val intent = Intent(this, SubjectAssignmentActivity::class.java) startActivity(intent) } getCustomSubjectsData() getCustomShopData() } private fun getCustomSubjectsData(){ subjectViewModel.subjectsLiveData.observe(this) { subjectsList -> adapter = SubjectAdapter(this, subjectsList) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) subjectSpinner.adapter = adapter subjectSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { val selectedObject = subjectSpinner.selectedItem as SubjectData Toast.makeText ( this@EditAssignmentActivity, "ID: ${selectedObject.id} Name: ${selectedObject.subject_name}", Toast.LENGTH_SHORT ).show() } } } } private fun getCustomShopData(){ shopViewModel.shopLiveData.observe(this){shopList -> shopAdapter=ShopAdapter(this, shopList) shopAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) shopSpinner.adapter = shopAdapter shopSpinner.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{ override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { val selectedObject = shopSpinner.selectedItem as ShopData Toast.makeText( this@EditAssignmentActivity, "ID: ${selectedObject.id} Name: ${selectedObject.category}", Toast.LENGTH_SHORT ).show() } override fun onNothingSelected(p0: AdapterView<*>?) { } } } } fun formatDate():String{ val now= LocalDateTime.now() val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm[:ss[.uuuuuu]][XXX]") return formatter.format(now) } fun postAsignment() { val dueDate = formatDate() val topic = binding.ettopic.text.toString() val task = binding.ettypemessage.text.toString() val resources = binding.etresources.text.toString() val compentecy = binding.etcompetency.text.toString() val selectedSubject = subjectSpinner.selectedItem as SubjectData val selectedShop = shopSpinner.selectedItem as ShopData val assignmentData = AssignmentsData( topic = topic, task = task, category = selectedShop.id, competency= compentecy, due_date =dueDate, resources = arrayOf(resources), subject = selectedSubject.id ) CoroutineScope(Dispatchers.IO).launch{ postrepo.postAssignment(assignmentData) } } fun showDatePickerDialog(view: View) { val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) val datePickerDialog = DatePickerDialog( this, { _, selectedYear, selectedMonth, selectedDay -> editTextDate.setText( String.format( Locale.getDefault(), "%02d/%02d/%04d", selectedDay, selectedMonth + 1, selectedYear ) ) }, year, month, day ) datePickerDialog.show() } fun validateEditAssignment(): Boolean { val topic = binding.ettopic.text.toString() val message = binding.ettypemessage.text.toString() val resources = binding.etresources.text.toString() var error = false if (topic.isBlank()) { binding.tiltopic.error = "Topic is required" error = true } if (message.isBlank()) { binding.tiltypemessage.error = "Message is required" error = true } if (resources.isBlank()) { binding.tilresources.error = "Resources is required" error = true } return !error } fun clearErrors() { binding.tilresources.error = null binding.tiltopic.error = null binding.tiltypemessage.error = null } }
0
Kotlin
0
0
e4c7c167efb9b1373f2ecf231fd126ab6ff9675b
7,384
Sakigake-mobile
MIT License
nativelogger/src/main/java/cn/jesse/nativelogger/util/ZipUtil.kt
284919275IOS
499,047,712
true
{"Java": 685158, "Kotlin": 112011}
package cn.jesse.nativelogger.util import android.text.TextUtils import cn.jesse.nativelogger.NLogger import java.io.* import java.nio.charset.Charset import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream /** * 压缩工具 * * @author Jesse */ object ZipUtil { val SUFFIX_ZIP = ".zip" private val BUFF_SIZE = 1024 * 1024 private val SUFFIX_LOCK = ".lck" /** * get suitable files from path depend on pack num ,clear redundant files * * @param path source files path * @param expiredPeriod expired file period */ fun getSuitableFilesWithClear(path: String, expiredPeriod: Int): Collection<File> { val files = ArrayList<File>() val file = File(path) val subFile = file.listFiles() if (subFile != null && !subFile.isEmpty()) { for (item in subFile) { if (item.isDirectory) { continue } val expired = expiredPeriod * 24 * 60 * 60 * 1000L if ((System.currentTimeMillis() - item.lastModified() > expired) && !item.delete()) { NLogger.e("can not delete expired file " + item.name) } if (item.name.endsWith(SUFFIX_LOCK) || item.name.endsWith(SUFFIX_ZIP)) { continue } files.add(item) } } return files } /** * zip files * * @param resFileList zip from files * @param zipFile zip to file * @param comment comment of target file */ @Throws(IOException::class) fun zipFiles(resFileList: Collection<File>?, zipFile: File, comment: String): Boolean { if (null == resFileList || resFileList.isEmpty()) { return false } val zipOutputStream = ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile), BUFF_SIZE)) for (resFile in resFileList) { zipFile(resFile, zipOutputStream, "") } if (!TextUtils.isEmpty(comment)) { zipOutputStream.setComment(comment) } CloseUtil.close(zipOutputStream) return true } /** * zip file * * @param resFile zip from file * @param zipOut zip to file * @param rootPath target file path */ @Throws(IOException::class) fun zipFile(resFile: File, zipOut: ZipOutputStream, rootPath: String) { var separator = "" if (rootPath.isNotEmpty()) { separator = File.separator } var filePath = rootPath + separator + resFile.name filePath = String(filePath.toByteArray(), Charset.forName("GB2312")) if (resFile.isDirectory) { val fileList = resFile.listFiles() for (file in fileList!!) { zipFile(file, zipOut, filePath) } return } val buffer = ByteArray(BUFF_SIZE) val bis = BufferedInputStream(FileInputStream(resFile), BUFF_SIZE) zipOut.putNextEntry(ZipEntry(filePath)) var realLength = bis.read(buffer) while (realLength != -1) { zipOut.write(buffer, 0, realLength) realLength = bis.read(buffer) } CloseUtil.close(bis) zipOut.flush() zipOut.closeEntry() } }
0
null
0
0
4e0b4da53b87c6afa0c4787357b75ac1edd76a22
3,331
XDroidMvp-AndroidX
MIT License
app/src/main/java/zebrostudio/wallr100/android/AndroidBackgroundThreads.kt
abhriyaroy
119,387,578
false
null
package zebrostudio.wallr100.android import io.reactivex.Scheduler import io.reactivex.schedulers.Schedulers import zebrostudio.wallr100.domain.executor.ExecutionThread class AndroidBackgroundThreads : ExecutionThread { override val ioScheduler: Scheduler get() = Schedulers.io() override val computationScheduler: Scheduler get() = Schedulers.computation() }
1
null
1
1
ff76741976c2fe5b68360fc970531124a2ff516b
375
WallR2.0
Apache License 2.0
redwood-protocol-guest/src/commonTest/kotlin/app/cash/redwood/protocol/guest/GuestProtocolAdapterTest.kt
cashapp
305,409,146
false
null
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.redwood.protocol.guest import app.cash.redwood.Modifier import app.cash.redwood.protocol.Create import app.cash.redwood.protocol.Event import app.cash.redwood.protocol.EventTag import app.cash.redwood.protocol.Id import app.cash.redwood.protocol.ModifierChange import app.cash.redwood.protocol.ModifierElement import app.cash.redwood.protocol.ModifierTag import app.cash.redwood.protocol.PropertyChange import app.cash.redwood.protocol.PropertyTag import app.cash.redwood.protocol.WidgetTag import assertk.assertThat import assertk.assertions.hasMessage import assertk.assertions.isEqualTo import com.example.redwood.testing.compose.TestSchemaProtocolBridge import com.example.redwood.testing.compose.TestScope import kotlin.test.Test import kotlin.test.assertFailsWith import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.modules.SerializersModule class GeneratedProtocolBridgeTest { @Test fun propertyUsesSerializersModule() { val json = Json { serializersModule = SerializersModule { contextual(Duration::class, DurationIsoSerializer) } } val bridge = TestSchemaProtocolBridge.create(json) val textInput = bridge.widgetSystem.TestSchema.TextInput() textInput.customType(10.seconds) val expected = listOf( Create(Id(1), WidgetTag(5)), PropertyChange(Id(1), PropertyTag(2), JsonPrimitive("PT10S")), ) assertThat(bridge.getChangesOrNull()).isEqualTo(expected) } @Test fun modifierUsesSerializersModule() { val json = Json { serializersModule = SerializersModule { contextual(Duration::class, DurationIsoSerializer) } } val bridge = TestSchemaProtocolBridge.create(json) val button = bridge.widgetSystem.TestSchema.Button() button.modifier = with(object : TestScope {}) { Modifier.customType(10.seconds) } val expected = listOf( Create(Id(1), WidgetTag(4)), ModifierChange( Id(1), listOf( ModifierElement( ModifierTag(3), buildJsonObject { put("customType", JsonPrimitive("PT10S")) }, ), ), ), ) assertThat(bridge.getChangesOrNull()).isEqualTo(expected) } @Test fun modifierDefaultValueNotSerialized() { val json = Json { serializersModule = SerializersModule { contextual(Duration::class, DurationIsoSerializer) } } val bridge = TestSchemaProtocolBridge.create(json) val button = bridge.widgetSystem.TestSchema.Button() button.modifier = with(object : TestScope {}) { Modifier.customTypeWithDefault(10.seconds, "sup") } val expected = listOf( Create(Id(1), WidgetTag(4)), ModifierChange( Id(1), listOf( ModifierElement( ModifierTag(5), buildJsonObject { put("customType", JsonPrimitive("PT10S")) }, ), ), ), ) assertThat(bridge.getChangesOrNull()).isEqualTo(expected) } @Test fun eventUsesSerializersModule() { val json = Json { serializersModule = SerializersModule { contextual(Duration::class, DurationIsoSerializer) } } val bridge = TestSchemaProtocolBridge.create(json) val textInput = bridge.widgetSystem.TestSchema.TextInput() val protocolWidget = textInput as ProtocolWidget var argument: Duration? = null textInput.onChangeCustomType { argument = it } protocolWidget.sendEvent(Event(Id(1), EventTag(4), listOf(JsonPrimitive("PT10S")))) assertThat(argument).isEqualTo(10.seconds) } @Test fun unknownEventThrowsDefault() { val bridge = TestSchemaProtocolBridge.create() val button = bridge.widgetSystem.TestSchema.Button() as ProtocolWidget val t = assertFailsWith<IllegalArgumentException> { button.sendEvent(Event(Id(1), EventTag(3456543))) } assertThat(t).hasMessage("Unknown event tag 3456543 for widget tag 4") } @Test fun unknownEventCallsHandler() { val handler = RecordingProtocolMismatchHandler() val bridge = TestSchemaProtocolBridge.create(mismatchHandler = handler) val button = bridge.widgetSystem.TestSchema.Button() as ProtocolWidget button.sendEvent(Event(Id(1), EventTag(3456543))) assertThat(handler.events.single()).isEqualTo("Unknown event 3456543 for 4") } @Test fun unknownEventNodeThrowsDefault() { val bridge = TestSchemaProtocolBridge.create() val t = assertFailsWith<IllegalArgumentException> { bridge.sendEvent(Event(Id(3456543), EventTag(1))) } assertThat(t).hasMessage("Unknown node ID 3456543 for event with tag 1") } @Test fun unknownEventNodeCallsHandler() { val handler = RecordingProtocolMismatchHandler() val bridge = TestSchemaProtocolBridge.create(mismatchHandler = handler) bridge.sendEvent(Event(Id(3456543), EventTag(1))) assertThat(handler.events.single()).isEqualTo("Unknown ID 3456543 for event tag 1") } }
98
null
73
1,648
3f14e622c2900ec7e0dfaff5bd850c95a7f29937
5,781
redwood
Apache License 2.0
ground/src/main/java/com/google/android/ground/persistence/local/room/dao/TaskDao.kt
google
127,777,820
false
{"Kotlin": 1400241}
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.persistence.local.room.dao import androidx.room.Dao import com.google.android.ground.persistence.local.room.entity.ExpressionEntity @Dao interface ExpressionDao : BaseDao<ExpressionEntity>
235
Kotlin
116
245
bb5229149eb3687923a8391f30f7279e477562a8
820
ground-android
Apache License 2.0
apps/etterlatte-trygdetid/src/test/kotlin/no/nav/etterlatte/trygdetid/TrygdetidServiceTest.kt
navikt
417,041,535
false
{"Kotlin": 7159442, "TypeScript": 1725433, "Handlebars": 26265, "Shell": 12687, "HTML": 1734, "CSS": 598, "PLpgSQL": 556, "Dockerfile": 547}
package no.nav.etterlatte.trygdetid import com.fasterxml.jackson.databind.JsonNode import io.kotest.matchers.collections.shouldNotContain import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.clearAllMocks import io.mockk.coEvery import io.mockk.coVerify import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.spyk import io.mockk.verify import kotlinx.coroutines.runBlocking import no.nav.etterlatte.libs.common.behandling.BehandlingStatus import no.nav.etterlatte.libs.common.behandling.BehandlingType import no.nav.etterlatte.libs.common.behandling.DetaljertBehandling import no.nav.etterlatte.libs.common.behandling.Prosesstype import no.nav.etterlatte.libs.common.behandling.Revurderingaarsak import no.nav.etterlatte.libs.common.behandling.SisteIverksatteBehandling import no.nav.etterlatte.libs.common.grunnlag.Grunnlag import no.nav.etterlatte.libs.common.grunnlag.Grunnlagsdata import no.nav.etterlatte.libs.common.grunnlag.Grunnlagsopplysning import no.nav.etterlatte.libs.common.grunnlag.Opplysning import no.nav.etterlatte.libs.common.grunnlag.hentDoedsdato import no.nav.etterlatte.libs.common.grunnlag.hentFoedselsdato import no.nav.etterlatte.libs.common.grunnlag.hentFoedselsnummer import no.nav.etterlatte.libs.common.grunnlag.opplysningstyper.Opplysningstype import no.nav.etterlatte.libs.common.person.Folkeregisteridentifikator import no.nav.etterlatte.libs.common.person.PersonRolle import no.nav.etterlatte.libs.common.tidspunkt.Tidspunkt import no.nav.etterlatte.libs.common.toJsonNode import no.nav.etterlatte.libs.common.trygdetid.DetaljertBeregnetTrygdetidResultat import no.nav.etterlatte.libs.common.trygdetid.FaktiskTrygdetid import no.nav.etterlatte.libs.common.trygdetid.land.LandNormalisert import no.nav.etterlatte.libs.testdata.grunnlag.AVDOED2_FOEDSELSNUMMER import no.nav.etterlatte.libs.testdata.grunnlag.AVDOED_FOEDSELSNUMMER import no.nav.etterlatte.libs.testdata.grunnlag.GrunnlagTestData import no.nav.etterlatte.libs.testdata.grunnlag.eldreAvdoedTestopplysningerMap import no.nav.etterlatte.trygdetid.klienter.BehandlingKlient import no.nav.etterlatte.trygdetid.klienter.GrunnlagKlient import no.nav.etterlatte.trygdetid.klienter.PesysKlient import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.time.LocalDate import java.time.Period import java.util.UUID.randomUUID internal class TrygdetidServiceTest { private val repository: TrygdetidRepository = mockk() private val behandlingKlient: BehandlingKlient = mockk() private val grunnlagKlient: GrunnlagKlient = mockk() private val beregningService: TrygdetidBeregningService = spyk(TrygdetidBeregningService) private val service: TrygdetidService = TrygdetidServiceImpl( repository, behandlingKlient, grunnlagKlient, beregningService, mockk<PesysKlient>(), ) @BeforeEach fun beforeEach() { clearAllMocks() coEvery { behandlingKlient.kanOppdatereTrygdetid(any(), any()) } returns true } @AfterEach fun afterEach() { confirmVerified() } @Test fun `skal hente trygdetid`() { val behandlingId = randomUUID() coEvery { repository.hentTrygdetiderForBehandling(any()) } returns listOf(trygdetid(behandlingId)) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns GrunnlagTestData().hentOpplysningsgrunnlag() val trygdetider = runBlocking { service.hentTrygdetiderIBehandling(behandlingId, saksbehandler) } trygdetider shouldNotBe null verify(exactly = 1) { repository.hentTrygdetiderForBehandling(behandlingId) } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(any(), any()) } } @Test fun `skal returnere null hvis trygdetid ikke finnes for behandling`() { val behandlingId = randomUUID() every { repository.hentTrygdetiderForBehandling(any()) } returns emptyList() val trygdetider = runBlocking { service.hentTrygdetiderIBehandling(behandlingId, saksbehandler) } trygdetider shouldBe emptyList() verify(exactly = 1) { repository.hentTrygdetiderForBehandling(behandlingId) } } @Test fun `skal opprette trygdetid`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.FØRSTEGANGSBEHANDLING } val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() val forventetFoedselsdato = grunnlag .hentAvdoede() .first() .hentFoedselsdato()!! .verdi val forventetDoedsdato = grunnlag .hentAvdoede() .first() .hentDoedsdato()!! .verdi val forventetIdent = grunnlag .hentAvdoede() .first() .hentFoedselsnummer()!! .verdi val trygdetid = trygdetid(behandlingId, sakId, ident = forventetIdent.value) every { repository.hentTrygdetiderForBehandling(any()) } returns emptyList() andThen listOf(trygdetid) every { repository.hentTrygdetid(any()) } returns trygdetid every { repository.hentTrygdetidMedId(any(), any()) } returns trygdetid coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag every { repository.opprettTrygdetid(any()) } returns trygdetid coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.oppdaterTrygdetid(any()) } returnsArgument 0 runBlocking { val opprettetTrygdetider = service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) opprettetTrygdetider.first().trygdetidGrunnlag.size shouldBe 1 opprettetTrygdetider.first().trygdetidGrunnlag[0].type shouldBe TrygdetidType.FREMTIDIG opprettetTrygdetider.first().beregnetTrygdetid?.resultat?.prorataBroek?.let { it.nevner shouldNotBe 0 } } coVerify { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } coVerify(exactly = 2) { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) } coVerify(exactly = 1) { behandlingKlient.hentBehandling(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) repository.hentTrygdetidMedId(any(), any()) repository.opprettTrygdetid( withArg { trygdetid -> trygdetid.opplysninger.let { opplysninger -> with(opplysninger[0]) { type shouldBe TrygdetidOpplysningType.FOEDSELSDATO opplysning shouldBe forventetFoedselsdato.toJsonNode() kilde shouldNotBe null } with(opplysninger[1]) { type shouldBe TrygdetidOpplysningType.FYLT_16 opplysning shouldBe forventetFoedselsdato.plusYears(16).toJsonNode() kilde shouldNotBe null } with(opplysninger[2]) { type shouldBe TrygdetidOpplysningType.FYLLER_66 opplysning shouldBe forventetFoedselsdato.plusYears(66).toJsonNode() kilde shouldNotBe null } with(opplysninger[3]) { type shouldBe TrygdetidOpplysningType.DOEDSDATO opplysning shouldBe forventetDoedsdato!!.toJsonNode() kilde shouldNotBe null } } }, ) repository.oppdaterTrygdetid( withArg { trygdetid -> with(trygdetid.trygdetidGrunnlag[0]) { type shouldBe TrygdetidType.FREMTIDIG } }, ) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } verify { behandling.id behandling.sak behandling.behandlingType } } @Test fun `skal kopiere trygdetid hvis revurdering`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.REVURDERING every { revurderingsaarsak } returns Revurderingaarsak.DOEDSFALL } val forrigebehandlingId = randomUUID() val trygdetid = trygdetid(behandlingId, sakId) val oppdatertTrygdetidCaptured = slot<Trygdetid>() every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { behandlingKlient.hentSisteIverksatteBehandling(any(), any()) } returns SisteIverksatteBehandling( forrigebehandlingId, ) every { repository.hentTrygdetiderForBehandling(forrigebehandlingId) } returns listOf(trygdetid) every { repository.opprettTrygdetid(capture(oppdatertTrygdetidCaptured)) } returns trygdetid coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns GrunnlagTestData().hentOpplysningsgrunnlag() runBlocking { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) behandlingKlient.hentBehandling(behandlingId, saksbehandler) behandlingKlient.hentSisteIverksatteBehandling(sakId, saksbehandler) repository.hentTrygdetiderForBehandling(forrigebehandlingId) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) repository.opprettTrygdetid(oppdatertTrygdetidCaptured.captured) with(oppdatertTrygdetidCaptured.captured) { this.opplysninger.size shouldBe trygdetid.opplysninger.size for (i in 0 until this.opplysninger.size) { this.opplysninger[i].opplysning shouldBe trygdetid.opplysninger[i].opplysning this.opplysninger[i].kilde shouldBe trygdetid.opplysninger[i].kilde this.opplysninger[i].type shouldBe trygdetid.opplysninger[i].type } } } coVerify { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) } verify { behandling.id behandling.sak behandling.behandlingType behandling.revurderingsaarsak } } @Test fun `skal opprette trygdetid hvis revurdering og forrige trygdetid mangler og det ikke er regulering`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.REVURDERING every { revurderingsaarsak } returns Revurderingaarsak.SOESKENJUSTERING } val forrigeBehandlingId = randomUUID() val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() val forventetIdent = grunnlag .hentAvdoede() .first() .hentFoedselsnummer()!! .verdi val trygdetid = trygdetid(behandlingId, sakId, ident = forventetIdent.value) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { behandlingKlient.hentSisteIverksatteBehandling(any(), any()) } returns SisteIverksatteBehandling( forrigeBehandlingId, ) every { repository.hentTrygdetiderForBehandling(forrigeBehandlingId) } returns emptyList() every { repository.hentTrygdetidMedId(any(), any()) } returns trygdetid every { repository.opprettTrygdetid(any()) } returns trygdetid coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.oppdaterTrygdetid(any()) } returnsArgument 0 runBlocking { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } coVerify(exactly = 2) { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) behandlingKlient.hentBehandling(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) behandlingKlient.hentSisteIverksatteBehandling(sakId, saksbehandler) repository.hentTrygdetiderForBehandling(forrigeBehandlingId) repository.hentTrygdetidMedId(any(), any()) repository.opprettTrygdetid( withArg { it.trygdetidGrunnlag shouldBe emptyList() }, ) repository.oppdaterTrygdetid( withArg { trygdetid -> with(trygdetid.trygdetidGrunnlag[0]) { type shouldBe TrygdetidType.FREMTIDIG } }, ) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } verify { behandling.revurderingsaarsak behandling.id behandling.sak behandling.behandlingType } } @Test fun `skal ikke opprette trygdetid hvis revurdering og forrige trygdetid mangler og det er automatisk regulering`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.REVURDERING every { revurderingsaarsak } returns Revurderingaarsak.REGULERING every { prosesstype } returns Prosesstype.AUTOMATISK } val forrigeBehandlingId = randomUUID() val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { behandlingKlient.hentSisteIverksatteBehandling(any(), any()) } returns SisteIverksatteBehandling( forrigeBehandlingId, ) every { repository.hentTrygdetiderForBehandling(forrigeBehandlingId) } returns emptyList() every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag runBlocking { assertThrows<ManglerForrigeTrygdetidMaaReguleresManuelt> { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) behandlingKlient.hentBehandling(behandlingId, saksbehandler) behandlingKlient.hentSisteIverksatteBehandling(sakId, saksbehandler) repository.hentTrygdetiderForBehandling(forrigeBehandlingId) } coVerify { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) } verify { behandling.revurderingsaarsak behandling.prosesstype behandling.id behandling.sak behandling.behandlingType } } @Test fun `skal opprette trygdetid hvis revurdering og forrige trygdetid mangler og det er manuell regulering`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.REVURDERING every { revurderingsaarsak } returns Revurderingaarsak.REGULERING every { prosesstype } returns Prosesstype.MANUELL } val forrigeBehandlingId = randomUUID() val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() val forventetIdent = grunnlag .hentAvdoede() .first() .hentFoedselsnummer()!! .verdi val trygdetid = trygdetid(behandlingId, sakId, ident = forventetIdent.value) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { behandlingKlient.hentSisteIverksatteBehandling(any(), any()) } returns SisteIverksatteBehandling( forrigeBehandlingId, ) coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.hentTrygdetiderForBehandling(forrigeBehandlingId) } returns emptyList() every { repository.opprettTrygdetid(any()) } returns trygdetid every { repository.hentTrygdetidMedId(any(), any()) } returns trygdetid every { repository.oppdaterTrygdetid(any()) } returnsArgument 0 runBlocking { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } coVerify(exactly = 2) { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) behandlingKlient.hentSisteIverksatteBehandling(sakId, saksbehandler) repository.hentTrygdetiderForBehandling(forrigeBehandlingId) behandlingKlient.hentBehandling(behandlingId, saksbehandler) repository.hentTrygdetidMedId(any(), any()) repository.opprettTrygdetid( withArg { it.trygdetidGrunnlag shouldBe emptyList() }, ) repository.oppdaterTrygdetid( withArg { trygdetid -> with(trygdetid.trygdetidGrunnlag[0]) { type shouldBe TrygdetidType.FREMTIDIG } }, ) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } verify { behandling.revurderingsaarsak behandling.prosesstype behandling.id behandling.sak behandling.behandlingType } } @Test fun `skal feile ved opprettelse av trygdetid naar det allerede finnes for behandling`() { val behandlingId = randomUUID() val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() every { repository.hentTrygdetiderForBehandling(any()) } returns listOf(trygdetid(behandlingId)) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag runBlocking { assertThrows<TrygdetidAlleredeOpprettetException> { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } } coVerify { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) } coVerify(exactly = 1) { repository.hentTrygdetiderForBehandling(behandlingId) behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } } @Test fun `skal opprette manglende trygdetid ved opprettelse naar det allerede finnes men ikke for alle avdoede`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.FØRSTEGANGSBEHANDLING } val doedsdato = LocalDate.of(2023, 11, 12) val foedselsdato = doedsdato.minusYears(30) val grunnlag = grunnlagMedEkstraAvdoedForelder(foedselsdato, doedsdato) val trygdetid = trygdetid(behandlingId) every { repository.hentTrygdetiderForBehandling(any()) } returns listOf(trygdetid) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling every { repository.opprettTrygdetid(any()) } returns trygdetid every { repository.hentTrygdetidMedId(behandlingId, any()) } returns trygdetid every { repository.oppdaterTrygdetid(any()) } returnsArgument 0 coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true runBlocking { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) repository.hentTrygdetidMedId(behandlingId, any()) repository.oppdaterTrygdetid(any(), any()) behandlingKlient.hentBehandling(behandlingId, saksbehandler) repository.opprettTrygdetid( withArg { trygdetid -> trygdetid.ident shouldBe AVDOED2_FOEDSELSNUMMER.value trygdetid.sakId shouldBe sakId trygdetid.behandlingId shouldBe behandlingId trygdetid.opplysninger.let { opplysninger -> with(opplysninger[0]) { type shouldBe TrygdetidOpplysningType.FOEDSELSDATO opplysning shouldBe foedselsdato.toJsonNode() kilde shouldNotBe null } with(opplysninger[1]) { type shouldBe TrygdetidOpplysningType.FYLT_16 opplysning shouldBe foedselsdato.plusYears(16).toJsonNode() kilde shouldNotBe null } with(opplysninger[2]) { type shouldBe TrygdetidOpplysningType.FYLLER_66 opplysning shouldBe foedselsdato.plusYears(66).toJsonNode() kilde shouldNotBe null } with(opplysninger[3]) { type shouldBe TrygdetidOpplysningType.DOEDSDATO opplysning shouldBe doedsdato!!.toJsonNode() kilde shouldNotBe null } } }, ) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } coVerify(exactly = 2) { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) } verify { behandling.id behandling.sak behandling.behandlingType } } @Test fun `skal feile ved opprettelse av trygdetid dersom behandling er i feil tilstand`() { val behandlingId = randomUUID() coEvery { behandlingKlient.kanOppdatereTrygdetid(any(), any()) } returns false runBlocking { assertThrows<Exception> { service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) } } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } } @Test fun `skal lagre nytt trygdetidsgrunnlag`() { val behandlingId = randomUUID() val trygdetidGrunnlag = trygdetidGrunnlag() val eksisterendeTrygdetid = trygdetid(behandlingId, ident = AVDOED_FOEDSELSNUMMER.value) val grunnlag = mockk<Grunnlag>() val avdoedGrunnlag = mockk<Grunnlagsdata<JsonNode>>() coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.hentTrygdetid(behandlingId) } returns eksisterendeTrygdetid every { repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) } returns eksisterendeTrygdetid every { repository.oppdaterTrygdetid(any()) } answers { firstArg() } coEvery { behandlingKlient.hentBehandling(any(), any()) } answers { behandling(behandlingId = behandlingId) } every { grunnlag.hentAvdoede() } returns listOf(avdoedGrunnlag) every { avdoedGrunnlag[Opplysningstype.FOEDSELSDATO] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), verdi = LocalDate.now().toJsonNode(), ) } every { avdoedGrunnlag[Opplysningstype.FOEDSELSNUMMER] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Pdl( tidspunktForInnhenting = Tidspunkt.now(), registersReferanse = null, opplysningId = null, ), verdi = Folkeregisteridentifikator.of(AVDOED_FOEDSELSNUMMER.value).toJsonNode(), ) } every { avdoedGrunnlag[Opplysningstype.DOEDSDATO] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), verdi = LocalDate.now().toJsonNode(), ) } val trygdetid = runBlocking { service.lagreTrygdetidGrunnlagForTrygdetidMedIdIBehandlingMedSjekk( behandlingId, eksisterendeTrygdetid.id, trygdetidGrunnlag, saksbehandler, ) } with(trygdetid.trygdetidGrunnlag.first()) { beregnetTrygdetid?.verdi shouldBe Period.of(0, 1, 1) beregnetTrygdetid?.regelResultat shouldNotBe null beregnetTrygdetid?.tidspunkt shouldNotBe null } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) repository.hentTrygdetidMedId(behandlingId, trygdetid.id) repository.oppdaterTrygdetid( withArg { it.trygdetidGrunnlag.first().let { tg -> tg.id shouldBe trygdetidGrunnlag.id } }, ) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } } @Test fun `skal lagre nytt trygdetidsgrunnlag med overstyrt poengaar`() { val behandlingId = randomUUID() val trygdetidGrunnlag = trygdetidGrunnlag().copy( periode = TrygdetidPeriode(LocalDate.now().minusYears(2), LocalDate.now().minusYears(1)), ) val eksisterendeTrygdetid = trygdetid(behandlingId, ident = AVDOED_FOEDSELSNUMMER.value).copy(overstyrtNorskPoengaar = 10) val grunnlag = mockk<Grunnlag>() coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.hentTrygdetid(behandlingId) } returns eksisterendeTrygdetid every { repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) } returns eksisterendeTrygdetid every { repository.oppdaterTrygdetid(any()) } answers { firstArg() } coEvery { behandlingKlient.hentBehandling(any(), any()) } answers { behandling(behandlingId = behandlingId) } coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag val trygdetid = runBlocking { service.lagreTrygdetidGrunnlagForTrygdetidMedIdIBehandlingMedSjekk( behandlingId, eksisterendeTrygdetid.id, trygdetidGrunnlag, saksbehandler, ) } with(trygdetid.trygdetidGrunnlag.first()) { beregnetTrygdetid?.verdi shouldBe Period.of(1, 0, 1) beregnetTrygdetid?.regelResultat shouldNotBe null beregnetTrygdetid?.tidspunkt shouldNotBe null } trygdetid.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 10 coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) repository.hentTrygdetidMedId(behandlingId, trygdetid.id) repository.oppdaterTrygdetid( withArg { it.trygdetidGrunnlag.first().let { tg -> tg.id shouldBe trygdetidGrunnlag.id } }, ) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } } @Test fun `skal oppdatere trygdetidsgrunnlag`() { val behandlingId = randomUUID() val trygdetidGrunnlag = trygdetidGrunnlag() val eksisterendeTrygdetid = trygdetid(behandlingId, trygdetidGrunnlag = listOf(trygdetidGrunnlag), ident = AVDOED_FOEDSELSNUMMER.value) val endretTrygdetidGrunnlag = trygdetidGrunnlag.copy(bosted = LandNormalisert.NORGE.isoCode) coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true val grunnlag = mockk<Grunnlag>() val avdoedGrunnlag = mockk<Grunnlagsdata<JsonNode>>() every { repository.hentTrygdetid(behandlingId) } returns eksisterendeTrygdetid every { repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) } returns eksisterendeTrygdetid every { repository.oppdaterTrygdetid(any()) } answers { firstArg() } coEvery { behandlingKlient.hentBehandling(any(), any()) } answers { behandling(behandlingId = behandlingId) } coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag every { grunnlag.hentAvdoede() } returns listOf(avdoedGrunnlag) every { avdoedGrunnlag[Opplysningstype.FOEDSELSDATO] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), verdi = LocalDate.now().toJsonNode(), ) } every { avdoedGrunnlag[Opplysningstype.FOEDSELSNUMMER] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Pdl( tidspunktForInnhenting = Tidspunkt.now(), registersReferanse = null, opplysningId = null, ), verdi = Folkeregisteridentifikator.of(AVDOED_FOEDSELSNUMMER.value).toJsonNode(), ) } every { avdoedGrunnlag[Opplysningstype.DOEDSDATO] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), verdi = LocalDate.now().toJsonNode(), ) } val trygdetid = runBlocking { service.lagreTrygdetidGrunnlagForTrygdetidMedIdIBehandlingMedSjekk( behandlingId, eksisterendeTrygdetid.id, endretTrygdetidGrunnlag, saksbehandler, ) } with(trygdetid.trygdetidGrunnlag.first()) { beregnetTrygdetid?.verdi shouldBe Period.of(0, 1, 1) beregnetTrygdetid?.regelResultat shouldNotBe null beregnetTrygdetid?.tidspunkt shouldNotBe null } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) repository.oppdaterTrygdetid( withArg { it.trygdetidGrunnlag.first().let { tg -> tg.id shouldBe trygdetidGrunnlag.id tg.bosted shouldBe LandNormalisert.NORGE.isoCode } }, ) beregningService.beregnTrygdetidGrunnlag(any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) } } @Test fun `skal slette trygdetidsgrunnlag`() { val behandlingId = randomUUID() val trygdetidGrunnlag = trygdetidGrunnlag() val eksisterendeTrygdetid = trygdetid(behandlingId, trygdetidGrunnlag = listOf(trygdetidGrunnlag), ident = AVDOED_FOEDSELSNUMMER.value) coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true val grunnlag = mockk<Grunnlag>() val avdoedGrunnlag = mockk<Grunnlagsdata<JsonNode>>() every { repository.hentTrygdetiderForBehandling(behandlingId) } returns listOf(eksisterendeTrygdetid) every { repository.hentTrygdetid(behandlingId) } returns eksisterendeTrygdetid every { repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) } returns eksisterendeTrygdetid every { repository.oppdaterTrygdetid(any()) } answers { firstArg() } coEvery { behandlingKlient.hentBehandling(any(), any()) } answers { behandling(behandlingId = behandlingId) } coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag every { grunnlag.hentAvdoede() } returns listOf(avdoedGrunnlag) every { avdoedGrunnlag[Opplysningstype.FOEDSELSDATO] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), verdi = LocalDate.now().toJsonNode(), ) } every { avdoedGrunnlag[Opplysningstype.FOEDSELSNUMMER] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Pdl( tidspunktForInnhenting = Tidspunkt.now(), registersReferanse = null, opplysningId = null, ), verdi = Folkeregisteridentifikator.of(AVDOED_FOEDSELSNUMMER.value).toJsonNode(), ) } every { avdoedGrunnlag[Opplysningstype.DOEDSDATO] } answers { Opplysning.Konstant( id = randomUUID(), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), verdi = LocalDate.now().toJsonNode(), ) } val trygdetid = runBlocking { service.slettTrygdetidGrunnlagForTrygdetid( behandlingId, eksisterendeTrygdetid.id, trygdetidGrunnlag.id, saksbehandler, ) } trygdetid.trygdetidGrunnlag shouldNotContain trygdetidGrunnlag trygdetid.beregnetTrygdetid shouldBe null coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) repository.hentTrygdetidMedId(behandlingId, trygdetid.id) repository.oppdaterTrygdetid( withArg { it.trygdetidGrunnlag shouldBe emptyList() }, ) beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) } } @Test fun `skal overstyre beregnet trygdetid og slette grunnlaget`() { val behandlingId = randomUUID() val trygdetidGrunnlag = trygdetidGrunnlag() val eksisterendeTrygdetid = trygdetid( behandlingId, trygdetidGrunnlag = listOf(trygdetidGrunnlag), ident = AVDOED_FOEDSELSNUMMER.value, beregnetTrygdetid = beregnetTrygdetid(35, Tidspunkt.now()), ) val oppdatertTrygdetidCaptured = slot<Trygdetid>() coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true coEvery { repository.hentTrygdetid(behandlingId) } returns eksisterendeTrygdetid coEvery { repository.hentTrygdetiderForBehandling(behandlingId) } returns listOf(eksisterendeTrygdetid) coEvery { repository.oppdaterTrygdetid( capture(oppdatertTrygdetidCaptured), true, ) } returns eksisterendeTrygdetid service.overstyrBeregnetTrygdetidForAvdoed( behandlingId, eksisterendeTrygdetid.ident, beregnetTrygdetid(25, Tidspunkt.now()).resultat, ) coVerify(exactly = 1) { repository.hentTrygdetiderForBehandling(behandlingId) repository.oppdaterTrygdetid(oppdatertTrygdetidCaptured.captured, true) } with(oppdatertTrygdetidCaptured.captured) { this.trygdetidGrunnlag.size shouldBe 0 this.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 25 } } @Test fun `skal kunne reberegne trygdetid uten fremtidig trygdetid grunnlag`() { val behandlingId = randomUUID() val behandling = behandling(behandlingId) val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() val trygdetidGrunnlag = trygdetidGrunnlag(periode = TrygdetidPeriode(LocalDate.of(2000, 1, 1), LocalDate.of(2009, 12, 31))) val fremtidigTrygdetidGrunnlag = trygdetidGrunnlag( trygdetidType = TrygdetidType.FREMTIDIG, periode = TrygdetidPeriode(LocalDate.of(2010, 1, 1), LocalDate.of(2015, 12, 31)), ) val eksisterendeTrygdetid = trygdetid( behandlingId, trygdetidGrunnlag = listOf(trygdetidGrunnlag, fremtidigTrygdetidGrunnlag), ident = AVDOED_FOEDSELSNUMMER.value, beregnetTrygdetid = beregnetTrygdetid(35, Tidspunkt.now()), ) val oppdatertTrygdetidCaptured = slot<Trygdetid>() coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true coEvery { behandlingKlient.hentBehandling(behandlingId, saksbehandler) } returns behandling coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag coEvery { repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) } returns eksisterendeTrygdetid coEvery { repository.oppdaterTrygdetid( capture(oppdatertTrygdetidCaptured), false, ) } returns eksisterendeTrygdetid runBlocking { service.reberegnUtenFremtidigTrygdetid(behandlingId, eksisterendeTrygdetid.id, saksbehandler) } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(any(), any()) repository.hentTrygdetidMedId(behandlingId, eksisterendeTrygdetid.id) repository.oppdaterTrygdetid(oppdatertTrygdetidCaptured.captured, false) } verify(exactly = 1) { beregningService.beregnTrygdetid(any(), any(), any(), any(), any()) } with(oppdatertTrygdetidCaptured.captured) { this.trygdetidGrunnlag.size shouldBe 1 this.trygdetidGrunnlag.first().type shouldBe TrygdetidType.FAKTISK this.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 10 } } @Test fun `skal feile ved lagring av trygdetidsgrunnlag hvis behandling er i feil tilstand`() { val behandlingId = randomUUID() val trygdetidGrunnlag = trygdetidGrunnlag() val eksisterendeTrygdetid = trygdetid(behandlingId) coEvery { repository.hentTrygdetid(any()) } returns eksisterendeTrygdetid coEvery { behandlingKlient.kanOppdatereTrygdetid(any(), any()) } returns false runBlocking { assertThrows<Exception> { service.lagreTrygdetidGrunnlagForTrygdetidMedIdIBehandlingMedSjekk( behandlingId, eksisterendeTrygdetid.id, trygdetidGrunnlag, saksbehandler, ) } } coVerify { behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) } } @Test fun `skal opprette ny trygdetid av kopi fra forrige behandling`() { val sakId = 123L val behandlingId = randomUUID() val forrigeBehandlingId = randomUUID() val forrigeTrygdetidGrunnlag = trygdetidGrunnlag() val forrigeTrygdetidOpplysninger = standardOpplysningsgrunnlag() val forrigeTrygdetid = trygdetid( forrigeBehandlingId, trygdetidGrunnlag = listOf(forrigeTrygdetidGrunnlag), opplysninger = forrigeTrygdetidOpplysninger, ) val regulering = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId } coEvery { behandlingKlient.hentBehandling(behandlingId, saksbehandler) } returns regulering every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() every { repository.hentTrygdetiderForBehandling(forrigeBehandlingId) } returns listOf(forrigeTrygdetid) every { repository.opprettTrygdetid(any()) } answers { firstArg() } coEvery { grunnlagKlient.hentGrunnlag( forrigeBehandlingId, saksbehandler, ) } returns GrunnlagTestData().hentOpplysningsgrunnlag() runBlocking { service.kopierSisteTrygdetidberegninger(behandlingId, forrigeBehandlingId, saksbehandler) } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(forrigeBehandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) repository.hentTrygdetiderForBehandling(forrigeBehandlingId) behandlingKlient.hentBehandling(behandlingId, saksbehandler) repository.opprettTrygdetid(match { it.behandlingId == behandlingId }) } verify { regulering.id regulering.sak } } @Test fun `skal opprette manglende trygdetid av kopi fra forrige behandling`() { val sakId = 123L val behandlingId = randomUUID() val forrigeBehandlingId = randomUUID() val forrigeTrygdetidGrunnlag = trygdetidGrunnlag(begrunnelse = "Forrige") val forrigeTrygdetidOpplysninger = standardOpplysningsgrunnlag() val trygdetidGrunnlag = trygdetidGrunnlag(begrunnelse = "Eksisterende") val trygdetidOpplysninger = standardOpplysningsgrunnlag() val forrigeTrygdetid = trygdetid( forrigeBehandlingId, trygdetidGrunnlag = listOf(forrigeTrygdetidGrunnlag), opplysninger = forrigeTrygdetidOpplysninger, ident = AVDOED2_FOEDSELSNUMMER.value, ) val eksisterendeTrygdetid = trygdetid( behandlingId, trygdetidGrunnlag = listOf(trygdetidGrunnlag), opplysninger = trygdetidOpplysninger, ) val revurdering = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId } val doedsdato = LocalDate.of(2023, 11, 12) val foedselsdato = doedsdato.minusYears(30) val nyligAvdoedFoedselsnummer = AVDOED2_FOEDSELSNUMMER val nyligAvdoed: Grunnlagsdata<JsonNode> = mapOf( Opplysningstype.DOEDSDATO to konstantOpplysning(doedsdato), Opplysningstype.PERSONROLLE to konstantOpplysning(PersonRolle.AVDOED), Opplysningstype.FOEDSELSNUMMER to konstantOpplysning(nyligAvdoedFoedselsnummer), Opplysningstype.FOEDSELSDATO to konstantOpplysning(foedselsdato), ) coEvery { behandlingKlient.hentBehandling(behandlingId, saksbehandler) } returns revurdering every { repository.hentTrygdetiderForBehandling(behandlingId) } returns listOf(eksisterendeTrygdetid) every { repository.hentTrygdetiderForBehandling(forrigeBehandlingId) } returns listOf(forrigeTrygdetid) every { repository.opprettTrygdetid(any()) } answers { firstArg() } coEvery { grunnlagKlient.hentGrunnlag( behandlingId, saksbehandler, ) } returns GrunnlagTestData().hentOpplysningsgrunnlag() coEvery { grunnlagKlient.hentGrunnlag(forrigeBehandlingId, saksbehandler) } returns GrunnlagTestData(opplysningsmapAvdoedOverrides = nyligAvdoed).hentOpplysningsgrunnlag() runBlocking { val trygdetider = service.kopierSisteTrygdetidberegninger(behandlingId, forrigeBehandlingId, saksbehandler) assertEquals(2, trygdetider.size) assertTrue(trygdetider.any { it.ident == AVDOED_FOEDSELSNUMMER.value }) assertTrue(trygdetider.any { it.ident == AVDOED2_FOEDSELSNUMMER.value }) } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) grunnlagKlient.hentGrunnlag(forrigeBehandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) repository.hentTrygdetiderForBehandling(forrigeBehandlingId) behandlingKlient.hentBehandling(behandlingId, saksbehandler) repository.opprettTrygdetid(match { it.behandlingId == behandlingId }) } verify { revurdering.id revurdering.sak } } @Test fun `skal oppdater yrkesskade`() { val behandlingId = randomUUID() val behandling = behandling(behandlingId) val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() val forventetIdent = grunnlag .hentAvdoede() .first() .hentFoedselsnummer()!! .verdi val beregnetTrygdetid = DetaljertBeregnetTrygdetid( resultat = DetaljertBeregnetTrygdetidResultat( faktiskTrygdetidNorge = FaktiskTrygdetid( periode = Period.ofYears(5), antallMaaneder = 5 * 12, ), faktiskTrygdetidTeoretisk = null, fremtidigTrygdetidNorge = null, fremtidigTrygdetidTeoretisk = null, samletTrygdetidNorge = 5, samletTrygdetidTeoretisk = null, prorataBroek = null, overstyrt = false, yrkesskade = false, beregnetSamletTrygdetidNorge = null, ), tidspunkt = Tidspunkt.now(), regelResultat = "".toJsonNode(), ) val eksisterendeTrygdetid = trygdetid( behandlingId, beregnetTrygdetid = beregnetTrygdetid, ident = forventetIdent.value, trygdetidGrunnlag = listOf( TrygdetidGrunnlag( id = randomUUID(), type = TrygdetidType.FAKTISK, bosted = "", periode = TrygdetidPeriode(fra = LocalDate.now().minusYears(5), til = LocalDate.now()), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), beregnetTrygdetid = BeregnetTrygdetidGrunnlag( verdi = Period.ofYears(5), tidspunkt = Tidspunkt.now(), regelResultat = "".toJsonNode(), ), begrunnelse = "", poengInnAar = false, poengUtAar = false, prorata = false, ), ), ) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { repository.hentTrygdetidMedId(any(), any()) } returns eksisterendeTrygdetid coEvery { repository.oppdaterTrygdetid(any(), any()) } returnsArgument 0 coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true val trygdetid = runBlocking { service.setYrkesskade(eksisterendeTrygdetid.id, behandlingId, true, saksbehandler) } trygdetid shouldNotBe null trygdetid.yrkesskade shouldBe true trygdetid.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 40 coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(any(), any()) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } verify(exactly = 1) { repository.hentTrygdetidMedId(any(), any()) beregningService.beregnTrygdetid(any(), any(), any(), any(), true) repository.oppdaterTrygdetid( withArg { it.yrkesskade shouldBe true it.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 40 }, ) } } @Test fun `skal oppdater overstyrt poengaar`() { val behandlingId = randomUUID() val behandling = behandling(behandlingId) val grunnlag = GrunnlagTestData().hentOpplysningsgrunnlag() val forventetIdent = grunnlag .hentAvdoede() .first() .hentFoedselsnummer()!! .verdi val beregnetTrygdetid = DetaljertBeregnetTrygdetid( resultat = DetaljertBeregnetTrygdetidResultat( faktiskTrygdetidNorge = FaktiskTrygdetid( periode = Period.ofYears(5), antallMaaneder = 5 * 12, ), faktiskTrygdetidTeoretisk = null, fremtidigTrygdetidNorge = null, fremtidigTrygdetidTeoretisk = null, samletTrygdetidNorge = 5, samletTrygdetidTeoretisk = null, prorataBroek = null, overstyrt = false, yrkesskade = false, beregnetSamletTrygdetidNorge = null, ), tidspunkt = Tidspunkt.now(), regelResultat = "".toJsonNode(), ) val eksisterendeTrygdetid = trygdetid( behandlingId, beregnetTrygdetid = beregnetTrygdetid, ident = forventetIdent.value, trygdetidGrunnlag = listOf( TrygdetidGrunnlag( id = randomUUID(), type = TrygdetidType.FAKTISK, bosted = "", periode = TrygdetidPeriode(fra = LocalDate.now().minusYears(5), til = LocalDate.now()), kilde = Grunnlagsopplysning.Saksbehandler("", Tidspunkt.now()), beregnetTrygdetid = BeregnetTrygdetidGrunnlag( verdi = Period.ofYears(5), tidspunkt = Tidspunkt.now(), regelResultat = "".toJsonNode(), ), begrunnelse = "", poengInnAar = false, poengUtAar = false, prorata = false, ), ), ) coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { repository.hentTrygdetidMedId(any(), any()) } returns eksisterendeTrygdetid coEvery { repository.oppdaterTrygdetid(any(), any()) } returnsArgument 0 coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true val trygdetid = runBlocking { service.overstyrNorskPoengaaarForTrygdetid(eksisterendeTrygdetid.id, behandlingId, 10, saksbehandler) } trygdetid shouldNotBe null trygdetid.overstyrtNorskPoengaar shouldBe 10 trygdetid.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 10 coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(any(), any()) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } verify(exactly = 1) { repository.hentTrygdetidMedId(any(), any()) beregningService.beregnTrygdetid(any(), any(), any(), 10, any()) repository.oppdaterTrygdetid( withArg { it.overstyrtNorskPoengaar shouldBe 10 it.beregnetTrygdetid?.resultat?.samletTrygdetidNorge shouldBe 10 }, ) } } @Test fun `skal sjekke gyldighet og oppdatere status hvis behandlingstatus er VILKAARSVURDERT`() { val behandlingId = randomUUID() val eksisterendeTrygdetid = trygdetid(behandlingId, beregnetTrygdetid = beregnetTrygdetid()) coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling(behandlingId, behandlingStatus = BehandlingStatus.VILKAARSVURDERT) coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.hentTrygdetiderForBehandling(behandlingId) } returns listOf(eksisterendeTrygdetid) runBlocking { val oppdatert = service.sjekkGyldighetOgOppdaterBehandlingStatus(behandlingId, saksbehandler) oppdatert shouldBe true } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(any(), any()) behandlingKlient.hentBehandling(any(), any()) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) repository.hentTrygdetiderForBehandling(behandlingId) } } @Test fun `skal feile ved sjekking av gyldighet dersom det ikke finnes noe trygdetid`() { val behandlingId = randomUUID() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling(behandlingId, behandlingStatus = BehandlingStatus.VILKAARSVURDERT) every { repository.hentTrygdetiderForBehandling(behandlingId) } returns emptyList() runBlocking { assertThrows<IngenTrygdetidFunnetForAvdoede> { service.sjekkGyldighetOgOppdaterBehandlingStatus(behandlingId, saksbehandler) } } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(any(), any()) behandlingKlient.hentBehandling(any(), any()) repository.hentTrygdetiderForBehandling(behandlingId) } } @Test fun `skal feile ved sjekking av gyldighet dersom det ikke finnes noe beregning i trygdetid`() { val behandlingId = randomUUID() val eksisterendeTrygdetid = trygdetid(behandlingId, beregnetTrygdetid = null) coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling(behandlingId, behandlingStatus = BehandlingStatus.VILKAARSVURDERT) coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.hentTrygdetiderForBehandling(behandlingId) } returns listOf(eksisterendeTrygdetid) runBlocking { assertThrows<TrygdetidManglerBeregning> { service.sjekkGyldighetOgOppdaterBehandlingStatus(behandlingId, saksbehandler) } } coVerify(exactly = 1) { behandlingKlient.kanOppdatereTrygdetid(any(), any()) behandlingKlient.hentBehandling(any(), any()) repository.hentTrygdetiderForBehandling(behandlingId) } } @Test fun `skal ikke opprette fremtidig grunnlag hvis man er for gammel`() { val behandlingId = randomUUID() val sakId = 123L val behandling = mockk<DetaljertBehandling>().apply { every { id } returns behandlingId every { sak } returns sakId every { behandlingType } returns BehandlingType.FØRSTEGANGSBEHANDLING } val grunnlag = GrunnlagTestData(opplysningsmapAvdoedOverrides = eldreAvdoedTestopplysningerMap).hentOpplysningsgrunnlag() val forventetFoedselsdato = grunnlag .hentAvdoede() .first() .hentFoedselsdato()!! .verdi val forventetDoedsdato = grunnlag .hentAvdoede() .first() .hentDoedsdato()!! .verdi val forventetIdent = grunnlag .hentAvdoede() .first() .hentFoedselsnummer()!! .verdi val trygdetid = trygdetid(behandlingId, sakId, ident = forventetIdent.value) every { repository.hentTrygdetiderForBehandling(any()) } returns emptyList() andThen listOf(trygdetid) every { repository.hentTrygdetid(any()) } returns trygdetid coEvery { behandlingKlient.hentBehandling(any(), any()) } returns behandling coEvery { grunnlagKlient.hentGrunnlag(any(), any()) } returns grunnlag every { repository.opprettTrygdetid(any()) } returns trygdetid coEvery { behandlingKlient.settBehandlingStatusTrygdetidOppdatert(any(), any()) } returns true every { repository.oppdaterTrygdetid(any()) } returnsArgument 0 runBlocking { val opprettetTrygdetid = service.opprettTrygdetiderForBehandling(behandlingId, saksbehandler) opprettetTrygdetid.first().trygdetidGrunnlag.size shouldBe 0 } coVerify(exactly = 1) { grunnlagKlient.hentGrunnlag(behandlingId, saksbehandler) behandlingKlient.kanOppdatereTrygdetid(behandlingId, saksbehandler) behandlingKlient.hentBehandling(behandlingId, saksbehandler) behandlingKlient.settBehandlingStatusTrygdetidOppdatert(behandlingId, saksbehandler) repository.hentTrygdetiderForBehandling(behandlingId) repository.opprettTrygdetid( withArg { trygdetid -> trygdetid.opplysninger.let { opplysninger -> with(opplysninger[0]) { type shouldBe TrygdetidOpplysningType.FOEDSELSDATO opplysning shouldBe forventetFoedselsdato.toJsonNode() kilde shouldNotBe null } with(opplysninger[1]) { type shouldBe TrygdetidOpplysningType.FYLT_16 opplysning shouldBe forventetFoedselsdato.plusYears(16).toJsonNode() kilde shouldNotBe null } with(opplysninger[2]) { type shouldBe TrygdetidOpplysningType.FYLLER_66 opplysning shouldBe forventetFoedselsdato.plusYears(66).toJsonNode() kilde shouldNotBe null } with(opplysninger[3]) { type shouldBe TrygdetidOpplysningType.DOEDSDATO opplysning shouldBe forventetDoedsdato!!.toJsonNode() kilde shouldNotBe null } } }, ) } verify { behandling.id behandling.sak behandling.behandlingType } } private fun beregnetTrygdetid() = DetaljertBeregnetTrygdetid( resultat = DetaljertBeregnetTrygdetidResultat( faktiskTrygdetidNorge = FaktiskTrygdetid( periode = Period.ofYears(5), antallMaaneder = 5 * 12, ), faktiskTrygdetidTeoretisk = null, fremtidigTrygdetidNorge = null, fremtidigTrygdetidTeoretisk = null, samletTrygdetidNorge = 5, samletTrygdetidTeoretisk = null, prorataBroek = null, overstyrt = false, yrkesskade = false, beregnetSamletTrygdetidNorge = null, ), tidspunkt = Tidspunkt.now(), regelResultat = "".toJsonNode(), ) private fun <T : Any> konstantOpplysning(a: T): Opplysning.Konstant<JsonNode> { val kilde = Grunnlagsopplysning.Pdl(Tidspunkt.now(), "", "") return Opplysning.Konstant(randomUUID(), kilde, a.toJsonNode()) } private fun grunnlagMedEkstraAvdoedForelder( foedselsdato: LocalDate, doedsdato: LocalDate, ): Grunnlag { val grunnlagEnAvdoed = GrunnlagTestData().hentOpplysningsgrunnlag() val nyligAvdoedFoedselsnummer = AVDOED2_FOEDSELSNUMMER val nyligAvdoed: Grunnlagsdata<JsonNode> = mapOf( Opplysningstype.DOEDSDATO to konstantOpplysning(doedsdato), Opplysningstype.PERSONROLLE to konstantOpplysning(PersonRolle.AVDOED), Opplysningstype.FOEDSELSNUMMER to konstantOpplysning(nyligAvdoedFoedselsnummer), Opplysningstype.FOEDSELSDATO to konstantOpplysning(foedselsdato), ) return GrunnlagTestData( opplysningsmapAvdoedeOverrides = listOf(nyligAvdoed) + grunnlagEnAvdoed.hentAvdoede(), ).hentOpplysningsgrunnlag() } }
9
Kotlin
0
6
fe4ed6670fcc0d3fcd117c51b5a7acc224fa6bd2
66,074
pensjon-etterlatte-saksbehandling
MIT License
korge/test/korlibs/korge/view/ImageAnimationViewTest.kt
korlibs
80,095,683
false
{"Kotlin": 4210038, "C": 105670, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 1068, "Shell": 439, "CMake": 202, "Batchfile": 41, "CSS": 33}
package korlibs.korge.view import korlibs.image.bitmap.* import korlibs.image.format.* import korlibs.korge.view.animation.* import korlibs.time.* import kotlin.test.* class ImageAnimationViewTest { private val animImages4Layers1 = ImageAnimation( frames = listOf( ImageFrame(0, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 1 ))), ImageFrame(1, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 2 ))), ImageFrame(2, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 3 ))), ImageFrame(3, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 4 ))) ), direction = ImageAnimation.Direction.FORWARD, name = "anim1", layers = listOf(ImageLayer(0, "layer0")) ) private val animImages6Layers2 = ImageAnimation( frames = listOf( ImageFrame(10, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 1 ), ImageFrameLayer(ImageLayer(1, "layer1"), Bitmaps.transparent, 10))), ImageFrame(12, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 2 ), ImageFrameLayer(ImageLayer(1, "layer1"), Bitmaps.transparent, 20))), ImageFrame(11, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 3 ), ImageFrameLayer(ImageLayer(1, "layer1"), Bitmaps.transparent, 30))), ImageFrame(13, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 4 ), ImageFrameLayer(ImageLayer(1, "layer1"), Bitmaps.transparent, 40))), ImageFrame(14, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 5 ), ImageFrameLayer(ImageLayer(1, "layer1"), Bitmaps.transparent, 50))), ImageFrame(15, 60.milliseconds, listOf(ImageFrameLayer( ImageLayer(0, "layer0"), Bitmaps.transparent, 6 ), ImageFrameLayer(ImageLayer(1, "layer1"), Bitmaps.transparent, 60))) ), direction = ImageAnimation.Direction.REVERSE, name = "anim2", layers = listOf(ImageLayer(0, "layer0"), ImageLayer(1, "layer1")) ) private val anim = ImageAnimationView { Image(Bitmaps.transparent) } @Test fun testNumberOfChildren() { // Test if correct number of layers are added as children to the Container anim.animation = animImages4Layers1 assertEquals(1, anim.numLayers) anim.animation = animImages6Layers2 assertEquals(2, anim.numLayers) } @Test fun testSetFirstFrame() { // Test if the correct frame is set as first frame // Here we check if the corresponding targetX value was set as X position of the layer. anim.animation = animImages4Layers1 assertEquals(1, anim.layers[0].x.toInt()) anim.direction = ImageAnimation.Direction.REVERSE anim.rewind() assertEquals(4, anim.layers[0].x.toInt()) anim.animation = animImages6Layers2 assertEquals(6, anim.layers[0].x.toInt()) assertEquals(60, anim.layers[1].x.toInt()) } // println("children: ${imageanimView.children.size}") }
464
Kotlin
123
2,497
1a565007ab748e00a4d602fcd78f7d4032afaf0b
3,887
korge
Apache License 2.0
core/infrastructure/rickandmorty/src/test/java/com/rlad/core/infrastructure/rickandmorty/remote/RickAndMortyRemoteDataSourceTest.kt
adamdanielczyk
259,461,736
false
{"Kotlin": 122467}
package com.rlad.core.infrastructure.rickandmorty.remote import com.rlad.core.infrastructure.rickandmorty.remote.ServerCharacter.Gender import com.rlad.core.infrastructure.rickandmorty.remote.ServerCharacter.Location import com.rlad.core.infrastructure.rickandmorty.remote.ServerCharacter.Status import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Test class RickAndMortyRemoteDataSourceTest { private val characters = listOf( ServerCharacter( id = 1, name = "<NAME>", status = Status.ALIVE, species = "species 1", type = "type 1", gender = Gender.MALE, location = Location("location 1"), imageUrl = "url 1", created = "created 1", ), ServerCharacter( id = 2, name = "<NAME>", status = Status.ALIVE, species = "species 2", type = "type 2", gender = Gender.MALE, location = Location("location 2"), imageUrl = "url 2", created = "created 2", ), ) private val fakeRickAndMortyApi = FakeRickAndMortyApi(characters) private val remoteDataSource = RickAndMortyRemoteDataSource(fakeRickAndMortyApi) @Test fun getCharacters_allApiItemsAreReturned() = runTest { assertEquals( ServerGetCharacters(characters), remoteDataSource.getRootData(offset = 0, pageSize = 10), ) } @Test fun getCharacters_apiItemsAreFilteredByName() = runTest { assertEquals( ServerGetCharacters(listOf(characters[1])), remoteDataSource.search(query = "Morty", offset = 0, pageSize = 10), ) } @Test fun getCharacter_itemWithMatchingIdIsReturned() = runTest { assertEquals( characters[1], remoteDataSource.getItem(id = "2"), ) } private class FakeRickAndMortyApi( private val characters: List<ServerCharacter>, ) : RickAndMortyApi { override suspend fun getCharacters(page: Int, name: String?): ServerGetCharacters { val characters = if (name != null) { characters.filter { it.name.contains(name) } } else { characters } return ServerGetCharacters(characters) } override suspend fun getCharacter(id: Int): ServerCharacter { return characters.first { it.id == id } } } }
7
Kotlin
0
4
f1de80d2ce3a230296341f0ec9d1dd335cdbe749
2,547
RLAD
MIT License
ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/importordering/ImportOrderingRuleIdeaTest.kt
pinterest
64,293,719
false
null
package com.pinterest.ktlint.ruleset.standard.importordering import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.core.api.FeatureInAlphaState import com.pinterest.ktlint.ruleset.standard.ImportOrderingRule import com.pinterest.ktlint.test.EditorConfigOverride import com.pinterest.ktlint.test.format import com.pinterest.ktlint.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test @OptIn(FeatureInAlphaState::class) class ImportOrderingRuleIdeaTest { private val rule = ImportOrderingRule() @Test fun testFormat() { val imports = """ import a.A import b.C import a.AB """.trimIndent() val formattedImports = """ import a.A import a.AB import b.C """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(expectedErrors) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun testFormatOk() { val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import kotlinx.coroutines.CoroutineDispatcher import ru.example.a import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.Thread import kotlin.io.Closeable import android.content.Context as Ctx import androidx.fragment.app.Fragment as F """.trimIndent() assertThat( rule.lint(formattedImports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEmpty() assertThat( rule.format(formattedImports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun testFormatWrongOrder() { val imports = """ import android.app.Activity import android.content.Context as Ctx import androidx.fragment.app.Fragment as F import android.view.View import android.view.ViewGroup import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.io.Closeable import kotlin.concurrent.Thread import kotlinx.coroutines.CoroutineDispatcher import ru.example.a """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import kotlinx.coroutines.CoroutineDispatcher import ru.example.a import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.Thread import kotlin.io.Closeable import android.content.Context as Ctx import androidx.fragment.app.Fragment as F """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(expectedErrors) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun `remove duplicate class imports unless they have distinct aliases`() { val imports = """ import android.view.View import android.view.ViewGroup import android.view.View import android.content.Context as Ctx1 import android.content.Context as Ctx2 import android.content.Context as Ctx1 """.trimIndent() val formattedImports = """ import android.view.View import android.view.ViewGroup import android.content.Context as Ctx1 import android.content.Context as Ctx2 """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).containsExactly( LintError(3, 1, "import-ordering", "Duplicate 'import android.view.View' found"), LintError(6, 1, "import-ordering", "Duplicate 'import android.content.Context as Ctx1' found") ) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun testFormatWrongOrderAndBlankLines() { val imports = """ import android.app.Activity import android.content.Context as Ctx import androidx.fragment.app.Fragment as F import android.view.View import android.view.ViewGroup import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.io.Closeable import kotlin.concurrent.Thread import kotlinx.coroutines.CoroutineDispatcher import ru.example.a """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import kotlinx.coroutines.CoroutineDispatcher import ru.example.a import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.Thread import kotlin.io.Closeable import android.content.Context as Ctx import androidx.fragment.app.Fragment as F """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(expectedErrors) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun testFormatBlankLines() { val imports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import kotlinx.coroutines.CoroutineDispatcher import ru.example.a import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.Thread import kotlin.io.Closeable import android.content.Context as Ctx import androidx.fragment.app.Fragment as F """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View import android.view.ViewGroup import kotlinx.coroutines.CoroutineDispatcher import ru.example.a import java.util.List import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.Thread import kotlin.io.Closeable import android.content.Context as Ctx import androidx.fragment.app.Fragment as F """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(expectedErrors) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun testFormatImportsWithEOLComments() { val imports = """ import android.app.Activity import android.content.Context as Ctx import androidx.fragment.app.Fragment as F // comment 3 import android.view.ViewGroup import android.view.View // comment 1 import java.util.List // comment 2 import javax.net.ssl.SSLHandshakeException import kotlin.io.Closeable import kotlin.concurrent.Thread import kotlinx.coroutines.CoroutineDispatcher import ru.example.a """.trimIndent() val formattedImports = """ import android.app.Activity import android.view.View // comment 1 import android.view.ViewGroup import kotlinx.coroutines.CoroutineDispatcher import ru.example.a import java.util.List // comment 2 import javax.net.ssl.SSLHandshakeException import kotlin.concurrent.Thread import kotlin.io.Closeable import android.content.Context as Ctx import androidx.fragment.app.Fragment as F // comment 3 """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(expectedErrors) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun `format imports containing "as" in the path - does not remove them`() { val formattedImports = """ import assertk.all import assertk.assertThat import assertk.assertions.contains import assertk.assertions.doesNotContain import assertk.assertions.isEqualTo import assertk.assertions.isFailure import assertk.assertions.isInstanceOf import assertk.assertions.isNotNull import assertk.assertions.isNull import assertk.assertions.message import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.databind.JsonMappingException import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.google.inject.multibindings.MapBinder import com.google.inject.name.Names import com.trib3.json.modules.ObjectMapperModule import dev.misfitlabs.kotlinguice4.KotlinModule import dev.misfitlabs.kotlinguice4.typeLiteral import org.testng.annotations.Guice import org.testng.annotations.Test import org.threeten.extra.YearQuarter import java.time.LocalDate import javax.inject.Inject import kotlin.reflect.KClass """.trimIndent() assertThat( rule.lint(formattedImports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEmpty() assertThat( rule.format(formattedImports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun `formats aliases correctly`() { val formattedImports = """ import android.view.ViewGroup.LayoutParams.MATCH_PARENT as MATCH import android.view.ViewGroup.LayoutParams.WRAP_CONTENT as WRAP """.trimIndent() assertThat( rule.lint(formattedImports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEmpty() assertThat( rule.format(formattedImports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } @Test fun `Issue 1243 - Format should not remove imports when having a distinct alias`() { val imports = """ import foo.Bar as Bar1 import foo.Bar as Bar2 import foo.Bar as Bar2 val bar1 = Bar1() val bar2 = Bar2() """.trimIndent() val formattedImports = """ import foo.Bar as Bar1 import foo.Bar as Bar2 val bar1 = Bar1() val bar2 = Bar2() """.trimIndent() assertThat( rule.lint(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).containsExactly( LintError(3, 1, "import-ordering", "Duplicate 'import foo.Bar as Bar2' found") ) assertThat( rule.format(imports, IDEA_DEFAULT_IMPORT_ORDERING) ).isEqualTo(formattedImports) } private companion object { val expectedErrors = listOf( LintError( 1, 1, "import-ordering", "Imports must be ordered in lexicographic order without any empty lines in-between with \"java\", \"javax\", \"kotlin\" and aliases in the end" ) ) val IDEA_DEFAULT_IMPORT_ORDERING = EditorConfigOverride.from( ImportOrderingRule.ideaImportsLayoutProperty to "*,java.**,javax.**,kotlin.**,^" ) } }
83
Kotlin
401
4,875
c42647182196339f08ff14cea9dd0321d69014fc
12,451
ktlint
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/FreeBreakfastSharp.kt
karakum-team
387,062,541
false
{"Kotlin": 3059969, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/FreeBreakfastSharp") package mui.icons.material @JsName("default") external val FreeBreakfastSharp: SvgIconComponent
0
Kotlin
5
35
45ca2eabf1d75a64ab7454fa62a641221ec0aa25
200
mui-kotlin
Apache License 2.0
app/src/main/java/pl/krzysztof/drobek/wemple3/WeatherApplication.kt
krzysztofdrobek
348,763,702
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.krzysztof.drobek.wemple3 import android.app.Application import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.GlobalContext.startKoin import pl.krzysztof.drobek.wemple3.di.repositoryModule import pl.krzysztof.drobek.wemple3.di.viewModelLocator class WeatherApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@WeatherApplication) modules( viewModelLocator, repositoryModule ) } } }
0
Kotlin
0
0
5c24460c1419a42e83ebd9c68b413dcc7f80b35e
1,262
weather-android-dev-challange
Apache License 2.0
nativechain/src/main/kotlin/com/sys1yagi/websocket/interface/WebSocketInterface.kt
sys1yagi
116,396,177
false
null
package com.sys1yagi.nativechain.p2p.connection import kotlinx.coroutines.experimental.channels.ReceiveChannel interface Connection { fun send(message: String) fun receiveChannel(): ReceiveChannel<String> fun peer(): String }
0
Kotlin
2
4
b106c8beb2449ff1760dee71fba4349940475b18
240
nativechain-kotlin
MIT License
cap11-api-backend/src/main/java/tech/salvatore/livro_android_kotlin_paulo_salvatore/view/creatures/CreaturesListFragment.kt
FabricaDeSinapse
387,030,484
false
null
package tech.salvatore.livro_android_kotlin_paulo_salvatore.view.creatures import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.hilt.android.AndroidEntryPoint import tech.salvatore.livro_android_kotlin_paulo_salvatore.R import tech.salvatore.livro_android_kotlin_paulo_salvatore.viewmodel.CreaturesViewModel @AndroidEntryPoint class CreaturesListFragment : Fragment() { private val creaturesViewModel: CreaturesViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.creatures_list_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) creaturesViewModel.creatures.observe(viewLifecycleOwner) { recyclerView.adapter = CreaturesListAdapter(it) { creature -> if (!creature.isKnown) { return@CreaturesListAdapter } val action = CreaturesListFragmentDirections .creatureViewAction(creature.number) findNavController().navigate(action) } } } }
0
null
6
12
625321562bb79ad5729be634e0690815425520b2
1,732
livro-android-casa-do-codigo
MIT License
tooling-country/src/commonMain/kotlin/dev/datlag/tooling/country/Algeria.kt
DatL4g
739,165,922
false
{"Kotlin": 532513}
package dev.datlag.tooling.country data object Algeria : Country { override val codeAlpha2: Country.Code.Alpha2 = Country.Code.Alpha2("DZ") override val codeAlpha3: Country.Code.Alpha3 = Country.Code.Alpha3("DZA") override val codeNumeric: Country.Code.Numeric = Country.Code.Numeric(12) }
0
Kotlin
0
3
e4d2bf45d9d34e80107e9b1558fd982e511ab28c
303
tooling
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/serviceworker/ExtendableEvent.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! @file:Suppress( "EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER", ) package web.serviceworker import js.promise.Promise import web.events.Event import web.events.EventType /** * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ open external class ExtendableEvent( override val type: EventType<ExtendableEvent>, init: ExtendableEventInit = definedExternally, ) : Event { /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ fun waitUntil(f: Promise<*>) companion object : ExtendableEventTypes }
0
null
7
29
86021857be9c82b4e56221db1a399a9775d9570d
936
types-kotlin
Apache License 2.0
app/src/main/kotlin/com/mhp/showcase/block/header/HeaderBlock.kt
MHP-A-Porsche-Company
100,703,518
false
null
package com.mhp.showcase.block.header import com.mhp.showcase.block.BaseBlock data class HeaderBlock(override val id: String, val title: String, val subtitle: String) : BaseBlock
0
Kotlin
0
2
e3a9884a090be8cdb909981f4267fdb61cf91455
226
CDUI-Showcase-Android
MIT License
presentation/fishingspot/src/main/java/com/qure/fishingspot/FishingSpotNavigatorImpl.kt
hegleB
613,354,773
false
null
package com.qure.fishingspot import android.content.Context import android.content.Intent import com.qure.navigator.FishingSpotNavigator import javax.inject.Inject class FishingSpotNavigatorImpl @Inject constructor(): FishingSpotNavigator { override fun intent(context: Context): Intent { return Intent(context, FishingSpotActivity::class.java) } }
0
Kotlin
0
1
dacdd36c449a6d2d08e80bd4b3ce357b58f6feda
368
FishingMemory
The Unlicense
src/main/kotlin/glm_/mat2x4/Mat2x4d.kt
kotlin-graphics
71,653,021
false
null
package glm_.mat2x4 import glm_.ToDoubleBuffer import glm_.d import glm_.toDouble import glm_.vec4.Vec4d import glm_.vec4.Vec4t import kool.BYTES import kool.set import java.nio.ByteBuffer import java.nio.DoubleBuffer /** * Created by GBarbieri on 09.12.2016. */ class Mat2x4d(var array: DoubleArray) : Mat2x4t<Double>(), ToDoubleBuffer { constructor(list: Iterable<*>, index: Int = 0) : this(DoubleArray(8) { list.elementAt(index + it)!!.toDouble }) // -- Accesses -- override operator fun get(index: Int) = Vec4d(index * 4, array) override operator fun get(column: Int, row: Int) = array[column * 4 + row] override operator fun set(column: Int, row: Int, value: Double) = array.set(column * 4 + row, value) override operator fun set(index: Int, value: Vec4t<out Number>) { array[index * 4] = value._x.d array[index * 4 + 1] = value._y.d array[index * 4 + 2] = value._z.d array[index * 4 + 2] = value._w.d } operator fun set(i: Int, v: Vec4d) { v.to(array, i * 4) } fun toDoubleArray(): DoubleArray = to(DoubleArray(length), 0) infix fun to(doubles: DoubleArray): DoubleArray = to(doubles, 0) fun to(doubles: DoubleArray, index: Int): DoubleArray { System.arraycopy(array, 0, doubles, index, length) return doubles } override fun to(buf: ByteBuffer, offset: Int): ByteBuffer { return buf .putDouble(offset + 0 * Double.BYTES, array[0]) .putDouble(offset + 1 * Double.BYTES, array[1]) .putDouble(offset + 2 * Double.BYTES, array[2]) .putDouble(offset + 3 * Double.BYTES, array[3]) .putDouble(offset + 4 * Double.BYTES, array[4]) .putDouble(offset + 5 * Double.BYTES, array[5]) .putDouble(offset + 6 * Double.BYTES, array[6]) .putDouble(offset + 7 * Double.BYTES, array[7]) } override fun to(buf: DoubleBuffer, index: Int): DoubleBuffer { buf[index + 0] = array[0] buf[index + 1] = array[1] buf[index + 2] = array[2] buf[index + 3] = array[3] buf[index + 4] = array[4] buf[index + 5] = array[5] buf[index + 6] = array[6] buf[index + 7] = array[7] return buf } override var a0: Double get() = array[0] set(v) = array.set(0, v) override var a1: Double get() = array[1] set(v) = array.set(1, v) override var a2: Double get() = array[2] set(v) = array.set(2, v) override var a3: Double get() = array[3] set(v) = array.set(3, v) override var b0: Double get() = array[4] set(v) = array.set(4, v) override var b1: Double get() = array[5] set(v) = array.set(5, v) override var b2: Double get() = array[6] set(v) = array.set(6, v) override var b3: Double get() = array[7] set(v) = array.set(7, v) companion object { const val length = Mat2x4t.length @JvmField val size = length * Double.BYTES } override fun size() = size override fun elementCount() = length override fun equals(other: Any?) = other is Mat2x4d && array.contentEquals(other.array) override fun hashCode() = 31 * this[0].hashCode() + this[1].hashCode() }
5
null
19
99
dcbdd6237fbc5af02722b8ea1b404a93ce38a043
3,373
glm
MIT License
src/com/interview/kotlinbasics/Dummy2.kt
prdp89
109,804,931
true
{"Java": 3495725, "Python": 105849, "C++": 26234, "Kotlin": 4167}
package com.interview.kotlinbasics /*class Dummy2 { //https://github.com/ResoCoder/coroutines-kotlin-tutorial suspend fun abc(){ } } fun main(args: Array<String>) { print("hello") }*/
1
Java
1
1
04424ec1f13b0d1555382090d35c394b99a3a24b
204
interview
Apache License 2.0
node/perfdiagram/src/main/kotlin/matt/fx/node/perfdiagram/perfdiagram.kt
mgroth0
497,866,693
false
{"Kotlin": 1343008}
package matt.fx.node.perfdiagram import matt.fig.modell.sankey.SankeyConnection import matt.fig.modell.sankey.SankeyIr import matt.log.profile.stopwatch.Stopwatch fun Stopwatch.analysisNodeIr() = SankeyIr( increments().map { SankeyConnection(from = prefix ?: "null", to = it.second, weight = it.first.inWholeMilliseconds) } )
0
Kotlin
0
0
ed503cefeab036423dab613ae5b2e08cbd79d710
343
fx
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/UserCowboy.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled 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.straight.Icons public val Icons.Filled.UserCowboy: ImageVector get() { if (_userCowboy != null) { return _userCowboy!! } _userCowboy = Builder(name = "UserCowboy", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(21.0f, 24.0f) lineTo(3.0f, 24.0f) verticalLineToRelative(-3.5f) curveToRelative(0.0f, -2.481f, 2.019f, -4.5f, 4.5f, -4.5f) horizontalLineToRelative(9.0f) curveToRelative(2.481f, 0.0f, 4.5f, 2.019f, 4.5f, 4.5f) verticalLineToRelative(3.5f) close() moveTo(22.296f, 0.748f) curveToRelative(-0.088f, 0.122f, -1.623f, 2.162f, -4.987f, 3.371f) curveToRelative(-0.635f, -1.618f, -1.888f, -4.119f, -2.88f, -4.119f) curveToRelative(-0.533f, 0.0f, -0.865f, 0.312f, -1.085f, 0.52f) curveToRelative(-0.251f, 0.236f, -0.51f, 0.48f, -1.345f, 0.48f) reflectiveCurveToRelative(-1.094f, -0.244f, -1.345f, -0.48f) curveToRelative(-0.22f, -0.207f, -0.552f, -0.52f, -1.085f, -0.52f) curveToRelative(-1.001f, 0.0f, -2.239f, 2.477f, -2.879f, 4.118f) curveTo(3.337f, 2.91f, 1.812f, 0.872f, 1.724f, 0.751f) lineTo(0.096f, 1.911f) curveToRelative(0.147f, 0.208f, 3.704f, 5.089f, 11.904f, 5.089f) reflectiveCurveTo(23.774f, 2.121f, 23.922f, 1.914f) lineToRelative(-1.625f, -1.166f) close() moveTo(11.999f, 9.0f) curveToRelative(-2.312f, 0.0f, -4.304f, -0.357f, -5.994f, -0.895f) curveToRelative(0.057f, 3.26f, 2.721f, 5.895f, 5.995f, 5.895f) reflectiveCurveToRelative(5.93f, -2.628f, 5.994f, -5.881f) curveToRelative(-1.687f, 0.529f, -3.675f, 0.881f, -5.994f, 0.881f) close() } } .build() return _userCowboy!! } private var _userCowboy: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,935
icons
MIT License
src/main/kotlin/org/piecesapp/client/models/LocationTypeEnum.kt
pieces-app
726,212,140
false
null
/** * Pieces Isomorphic OpenAPI * Endpoints for Assets, Formats, Users, Asset, Format, User. * * The version of the OpenAPI document: 1.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.models import com.squareup.moshi.Json /** * * Values: pUBLIC,pRIVATE */ enum class AccessEnum(val value: kotlin.String){ @Json(name = "PUBLIC") pUBLIC("PUBLIC"), @Json(name = "PRIVATE") pRIVATE("PRIVATE"); /** This override toString avoids using the enum var name and uses the actual api value instead. In cases the var name and value are different, the client would send incorrect enums to the server. **/ override fun toString(): String { return value } }
9
null
2
6
9371158b0978cae518a6f2584dd452a2556b394f
882
pieces-os-client-sdk-for-kotlin
MIT License
src/main/kotlin/com/dsoftware/ghmanager/data/LogLoadingModelListener.kt
cunla
495,431,686
false
{"Kotlin": 144571}
package com.dsoftware.ghmanager.data import com.dsoftware.ghmanager.Constants.LOG_MSG_JOB_IN_PROGRESS import com.dsoftware.ghmanager.Constants.LOG_MSG_MISSING import com.dsoftware.ghmanager.Constants.LOG_MSG_PICK_JOB import com.dsoftware.ghmanager.api.model.Job import com.dsoftware.ghmanager.api.model.JobStep import com.intellij.collaboration.ui.SingleValueModel import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Disposer import org.jetbrains.plugins.github.pullrequest.ui.GHCompletableFutureLoadingModel import org.jetbrains.plugins.github.pullrequest.ui.GHLoadingModel class LogLoadingModelListener( disposable: Disposable, dataProviderModel: SingleValueModel<WorkflowRunLogsDataProvider?>, private val jobsSelectionHolder: JobListSelectionHolder, ) : GHLoadingModel.StateChangeListener { val logModel = SingleValueModel<String?>(null) val logsLoadingModel = GHCompletableFutureLoadingModel<Map<String, Map<Int, String>>>(disposable) init { jobsSelectionHolder.addSelectionChangeListener(disposable, this::setLogValue) logsLoadingModel.addStateChangeListener(this) var listenerDisposable: Disposable? = null dataProviderModel.addAndInvokeListener { val provider = dataProviderModel.value logsLoadingModel.future = null logsLoadingModel.future = provider?.request listenerDisposable = listenerDisposable?.let { Disposer.dispose(it) null } if (provider != null) { val disposable2 = Disposer.newDisposable("Log listener disposable") .apply { Disposer.register(disposable, this) } provider.addRunChangesListener(disposable2, object : DataProvider.DataProviderChangeListener { override fun changed() { logsLoadingModel.future = provider.request } }) listenerDisposable = disposable2 } } } private fun stepsAsLog(stepLogs: Map<Int, String>, selection: Job): String { val stepsResult: Map<Int, JobStep> = if (selection.steps == null) { emptyMap() } else { selection.steps.associateBy { it.number } } val stepNumbers = stepsResult.keys.sorted() if (!stepNumbers.containsAll(stepLogs.keys)) { LOG.warn( "Some logs do not have a step-result associated " + "[steps in results=$stepNumbers, step with logs=${stepLogs.keys}] " ) } val res = StringBuilder() for (index in stepNumbers) { val stepInfo = stepsResult[index]!! val logs = if (stepLogs.containsKey(index)) stepLogs[index] else "" res.append( when (stepInfo.conclusion) { "skipped" -> "\u001B[37m---- Step: ${index}_${stepInfo.name} (skipped) ----\u001b[0m\n" "failure" -> "\u001B[31m---- Step: ${index}_${stepInfo.name} (failed) ----\u001b[0m\n${logs}" else -> "\u001B[32m---- Step: ${index}_${stepInfo.name} ----\u001b[0m\n${logs}" } ) } return res.toString() } private fun setLogValue() { val removeChars = setOf('<', '>', '/', ':') val jobSelection = jobsSelectionHolder.selection val jobName = jobSelection?.name?.filterNot { removeChars.contains(it) }?.trim() val logs = if (jobName == null || !logsLoadingModel.resultAvailable) null else logsLoadingModel.result?.get(jobName) logModel.value = when { logsLoadingModel.result == null -> null jobName == null -> LOG_MSG_PICK_JOB logs == null && jobSelection.status == "in_progress" -> LOG_MSG_JOB_IN_PROGRESS logs == null -> LOG_MSG_MISSING + jobSelection.name else -> stepsAsLog(logs, jobSelection) } } override fun onLoadingCompleted() = setLogValue() override fun onLoadingStarted() = setLogValue() override fun onReset() = setLogValue() companion object { private val LOG = logger<LogLoadingModelListener>() } }
7
Kotlin
9
52
239789f77d6706067bd8dab32ec4155e1cfd9962
4,440
ghactions-manager
MIT License
rsocket-transport-nodejs-tcp/src/jsMain/kotlin/io/rsocket/kotlin/transport/nodejs/tcp/FrameWithLengthAssembler.kt
rsocket
109,894,810
false
null
package io.rsocket.kotlin.transport.nodejs.tcp import io.ktor.utils.io.core.* import io.rsocket.kotlin.frame.io.* internal fun ByteReadPacket.withLength(): ByteReadPacket = buildPacket { @Suppress("INVISIBLE_MEMBER") writeLength([email protected]()) writePacket(this@withLength) } internal class FrameWithLengthAssembler(private val onFrame: (frame: ByteReadPacket) -> Unit) { private var expectedFrameLength = 0 //TODO atomic for native private val packetBuilder: BytePacketBuilder = BytePacketBuilder() inline fun write(write: BytePacketBuilder.() -> Unit) { packetBuilder.write() loop() } private fun loop() { while (true) when { expectedFrameLength == 0 && packetBuilder.size < 3 -> return // no length expectedFrameLength == 0 -> withTemp { // has length expectedFrameLength = @Suppress("INVISIBLE_MEMBER") it.readLength() if (it.remaining >= expectedFrameLength) build(it) // if has length and frame } packetBuilder.size < expectedFrameLength -> return // not enough bytes to read frame else -> withTemp { build(it) } // enough bytes to read frame } } private fun build(from: ByteReadPacket) { val frame = buildPacket { writePacket(from, expectedFrameLength) } expectedFrameLength = 0 onFrame(frame) } private inline fun withTemp(block: (tempPacket: ByteReadPacket) -> Unit) { val tempPacket = packetBuilder.build() block(tempPacket) packetBuilder.writePacket(tempPacket) } }
24
Kotlin
31
398
8a7baeca7df5ddcd63bc4d0e391df835a207ec01
1,724
rsocket-android
Apache License 2.0
library/src/rpiMain/kotlin/dev/bluefalcon/BluetoothService.kt
jamesjmtaylor
319,074,911
false
null
package dev.bluefalcon import android.bluetooth.BluetoothGattService actual class BluetoothService(val service: BluetoothGattService) { actual val name: String? get() = service.uuid.toString() actual val characteristics: List<BluetoothCharacteristic> get() = service.characteristics.map { BluetoothCharacteristic(it) } }
0
null
1
8
68a9ccfad87809b9c4ecd657be3bdecca58ad65d
366
blue-falcon-ftms
MIT License
app/src/main/kotlin/com/xiaocydx/sample/paging/complex/VideoStreamFragment.kt
xiaocydx
460,257,515
false
null
package com.xiaocydx.sample.paging.complex import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.flowWithLifecycle import androidx.viewpager2.widget.ViewPager2 import androidx.viewpager2.widget.ViewPager2.ORIENTATION_VERTICAL import com.bumptech.glide.Glide import com.bumptech.glide.RequestManager import com.xiaocydx.cxrv.binding.bindingAdapter import com.xiaocydx.cxrv.itemclick.doOnLongItemClick import com.xiaocydx.cxrv.list.ListAdapter import com.xiaocydx.cxrv.list.ListState import com.xiaocydx.cxrv.paging.Pager import com.xiaocydx.cxrv.paging.broadcastIn import com.xiaocydx.cxrv.paging.isSuccess import com.xiaocydx.cxrv.paging.onEach import com.xiaocydx.cxrv.paging.pagingCollector import com.xiaocydx.cxrv.paging.storeIn import com.xiaocydx.sample.databinding.FragmetVideoStreamBinding import com.xiaocydx.sample.databinding.ItemVideoStreamBinding import com.xiaocydx.sample.doOnApplyWindowInsets import com.xiaocydx.sample.doOnStateChanged import com.xiaocydx.sample.launchRepeatOnLifecycle import com.xiaocydx.sample.launchSafely import com.xiaocydx.sample.paging.config.loadStatesFlow import com.xiaocydx.sample.paging.config.replaceWithSwipeRefresh import com.xiaocydx.sample.registerOnPageChangeCallback import com.xiaocydx.sample.snackbar import com.xiaocydx.sample.transition.transform.SystemBarsContainer import com.xiaocydx.sample.transition.transform.TransformReceiver import com.xiaocydx.sample.transition.transform.doOnEnd import com.xiaocydx.sample.transition.transform.setDarkStatusBarOnResume import com.xiaocydx.sample.transition.transform.setWindowNavigationBarColor import com.xiaocydx.sample.viewLifecycle import com.xiaocydx.sample.viewLifecycleScope import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach /** * 视频流页面 * * 在实际场景中,视频流页面可能会供多处业务复用,视频流的数据通过其他业务数据过滤、转换而来, * 分页加载是处理起来比较麻烦的场景,需要调用处页面和视频流页面共享分页数据来源和加载状态, * 共享分页数据来源和加载状态的做法,能彻底解决两个页面分开加载再进行同步而产生的一致性问题。 * * 示例代码是构建一个分页数据流,它会发射分页数据容器,其中包含分页初始配置和分页事件流, * 分页事件流发射加载过程产生的事件,分页事件携带加载状态和列表数据,加载状态保存在[Pager], * 列表数据保存在[ListState]。 * * [Pager]提供原始分页数据流和加载状态,通过[storeIn]得到的最终分页数据流, * 支持共享分页数据流、加载状态、列表状态,不满足两个页面分离列表状态的需求, * 在[storeIn]之前调用[broadcastIn],可以将原始分页数据流转换为广播发射, * 满足分离列表状态的需求。 * * 若两个页面的[ListState]还需要同步,例如在视频流页面的删除操作,需要同步到调用处页面, * 则通过发送事件完成[ListState]的同步即可,这种不涉及分页加载的同步需求,并不难处理。 * * 视频流的数据通过其他业务数据过滤、转换而来,因此存在一页数据过滤完后,没有视频流数据的问题, * `AppendTrigger`的实现已解决这个问题,当视频流页面收集到一页空数据时,会自动触发下一页加载, * [ComplexRepository.getComplexPager]形参`adKeyRange`的默认值修改为`true`,可以验证此效果, * `adKeyRange = true`,表示连续几页不包含视频流数据。 * * @author xcc * @date 2023/7/30 */ class VideoStreamFragment : Fragment(), TransformReceiver { private lateinit var requestManager: RequestManager private lateinit var binding: FragmetVideoStreamBinding private lateinit var videoAdapter: ListAdapter<VideoStreamItem, *> private val sharedViewModel: ComplexSharedViewModel by viewModels( ownerProducer = { parentFragment ?: requireActivity() } ) private val videoViewModel: VideoStreamViewModel by viewModels( factoryProducer = { VideoStreamViewModel.Factory(sharedViewModel) } ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { requestManager = Glide.with(this) binding = FragmetVideoStreamBinding .inflate(inflater, container, false) videoAdapter = bindingAdapter( uniqueId = VideoStreamItem::id, inflate = ItemVideoStreamBinding::inflate ) { onBindView { requestManager.load(it.coverUrl) .centerCrop().into(ivCover) } doOnLongItemClick { holder, _ -> binding.viewPager2.currentItem = 0 holder.itemView.snackbar() .setText("长按平滑滚动至首位") .show() false } } binding.viewPager2.apply { adapter = videoAdapter orientation = ORIENTATION_VERTICAL replaceWithSwipeRefresh(videoAdapter) } return SystemBarsContainer(requireContext()) .setDarkStatusBarOnResume(this) .setStatusBarEdgeToEdge(true) .setGestureNavBarEdgeToEdge(true) .setWindowNavigationBarColor(this) .attach(binding.root) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setupDebugLog() val enterTransition = setTransformEnterTransition() enterTransition.duration = 200 val viewPager2 = binding.viewPager2 if (savedInstanceState == null) { // Fragment首次创建,推迟过渡动画,直到选中位置的图片加载结束, // 过渡动画结束时,才将viewPager2.offscreenPageLimit修改为1, // 确保startPostponedEnterTransition()不受两侧加载图片影响。 EnterTransitionListener(this, requestManager).postpone() enterTransition.doOnEnd(once = true) { viewPager2.offscreenPageLimit = 1 } } else { // Fragment重新创建,直接将viewPager2.offscreenPageLimit修改为1 viewPager2.offscreenPageLimit = 1 } viewLifecycleScope.launchSafely { // 首次刷新完成后,再选中位置和注册页面回调,这个处理对Fragment重新创建同样适用 videoAdapter.pagingCollector.loadStatesFlow().first { it.refresh.isSuccess } viewPager2.setCurrentItem(videoViewModel.selectPosition.value, false) viewPager2.registerOnPageChangeCallback( onSelected = videoViewModel::selectVideo, onScrollStateChanged = changed@{ state -> // 不依靠onSelected()同步选中位置,因为该函数被调用时仍在进行平滑滚动, // 状态更改为IDLE时才同步选中位置,避免平滑滚动期间同步申请布局造成卡顿。 if (state != ViewPager2.SCROLL_STATE_IDLE) return@changed sharedViewModel.syncSenderId(videoViewModel.selectId) } ) } binding.tvTitle.doOnApplyWindowInsets { v, insets, initialState -> val statusBars = insets.getInsets(WindowInsetsCompat.Type.statusBars()) v.updatePadding(top = initialState.paddings.top + statusBars.top) } videoViewModel.selectTitle .flowWithLifecycle(viewLifecycle) .distinctUntilChanged() .onEach(binding.tvTitle::setText) .launchIn(viewLifecycleScope) videoViewModel.videoFlow .onEach(videoAdapter.pagingCollector) .launchRepeatOnLifecycle(viewLifecycle) } private fun setupDebugLog() { viewLifecycle.doOnStateChanged { source, event -> val currentState = source.lifecycle.currentState Log.d("VideoStreamFragment", "currentState = ${currentState}, event = $event") } videoAdapter.pagingCollector.addLoadStatesListener { _, current -> Log.d("VideoStreamFragment", "loadStates = $current") } } }
0
null
0
9
83ca90dc5c8ac6892c1cdfdb026b8afb187e48fd
7,268
CXRV
Apache License 2.0
wcmodel/src/main/kotlin/at/triply/wcmodel/model/CollectionLink.kt
triply-at
139,441,256
false
{"Kotlin": 37612}
package at.triply.wcmodel.model data class CollectionLink(val href: String)
0
Kotlin
2
1
d7ede01957fd0eb3adf55af5e5708b3a3bf7cadd
76
wcapi
The Unlicense
composeApp/src/commonMain/kotlin/org/xanderzhu/coincounter/expense/db/ExpenseLocalStorageDataSourceImpl.kt
XanderZhu
735,312,120
false
{"Kotlin": 12289}
package org.xanderzhu.coincounter.expense.db import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.xanderzhu.coincounter.data.ExpenseQueries import org.xanderzhu.coincounter.expense.data.source.ExpenseLocalStorageDataSource class ExpenseLocalStorageDataSourceImpl( private val expensesQueries: ExpenseQueries, private val queryDispatcher: CoroutineDispatcher ) : ExpenseLocalStorageDataSource { override suspend fun addExpense(amount: Long) { withContext(queryDispatcher) { expensesQueries.insert(amount, null) } } }
0
Kotlin
0
0
3d56c12ac2d09e9250fe4f0f962628eac0d1a1f8
603
cointcounter
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/FaceConfused.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.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.straight.Icons public val Icons.Bold.FaceConfused: ImageVector get() { if (_faceConfused != null) { return _faceConfused!! } _faceConfused = Builder(name = "FaceConfused", 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(12.0f, 0.0f) curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f) reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f) reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f) reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f) close() moveTo(12.0f, 21.0f) curveToRelative(-4.963f, 0.0f, -9.0f, -4.037f, -9.0f, -9.0f) reflectiveCurveTo(7.037f, 3.0f, 12.0f, 3.0f) reflectiveCurveToRelative(9.0f, 4.037f, 9.0f, 9.0f) reflectiveCurveToRelative(-4.037f, 9.0f, -9.0f, 9.0f) close() moveTo(12.0f, 14.0f) horizontalLineToRelative(5.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(-5.0f) curveToRelative(-1.828f, 0.0f, -3.429f, 1.55f, -3.444f, 1.565f) lineToRelative(-2.116f, -2.126f) curveToRelative(0.1f, -0.1f, 2.475f, -2.439f, 5.561f, -2.439f) close() moveTo(6.0f, 10.0f) curveToRelative(0.0f, -1.105f, 0.895f, -2.0f, 2.0f, -2.0f) reflectiveCurveToRelative(2.0f, 0.895f, 2.0f, 2.0f) reflectiveCurveToRelative(-0.895f, 2.0f, -2.0f, 2.0f) reflectiveCurveToRelative(-2.0f, -0.895f, -2.0f, -2.0f) close() moveTo(18.0f, 10.0f) curveToRelative(0.0f, 1.105f, -0.895f, 2.0f, -2.0f, 2.0f) reflectiveCurveToRelative(-2.0f, -0.895f, -2.0f, -2.0f) reflectiveCurveToRelative(0.895f, -2.0f, 2.0f, -2.0f) reflectiveCurveToRelative(2.0f, 0.895f, 2.0f, 2.0f) close() } } .build() return _faceConfused!! } private var _faceConfused: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,001
icons
MIT License
composeApp/src/commonMain/kotlin/dev/senk0n/moerisuto/preferences/model/Preference.kt
senk0n
606,822,939
false
{"Kotlin": 50292, "Batchfile": 2675, "Ruby": 1767, "Swift": 532, "HTML": 281}
package dev.senk0n.moerisuto.preferences.model import dev.senk0n.moerisuto.core.className import dev.senk0n.moerisuto.core.classNameOf import kotlinx.coroutines.flow.StateFlow interface Preference { val tag: PreferenceTag get() = PreferenceTag(className) } data class PreferenceTag(val tag: String) interface SinglePreference<T> : Preference { val value: T val default: T } interface ObservablePreference<T> : Preference { fun get(): T? val value: StateFlow<T> val default: T } inline fun <reified T : Preference> preferenceTagOf(): PreferenceTag = PreferenceTag(classNameOf<T>())
5
Kotlin
0
0
24ddc2ccb6a69157b9811901fe7191e3deedc18f
614
moe-risuto-app
MIT License
modules/wasm-binary/src/commonMain/kotlin/visitors/GlobalSectionAdapter.kt
wasmium
761,480,110
false
null
package org.wasmium.wasm.binary.visitors public open class GlobalSectionAdapter(protected val delegate: GlobalSectionVisitor? = null) : GlobalSectionVisitor { public override fun visitGlobalVariable(globalIndex: UInt): GlobalVariableVisitor { if (delegate != null) { return GlobalVariableAdapter(delegate.visitGlobalVariable(globalIndex)) } return GlobalVariableAdapter() } public override fun visitEnd() { delegate?.visitEnd() } }
0
null
0
1
f7ddef76630278616d221e7c8251adf0f11b9587
496
wasmium-wasm-binary
Apache License 2.0
subprojects/assemble/build-metrics/src/main/kotlin/com/avito/android/plugin/build_metrics/internal/CompositeBuildOperationsResultListener.kt
avito-tech
230,265,582
false
null
package com.avito.android.plugin.build_metrics.internal internal class CompositeBuildOperationsResultListener( private val listeners: List<BuildOperationsResultListener> ) : BuildOperationsResultListener { override fun onBuildFinished(result: BuildOperationsResult) { listeners.forEach { it.onBuildFinished(result) } } }
7
Kotlin
41
358
84c207b8d1a421470c8b94611eddefebbea55bfe
343
avito-android
MIT License
sdk/src/commonMain/kotlin/gitfox/model/interactor/CommitInteractor.kt
dector
341,706,824
false
null
package gitfox.model.interactor import gitfox.entity.Commit import gitfox.entity.DiffData import gitfox.model.data.server.GitlabApi /** * @author <NAME> (glvvl) on 18.06.19. */ class CommitInteractor internal constructor( private val api: GitlabApi ) { suspend fun getCommit(projectId: Long, commitId: String): Commit = api.getRepositoryCommit(projectId, commitId) suspend fun getCommitDiffData(projectId: Long, commitId: String): List<DiffData> = api.getCommitDiffData(projectId, commitId) }
0
Kotlin
0
1
7258eb2bc4ca9fcd1ebf3029217d80d6fd2de4b9
527
gitfox-mirror
Apache License 2.0
http4k-contract/src/main/kotlin/org/http4k/contract/ContractRoutingHttpHandler.kt
opencollective
102,504,841
true
{"Gradle": 20, "Text": 3, "JSON": 4, "Shell": 7, "Markdown": 39, "Ignore List": 2, "Batchfile": 1, "YAML": 2, "Kotlin": 228, "XML": 3, "OASv2-json": 1, "JavaScript": 2, "Java Properties": 1, "HTML": 7, "CSS": 1, "Handlebars": 4, "Java": 2}
package org.http4k.contract import org.http4k.core.Filter import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.then import org.http4k.core.with import org.http4k.filter.ServerFilters.CatchLensFailure import org.http4k.lens.Header import org.http4k.routing.RoutingHttpHandler class ContractRoutingHttpHandler internal constructor(val httpHandler: Handler) : RoutingHttpHandler { override fun match(request: Request): HttpHandler? = httpHandler.match(request) override fun invoke(request: Request): Response = httpHandler(request) override fun withBasePath(new: String): ContractRoutingHttpHandler = ContractRoutingHttpHandler(httpHandler.withBasePath(new)) override fun withFilter(new: Filter): RoutingHttpHandler = ContractRoutingHttpHandler(httpHandler.withFilter(new)) companion object { internal data class Handler(private val renderer: ContractRenderer, private val security: Security, private val descriptionPath: String, private val rootAsString: String = "", private val routes: List<ContractRoute> = emptyList(), private val filter: Filter = Filter { next -> { next(it) } } ) : RoutingHttpHandler { private val contractRoot = PathSegments(rootAsString) override fun withFilter(new: Filter) = copy(filter = filter.then(new)) override fun withBasePath(new: String) = copy(rootAsString = new + rootAsString) private val handler: HttpHandler = { match(it)?.invoke(it) ?: Response(NOT_FOUND.description("Route not found")) } override fun invoke(request: Request): Response = handler(request) private val descriptionRoute = ContractRouteSpec0({ PathSegments("$it$descriptionPath") }, emptyList(), null) to GET bind { renderer.description(contractRoot, security, routes) } private val routers = routes .map { it.toRouter(contractRoot) to CatchLensFailure.then(security.filter).then(identify(it)).then(filter) } .plus(descriptionRoute.toRouter(contractRoot) to identify(descriptionRoute).then(filter)) private val noMatch: HttpHandler? = null override fun toString(): String { return contractRoot.toString() + "\n" + routes.map { it.toString() }.joinToString("\n") } override fun match(request: Request): HttpHandler? = if (request.isIn(contractRoot)) { routers.fold(noMatch, { memo, (router, routeFilter) -> memo ?: router.match(request)?.let { routeFilter.then(it) } }) } else null private fun identify(route: ContractRoute): Filter = route.describeFor(contractRoot).let { routeIdentity -> Filter { next -> { next(it.with(Header.X_URI_TEMPLATE of if (routeIdentity.isEmpty()) "/" else routeIdentity)) } } } } } }
0
Kotlin
0
1
6a8ce15e4f40f10920a9b79f2d0a6d9296d7b195
3,248
http4k
Apache License 2.0
src/main/kotlin/de/skyrising/aoc2021/day22.kt
skyrising
317,830,992
false
{"Kotlin": 370865}
package de.skyrising.aoc2021 import de.skyrising.aoc.PuzzleInput import de.skyrising.aoc.TestInput import de.skyrising.aoc.part1 import de.skyrising.aoc.part2 import java.util.* @Suppress("unused") class BenchmarkDay22 : BenchmarkDayV1(22) @Suppress("unused") fun registerDay22() { val test = TestInput(""" on x=10..12,y=10..12,z=10..12 on x=11..13,y=11..13,z=11..13 off x=9..11,y=9..11,z=9..11 on x=10..10,y=10..10,z=10..10 """) val test2 = TestInput(""" on x=-20..26,y=-36..17,z=-47..7 on x=-20..33,y=-21..23,z=-26..28 on x=-22..28,y=-29..23,z=-38..16 on x=-46..7,y=-6..46,z=-50..-1 on x=-49..1,y=-3..46,z=-24..28 on x=2..47,y=-22..22,z=-23..27 on x=-27..23,y=-28..26,z=-21..29 on x=-39..5,y=-6..47,z=-3..44 on x=-30..21,y=-8..43,z=-13..34 on x=-22..26,y=-27..20,z=-29..19 off x=-48..-32,y=26..41,z=-47..-37 on x=-12..35,y=6..50,z=-50..-2 off x=-48..-32,y=-32..-16,z=-15..-5 on x=-18..26,y=-33..15,z=-7..46 off x=-40..-22,y=-38..-28,z=23..41 on x=-16..35,y=-41..10,z=-47..6 off x=-32..-23,y=11..30,z=-14..3 on x=-49..-5,y=-3..45,z=-29..18 off x=18..30,y=-20..-8,z=-3..13 on x=-41..9,y=-7..43,z=-33..15 on x=-54112..-39298,y=-85059..-49293,z=-27449..7877 on x=967..23432,y=45373..81175,z=27513..53682 """) val test3 = TestInput(""" on x=-5..47,y=-31..22,z=-19..33 on x=-44..5,y=-27..21,z=-14..35 on x=-49..-1,y=-11..42,z=-10..38 on x=-20..34,y=-40..6,z=-44..1 off x=26..39,y=40..50,z=-2..11 on x=-41..5,y=-41..6,z=-36..8 off x=-43..-33,y=-45..-28,z=7..25 on x=-33..15,y=-32..19,z=-34..11 off x=35..47,y=-46..-34,z=-11..5 on x=-14..36,y=-6..44,z=-16..29 on x=-57795..-6158,y=29564..72030,z=20435..90618 on x=36731..105352,y=-21140..28532,z=16094..90401 on x=30999..107136,y=-53464..15513,z=8553..71215 on x=13528..83982,y=-99403..-27377,z=-24141..23996 on x=-72682..-12347,y=18159..111354,z=7391..80950 on x=-1060..80757,y=-65301..-20884,z=-103788..-16709 on x=-83015..-9461,y=-72160..-8347,z=-81239..-26856 on x=-52752..22273,y=-49450..9096,z=54442..119054 on x=-29982..40483,y=-108474..-28371,z=-24328..38471 on x=-4958..62750,y=40422..118853,z=-7672..65583 on x=55694..108686,y=-43367..46958,z=-26781..48729 on x=-98497..-18186,y=-63569..3412,z=1232..88485 on x=-726..56291,y=-62629..13224,z=18033..85226 on x=-110886..-34664,y=-81338..-8658,z=8914..63723 on x=-55829..24974,y=-16897..54165,z=-121762..-28058 on x=-65152..-11147,y=22489..91432,z=-58782..1780 on x=-120100..-32970,y=-46592..27473,z=-11695..61039 on x=-18631..37533,y=-124565..-50804,z=-35667..28308 on x=-57817..18248,y=49321..117703,z=5745..55881 on x=14781..98692,y=-1341..70827,z=15753..70151 on x=-34419..55919,y=-19626..40991,z=39015..114138 on x=-60785..11593,y=-56135..2999,z=-95368..-26915 on x=-32178..58085,y=17647..101866,z=-91405..-8878 on x=-53655..12091,y=50097..105568,z=-75335..-4862 on x=-111166..-40997,y=-71714..2688,z=5609..50954 on x=-16602..70118,y=-98693..-44401,z=5197..76897 on x=16383..101554,y=4615..83635,z=-44907..18747 off x=-95822..-15171,y=-19987..48940,z=10804..104439 on x=-89813..-14614,y=16069..88491,z=-3297..45228 on x=41075..99376,y=-20427..49978,z=-52012..13762 on x=-21330..50085,y=-17944..62733,z=-112280..-30197 on x=-16478..35915,y=36008..118594,z=-7885..47086 off x=-98156..-27851,y=-49952..43171,z=-99005..-8456 off x=2032..69770,y=-71013..4824,z=7471..94418 on x=43670..120875,y=-42068..12382,z=-24787..38892 off x=37514..111226,y=-45862..25743,z=-16714..54663 off x=25699..97951,y=-30668..59918,z=-15349..69697 off x=-44271..17935,y=-9516..60759,z=49131..112598 on x=-61695..-5813,y=40978..94975,z=8655..80240 off x=-101086..-9439,y=-7088..67543,z=33935..83858 off x=18020..114017,y=-48931..32606,z=21474..89843 off x=-77139..10506,y=-89994..-18797,z=-80..59318 off x=8476..79288,y=-75520..11602,z=-96624..-24783 on x=-47488..-1262,y=24338..100707,z=16292..72967 off x=-84341..13987,y=2429..92914,z=-90671..-1318 off x=-37810..49457,y=-71013..-7894,z=-105357..-13188 off x=-27365..46395,y=31009..98017,z=15428..76570 off x=-70369..-16548,y=22648..78696,z=-1892..86821 on x=-53470..21291,y=-120233..-33476,z=-44150..38147 off x=-93533..-4276,y=-16170..68771,z=-104985..-24507 """) part1("Reactor Reboot") { val instructions = parseInput(this) val clamp = Region3d(-50..50, -50..50, -50..50) val initRegion = Bitmap3d(-50, -50, -50, 51, 51, 51) for ((region, value) in instructions) { region.intersect(clamp).forEach { x, y, z -> initRegion[x, y, z] = value } } initRegion.count() } part2 { val instructions = parseInput(this) val maxRange = Int.MIN_VALUE..Int.MAX_VALUE countCubes(instructions, Region3d(maxRange, maxRange, maxRange)) } } private fun parseInput(input: PuzzleInput): List<Instruction> { val instructions = mutableListOf<Instruction>() for (line in input.lines) { val value = line.substringBefore(' ') == "on" val xStr = line.substringAfter("x=") val yStr = xStr.substringAfter("y=") val zStr = yStr.substringAfter("z=") val (x1, x2) = xStr.substringBefore(',').split("..").map(String::toInt) val (y1, y2) = yStr.substringBefore(',').split("..").map(String::toInt) val (z1, z2) = zStr.split("..").map(String::toInt) instructions.add(Instruction(Region3d(x1..x2, y1..y2, z1..z2), value)) } return instructions } private fun countCubes(instrs: List<Instruction>, clamp: Region3d): Long { if (instrs.isEmpty()) return 0 val prevInstrs = instrs.subList(0, instrs.lastIndex) val prev = countCubes(prevInstrs, clamp) val (last, value) = instrs.last() val newClamp = clamp.intersect(last) if (newClamp.volume == 0L) return prev return prev + (if (value) newClamp.volume else 0) - countCubes(prevInstrs, newClamp) } data class Region3d(val x: IntRange, val y: IntRange, val z: IntRange) { val sizeX = x.last + 1 - x.first val sizeY = y.last + 1 - y.first val sizeZ = z.last + 1 - z.first val volume = maxOf(sizeX.toLong(), 0) * maxOf(sizeY.toLong(), 0) * maxOf(sizeZ.toLong(), 0) fun forEach(callback: (Int, Int, Int) -> Unit) { for (z in this.z) for (y in this.y) for (x in this.x) { callback(x, y, z) } } fun intersect(other: Region3d): Region3d { val x = maxOf(x.first, other.x.first)..minOf(x.last, other.x.last) val y = maxOf(y.first, other.y.first)..minOf(y.last, other.y.last) val z = maxOf(z.first, other.z.first)..minOf(z.last, other.z.last) return Region3d(x, y, z) } } data class Instruction(val region: Region3d, val value: Boolean) data class Bitmap3d(val minX: Int, val minY: Int, val minZ: Int, val maxX: Int, val maxY: Int, val maxZ: Int) { private val sizeX = maxX - minX private val sizeY = maxY - minY private val sizeZ = maxZ - minZ private val data = BitSet(sizeX * sizeY * sizeZ) private fun index(x: Int, y: Int, z: Int) = (((z - minZ) * sizeY) + y - minY) * sizeX + x - minX operator fun get(x: Int, y: Int, z: Int) = data[index(x, y, z)] operator fun set(x: Int, y: Int, z: Int, value: Boolean) { data[index(x, y, z)] = value } fun count() = data.cardinality() }
0
Kotlin
0
0
ca9cbf4212c50424f595c7ecbe3e13b53d4cefb6
7,877
aoc2020
MIT License
kotlin-web/src/jsTest/kotlin/web/events/EventTypesTest.kt
JetBrains
93,250,841
false
null
package web.events import web.events.ProgressEvent.Companion.PROGRESS import kotlin.test.Test import kotlin.test.assertEquals class EventTypesTest { @Test fun import() { assertEquals<Any>("abort", ProgressEvent.ABORT) } @Test fun staticImport() { assertEquals<Any>("progress", PROGRESS) } }
39
null
165
1,347
997ed3902482883db4a9657585426f6ca167d556
334
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/hfut/schedule/ui/Activity/success/search/Search/LoginWeb/loginWebUI.kt
Chiu-xaH
705,508,343
false
null
package com.hfut.schedule.ui.Activity.success.search.Search.LoginWeb import android.os.Handler import android.os.Looper import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.hfut.schedule.R import com.hfut.schedule.ViewModel.LoginSuccessViewModel import com.hfut.schedule.ViewModel.UIViewModel import com.hfut.schedule.logic.utils.SharePrefs import com.hfut.schedule.ui.Activity.success.cube.Settings.Items.getWebNew import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import java.math.BigDecimal import java.math.RoundingMode @Composable fun loginWebUI(vmUI : UIViewModel,vm : LoginSuccessViewModel) { val memoryWeb = SharePrefs.prefs.getString("memoryWeb","0") val flow = vmUI.webValue.value?.flow ?: memoryWeb val bd = BigDecimal((flow?.toDouble() ?: 0.0) / 1024) val str = bd.setScale(2, RoundingMode.HALF_UP).toString() var textStatus by remember { mutableStateOf("已用 ${flow}MB (${str}GB)\n余额 ¥${vmUI.webValue.value?.fee?: "0"}") } val bd2 = BigDecimal(((flow?.toDouble() ?: 0.0) / 40960) * 100) val precent = bd2.setScale(2, RoundingMode.HALF_UP).toString() // return str Card( elevation = CardDefaults.cardElevation(defaultElevation = 3.dp), modifier = Modifier .fillMaxWidth() .padding(horizontal = 15.dp, vertical = 5.dp), shape = MaterialTheme.shapes.medium, ){ ListItem( headlineContent = { Text(text = "月免费额度 50GB") }, trailingContent = { Text(text = "已用 ${precent}%")}, leadingContent = { Icon(painterResource(R.drawable.net), contentDescription = "Localized description",) }, modifier = Modifier.clickable { }, ) } Spacer(modifier = Modifier.height(5.dp)) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center){ Icon(painter = painterResource(id = R.drawable.net), contentDescription = "", Modifier.size(100.dp), tint = MaterialTheme.colorScheme.primary) } Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center){ Text(text = textStatus, color = MaterialTheme.colorScheme.primary) } Spacer(modifier = Modifier.height(15.dp)) val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() val scale = animateFloatAsState( targetValue = if (isPressed) 0.8f else 1f, // 按下时为0.9,松开时为1 animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy), label = "" // 使用弹簧动画 ) var textLogin by remember { mutableStateOf("登录") } var textLogout by remember { mutableStateOf("注销") } vmUI.getWebInfo() getWebNew(vm,vmUI) CoroutineScope(Job()).launch { Handler(Looper.getMainLooper()).post{ vmUI.resultValue.observeForever { result -> if (result != null) { if(result.contains("登录成功") && !result.contains("已使用")) { vmUI.getWebInfo() textLogin = "已登录" textLogout = "注销" // textStatus = "已登录" } else if(result == "Error") { textStatus = "网络错误" } else if(result.contains("已使用")) { textLogout = "已注销" // textStatus = "已注销" textLogin = "登录" } } } } } Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Button( onClick = { vmUI.loginWeb() // vmUI.loginWeb2() },modifier = Modifier .scale(scale.value), interactionSource = interactionSource,) { Text(text = textLogin) } Spacer(modifier = Modifier.width(10.dp)) Button( onClick = { vmUI.logoutWeb() }, //modifier = Modifier // .scale(scale.value), //interactionSource = interactionSource, ) { Text(text = textLogout) } } } fun getWebInfos(html : String) : WebInfo { try { //本段照搬前端 val flow = html.substringAfter("flow").substringBefore(" ").substringAfter("'").toDouble() val fee = html.substringAfter("fee").substringBefore(" ").substringAfter("'").toDouble() var flow0 = flow % 1024 val flow1 = flow - flow0 flow0 *= 1000 flow0 -= flow0 % 1024 var fee1 = fee - fee % 100 var flow3 = "." if (flow0 / 1024 < 10) flow3 = ".00" else { if (flow0 / 1024 < 100) flow3 = ".0"; } val resultFee = (fee1 / 10000).toString() val resultFlow : String = ((flow1 / 1024).toString() + flow3 + (flow0 / 1024)).substringBefore(".") return WebInfo(resultFee,resultFlow) } catch (e : Exception) { return WebInfo("未获取到数据","未获取到数据") } } data class WebInfo(val fee : String, val flow : String)
0
null
1
3
aead3d3e437531c52a0ba99d71fae27d4ea0fe4f
6,515
HFUT-Schedule
Apache License 2.0
app/src/main/java/app/odapplications/bitstashwallet/modules/send/submodules/memo/SendMemoViewModel.kt
bitstashco
220,133,996
false
null
package app.odapplications.bitstashwallet.modules.send.submodules.memo import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SendMemoViewModel : ViewModel(), SendMemoModule.IView { lateinit var delegate: SendMemoModule.IViewDelegate val maxLength = MutableLiveData<Int>() fun init(maxLength: Int): SendMemoModule.IMemoModule { return SendMemoModule.init(this, maxLength) } override fun setMaxLength(maxLength: Int) { this.maxLength.value = maxLength } }
3
null
3
11
64c242dbbcb6b4df475a608b1edb43f87e5091fd
530
BitStash-Android-Wallet
MIT License
linea/src/commonMain/kotlin/compose/icons/lineaicons/basic/BookPencil.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineaicons.basic import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.lineaicons.BasicGroup public val BasicGroup.BookPencil: ImageVector get() { if (_bookPencil != null) { return _bookPencil!! } _bookPencil = Builder(name = "BookPencil", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.0f, 1.0f) horizontalLineToRelative(46.0f) verticalLineToRelative(62.0f) horizontalLineToRelative(-46.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 63.0f) lineTo(9.0f, 2.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 15.0f) lineTo(42.0f, 15.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 21.0f) lineTo(42.0f, 21.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(55.0f, 1.0f) lineToRelative(0.0f, 53.0f) lineToRelative(4.0f, 8.0f) lineToRelative(4.0f, -8.0f) lineToRelative(0.0f, -53.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(55.0f, 11.0f) lineTo(63.0f, 11.0f) } } .build() return _bookPencil!! } private var _bookPencil: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
3,467
compose-icons
MIT License
filepickerlibrary/src/main/java/com/nareshchocha/filepickerlibrary/ui/activitys/MediaFilePickerActivity.kt
ChochaNaresh
637,484,561
false
null
package com.nareshchocha.filepickerlibrary.ui.activitys import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import com.nareshchocha.filepickerlibrary.R import com.nareshchocha.filepickerlibrary.models.ImageOnly import com.nareshchocha.filepickerlibrary.models.PickMediaConfig import com.nareshchocha.filepickerlibrary.permission.PermissionUtils.checkPermission import com.nareshchocha.filepickerlibrary.picker.PickerUtils.selectFile import com.nareshchocha.filepickerlibrary.utilities.FileUtils import com.nareshchocha.filepickerlibrary.utilities.appConst.Const import com.nareshchocha.filepickerlibrary.utilities.extentions.getMediaIntent import com.nareshchocha.filepickerlibrary.utilities.extentions.getSettingIntent import com.nareshchocha.filepickerlibrary.utilities.extentions.setCanceledResult import com.nareshchocha.filepickerlibrary.utilities.extentions.setSuccessResult import com.nareshchocha.filepickerlibrary.utilities.extentions.showMyDialog import timber.log.Timber internal class MediaFilePickerActivity : AppCompatActivity() { private val mPickMediaConfig: PickMediaConfig? by lazy { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra( Const.BundleInternalExtras.PICK_MEDIA, PickMediaConfig::class.java, ) } else { @Suppress("DEPRECATION") intent.getParcelableExtra(Const.BundleInternalExtras.PICK_MEDIA) as PickMediaConfig? } } private val checkPermission = checkPermission(ActivityResultContracts.RequestPermission(), resultCallBack = { if (it) { launchFilePicker() } else if (ActivityCompat.shouldShowRequestPermissionRationale( this, getPermission( mPickMediaConfig = mPickMediaConfig!!, ), ) ) { showAskDialog() } else { showGotoSettingDialog() } }) private val selectFile = selectFile(ActivityResultContracts.StartActivityForResult(), resultCallBack = { result -> if (result.resultCode == Activity.RESULT_OK && result.data != null) { if (mPickMediaConfig?.allowMultiple == true && result.data?.clipData != null) { val uris = result.data?.getClipDataUris() Timber.tag(Const.LogTag.FILE_RESULT).v("File Uri ::: $uris") val filePaths = uris?.getFilePathList(this) Timber.tag(Const.LogTag.FILE_RESULT).v("filePath ::: $filePaths") setSuccessResult(uris, filePath = filePaths) } else if (result.data?.data != null) { val data = result.data?.data Timber.tag(Const.LogTag.FILE_RESULT).v("File Uri ::: ${data?.toString()}") val filePath = data?.let { FileUtils.getRealPath(this, it) } Timber.tag(Const.LogTag.FILE_RESULT).v("filePath ::: $filePath") setSuccessResult(data, filePath) } } else { Timber.tag(Const.LogTag.FILE_PICKER_ERROR) .v(getString(R.string.err_media_pick_error)) setCanceledResult(getString(R.string.err_media_pick_error)) } }) private fun Intent.getClipDataUris(): ArrayList<Uri> { val resultSet = LinkedHashSet<Uri>() data?.let { data -> resultSet.add(data) } val clipData = clipData if (clipData == null && resultSet.isEmpty()) { return ArrayList() } else if (clipData != null) { for (i in 0 until clipData.itemCount) { val uri = clipData.getItemAt(i).uri if (uri != null) { resultSet.add(uri) } } } return ArrayList(resultSet) } private fun List<Uri>.getFilePathList(context: Context): ArrayList<String> { val filePathList = ArrayList<String>() forEach { uri -> FileUtils.getRealPath(context, uri)?.also { filePath -> filePathList.add(filePath) } } return filePathList } private fun launchFilePicker() { if (mPickMediaConfig != null) { selectFile.launch(getMediaIntent(mPickMediaConfig!!)) } else { setCanceledResult( getString( R.string.err_config_null, this::mPickMediaConfig::class.java.name, ), ) } } override fun onCreate(savedInstanceState: Bundle?) { supportActionBar?.hide() super.onCreate(savedInstanceState) title = "" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkPermission() } else { launchFilePicker() } } private fun showAskDialog() { showMyDialog( mPickMediaConfig?.askPermissionTitle ?: getString(R.string.err_permission_denied), mPickMediaConfig?.askPermissionMessage ?: getString( R.string.err_write_storage_permission, getPermission(mPickMediaConfig!!).split(".").lastOrNull() ?: "", ), negativeClick = { setCanceledResult(getString(R.string.err_permission_result)) }, positiveClick = { checkPermission() }, ) } private fun showGotoSettingDialog() { if (mPickMediaConfig != null) { showMyDialog( mPickMediaConfig?.settingPermissionTitle ?: getString(R.string.err_permission_denied), mPickMediaConfig?.settingPermissionMessage ?: getString( R.string.err_write_storage_setting, getPermission(mPickMediaConfig!!).split(".").lastOrNull() ?: "", ), positiveButtonText = getString(R.string.str_go_to_setting), negativeClick = { setCanceledResult(getString(R.string.err_permission_result)) }, positiveClick = { settingCameraResultLauncher.launch(getSettingIntent()) }, ) } else { setCanceledResult( getString( R.string.err_config_null, this::mPickMediaConfig::class.java.name, ), ) } } private val settingCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (mPickMediaConfig != null) { if (ActivityCompat.checkSelfPermission( this, getPermission(mPickMediaConfig!!), ) == PackageManager.PERMISSION_GRANTED ) { launchFilePicker() } else { setCanceledResult(getString(R.string.err_permission_result)) } } else { setCanceledResult( getString( R.string.err_config_null, this::mPickMediaConfig::class.java.name, ), ) } } private fun checkPermission() { if (mPickMediaConfig != null) { checkPermission.launch( getPermission( mPickMediaConfig = mPickMediaConfig!!, ), ) } else { setCanceledResult( getString( R.string.err_config_null, this::mPickMediaConfig::class.java.name, ), ) } } companion object { private fun getPermission(mPickMediaConfig: PickMediaConfig): String { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (mPickMediaConfig.mPickMediaType == ImageOnly) { Manifest.permission.READ_MEDIA_IMAGES } else { Manifest.permission.READ_MEDIA_VIDEO } } else { Manifest.permission.READ_EXTERNAL_STORAGE } } fun getInstance(mContext: Context, mPickMediaConfig: PickMediaConfig?): Intent { val filePickerIntent = Intent(mContext, MediaFilePickerActivity::class.java) mPickMediaConfig?.let { filePickerIntent.putExtra(Const.BundleInternalExtras.PICK_MEDIA, it) } return filePickerIntent } } }
1
null
7
93
f01cad5848595e595f9ffd086397d1644c9d8aa4
9,138
FilePicker
Apache License 2.0
app/src/main/java/com/google/samples/apps/sunflower/data/GardenPlantingRepository.kt
LiuPangYao
380,426,708
false
null
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.data import javax.inject.Inject import javax.inject.Singleton @Singleton class GardenPlantingRepository @Inject constructor( private val gardenPlantingDao: GardenPlantingDao ) { suspend fun createGardenPlanting(plantId: String, dateBuy: String) { val gardenPlanting:GardenPlanting when (plantId) { "BW7-Moss" -> { gardenPlanting = GardenPlanting(plantId, "2021-06-11", dateBuy) } "BW7-柯博文" -> { gardenPlanting = GardenPlanting(plantId, "2021-05-02", dateBuy) } "BW7-原子小金剛" -> { gardenPlanting = GardenPlanting(plantId, "2021-01-30", dateBuy) } "BW7-大黃蜂" -> { gardenPlanting = GardenPlanting(plantId, "2020-12-20", dateBuy) } "BW7-巴斯光年" -> { gardenPlanting = GardenPlanting(plantId, "2020-11-01", dateBuy) } "BW7-復仇者聯盟" -> { gardenPlanting = GardenPlanting(plantId, "2020-10-21", dateBuy) } "BW7-紅" -> { gardenPlanting = GardenPlanting(plantId, "2019-12-25", dateBuy) } "BW7-綠" -> { gardenPlanting = GardenPlanting(plantId, "2019-12-20", dateBuy) } "BW7-藍" -> { gardenPlanting = GardenPlanting(plantId, "2019-12-21", dateBuy) } "BW7-GID" -> { gardenPlanting = GardenPlanting(plantId, "2021-07-01", dateBuy) } "BW7-戰士" -> { gardenPlanting = GardenPlanting(plantId, "2021-08-19", dateBuy) } "BW7-金剛" -> { gardenPlanting = GardenPlanting(plantId, "2021-08-24", dateBuy) } else -> { gardenPlanting = GardenPlanting(plantId, "unknow", dateBuy) } } gardenPlantingDao.insertGardenPlanting(gardenPlanting) } private fun switch(plantId: String, function: () -> Nothing) { } suspend fun removeGardenPlanting(gardenPlanting: GardenPlanting) { gardenPlantingDao.deleteGardenPlanting(gardenPlanting) } suspend fun removeGardenPlantingUseId(plantId: String) { gardenPlantingDao.deleteGardenPlantingUseId(plantId) } fun isPlanted(plantId: String) = gardenPlantingDao.isPlanted(plantId) fun getPlantedGardens() = gardenPlantingDao.getPlantedGardens() }
0
Kotlin
0
1
ae02063ca7ffed7fae8ead43a1e9b5344590709f
3,105
bw7
Apache License 2.0
compiler/test/data/typescriptBodies/import/simpleImport.kt
Kotlin
159,510,660
false
{"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* fun h() { SomeNamespace.a() SomeNamespace.Class() c() } // ------------------------------------------------------------------------------------------ @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* external fun c() // ------------------------------------------------------------------------------------------ @file:JsQualifier("SomeNamespace") @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") package SomeNamespace import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* external fun a() external open class Class
244
Kotlin
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
1,890
dukat
Apache License 2.0
app/src/main/java/com/danielvilha/luasapp/di/component/ApplicationComponent.kt
danielvilha
273,302,957
false
null
package com.danielvilha.luasapp.di.component import android.app.Application import com.danielvilha.luasapp.AppApplication import com.danielvilha.luasapp.data.remote.MiddlewareApi import com.danielvilha.luasapp.data.repository.MiddlewareRepository import com.danielvilha.luasapp.di.module.ApplicationModule import com.danielvilha.luasapp.utils.SchedulerProvider import com.danielvilha.luasapp.utils.network.InternetHelper import dagger.Component import io.reactivex.disposables.CompositeDisposable import javax.inject.Singleton /** * Created by danielvilha on 21/06/20 */ @Singleton @Component(modules = [ApplicationModule::class]) interface ApplicationComponent { fun inject(app: AppApplication) fun getApplication(): Application fun getSchedulerProvider(): SchedulerProvider fun getCompositeDisposable(): CompositeDisposable fun getNetworkingService(): MiddlewareApi fun getNetworkHelper(): InternetHelper fun getWebRepository(): MiddlewareRepository }
0
Kotlin
0
0
f39817cdb4e870456319dd69ca9e2c64c3b026dd
985
kotlin-luas-app
The Unlicense
solidblocks-rds-postgresql/test/src/test/kotlin/de/solidblocks/rds/postgresql/test/RdsPostgresqlInvalidConfigIntegrationTest.kt
pellepelster
427,474,970
false
null
package de.solidblocks.rds.postgresql.test import de.solidblocks.rds.postgresql.test.RdsPostgresqlMinioBackupIntegrationTest.Companion.database import mu.KotlinLogging import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.extension.ExtendWith import org.testcontainers.containers.ContainerLaunchException import org.testcontainers.containers.GenericContainer import org.testcontainers.containers.output.Slf4jLogConsumer import java.util.* @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(RdsTestBedExtension::class) @Disabled class RdsPostgresqlInvalidConfigIntegrationTest { private val logger = KotlinLogging.logger {} companion object { val backupHost = "minio" val bucket = "database1-backup" val accessKey = "database1-user1" val secretKey = "<KEY>" val database = "database1" val databaseUser = "user1" val databasePassword = "<PASSWORD>" val caPublicBase64 = Base64.getEncoder().encodeToString( RdsPostgresqlInvalidConfigIntegrationTest::class.java.getResource("/ca.pem").readBytes() ) } @Test fun doesNotStartIfNoDataDirIsMounted() { val logConsumer = TestContainersLogConsumer(Slf4jLogConsumer(logger)) val container = GenericContainer("solidblocks-rds-postgresql").apply { withLogConsumer(logConsumer) withEnv( mapOf( "DB_BACKUP_S3" to "1", "DB_BACKUP_S3_HOST" to backupHost, "DB_BACKUP_S3_BUCKET" to bucket, "DB_BACKUP_S3_ACCESS_KEY" to accessKey, "DB_BACKUP_S3_SECRET_KEY" to secretKey, "DB_INSTANCE_NAME" to database, "DB_DATABASE_${RdsPostgresqlMinioBackupIntegrationTest.database}" to database, "DB_USERNAME_${RdsPostgresqlMinioBackupIntegrationTest.database}" to databaseUser, "DB_PASSWORD_${RdsPostgresqlMinioBackupIntegrationTest.database}" to databasePassword, "DB_BACKUP_S3_CA_PUBLIC_KEY" to caPublicBase64, ) ) } Assertions.assertThrows(ContainerLaunchException::class.java) { container.start() } logConsumer.waitForLogLine("[solidblocks-rds-postgresql] storage dir '/storage/data' not mounted") } @Test fun doesNotStartIfNoBackupMethodSelected(rdsTestBed: RdsTestBed) { val logConsumer = TestContainersLogConsumer(Slf4jLogConsumer(logger)) Assertions.assertThrows(ContainerLaunchException::class.java) { rdsTestBed.createAndStartPostgresContainer( mapOf( ), initWorldReadableTempDir(), logConsumer ) } logConsumer.waitForLogLine("[solidblocks-rds-postgresql] either 'DB_BACKUP_S3' or 'DB_BACKUP_LOCAL' has to be activated") } @Test fun doesNotStartIfNoBackupDirMounted(rdsTestBed: RdsTestBed) { val logConsumer = TestContainersLogConsumer(Slf4jLogConsumer(logger)) Assertions.assertThrows(ContainerLaunchException::class.java) { rdsTestBed.createAndStartPostgresContainer( mapOf( "DB_BACKUP_LOCAL" to "1" ), initWorldReadableTempDir(), logConsumer ) } logConsumer.waitForLogLine("[solidblocks-rds-postgresql] local backup dir '/storage/backup' not mounted") } }
6
Kotlin
5
8
d73a91b20e799a1dc075428266a0644e4fddd303
3,751
solidblocks
MIT License
vilkår/uføre/domain/src/main/kotlin/vilkår/uføre/domain/UføreVilkår.kt
navikt
227,366,088
false
{"Kotlin": 10119313, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209}
package vilkår.uføre.domain import arrow.core.Either import arrow.core.Nel import arrow.core.left import arrow.core.nonEmptyListOf import arrow.core.right import no.nav.su.se.bakover.common.domain.Stønadsperiode import no.nav.su.se.bakover.common.domain.tidslinje.Tidslinje.Companion.lagTidslinje import no.nav.su.se.bakover.common.extensions.toNonEmptyList import no.nav.su.se.bakover.common.tid.periode.Periode import no.nav.su.se.bakover.common.tid.periode.harOverlappende import no.nav.su.se.bakover.common.tid.periode.minus import vilkår.common.domain.Avslagsgrunn import vilkår.common.domain.IkkeVurdertVilkår import vilkår.common.domain.Inngangsvilkår import vilkår.common.domain.Vilkår import vilkår.common.domain.Vurdering import vilkår.common.domain.VurdertVilkår import vilkår.common.domain.erLik import vilkår.common.domain.kastHvisPerioderErUsortertEllerHarDuplikater import vilkår.common.domain.kronologisk import vilkår.common.domain.slåSammenLikePerioder const val UFØRETRYGD_MINSTE_ALDER = 18 const val UFØRETRYGD_MAX_ALDER = 67 val UFØRETRYGD_ALDERSINTERVALL = UFØRETRYGD_MINSTE_ALDER..UFØRETRYGD_MAX_ALDER sealed interface UføreVilkår : Vilkår { override val vilkår get() = Inngangsvilkår.Uførhet override val grunnlag: List<Uføregrunnlag> fun oppdaterStønadsperiode(stønadsperiode: Stønadsperiode): UføreVilkår abstract override fun lagTidslinje(periode: Periode): UføreVilkår data object IkkeVurdert : UføreVilkår, IkkeVurdertVilkår { override val grunnlag = emptyList<Uføregrunnlag>() override fun oppdaterStønadsperiode(stønadsperiode: Stønadsperiode): IkkeVurdert = this override fun lagTidslinje(periode: Periode): IkkeVurdert = this override fun erLik(other: Vilkår): Boolean = other is IkkeVurdert override fun slåSammenLikePerioder(): Vilkår = this } data class Vurdert private constructor( override val vurderingsperioder: Nel<VurderingsperiodeUføre>, ) : UføreVilkår, VurdertVilkår { init { kastHvisPerioderErUsortertEllerHarDuplikater() require(!vurderingsperioder.harOverlappende()) } override val grunnlag: List<Uføregrunnlag> = vurderingsperioder.mapNotNull { it.grunnlag } override val avslagsgrunner: List<Avslagsgrunn> = when (vurdering) { Vurdering.Innvilget -> emptyList() Vurdering.Uavklart -> emptyList() Vurdering.Avslag -> listOf(Avslagsgrunn.UFØRHET) } override fun erLik(other: Vilkår): Boolean { return other is Vurdert && vurderingsperioder.erLik(other.vurderingsperioder) } override fun slåSammenLikePerioder(): Vurdert { return Vurdert(vurderingsperioder = vurderingsperioder.slåSammenLikePerioder()) } override fun copyWithNewId(): Vurdert = this.copy(vurderingsperioder = vurderingsperioder.map { it.copyWithNewId() }) companion object { fun tryCreate(vurderingsperiode: VurderingsperiodeUføre): Either<UgyldigUførevilkår, Vurdert> { return Vurdert(nonEmptyListOf(vurderingsperiode)).right() } fun tryCreate( vurderingsperioder: Nel<VurderingsperiodeUføre>, ): Either<UgyldigUførevilkår, Vurdert> { if (vurderingsperioder.harOverlappende()) { return UgyldigUførevilkår.OverlappendeVurderingsperioder.left() } return Vurdert(vurderingsperioder).right() } fun fromVurderingsperioder( vurderingsperioder: Nel<VurderingsperiodeUføre>, ): Either<UgyldigUførevilkår, Vurdert> { if (vurderingsperioder.harOverlappende()) { return UgyldigUførevilkår.OverlappendeVurderingsperioder.left() } return Vurdert(vurderingsperioder.kronologisk()).right() } } sealed interface UgyldigUførevilkår { data object OverlappendeVurderingsperioder : UgyldigUførevilkår } override fun oppdaterStønadsperiode(stønadsperiode: Stønadsperiode): Vurdert { val overlapp = vurderingsperioder.any { it.periode overlapper stønadsperiode.periode } return if (overlapp) { val vurderingerMedOverlapp = lagTidslinje(stønadsperiode.periode).vurderingsperioder val manglendePerioder = listOf(stønadsperiode.periode) .minus(vurderingerMedOverlapp.map { it.periode }) .sortedBy { it.fraOgMed }.toSet() val paired: List<Pair<Periode, VurderingsperiodeUføre?>> = vurderingerMedOverlapp.map { it.periode to it }.plus( manglendePerioder.map { it to null }, ) paired.fold(mutableListOf<Pair<Periode, VurderingsperiodeUføre>>()) { acc, (periode, vurdering) -> if (vurdering != null) { acc.add((periode to vurdering)) } else { val tidligere = vurderingerMedOverlapp.lastOrNull { it.periode starterSamtidigEllerTidligere periode } val senere = vurderingerMedOverlapp.firstOrNull { it.periode starterSamtidigEllerSenere periode } if (tidligere != null) { acc.add( periode to tidligere.oppdaterStønadsperiode( Stønadsperiode.create(periode = periode), ), ) } else if (senere != null) { acc.add( periode to senere.oppdaterStønadsperiode( Stønadsperiode.create(periode = periode), ), ) } } acc }.map { it.second }.let { Vurdert(vurderingsperioder = it.slåSammenLikePerioder()) } } else { val tidligere = stønadsperiode.periode.starterTidligere( vurderingsperioder.map { it.periode } .minByOrNull { it.fraOgMed }!!, ) if (tidligere) { Vurdert( vurderingsperioder = ( listOf( vurderingsperioder.minByOrNull { it.periode.fraOgMed }!! .oppdaterStønadsperiode(stønadsperiode), ).toNonEmptyList() ).slåSammenLikePerioder(), ) } else { Vurdert( vurderingsperioder = ( listOf( vurderingsperioder.maxByOrNull { it.periode.tilOgMed }!! .oppdaterStønadsperiode(stønadsperiode), ).toNonEmptyList() ).slåSammenLikePerioder(), ) } } } override fun lagTidslinje(periode: Periode): Vurdert { return Vurdert( vurderingsperioder = vurderingsperioder.lagTidslinje().krympTilPeriode(periode)!!.toNonEmptyList(), ) } } }
5
Kotlin
1
1
fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda
7,729
su-se-bakover
MIT License
sceneview_2_0_0/src/main/java/io/github/sceneview/utils/FrameTime.kt
SceneView
426,414,439
false
null
package io.github.sceneview.utils import kotlin.time.Duration import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.DurationUnit /** * ### Provides time information for the current frame. * * @param nanoseconds The time when this frame started * @param lastNanoseconds The time when the previous frame started */ data class FrameTime(val nanoseconds: Long, val lastNanoseconds: Long? = null) { /** * ### The duration between this frame and the last frame */ val interval: Duration by lazy { interval(lastNanoseconds) } val intervalSeconds: Double by lazy { intervalSeconds(lastNanoseconds) } val fps: Double by lazy { fps(lastNanoseconds) } /** * ### The duration between this frame and the last frame */ fun interval(lastNanoseconds: Long?): Duration = (nanoseconds - (lastNanoseconds ?: 0)).nanoseconds fun intervalSeconds(lastNanoseconds: Long?): Double = interval(lastNanoseconds).toDouble( DurationUnit.SECONDS ) fun fps(lastNanoseconds: Long?): Double = 1.0 / intervalSeconds(lastNanoseconds) fun fps(frameTime: FrameTime?): Double = fps(frameTime?.nanoseconds) }
55
null
90
662
001ee5e60166bee050d02f931f106d687b47e3cd
1,174
sceneview-android
Apache License 2.0
src/main/kotlin/g0001_0100/s0092_reverse_linked_list_ii/Solution.kt
javadev
190,711,550
false
null
/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? { var head = head var right = right if (left == right) { return head } var prev: ListNode? = null var temp = head val start: ListNode? var k = left while (temp != null && k > 1) { prev = temp temp = temp.next k-- } if (left > 1 && prev != null) { prev.next = null } var prev1: ListNode? = null start = temp while (temp != null && right - left >= 0) { prev1 = temp temp = temp.next right-- } if (prev1 != null) { prev1.next = null } if (left > 1 && prev != null) { prev.next = reverse(start) } else { head = reverse(start) prev = head } while (prev!!.next != null) { prev = prev.next } prev.next = temp return head } fun reverse(head: ListNode?): ListNode? { var p: ListNode? var q: ListNode? var r: ListNode? = null p = head while (p != null) { q = p.next p.next = r r = p p = q } return r } }
1
null
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
1,535
LeetCode-in-Kotlin
MIT License
platform/credential-store/src/libraries/linuxSecretLibrary.kt
afdw
66,280,367
true
{"Text": 2540, "XML": 4219, "Ant Build System": 19, "Shell": 34, "Markdown": 6, "Ignore List": 22, "Git Attributes": 4, "Batchfile": 23, "Java": 50569, "Java Properties": 85, "HTML": 2441, "Kotlin": 436, "Groovy": 2258, "JavaScript": 44, "JFlex": 23, "XSLT": 109, "CSS": 70, "desktop": 2, "Python": 7648, "INI": 186, "SVG": 4, "C#": 32, "Smalltalk": 14, "Rich Text Format": 2, "JSON": 176, "CoffeeScript": 3, "JSON with Comments": 1, "J": 18, "Protocol Buffer": 2, "JAR Manifest": 6, "Gradle": 30, "E-mail": 18, "Roff": 38, "Roff Manpage": 1, "Gherkin": 4, "Diff": 16, "YAML": 88, "Maven POM": 1, "Checksums": 42, "Java Server Pages": 24, "C": 38, "AspectJ": 2, "Perl": 4, "HLSL": 2, "Erlang": 1, "Scala": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "Microsoft Visual Studio Solution": 10, "C++": 20, "Objective-C": 9, "OpenStep Property List": 2, "NSIS": 12, "Thrift": 2, "Cython": 7, "TeX": 7, "reStructuredText": 41, "Gettext Catalog": 125, "Jupyter Notebook": 4, "Regular Expression": 5}
package com.intellij.credentialStore.linux import com.intellij.credentialStore.CredentialStore import com.intellij.credentialStore.LOG import com.intellij.jna.DisposableMemory import com.sun.jna.Library import com.sun.jna.Native import com.sun.jna.Pointer private val LIBRARY by lazy { Native.loadLibrary("secret-1", SecretLibrary::class.java) as SecretLibrary } private const val SECRET_SCHEMA_NONE = 0 private const val SECRET_SCHEMA_ATTRIBUTE_STRING = 0 // explicitly create pointer to be explicitly dispose it to avoid sensitive data in the memory internal fun stringPointer(data: ByteArray): DisposableMemory { val pointer = DisposableMemory(data.size + 1L) pointer.write(0, data, 0, data.size) pointer.setByte(data.size.toLong(), 0.toByte()) return pointer } // we use default collection, it seems no way to use custom internal class SecretCredentialStore(schemeName: String) : CredentialStore { private val keyAttributeNamePointer by lazy { stringPointer("key".toByteArray()) } private val scheme by lazy { LIBRARY.secret_schema_new(schemeName, SECRET_SCHEMA_NONE, keyAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING, null) } override fun get(key: String): String? { val keyPointer = stringPointer(key.toByteArray()) return checkError("secret_password_lookup_sync") { errorRef -> LIBRARY.secret_password_lookup_sync(scheme, null, errorRef, keyAttributeNamePointer, keyPointer, null) } } override fun set(key: String, password: ByteArray?) { val keyPointer = stringPointer(key.toByteArray()) if (password == null) { checkError("secret_password_store_sync") { errorRef -> LIBRARY.secret_password_clear_sync(scheme, null, errorRef, keyAttributeNamePointer, keyPointer, null) } return } val passwordPointer = stringPointer(password) password.fill(0) checkError("secret_password_store_sync") { errorRef -> try { LIBRARY.secret_password_store_sync(scheme, null, keyPointer, passwordPointer, null, errorRef, keyAttributeNamePointer, keyPointer, null) } finally { passwordPointer.dispose() keyPointer.dispose() } } } } private inline fun <T> checkError(method: String, task: (errorRef: Array<GErrorStruct?>) -> T): T { val errorRef = arrayOf<GErrorStruct?>(null) val result = task(errorRef) val error = errorRef.get(0) if (error != null && error.code !== 0) { LOG.error("$method error code ${error.code}, error message ${error.message}") } return result } // we use sync API to simplify - client will use postponed write private interface SecretLibrary : Library { fun secret_schema_new(name: String, flags: Int, vararg attributes: Any?): Pointer fun secret_password_store_sync(scheme: Pointer, collection: Pointer?, label: Pointer, password: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?) fun secret_password_lookup_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?): String fun secret_password_clear_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?) } @Suppress("unused") class GErrorStruct : com.sun.jna.Structure() { @JvmField var domain = 0 @JvmField var code = 0 @JvmField var message: String? = null override fun getFieldOrder() = listOf("domain", "code", "message") }
0
Java
0
0
759cd48f7a36a7df41c28fd259fdcf8816cca9d9
3,421
intellij-community
Apache License 2.0
core/testing/src/main/java/io/github/droidkaigi/confsched/testing/robot/SponsorsScreenRobot.kt
DroidKaigi
776,354,672
false
{"Kotlin": 1119401, "Swift": 211686, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
package io.github.droidkaigi.confsched.testing.robot import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.filter import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isDisplayed import androidx.compose.ui.test.onChildren import androidx.compose.ui.test.onFirst import androidx.compose.ui.test.performScrollToNode import io.github.droidkaigi.confsched.designsystem.theme.KaigiTheme import io.github.droidkaigi.confsched.model.Plan import io.github.droidkaigi.confsched.model.Plan.GOLD import io.github.droidkaigi.confsched.model.Plan.PLATINUM import io.github.droidkaigi.confsched.model.Plan.SUPPORTER import io.github.droidkaigi.confsched.model.Sponsor import io.github.droidkaigi.confsched.model.fakes import io.github.droidkaigi.confsched.sponsors.SponsorsScreen import io.github.droidkaigi.confsched.sponsors.component.SponsorItemImageTestTag import io.github.droidkaigi.confsched.sponsors.section.SponsorsListLazyVerticalGridTestTag import io.github.droidkaigi.confsched.sponsors.section.SponsorsListSponsorHeaderTestTagPrefix import io.github.droidkaigi.confsched.sponsors.section.SponsorsListSponsorItemTestTagPrefix import io.github.droidkaigi.confsched.testing.utils.assertCountAtLeast import io.github.droidkaigi.confsched.testing.utils.hasTestTag import javax.inject.Inject class SponsorsScreenRobot @Inject constructor( private val screenRobot: DefaultScreenRobot, private val sponsorsServerRobot: DefaultSponsorsServerRobot, ) : ScreenRobot by screenRobot, SponsorsServerRobot by sponsorsServerRobot { enum class SponsorType( val typeName: String, ) { Platinum("PLATINUM SPONSORS"), Gold("GOLD SPONSORS"), Supporters("SUPPORTERS"), } fun setupScreenContent() { robotTestRule.setContent { KaigiTheme { SponsorsScreen( onNavigationIconClick = {}, onSponsorsItemClick = {}, ) } } } fun scrollToGoldSponsorsHeader() { scrollToSponsorHeader(SponsorType.Gold) } fun scrollToSupportersSponsorsHeader() { scrollToSponsorHeader(SponsorType.Supporters) } private fun scrollToSponsorHeader( sponsorType: SponsorType, ) { composeTestRule .onNode(hasTestTag(SponsorsListLazyVerticalGridTestTag)) .performScrollToNode( hasTestTag(SponsorsListSponsorHeaderTestTagPrefix.plus(sponsorType.typeName)), ) } fun scrollBottom() { composeTestRule .onNode(hasTestTag(SponsorsListLazyVerticalGridTestTag)) .performScrollToNode( hasTestTag(SponsorsListSponsorItemTestTagPrefix.plus(Sponsor.fakes().last().name)), ) } fun checkDisplayPlatinumSponsors() { checkSponsorItemsDisplayedByRangeAndSponsorType( sponsorType = SponsorType.Platinum, fromTo = 0..2, ) } fun checkDisplayGoldSponsors() { checkSponsorItemsDisplayedByRangeAndSponsorType( sponsorType = SponsorType.Gold, fromTo = 0..2, ) } fun checkDisplaySupportersSponsors() { checkSponsorItemsDisplayedByRangeAndSponsorType( sponsorType = SponsorType.Supporters, fromTo = 0..2, ) } private fun checkSponsorItemsDisplayedByRangeAndSponsorType( sponsorType: SponsorType, fromTo: IntRange, ) { val sponsorList = Sponsor.fakes().filter { it.plan.toSponsorType() == sponsorType } .subList(fromTo.first, fromTo.last) sponsorList.forEach { sponsor -> composeTestRule .onNode(hasTestTag(SponsorsListSponsorItemTestTagPrefix.plus(sponsor.name))) .assertExists() .assertIsDisplayed() composeTestRule .onNode( hasTestTag(SponsorsListSponsorItemTestTagPrefix.plus(sponsor.name)), true, ) .onChildren() .filter(matcher = hasTestTag(SponsorItemImageTestTag)) .onFirst() .assertExists() .assertIsDisplayed() .assertContentDescriptionEquals("${sponsor.name} sponsor logo") } } fun checkSponsorItemsDisplayed() { // Check there are two sponsors composeTestRule .onAllNodes( hasTestTag( testTag = SponsorsListSponsorItemTestTagPrefix, substring = true, ), ) .assertCountAtLeast(2) } fun checkDoesNotSponsorItemsDisplayed() { val sponsor = Sponsor.fakes().first() composeTestRule .onNode( hasTestTag( testTag = SponsorsListSponsorItemTestTagPrefix, substring = true, ), ) .assertDoesNotExist() composeTestRule .onNode( matcher = hasTestTag(SponsorItemImageTestTag.plus(sponsor.name)), useUnmergedTree = true, ) .assertDoesNotExist() } fun checkErrorSnackbarDisplayed() { composeTestRule .onNode(hasText("Fake IO Exception")) .isDisplayed() } private fun Plan.toSponsorType() = when (this) { PLATINUM -> SponsorType.Platinum GOLD -> SponsorType.Gold SUPPORTER -> SponsorType.Supporters } }
71
Kotlin
201
438
57c38a76beb5b75edc9220833162e1257f40ac06
5,698
conference-app-2024
Apache License 2.0
app/src/test/java/com/example/homepage/loginSignup/HelperSignInSignUpTest.kt
Parvez-Uni-Projects
516,901,454
false
null
package com.example.homepage.loginSignup import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class HelperSignInSignUpTest( private val testData: EmailPasswordTestData ) { companion object { @JvmStatic @Parameterized.Parameters(name = "{index}: {0}") fun data() = getTestData().map { arrayOf(it) } } private lateinit var testingClass: HelperSignInSignUp @Before fun setUp() { testingClass = HelperSignInSignUp() } @Test fun `given email, password, and retype password, when emailPasswordValidation is called, then it should return expected result`() { // ACT val result = testingClass.emailPasswordValidation( testData.email, testData.password, testData.retypePassword ) // ASSERT assertEquals(testData.expected, result) } }
10
null
4
9
a2bbc2ca9310241e623b123b4e9f62004c28e2e5
1,015
AUST_BUDDY
MIT License
src/main/kotlin/me/javahere/apipathpamanager/ApiPathBuilderExtensions.kt
javokhirakramjonov
765,915,618
false
null
package me.javahere.apipathpamanager internal fun ApiPathSegment.printPaths() { println("All possible endpoints:") printSegments(String.EMPTY, this) println("Finish.") } private fun printSegments( currentPath: String, apiPathSegment: ApiPathSegment, ) { val path = if (currentPath.isEmpty()) { apiPathSegment.formattedSegmentName } else { "$currentPath/${apiPathSegment.formattedSegmentName}" } if (apiPathSegment.nestedSegments.isEmpty() || apiPathSegment.shouldStop) { println(path) } for (nested in apiPathSegment.nestedSegments) { printSegments(path, nested) } }
0
null
0
1
3bf25173627790d618a2f63c9d3df7c43f6c71a6
677
api-path-manager
MIT License
app/src/main/java/com/hal/kaiyan/ui/home/fragment/RelatedFragment.kt
leihaogit
734,572,648
false
null
package com.hal.kaiyan.ui.home.fragment import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.hal.kaiyan.adapter.RelatedAdapter import com.hal.kaiyan.databinding.FragmentRelatedBinding import com.hal.kaiyan.entity.ItemList import com.hal.kaiyan.entity.VideoInfoData import com.hal.kaiyan.net.DataState import com.hal.kaiyan.ui.base.BaseFragment import com.hal.kaiyan.ui.base.Constant import com.hal.kaiyan.ui.home.activity.PlayVideoActivity import com.hal.kaiyan.viewmodel.KaiYanViewModel import kotlinx.coroutines.launch import java.util.Date /** * @author LeiHao * @date 2023/12/19 * @description 视频相关信息界面 */ class RelatedFragment : BaseFragment() { companion object { @JvmStatic fun newInstance(videoInfoData: VideoInfoData?) = RelatedFragment().apply { arguments = Bundle().apply { putSerializable(Constant.VIDEO_INFO_DATA, videoInfoData) } } } private val kaiYanViewModel: KaiYanViewModel by viewModels() //本界面接收的视频数据 private var videoInfoData: VideoInfoData? = null private lateinit var binding: FragmentRelatedBinding //本界面的所有相关数据,包括自身 private val videos: MutableList<VideoInfoData> = mutableListOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { videoInfoData = it.getSerializable(Constant.VIDEO_INFO_DATA) as VideoInfoData? } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentRelatedBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initData() initEvent() } private fun initEvent() { binding.refreshLayout.run { setOnRefreshListener { requireActivity().finish() } } } private fun initData() { //获取视频相关推荐 bindToAdapter() } /** * 视频相关推荐 */ @SuppressLint("NotifyDataSetChanged") private fun bindToAdapter() { videoInfoData?.let { videos.add(it) } val relatedAdapter = RelatedAdapter(videos) binding.recyclerView.layoutManager = LinearLayoutManager(requireContext()) binding.recyclerView.adapter = relatedAdapter //跳转到播放页面 relatedAdapter.setOnItemClickListener(object : RelatedAdapter.OnItemClickListener { override fun onItemClick(videoInfoData: VideoInfoData, type: String) { vibrate() if (type == "reply") { (requireActivity() as PlayVideoActivity).toPosition(1) } else if (type == "refresh") { (requireActivity() as PlayVideoActivity).refresh(videoInfoData) } } }) var hasVideo = 0 kaiYanViewModel.hasVideo(videoInfoData!!.id).observe(viewLifecycleOwner) { hasVideo = it videoInfoData!!.collectDate = if (hasVideo == 0) null else Date() relatedAdapter.notifyItemChanged(0) } //点击收藏 relatedAdapter.setOnCollectClickListener(object : RelatedAdapter.OnCollectClickListener { override fun onCollectClick(videoInfoData: VideoInfoData, view: View) { lifecycleScope.launch { if (hasVideo == 0) { kaiYanViewModel.insertVideo(videoInfoData.apply { collectDate = Date() }) hasVideo = 1 } else { kaiYanViewModel.deleteVideo(videoInfoData) hasVideo = 0 } relatedAdapter.notifyItemChanged(0) } } }) kaiYanViewModel.videoRelatedData.observe(viewLifecycleOwner) { when (it.dataState) { DataState.SUCCESS -> { //拿到视频相关数据了 val realData = mutableListOf<VideoInfoData>() it.itemList!!.forEach { item -> when (item.type) { "videoSmallCard" -> { realData.add(swapToVideoInfoData(item.data)) } } } videos.addAll(realData) relatedAdapter.notifyDataSetChanged() } else -> {} } } //获取一下视频相关信息 kaiYanViewModel.getVideoRelatedData(videoInfoData?.id.toString()) } /** * 转换为VideoInfoData对象 */ private fun swapToVideoInfoData(data: ItemList.Data) = data.run { VideoInfoData( id, playUrl, cover.feed, cover.blurred, title, category, description, VideoInfoData.Consumption( consumption.collectionCount, consumption.shareCount, consumption.replyCount ), author?.name, author?.description, author?.icon, duration, releaseTime, null ) } }
0
null
1
6
dc9cbb8035f46e35c7a2f648fc9e3bdf7a8eb7d6
5,603
kaiyan
Apache License 2.0
app/src/main/java/com/mkdev/zerotohero/extension/ActivityExtensions.kt
msddev
408,932,522
false
null
package com.d204.algo.ui.extension import android.app.Activity import android.content.Context import android.content.Intent import android.view.View import android.widget.Toast import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar internal fun Activity.showSnackBar(view: View, message: String) { Snackbar.make(view, message, Snackbar.LENGTH_LONG).apply { //anchorView = view.rootView.findViewById(R.id.bottomNavigationView) show() } } internal fun Fragment.showSnackBar(view: View, message: String) { Snackbar.make(view, message, Snackbar.LENGTH_LONG).apply { //anchorView = view.rootView.findViewById(R.id.bottomNavigationView) show() } } internal fun Context.showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } internal inline fun <reified T : Activity> Context.startActivity(block: Intent.() -> Unit = {}) { val intent = Intent(this, T::class.java) block(intent) startActivity(intent) }
0
null
1
6
5d174a554a196bc3ee2823b1d8c12a6dcd60b1ce
1,033
Sample-MVVM-Clean-Arch
Apache License 2.0
light/src/main/kotlin/net/kotlinx/okhttp/OkHttpSupport.kt
mypojo
565,799,715
false
{"Kotlin": 1352508, "Jupyter Notebook": 13439, "Java": 9531}
package net.kotlinx.okhttp import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.Response import java.io.File private val OKHTTP_REQ_INTERCEPTOR: MutableMap<OkHttpClient, (OkHttpReq) -> Unit> = mutableMapOf() /** interceptor 설정 추가 */ var OkHttpClient.reqInterceptor: (OkHttpReq) -> Unit get() = OKHTTP_REQ_INTERCEPTOR.getOrDefault(this) {} set(value) { OKHTTP_REQ_INTERCEPTOR[this] = value } /** * 멀티파트 파일 업로드 샘플 * https://httpbin.org/post 로 테스트 가능 * 사용금지!! 가능하면 프리사인 사용하세요!! * */ fun OkHttpClient.fileUploadSample(url: String, file: File, block: MultipartBody.Builder.() -> Unit = {}): Response { val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.name, file.asRequestBody(OkHttpMediaType.STREAM)) //.addFormDataPart("", "") .apply(block) .build() val request = Request.Builder() .url(url) .post(requestBody) .build() return this.newCall(request).execute() }
0
Kotlin
0
1
fb930ed8208165b710de3eff879e1aaa2f154655
1,110
kx_kotlin_support
MIT License
core/src/main/kotlin/net/ormr/kommando/utils/emojis.kt
Olivki
473,789,476
false
{"Kotlin": 389470}
/* * MIT License * * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.ormr.kommando.utils import dev.kord.common.entity.DiscordPartialEmoji import dev.kord.common.entity.optional.optional import dev.kord.core.builder.components.emoji import dev.kord.core.entity.GuildEmoji import dev.kord.core.entity.ReactionEmoji import dev.kord.rest.builder.component.ButtonBuilder import dev.kord.rest.builder.component.SelectOptionBuilder import dev.kord.x.emoji.DiscordEmoji import dev.kord.x.emoji.toReaction public fun ButtonBuilder.emoji(emoji: DiscordEmoji) { emoji(emoji.toReaction()) } public fun SelectOptionBuilder.emoji(emoji: GuildEmoji) { this.emoji = DiscordPartialEmoji(id = emoji.id, name = null, animated = emoji.isAnimated.optional()) } public fun SelectOptionBuilder.emoji(emoji: ReactionEmoji.Unicode) { this.emoji = DiscordPartialEmoji(name = emoji.name, id = null) } public fun SelectOptionBuilder.emoji(emoji: ReactionEmoji.Custom) { this.emoji = DiscordPartialEmoji(name = emoji.name, id = emoji.id, animated = emoji.isAnimated.optional()) } public fun SelectOptionBuilder.emoji(emoji: DiscordEmoji) { emoji(emoji.toReaction()) }
3
Kotlin
0
2
a3cbb08a332873cc783296c45c21cf950aed7ed5
2,238
kommando
MIT License
app/src/main/kotlin/taiwan/no1/app/mvp/models/tv/TvBriefModel.kt
pokk
77,319,651
false
null
package taiwan.no1.app.mvp.models.tv import android.os.Parcel import android.os.Parcelable import taiwan.no1.app.mvp.models.IVisitable import taiwan.no1.app.ui.adapter.viewholder.viewtype.IViewTypeFactory import java.util.* /** * * @author Jieyi * @since 2/5/17 */ data class TvBriefModel(val poster_path: String? = null, val popularity: Double = 0.toDouble(), val id: Int = 0, val backdrop_path: String? = null, val vote_average: Double = 0.toDouble(), val overview: String? = null, val first_air_date: String? = null, val original_language: String? = null, val vote_count: Int = 0, val name: String? = null, val original_name: String? = null, val origin_country: List<String>? = null, var isMainView: Boolean = true, // This is for difference view type. val genre_ids: List<Int>? = null): Parcelable, IVisitable { override fun type(typeFactory: IViewTypeFactory): Int = typeFactory.type(this, this.isMainView) //region Parcelable companion object { @JvmField val CREATOR: Parcelable.Creator<TvBriefModel> = object: Parcelable.Creator<TvBriefModel> { override fun createFromParcel(source: Parcel): TvBriefModel = TvBriefModel(source) override fun newArray(size: Int): Array<TvBriefModel?> = arrayOfNulls(size) } } constructor(source: Parcel): this(source.readString(), source.readDouble(), source.readInt(), source.readString(), source.readDouble(), source.readString(), source.readString(), source.readString(), source.readInt(), source.readString(), source.readString(), ArrayList<String>().also { source.readList(it, String::class.java.classLoader) }, 1 == source.readInt(), ArrayList<Int>().also { source.readList(it, Int::class.java.classLoader) }) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeString(poster_path) dest?.writeDouble(popularity) dest?.writeInt(id) dest?.writeString(backdrop_path) dest?.writeDouble(vote_average) dest?.writeString(overview) dest?.writeString(first_air_date) dest?.writeString(original_language) dest?.writeInt(vote_count) dest?.writeString(name) dest?.writeString(original_name) dest?.writeList(origin_country) dest?.writeInt((if (isMainView) 1 else 0)) dest?.writeList(genre_ids) } //endregion }
0
Kotlin
5
5
d5c8c3e473e6c480e1eb1660caf477ada65859f0
2,863
mvp-magazine
Apache License 2.0
client/src/main/kotlin/com/configset/client/ObservableConfProperty.kt
raymank26
296,910,120
false
null
package com.configset.client import com.configset.client.converter.Converter import com.configset.sdk.extension.createLoggerStatic private val LOG = createLoggerStatic<ObservableConfProperty<*>>() class ObservableConfProperty<T>( private val configPropertyLinkProcessor: ConfigPropertyLinkProcessor, private val valueDependencyResolver: PropertyFullResolver, private val name: String, private val defaultValue: T, private val converter: Converter<T>, dynamicValue: DynamicValue<String?>, ) : ConfProperty<T> { @Volatile private lateinit var state: PropertyState<T> private val listeners: MutableSet<Subscriber<T>> = HashSet() init { evaluate(dynamicValue.value) val subscriber = Subscriber<String?> { value -> evaluate(value) } dynamicValue.observable.onSubscribe(subscriber) } override fun getValue(): T { return state.value } @Synchronized private fun evaluate(value: String?) { if (::state.isInitialized) { state.dependencySubscriptions.map { it.unsubscribe() } } val depSubscriptions = mutableListOf<Subscription>() val currentValueStr = if (value != null) { val tokensNode = configPropertyLinkProcessor.parse(value) for (token in tokensNode.tokens) { if (token is Link) { val sub = valueDependencyResolver.getConfProperty(token.appName, token.propertyName).subscribe { evaluate(value) } depSubscriptions.add(sub) } } configPropertyLinkProcessor.evaluate(tokensNode, valueDependencyResolver) } else { null } state = PropertyState(convertSafely(currentValueStr), depSubscriptions) fireListeners(state.value) } @Synchronized override fun subscribe(listener: Subscriber<T>): Subscription { listeners.add(listener) return object : Subscription { override fun unsubscribe() { listeners.remove(listener) } } } private fun convertSafely(value: String?): T { return try { if (value == null) { return defaultValue } else { converter.convert(value) } } catch (e: Exception) { LOG.warn("For propertyName = $name unable to convert value = $value", e) defaultValue } } private fun fireListeners(value: T) { // it might be possible that somebody unsubscribes while iterating. That's why we do a copy here. for (listener in HashSet(listeners)) { try { LOG.debug("Listener of {}", this) listener.process(value) } catch (e: Exception) { LOG.warn("For propertyName = $name unable to call listener for value = $value", e) } } } } data class PropertyState<T>(val value: T, val dependencySubscriptions: List<Subscription>)
0
Kotlin
0
0
a43603265e1c7e4c5e38d69ecd3bb8a210ba3691
3,080
configset
Apache License 2.0
app/src/main/kotlin/app/luisramos/ler/ui/settings/SettingsItemSwitchView.kt
orgmir
244,587,282
false
{"Kotlin": 217708, "HTML": 8054, "Ruby": 1070}
package app.luisramos.ler.ui.settings import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.widget.TextView import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.core.view.updatePadding import app.luisramos.ler.R import app.luisramos.ler.ui.views.getDrawable import com.google.android.material.switchmaterial.SwitchMaterial import com.squareup.contour.ContourLayout class SettingsItemSwitchView( context: Context, attrs: AttributeSet? = null ) : ContourLayout(context, attrs) { var clickListener = {} val titleTextView = TextView(context).apply { setTextAppearance(R.style.TextAppearance_MaterialComponents_Body1) gravity = Gravity.CENTER_VERTICAL updatePadding(left = 16.dip, right = 16.dip, top = 16.dip, bottom = 4.dip) isClickable = false } val subTitleTextView = TextView(context).apply { setTextAppearance(R.style.TextAppearance_MaterialComponents_Caption) gravity = Gravity.CENTER_VERTICAL updatePadding(left = 16.dip, right = 16.dip, top = 4.dip, bottom = 16.dip) setOnClickListener { switch.performClick() } visibility = GONE isClickable = false } val switch = SwitchMaterial(context).apply { setOnClickListener { clickListener() } } init { background = getDrawable(R.attr.selectableItemBackground) setOnClickListener { switch.performClick() } switch.layoutBy( x = rightTo { parent.width() - 16.xdip }, y = centerVerticallyTo { parent.centerY() } ) titleTextView.layoutBy( x = leftTo { 0.xdip }.rightTo { switch.left() }, y = topTo { 0.ydip }.heightOf { titleTextView.preferredHeight() } ) subTitleTextView.layoutBy( x = matchXTo(titleTextView), y = topTo { titleTextView.bottom() }.heightOf { subTitleTextView.preferredHeight() } ) contourHeightOf { if (subTitleTextView.isGone) { titleTextView.bottom() + 12.dip } else { subTitleTextView.bottom() } } if (isInEditMode) { titleTextView.text = resources.getString(R.string.settings_new_post_notif_switch) subTitleTextView.text = resources.getString(R.string.settings_new_post_notif_desc) subTitleTextView.isVisible = true } } }
2
Kotlin
0
1
b703b241c8b0d1093ae4fe89b0d7a5ca1df03cb4
2,485
ler-android
Apache License 2.0
app/src/test/java/com/fappslab/bookshelf/main/domain/usecase/SetFavoriteUseCaseTest.kt
F4bioo
661,873,124
false
null
package com.fappslab.bookshelf.main.domain.usecase import com.fappslab.bookshelf.main.domain.repository.BookshelfRepository import com.fappslab.bookshelf.stub.BooksFactory.book import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.reactivex.Completable import io.reactivex.Flowable import org.junit.Test class SetFavoriteUseCaseTest { private val repository: BookshelfRepository = mockk() private val subject = SetFavoriteUseCase(repository) @Test fun `setFavoriteSuccess Should complete with success When use case is invoked`() { // Given every { repository.setBook(any()) } returns Completable.complete() // When val result = subject(book = book).test() // Then result.assertComplete() verify { repository.setBook(any()) } } @Test fun `setFavoriteFailure Should throw exception When use case get failure`() { // Given val expectedResult = "Some error" every { repository.setBook(any()) } returns Completable.error(Throwable(expectedResult)) // When val result = subject(book = book).test() // Then result.assertError { cause -> expectedResult == cause.message } verify { repository.setBook(any()) } } }
0
Kotlin
0
0
3b3f5a9759e9f94068d3eba8a2fa01f647096b8d
1,309
Bookshelf
MIT License