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
transport/rabbitmq/src/main/kotlin/RabbitMqMessageSenderFactory.kt
eclipse-apoapsis
760,319,414
false
null
/* * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.eclipse.apoapsis.ortserver.transport.rabbitmq import com.rabbitmq.client.ConnectionFactory import org.eclipse.apoapsis.ortserver.config.ConfigManager import org.eclipse.apoapsis.ortserver.transport.Endpoint import org.eclipse.apoapsis.ortserver.transport.MessageSender import org.eclipse.apoapsis.ortserver.transport.MessageSenderFactory import org.slf4j.LoggerFactory /** * Implementation of the [MessageSenderFactory] interface for RabbitMQ. */ class RabbitMqMessageSenderFactory : MessageSenderFactory { companion object { private val logger = LoggerFactory.getLogger(this::class.java) } override val name: String = RabbitMqConfig.TRANSPORT_NAME override fun <T : Any> createSender(to: Endpoint<T>, configManager: ConfigManager): MessageSender<T> { val rabbitMqConfig = RabbitMqConfig.createConfig(configManager) logger.info("Creating RabbitMQ sender for endpoint '${to.configPrefix}'.") rabbitMqConfig.log(logger) val connectionFactory = ConnectionFactory().apply { setUri(rabbitMqConfig.serverUri) username = rabbitMqConfig.username password = rabbitMqConfig.password } return createSenderWithConnection(to, connectionFactory, rabbitMqConfig.queueName) } /** * Create a [MessageSender] for RabbitMQ that sends messages to the given [endpoint][to] via the queue with the * given [queueName]. Creates a channel for the [queueName] using the [connectionFactory]. */ internal fun <T : Any> createSenderWithConnection( to: Endpoint<T>, connectionFactory: ConnectionFactory, queueName: String ): MessageSender<T> { val connection = connectionFactory.newConnection( "ort-server-${to.configPrefix}-${to.messageClass.simpleName}" ) return runCatching { val channel = connection.createChannel().also { // Check that the queue exists. If it doesn't this operation fails with a channel level exception. it.queueDeclarePassive(queueName) } RabbitMqMessageSender(channel, queueName, to) }.onFailure { connection.close() }.getOrThrow() } }
18
null
2
9
0af70d6382a86f0ebc35d9b377f4229c6a71637a
3,009
ort-server
Apache License 2.0
messaging/src/androidTest/java/academy/compose/messaging/ui/MessagesTest.kt
roshanrai06
464,025,442
false
{"Kotlin": 789427}
/* * Copyright 2021 Compose Academy * * 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 academy.compose.messaging.ui import academy.compose.messaging.MessageFactory import academy.compose.messaging.ui.message.Messages import academy.compose.messaging.Tags.TAG_EMPTY import academy.compose.messaging.Tags.TAG_MESSAGE import academy.compose.messaging.Tags.TAG_MESSAGES import academy.compose.messaging.util.groupMessagesByDate import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.ui.test.* import androidx.compose.ui.test.junit4.createComposeRule import org.junit.Rule import org.junit.Test @ExperimentalFoundationApi @ExperimentalAnimationApi class MessagesTest { @get:Rule val composeTestRule = createComposeRule() @Test fun Messages_Displayed() { val messages = MessageFactory.makeMessages() composeTestRule.setContent { Messages( messages = MessageFactory.makeMessages(), onMessageSelected = { }, unSendMessage = { } ) } groupMessagesByDate(messages).forEach { entry -> composeTestRule.onNodeWithTag(TAG_MESSAGES) .onChildren() .assertAny(hasTestTag(entry.key.timeInMillis.toString())) entry.value.forEach { message -> composeTestRule.onNodeWithTag(TAG_MESSAGES) .onChildren() .assertAny(hasTestTag(TAG_MESSAGE + message.id)) } } } @Test fun Empty_Messages_Never_Displayed() { composeTestRule.setContent { Messages( messages = MessageFactory.makeMessages(), onMessageSelected = { }, unSendMessage = { } ) } composeTestRule.onNodeWithTag(TAG_EMPTY) .assertDoesNotExist() } @Test fun Empty_Messages_Displayed() { composeTestRule.setContent { Messages( messages = emptyList(), onMessageSelected = { }, unSendMessage = { } ) } composeTestRule.onNodeWithTag(TAG_EMPTY) .assertIsDisplayed() } }
0
Kotlin
0
0
37aae28e27d9a52bb44536af92f8b6111a27b1da
2,809
Compose_Acadmy
Apache License 2.0
androidApp/src/androidMain/kotlin/com/myapplication/MainActivity.kt
yeshuwahane
696,453,657
false
{"Kotlin": 6696, "Swift": 686, "Shell": 228}
package com.myapplication import MainView import android.os.Build import android.os.Bundle import android.util.Log import androidx.activity.compose.setContent import androidx.annotation.RequiresExtension import androidx.appcompat.app.AppCompatActivity import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.lifecycle.lifecycleScope import data.remote.api.Api import data.remote.dto.JokeDto import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val mainScope = MainScope() var jokeDto:JokeDto? = null @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainScope.launch { kotlin.runCatching { jokeDto = Api().getRandomJoke() }.onSuccess { setContent { jokeDto?.let { it1 -> MainView(it1) } } }.onFailure { Log.d("alien","Error") } } } }
0
Kotlin
0
0
c29298a0f9259e20a8c3771f54c351af90f6eb18
1,315
CMM
Apache License 2.0
src/main/kotlin/org/move/ide/intentions/InlineAddressBlockIntention.kt
pontem-network
279,299,159
false
null
package org.move.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.move.lang.core.psi.MvAddressDef import org.move.lang.core.psi.MvModuleBlock import org.move.lang.core.psi.ext.ancestorStrict import org.move.lang.core.psi.ext.hasAncestorOrSelf import org.move.lang.core.psi.ext.modules import org.move.lang.core.psi.ext.startOffset import org.move.lang.core.psi.psiFactory class InlineAddressBlockIntention: MvElementBaseIntentionAction<InlineAddressBlockIntention.Context>() { override fun getText(): String = "Inline address block" override fun getFamilyName(): String = text data class Context(val address: MvAddressDef) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { if (element.hasAncestorOrSelf<MvModuleBlock>()) return null val address = element.ancestorStrict<MvAddressDef>() ?: return null if (address.modules().size != 1) return null return Context(address) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val address = ctx.address val addressText = address.addressRef?.text ?: return val module = address.modules().firstOrNull() ?: return val moduleNameElement = module.nameElement ?: return val blockText = module.moduleBlock?.text ?: return // val nameOffset = moduleNameElement.startOffset // var caretOffset = editor.caretModel.offset // if (caretOffset > nameOffset) { // // focused on identifier // caretOffset += addressText.length + 2 // } val inlineModule = project.psiFactory.inlineModule(addressText, moduleNameElement.text, blockText) address.replace(inlineModule) // editor.caretModel.moveToOffset(caretOffset) } }
4
null
7
68
869d4901d6aebeb9c84bfb5809e4f547a0ac3427
1,897
intellij-move
MIT License
app/src/main/java/ly/david/mbjc/ui/stats/StatsScreen.kt
lydavid
458,021,427
false
null
package ly.david.mbjc.ui.stats import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import ly.david.data.network.MusicBrainzResource import ly.david.data.persistence.relation.RelationTypeCount import ly.david.data.persistence.releasegroup.ReleaseGroupTypeCount import ly.david.ui.common.R import ly.david.mbjc.ui.common.Tab import ly.david.ui.common.preview.DefaultPreviews import ly.david.ui.common.theme.PreviewTheme /** * Display all [stats] ordered/shown based on [tabs]. */ @Composable internal fun StatsScreen( tabs: List<Tab>, stats: Stats, modifier: Modifier = Modifier ) { LazyColumn(modifier = modifier) { tabs.forEach { tab -> when (tab) { Tab.EVENTS -> { addResourcesStatsSection( totalRemote = stats.totalRemoteEvents, totalLocal = stats.totalLocalEvents, headerRes = R.string.events, cachedLocalOfRemoteRes = R.string.cached_events ) } Tab.PLACES -> { addResourcesStatsSection( totalRemote = stats.totalRemotePlaces, totalLocal = stats.totalLocalPlaces, headerRes = R.string.places, cachedLocalOfRemoteRes = R.string.cached_places ) } Tab.RECORDINGS -> { addResourcesStatsSection( totalRemote = stats.totalRemoteRecordings, totalLocal = stats.totalLocalRecordings, headerRes = R.string.recordings, cachedLocalOfRemoteRes = R.string.cached_recordings ) } Tab.RELATIONSHIPS -> { addRelationshipsSection( totalRelations = stats.totalRelations, relationTypeCounts = stats.relationTypeCounts ) } Tab.RELEASES -> { addResourcesStatsSection( totalRemote = stats.totalRemoteReleases, totalLocal = stats.totalLocalReleases, headerRes = R.string.releases, cachedLocalOfRemoteRes = R.string.cached_releases ) } Tab.RELEASE_GROUPS -> { addReleaseGroupsSection( totalRemote = stats.totalRemoteReleaseGroups, totalLocal = stats.totalLocalReleaseGroups, releaseGroupTypeCounts = stats.releaseGroupTypeCounts ) } else -> { // No stats for these tabs yet. } } } } } // region Previews @DefaultPreviews @Composable private fun Preview() { PreviewTheme { Surface { StatsScreen( tabs = listOf(Tab.RELATIONSHIPS, Tab.RELEASE_GROUPS, Tab.RELEASES, Tab.PLACES), stats = Stats( totalRemoteReleaseGroups = 280, totalLocalReleaseGroups = 279, releaseGroupTypeCounts = listOf( ReleaseGroupTypeCount(primaryType = "Album", count = 13), ReleaseGroupTypeCount( primaryType = "Album", secondaryTypes = listOf("Compilation", "Demo"), count = 1 ), ), totalRelations = 696, relationTypeCounts = listOf( RelationTypeCount(linkedResource = MusicBrainzResource.ARTIST, count = 17), RelationTypeCount(linkedResource = MusicBrainzResource.RECORDING, count = 397), ), totalRemoteReleases = 20, totalLocalReleases = 15 ) ) } } } // endregion
54
null
0
4
052613fefaeb5a687ee36d0f3889d9a120224994
4,267
MusicSearch
Apache License 2.0
api_generator/tests/references/shared_data_kotlin/EntityWithRawArray.kt
divkit
523,491,444
false
{"Kotlin": 6844057, "Swift": 4512146, "TypeScript": 634790, "Dart": 552612, "Svelte": 478532, "Python": 461531, "Java": 378340, "JavaScript": 142322, "CSS": 35672, "HTML": 23068, "C++": 20911, "CMake": 18677, "Shell": 8952, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
// Generated code. Do not modify. package com.yandex.div2 import org.json.JSONObject class EntityWithRawArray( @JvmField final val array: Expression<JSONArray>, ) : Hashable { private var _hash: Int? = null override fun hash(): Int { _hash?.let { return it } val hash = array.hashCode() _hash = hash return hash } fun copy( array: Expression<JSONArray> = this.array, ) = EntityWithRawArray( array = array, ) companion object { const val TYPE = "entity_with_raw_array" } }
6
Kotlin
121
2,197
4675bf93c4a1cc34040537d16cd2777e2463a6bd
606
divkit
Apache License 2.0
app/src/main/java/com/aliernfrog/lactool/ui/component/ExpandableColumnRounded.kt
aliernfrog
344,576,839
false
null
package com.aliernfrog.lactool.ui.component import androidx.compose.animation.* import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.KeyboardArrowUp import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.aliernfrog.lactool.AppComponentShape import com.aliernfrog.lactool.util.extension.clickableWithColor @Composable fun ExpandableColumnRounded( title: String, description: String? = null, painter: Painter? = null, headerContainerColor: Color = MaterialTheme.colorScheme.primary, headerContentColor: Color = contentColorFor(headerContainerColor), containerColor: Color = MaterialTheme.colorScheme.surfaceVariant, expanded: Boolean, onExpandedChange: (expanded: Boolean) -> Unit, content: @Composable () -> Unit ) { val arrowAnimatedRotation by animateFloatAsState(if (expanded) 0f else 180f) Column( modifier = Modifier .fillMaxWidth() .padding(8.dp) .clip(AppComponentShape) .background(containerColor) ) { Row( modifier = Modifier .background(headerContainerColor) .clickableWithColor(headerContentColor) { onExpandedChange(!expanded) } .padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { if (painter != null) Icon( painter = painter, contentDescription = null, modifier = Modifier.padding(end = 4.dp).size(40.dp).padding(1.dp), tint = headerContentColor ) Column( modifier = Modifier.weight(1f) ) { Text( text = title, color = headerContentColor, fontWeight = FontWeight.Bold, fontSize = 16.sp ) if (description != null) Text( text = description, color = headerContentColor, modifier = Modifier.alpha(0.8f), fontSize = 14.sp, lineHeight = 18.sp ) } Icon( imageVector = Icons.Rounded.KeyboardArrowUp, contentDescription = null, modifier = Modifier.rotate(arrowAnimatedRotation), tint = headerContentColor ) } AnimatedVisibility( visible = expanded, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut() ) { Column { content() } } } }
3
Kotlin
0
0
51a78e60089f2bc22ffa89880e8f5819a651e839
3,427
lac-tool
MIT License
idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubConsistencyTest.kt
staltz
93,485,627
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.decompiler.textBuilder.buildDecompiledText import org.jetbrains.kotlin.idea.test.JetWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.load.kotlin.JvmVirtualFileFinder import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder import org.jetbrains.kotlin.name.FqName import kotlin.properties.Delegates public class ClsStubConsistencyTest : StubConsistencyBaseTest() { override fun getVirtualFileFinder(): VirtualFileFinder = JvmVirtualFileFinder.SERVICE.getInstance(getProject()) override fun getPackages(): List<FqName> = listOf(FqName("kotlin")) override fun createStubBuilder() = KotlinClsStubBuilder() override fun getDecompiledText(packageFile: VirtualFile): String = buildDecompiledText(packageFile).text override fun getProjectDescriptor() = JetWithJdkAndRuntimeLightProjectDescriptor.INSTANCE }
0
null
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
1,580
kotlin
Apache License 2.0
src/main/java/org/liangguo/breakingbad/entity/model/UndeadGusFringModel.kt
ldh-star
600,430,068
false
null
package org.liangguo.breakingbad.entity.model import net.minecraft.client.model.PlayerModel import net.minecraft.client.model.geom.ModelPart import net.minecraft.util.Mth import org.liangguo.breakingbad.entity.mobs.UndeadGusFring /** * @author ldh * 时间: 2023/2/7 13:31 * 邮箱: <EMAIL> */ class UndeadGusFringModel(part: ModelPart, private val slim: Boolean): PlayerModel<UndeadGusFring>(part, slim) { override fun setupAnim( mob: UndeadGusFring, p_103396_: Float, p_103397_: Float, p_103398_: Float, p_103399_: Float, p_103400_: Float ) { super.setupAnim(mob, p_103396_, p_103397_, p_103398_, p_103399_, p_103400_) if (mob.isSpellCasting) { rightArm.z = 0.0f rightArm.x = -5.0f leftArm.z = 0.0f leftArm.x = 5.0f rightArm.xRot = Mth.cos(p_103398_ * 0.6662f) * 0.25f leftArm.xRot = Mth.cos(p_103398_ * 0.6662f) * 0.25f rightArm.zRot = 2.3561945f leftArm.zRot = -2.3561945f rightArm.yRot = 0.0f leftArm.yRot = 0.0f } } }
0
Kotlin
0
0
dde7c4adf4990f205b23021c557d0509b83360f9
1,128
BreakingBad-Minecraft
MIT License
app/src/main/kotlin/com/importre/example/main/progress/ProgressModel.kt
importre
85,430,761
false
null
package com.importre.example.main.progress data class ProgressModel(val progress: Long = 0)
0
Kotlin
10
56
3b2e9f924bfa84066db7ad8fe1d19653ace1cda6
93
kotlin-maze
Apache License 2.0
HttpLogInterceptorExam/app/src/main/java/com/hans/android/httploginterceptorexam/data/city/CityEntity.kt
goldfing
256,676,960
false
null
package com.hans.android.httploginterceptorexam.data.city data class CityEntity(var title:String, var city: List<String>) { }
0
Kotlin
0
2
a792b90c587cf2cfe590dacd8645a83f31446ac4
128
AndroidProjects
MIT License
src/main/kotlin/software/amazon/smithy/intellij/psi/ext.kt
iancaffey
455,381,865
false
null
package software.amazon.smithy.intellij.psi import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocCommentBase import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.impl.FakePsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.PsiTreeUtil.getChildOfType import com.intellij.psi.util.PsiTreeUtil.getChildrenOfTypeAsList import com.intellij.psi.util.PsiTreeUtil.getParentOfType import com.intellij.psi.util.siblings import software.amazon.smithy.intellij.SmithyFile import software.amazon.smithy.intellij.SmithyIdReference import software.amazon.smithy.intellij.SmithyKeyReference import software.amazon.smithy.intellij.SmithyLanguage import software.amazon.smithy.intellij.SmithyMemberReference import software.amazon.smithy.intellij.SmithyReference import software.amazon.smithy.intellij.SmithyShapeAggregator.getDeclaration import software.amazon.smithy.intellij.SmithyShapeReference import software.amazon.smithy.intellij.SmithyShapeResolver.getNamespace import software.amazon.smithy.intellij.psi.impl.SmithyContainerShapeImpl import software.amazon.smithy.intellij.psi.impl.SmithyKeyedElementImpl import software.amazon.smithy.intellij.psi.impl.SmithyOperationPropertyImpl import software.amazon.smithy.intellij.psi.impl.SmithyPrimitiveImpl import software.amazon.smithy.intellij.psi.impl.SmithyShapeImpl import software.amazon.smithy.intellij.psi.impl.SmithyValueImpl import java.math.BigDecimal import java.math.BigInteger /** * A base [PsiElement] for all [SmithyElement] implementations. * * @author Ian Caffey * @since 1.0 */ open class SmithyPsiElement(node: ASTNode) : ASTWrapperPsiElement(node) { override fun toString(): String = name ?: text } interface SmithyElement : PsiElement interface SmithyContainer : SmithyElement interface SmithyNamedElement : SmithyElement, PsiNameIdentifierOwner { override fun getName(): String override fun getNameIdentifier(): PsiElement } abstract class SmithySyntheticElement : FakePsiElement(), SmithyElement { override fun getLanguage() = SmithyLanguage override fun getTextOffset() = parent?.node?.startOffset ?: 0 override fun getTextRange() = TextRange.from(textOffset, textLength) } interface SmithyStatement : SmithyElement { val type: String get() = typeIdentifier.text val typeIdentifier: PsiElement get() = firstChild } interface SmithyAppliedTraitExt : SmithyStatement { val memberId: SmithyMemberId? val shapeId: SmithyShapeId? val target: SmithyDefinition? val traits: List<SmithyTrait> } abstract class SmithyAppliedTraitMixin(node: ASTNode) : SmithyPsiElement(node), SmithyAppliedTrait { override val memberId: SmithyMemberId? get() = findChildByClass(SmithyMemberId::class.java) override val shapeId: SmithyShapeId? get() = findChildByClass(SmithyShapeId::class.java) override val target get() = memberId?.resolve() ?: shapeId?.resolve() override val traits: List<SmithyTrait> get() = getChildOfType(this, SmithyTrait::class.java)?.let { listOf(it) } ?: getChildOfType(this, SmithyAppliedTraitBody::class.java)?.traits ?: emptyList() } interface SmithyArrayExt : SmithyValue { override val reference: SmithyShapeReference } abstract class SmithyArrayMixin(node: ASTNode) : SmithyValueImpl(node), SmithyArray { override val type = SmithyValueType.ARRAY override val reference by lazy { SmithyShapeReference(this) } } interface SmithyBooleanExt : SmithyPrimitive { override val reference: SmithyShapeReference override fun asBoolean(): Boolean } abstract class SmithyBooleanMixin(node: ASTNode) : SmithyPrimitiveImpl(node), SmithyBoolean { override val type = SmithyValueType.BOOLEAN override val reference by lazy { SmithyShapeReference(this) } override fun asBoolean() = text.toBoolean() } interface SmithyContainerMemberExt : SmithyNamedElement, SmithyMemberDefinition { override val enclosingShape: SmithyShape override val declaredTarget: SmithyShapeId override val declaredTraits: List<SmithyTrait> } abstract class SmithyContainerMemberMixin(node: ASTNode) : SmithyPsiElement(node), SmithyContainerMember { private var _syntheticTraits: List<SmithyTraitDefinition>? = null override val enclosingShape: SmithyContainerShape get() = getParentOfType(this, SmithyContainerShape::class.java)!! override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: mutableListOf<SmithyTraitDefinition>().also { getChildOfType(this, SmithyDocumentation::class.java)?.let { docs -> it += SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(docs.toDocString()) ) } initializer?.value?.let { default -> it += SmithySyntheticTrait(this, "smithy.api", "default", default) } _syntheticTraits = it } override fun getName(): String = nameIdentifier.text override fun setName(newName: String) = setName<SmithyContainerMember>(this, newName) override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = resolvedTarget?.let { "$name: ${it.shapeName}" } ?: name override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } override fun subtreeChanged() { _syntheticTraits = null } } abstract class SmithyContainerShapeMixin(node: ASTNode) : SmithyShapeImpl(node), SmithyContainerShape { override val declaredMembers get() = body.members } interface SmithyControlExt : SmithyStatement abstract class SmithyControlMixin(node: ASTNode) : SmithyKeyedElementImpl(node), SmithyControl interface SmithyDocumentationExt : PsiDocCommentBase, SmithyElement { fun toDocString(): String } abstract class SmithyDocumentationMixin(node: ASTNode) : SmithyPsiElement(node), SmithyDocumentation { companion object { private val DOCUMENTATION_LINES = TokenSet.create(SmithyTypes.TOKEN_DOCUMENTATION_LINE) } override fun getOwner(): PsiElement = parent override fun getTokenType(): IElementType = SmithyTypes.DOCUMENTATION //see: https://awslabs.github.io/smithy/1.0/spec/core/idl.html#documentation-comment override fun toDocString() = node.getChildren(DOCUMENTATION_LINES).joinToString("\n") { node -> node.text.let { it.substring(if (it.length > 3 && it[3] == ' ') 4 else 3) } } } interface SmithyElidedMemberExt : SmithyNamedElement, SmithyMemberDefinition { val declaration: SmithyElidedMemberTarget? override val enclosingShape: SmithyShape override val declaredTraits: List<SmithyTrait> } abstract class SmithyElidedMemberMixin(node: ASTNode) : SmithyPsiElement(node), SmithyElidedMember { private var _syntheticTraits: List<SmithyTraitDefinition>? = null override val declaration get() = getDeclaration(this) override val enclosingShape: SmithyShape get() = getParentOfType(this, SmithyShape::class.java)!! override val declaredTarget: SmithyShapeTarget? = null override val resolvedTarget: SmithyShapeTarget? get() = declaration?.resolvedTarget override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: mutableListOf<SmithyTraitDefinition>().also { getChildOfType(this, SmithyDocumentation::class.java)?.let { docs -> it += SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(docs.toDocString()) ) } initializer?.value?.let { default -> it += SmithySyntheticTrait(this, "smithy.api", "default", default) } _syntheticTraits = it } override fun getName(): String = nameIdentifier.text override fun setName(newName: String) = setName<SmithyElidedMember>(this, newName) override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = resolvedTarget?.let { "$name: ${it.shapeName}" } ?: name override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } override fun subtreeChanged() { _syntheticTraits = null } } interface SmithyEntryExt : SmithyElement { fun resolve(): SmithyMemberDefinition? } abstract class SmithyEntryMixin(node: ASTNode) : SmithyKeyedElementImpl(node), SmithyEntry { override fun resolve() = key.reference.resolve() } abstract class SmithyEnumMixin(node: ASTNode) : SmithyShapeImpl(node), SmithyEnum { override val declaredMembers get() = body.members } interface SmithyEnumMemberExt : SmithyNamedElement, SmithyMemberDefinition { override val enclosingShape: SmithyEnum override val declaredTarget: SmithySyntheticShapeTarget override val resolvedTarget: SmithySyntheticShapeTarget override val declaredTraits: List<SmithyTrait> } abstract class SmithyEnumMemberMixin(node: ASTNode) : SmithyPsiElement(node), SmithyEnumMember { private var _syntheticTraits: List<SmithyTraitDefinition>? = null override val declaredTarget = SmithySyntheticShapeTarget(this, "smithy.api", "Unit", "string") override val resolvedTarget = declaredTarget override val enclosingShape: SmithyEnum get() = getParentOfType(this, SmithyEnum::class.java)!! override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: mutableListOf<SmithyTraitDefinition>().also { getChildOfType(this, SmithyDocumentation::class.java)?.let { docs -> it += SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(docs.toDocString()) ) } initializer?.value?.let { value -> it += SmithySyntheticTrait(this, "smithy.api", "enumValue", value) } _syntheticTraits = it } override fun getName(): String = nameIdentifier.text override fun setName(newName: String) = setName<SmithyEnumMember>(this, newName) override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = name override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } override fun subtreeChanged() { _syntheticTraits = null } } abstract class SmithyIdMixin(node: ASTNode) : SmithyPsiElement(node), SmithyId { val reference by lazy { SmithyIdReference(this) } } interface SmithyImportExt : SmithyStatement abstract class SmithyImportMixin(node: ASTNode) : SmithyPsiElement(node), SmithyImport interface SmithyIncompleteAppliedTraitExt : SmithyStatement abstract class SmithyIncompleteAppliedTraitMixin(node: ASTNode) : SmithyPsiElement(node), SmithyIncompleteAppliedTrait interface SmithyInputExt : SmithyContainerShape, SmithyShapeTarget { override val href: String get() = super<SmithyContainerShape>.href override val resource: SmithyShapeId? val operation: SmithyOperation } abstract class SmithyInputMixin(node: ASTNode) : SmithyContainerShapeImpl(node), SmithyInput { private var _syntheticTraits: List<SmithyTraitDefinition>? = null private val id = object : SmithySyntheticElement() { override fun getParent() = this@SmithyInputMixin override fun getTextOffset() = body.textOffset override fun getText() = "${operation.name}${(containingFile as? SmithyFile)?.model?.operationInputSuffix ?: "Input"}" } override val operation get() = getParentOfType(this, SmithyOperation::class.java)!! override val resource get() = resourceReference?.shapeId override val declaredNamespace = namespace override val resolvedNamespace = namespace override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: mutableListOf<SmithyTraitDefinition>().also { getChildOfType(this, SmithyDocumentation::class.java)?.let { docs -> it += SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(docs.toDocString()) ) } it += SmithySyntheticTrait(this, "smithy.api", "input") _syntheticTraits = it } override val typeIdentifier = object : SmithySyntheticElement() { override fun getParent() = this@SmithyInputMixin override fun getText() = "structure" } override fun getNameIdentifier() = id override fun resolve() = this override fun subtreeChanged() { _syntheticTraits = null } } abstract class SmithyIntEnumMixin(node: ASTNode) : SmithyShapeImpl(node), SmithyIntEnum { override val declaredMembers get() = body.members } interface SmithyIntEnumMemberExt : SmithyNamedElement, SmithyMemberDefinition { override val enclosingShape: SmithyIntEnum override val declaredTarget: SmithySyntheticShapeTarget override val resolvedTarget: SmithySyntheticShapeTarget override val declaredTraits: List<SmithyTrait> } abstract class SmithyIntEnumMemberMixin(node: ASTNode) : SmithyPsiElement(node), SmithyIntEnumMember { private var _syntheticTraits: List<SmithyTraitDefinition>? = null override val declaredTarget = SmithySyntheticShapeTarget(this, "smithy.api", "Unit", "integer") override val resolvedTarget = declaredTarget override val enclosingShape: SmithyIntEnum get() = getParentOfType(this, SmithyIntEnum::class.java)!! override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: mutableListOf<SmithyTraitDefinition>().also { getChildOfType(this, SmithyDocumentation::class.java)?.let { docs -> it += SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(docs.toDocString()) ) } initializer?.value?.let { value -> it += SmithySyntheticTrait(this, "smithy.api", "enumValue", value) } _syntheticTraits = it } override fun getName(): String = nameIdentifier.text override fun setName(newName: String) = setName<SmithyIntEnumMember>(this, newName) override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = name override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } override fun subtreeChanged() { _syntheticTraits = null } } interface SmithyKeyExt : SmithyElement { val reference: SmithyKeyReference fun stringValue(): String } abstract class SmithyKeyMixin(node: ASTNode) : SmithyPsiElement(node), SmithyKey { override val reference by lazy { SmithyKeyReference(this) } override fun stringValue(): String = id?.text ?: string?.asString() ?: text } interface SmithyKeyedElementExt : SmithyNamedElement { val nameIdentifier: SmithyKey } abstract class SmithyKeyedElementMixin(node: ASTNode) : SmithyPsiElement(node), SmithyKeyedElement { override val nameIdentifier get() = key override fun getName(): String = key.stringValue() override fun setName(newName: String) = setName<SmithyKeyedElement>(this, newName) override fun getTextOffset() = key.textOffset } abstract class SmithyListMixin(node: ASTNode) : SmithyContainerShapeImpl(node), SmithyList { override val requiredMembers = setOf("member") } abstract class SmithyMapMixin(node: ASTNode) : SmithyContainerShapeImpl(node), SmithyMap { override val requiredMembers = setOf("key", "value") } interface SmithyMemberBodyExt : SmithyElement { val members: List<SmithyMemberDefinition> } abstract class SmithyMemberBodyMixin(node: ASTNode) : SmithyPsiElement(node), SmithyMemberBodyExt { override val members: List<SmithyMemberDefinition> get() = getChildrenOfTypeAsList(this, SmithyMemberDefinition::class.java) } interface SmithyMemberIdExt : SmithyCharSequence { override val reference: SmithyMemberReference val memberName: String fun resolve() = reference.resolve() } abstract class SmithyMemberIdMixin(node: ASTNode) : SmithyPsiElement(node), SmithyMemberId { override val memberName: String get() = member.text override val reference by lazy { SmithyMemberReference(this) } override fun asString() = shapeId.asString()?.let { "$it$$memberName" } ?: memberName } interface SmithyMemberInitializerExt : SmithyElement { val enclosingMember: SmithyMemberDefinition } abstract class SmithyMemberInitializerMixin(node: ASTNode) : SmithyPsiElement(node), SmithyMemberInitializer { override val enclosingMember: SmithyMemberDefinition get() = parent as SmithyMemberDefinition } interface SmithyMetadataExt : SmithyStatement abstract class SmithyMetadataMixin(node: ASTNode) : SmithyKeyedElementImpl(node), SmithyMetadata interface SmithyMixinsExt : SmithyElement { val enclosingShape: SmithyShape } abstract class SmithyMixinsMixin(node: ASTNode) : SmithyPsiElement(node), SmithyMixins { override val enclosingShape: SmithyShape get() = parent as SmithyShape } interface SmithyModelExt : SmithyElement { val namespace: String? val version: String? val operationInputSuffix: String val operationOutputSuffix: String val control: List<SmithyControl> val metadata: List<SmithyMetadata> val shapes: List<SmithyShape> } abstract class SmithyModelMixin(node: ASTNode) : SmithyPsiElement(node), SmithyModel { override val namespace get() = getChildOfType(this, SmithyNamespace::class.java)?.namespaceId?.id override val version get() = control.firstNotNullOfOrNull { if (it.name == "version") it.value.asString() else null } override val operationInputSuffix get() = control.firstNotNullOfOrNull { if (it.name == "operationInputSuffix") it.value.asString() else null } ?: "Input" override val operationOutputSuffix get() = control.firstNotNullOfOrNull { if (it.name == "operationOutputSuffix") it.value.asString() else null } ?: "Output" override val control: List<SmithyControl> get() = getChildrenOfTypeAsList(this, SmithyControl::class.java) override val metadata: List<SmithyMetadata> get() = getChildrenOfTypeAsList(this, SmithyMetadata::class.java) override val shapes: List<SmithyShape> get() = mutableListOf<SmithyShape>().also { shapes -> firstChild?.siblings()?.forEach { if (it is SmithyShape) { shapes += it if (it is SmithyOperation) { it.input?.shape?.let { input -> shapes += input } it.output?.shape?.let { output -> shapes += output } } } } } } interface SmithyNamespaceExt : SmithyStatement abstract class SmithyNamespaceMixin(node: ASTNode) : SmithyPsiElement(node), SmithyNamespace interface SmithyNamespaceIdExt : SmithyElement { val id: String } abstract class SmithyNamespaceIdMixin(node: ASTNode) : SmithyPsiElement(node), SmithyNamespaceId { override val id = parts.joinToString(".") { it.text } override fun toString() = id } interface SmithyNullExt : SmithyPrimitive { override val reference: SmithyShapeReference } abstract class SmithyNullMixin(node: ASTNode) : SmithyPrimitiveImpl(node), SmithyNull { override val type = SmithyValueType.NULL override val reference by lazy { SmithyShapeReference(this) } } interface SmithyNumberExt : SmithyPrimitive { override val reference: SmithyShapeReference fun byteValue(): Byte = bigDecimalValue().byteValueExact() fun shortValue(): Short = bigDecimalValue().shortValueExact() fun intValue(): Int = bigDecimalValue().intValueExact() fun floatValue(): Float = bigDecimalValue().toFloat() fun doubleValue(): Double = bigDecimalValue().toDouble() fun longValue(): Long = bigDecimalValue().longValueExact() fun bigDecimalValue(): BigDecimal fun bigIntegerValue(): BigInteger = bigDecimalValue().toBigIntegerExact() } abstract class SmithyNumberMixin(node: ASTNode) : SmithyPrimitiveImpl(node), SmithyNumber { override val type = SmithyValueType.NUMBER override val reference by lazy { SmithyShapeReference(this) } override fun asNumber() = bigDecimalValue() override fun bigDecimalValue() = BigDecimal(text) } interface SmithyObjectExt : SmithyValue { override val reference: SmithyShapeReference } abstract class SmithyObjectMixin(node: ASTNode) : SmithyValueImpl(node), SmithyObject { private var parsed = false private var value: Map<String, SmithyValue> = emptyMap() override val type = SmithyValueType.OBJECT override val fields get() = if (parsed) value else entries.associate { it.name to it.value }.also { value = it parsed = true } override val reference by lazy { SmithyShapeReference(this) } override fun subtreeChanged() { parsed = false } } interface SmithyOperationExt : SmithyShape { override val input: SmithyOperationInput? override val output: SmithyOperationOutput? val errors: SmithyOperationErrors? } abstract class SmithyOperationMixin(node: ASTNode) : SmithyShapeImpl(node), SmithyOperation { override val input get() = body.properties.firstNotNullOfOrNull { it as? SmithyOperationInput } override val output get() = body.properties.firstNotNullOfOrNull { it as? SmithyOperationOutput } override val errors get() = body.properties.firstNotNullOfOrNull { it as? SmithyOperationErrors } } interface SmithyOperationPropertyExt : SmithyNamedElement { val enclosingShape: SmithyOperation } abstract class SmithyOperationPropertyMixin(node: ASTNode) : SmithyPsiElement(node), SmithyOperationProperty { override val enclosingShape: SmithyOperation get() = getParentOfType(this, SmithyOperation::class.java)!! override fun getName(): String = nameIdentifier.text override fun setName(newName: String): PsiElement? = null override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = name override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } } interface SmithyOperationErrorsExt : SmithyOperationPropertyExt abstract class SmithyOperationErrorsMixin(node: ASTNode) : SmithyOperationPropertyImpl(node), SmithyOperationErrors { override fun getNameIdentifier(): PsiElement = findChildByType(SmithyTypes.TOKEN_ERRORS)!! } interface SmithyOperationInputExt : SmithyOperationPropertyExt, SmithyShapeTarget { val target: SmithyShapeTarget } abstract class SmithyOperationInputMixin(node: ASTNode) : SmithyOperationPropertyImpl(node), SmithyOperationInput { override val target: SmithyShapeTarget get() = shapeId ?: shape!! override val href get() = target.href override val shapeName get() = target.shapeName override val declaredNamespace get() = target.declaredNamespace override val resolvedNamespace get() = target.resolvedNamespace override fun getNameIdentifier(): PsiElement = findChildByType(SmithyTypes.TOKEN_INPUT)!! override fun resolve() = target.resolve() } interface SmithyOperationOutputExt : SmithyOperationPropertyExt, SmithyShapeTarget { val target: SmithyShapeTarget } abstract class SmithyOperationOutputMixin(node: ASTNode) : SmithyOperationPropertyImpl(node), SmithyOperationOutput { override val target: SmithyShapeTarget get() = shapeId ?: shape!! override val href get() = target.href override val shapeName get() = target.shapeName override val declaredNamespace get() = target.declaredNamespace override val resolvedNamespace get() = target.resolvedNamespace override fun getNameIdentifier(): PsiElement = findChildByType(SmithyTypes.TOKEN_OUTPUT)!! override fun resolve() = target.resolve() } interface SmithyOutputExt : SmithyContainerShape, SmithyShapeTarget { override val href: String get() = super<SmithyContainerShape>.href override val resource: SmithyShapeId? val operation: SmithyOperation } abstract class SmithyOutputMixin(node: ASTNode) : SmithyContainerShapeImpl(node), SmithyOutput { private var _syntheticTraits: List<SmithyTraitDefinition>? = null private val id = object : SmithySyntheticElement() { override fun getParent() = this@SmithyOutputMixin override fun getTextOffset() = body.textOffset override fun getText() = "${operation.name}${(containingFile as? SmithyFile)?.model?.operationOutputSuffix ?: "Output"}" } override val operation get() = getParentOfType(this, SmithyOperation::class.java)!! override val resource get() = resourceReference?.shapeId override val declaredNamespace = namespace override val resolvedNamespace = namespace override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: mutableListOf<SmithyTraitDefinition>().also { getChildOfType(this, SmithyDocumentation::class.java)?.let { docs -> it += SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(docs.toDocString()) ) } it += SmithySyntheticTrait(this, "smithy.api", "output") _syntheticTraits = it } override val typeIdentifier = object : SmithySyntheticElement() { override fun getParent() = this@SmithyOutputMixin override fun getText() = "structure" } override fun getNameIdentifier() = id override fun resolve() = this override fun subtreeChanged() { _syntheticTraits = null } } interface SmithyResourceExt : SmithyShape { override val identifiers: List<SmithyResourceIdentifier> val create: SmithyShapeId? val put: SmithyShapeId? val read: SmithyShapeId? val update: SmithyShapeId? val delete: SmithyShapeId? val list: SmithyShapeId? val operations: List<SmithyShapeId> val collectionOperations: List<SmithyShapeId> val resources: List<SmithyShapeId> } abstract class SmithyResourceMixin(node: ASTNode) : SmithyShapeImpl(node), SmithyResource { override val identifiers: List<SmithyResourceIdentifier> get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceIdentifiers }?.identifiers ?: emptyList() override val properties: List<SmithyResourceProperty> get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceProperties }?.properties ?: emptyList() override val create: SmithyShapeId? get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceCreateOperation }?.shapeId override val put: SmithyShapeId? get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourcePutOperation }?.shapeId override val read: SmithyShapeId? get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceReadOperation }?.shapeId override val update: SmithyShapeId? get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceUpdateOperation }?.shapeId override val delete: SmithyShapeId? get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceDeleteOperation }?.shapeId override val list: SmithyShapeId? get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceListOperation }?.shapeId override val operations: List<SmithyShapeId> get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceOperations }?.shapes ?: emptyList() override val collectionOperations: List<SmithyShapeId> get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceCollectionOperations }?.shapes ?: emptyList() override val resources: List<SmithyShapeId> get() = body.entries.firstNotNullOfOrNull { it as? SmithyResourceResources }?.shapes ?: emptyList() } interface SmithyResourceEntryExt : SmithyElement { val enclosingResource: SmithyResource } abstract class SmithyResourceEntryMixin(node: ASTNode) : SmithyPsiElement(node), SmithyResourceEntry { override val enclosingResource: SmithyResource get() = parent.parent as SmithyResource } interface SmithyResourceIdentifierExt : SmithyResourceIdentifierDefinition { override val enclosingShape: SmithyResource } abstract class SmithyResourceIdentifierMixin(node: ASTNode) : SmithyPsiElement(node), SmithyResourceIdentifier { override val enclosingShape: SmithyResource get() = (parent as SmithyResourceIdentifiers).enclosingResource override val resolvedTarget: SmithyShapeId get() = declaredTarget override fun getName(): String = nameIdentifier.text override fun setName(newName: String) = setName<SmithyResourceIdentifier>(this, newName) override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = "$name: ${resolvedTarget.shapeName}" override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } } interface SmithyResourcePropertyExt : SmithyResourcePropertyDefinition { override val enclosingShape: SmithyResource } abstract class SmithyResourcePropertyMixin(node: ASTNode) : SmithyPsiElement(node), SmithyResourceProperty { override val enclosingShape: SmithyResource get() = (parent as SmithyResourceProperties).enclosingResource override val resolvedTarget: SmithyShapeId get() = declaredTarget override fun getName(): String = nameIdentifier.text override fun setName(newName: String) = setName<SmithyResourceProperty>(this, newName) override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = "$name: ${resolvedTarget.shapeName}" override fun getLocationString() = enclosingShape.shapeName override fun getIcon(unused: Boolean) = getIcon(0) } } abstract class SmithyServiceMixin(node: ASTNode) : SmithyShapeImpl(node), SmithyService abstract class SmithySetMixin(node: ASTNode) : SmithyContainerShapeImpl(node), SmithySet { override val requiredMembers = setOf("member") } interface SmithyShapeExt : SmithyNamedElement, SmithyShapeDefinition, SmithyStatement { override val type get() = super.type override val declaredTraits: List<SmithyTrait> override val mixins: List<SmithyShapeId> val model: SmithyModel val requiredMembers: Set<String> get() = emptySet() val supportedMembers: Set<String>? get() = requiredMembers.takeIf { it.isNotEmpty() } } abstract class SmithyShapeMixin(node: ASTNode) : SmithyPsiElement(node), SmithyShape { private var _syntheticTraits: List<SmithyTraitDefinition>? = null override val typeIdentifier get() = nameIdentifier.siblings(forward = false, withSelf = false).first { it !is PsiWhiteSpace && it !is PsiComment } override val namespace get() = model.namespace!! override val shapeName: String get() = nameIdentifier.text override val shapeId get() = "$namespace#$shapeName" override val model get() = (containingFile as? SmithyFile)?.model!! override val mixins: List<SmithyShapeId> get() = getChildOfType(this, SmithyMixins::class.java)?.shapes ?: emptyList() override val declaredMembers get(): List<@JvmWildcard SmithyMemberDefinition> = emptyList<SmithyMemberDefinition>() override val declaredTraits: List<SmithyTrait> get() = getChildrenOfTypeAsList(this, SmithyTrait::class.java) override val syntheticTraits: List<SmithyTraitDefinition> get() = _syntheticTraits ?: (getChildOfType(this, SmithyDocumentation::class.java)?.let { listOf( SmithySyntheticTrait( this, "smithy.api", "documentation", SmithySyntheticValue.String(it.toDocString()) ) ) } ?: emptyList()).also { _syntheticTraits = it } override fun getMember(name: String): SmithyMemberDefinition? = members.find { it.name == name } override fun getName() = shapeName override fun setName(newName: String) = setName<SmithyShape>(this, newName) override fun getNameIdentifier(): PsiElement = getChildOfType(this, SmithyShapeName::class.java)!! override fun getTextOffset() = nameIdentifier.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = shapeName override fun getLocationString(): String = namespace override fun getIcon(unused: Boolean) = getIcon(0) } override fun subtreeChanged() { _syntheticTraits = null } } interface SmithyShapeIdExt : SmithyCharSequence, SmithyShapeTarget, PsiNamedElement { override val reference: SmithyShapeReference val enclosingNamespace: String? } abstract class SmithyShapeIdMixin(node: ASTNode) : SmithyPrimitiveImpl(node), SmithyShapeId { override val reference by lazy { SmithyShapeReference(this) } override val shapeName: String get() = id.text override val declaredNamespace get() = namespaceId?.id override val enclosingNamespace get() = (containingFile as SmithyFile).model?.namespace override val resolvedNamespace: String? get() = declaredNamespace ?: getNamespace(this, shapeName) override fun asString() = resolvedNamespace?.let { "$it#$shapeName" } ?: shapeName override fun getName() = shapeName override fun setName(newName: String) = setName<SmithyShapeId>(this, id, newName) override fun getTextOffset() = id.textOffset override fun resolve() = reference.resolve() } private fun parseInnerText(text: String, start: Int = 0, end: Int = text.length - start): String? = buildString { var i = start val lastIndex = end.takeIf { it >= i } ?: return null while (i < lastIndex) { val n = i + 1 val c = text[i] if (c == '\r') { append('\n').also { i += if (n < lastIndex && text[n] == '\n') 2 else 1 } } else if (c != '\\') { append(c).also { i++ } } else if (i == lastIndex - 1) { return null //invalid string (closing quote is escaped) } else when (text[n]) { '\n' -> i += 2 //escaped new-line expands to nothing '\r' -> i += if (n < lastIndex - 1 && text[n + 1] == '\n') 3 else 2 //escaped new-line expands to nothing '"' -> append('"').also { i += 2 } '\\' -> append('\\').also { i += 2 } '/' -> append('/').also { i += 2 } 'b' -> append('\b').also { i += 2 } 'f' -> append('\u000c').also { i += 2 } 'n' -> append('\n').also { i += 2 } 'r' -> append('\r').also { i += 2 } 't' -> append('\t').also { i += 2 } 'u' -> { if (n >= lastIndex - 4) return null //invalid string (less than 4 digits in the unicode escape sequence) var unicode = 0 (1..4).forEach { unicode = when (val u = text[n + it]) { in '0'..'9' -> (unicode shl 4) or (u - '0') in 'a'..'f' -> (unicode shl 4) or (10 + (u - 'a')) in 'A'..'F' -> (unicode shl 4) or (10 + (u - 'A')) else -> return null //invalid string (non-digit in unicode escape sequence) } } append(unicode.toChar()).also { i += 6 } } else -> return null //invalid string (unknown escape sequence) } } } interface SmithyCharSequence : SmithyPrimitive { override val type get() = SmithyValueType.STRING val valid: Boolean get() = asString() != null } interface SmithyStringExt : SmithyCharSequence { override val reference: SmithyShapeReference } abstract class SmithyStringMixin(node: ASTNode) : SmithyPrimitiveImpl(node), SmithyString { private var parsed = false private var value: String? = null override fun asString(): String? = if (parsed) value else parseInnerText(text, 1).also { value = it parsed = true } override val reference by lazy { SmithyShapeReference(this) } override fun subtreeChanged() { parsed = false } } interface SmithyTextBlockExt : SmithyCharSequence { override val reference: SmithyShapeReference } abstract class SmithyTextBlockMixin(node: ASTNode) : SmithyPrimitiveImpl(node), SmithyTextBlock { private var parsed = false private var value: String? = null override fun asString(): String? = if (parsed) value else text.let { text -> val normalized = if ('\r' in text) text.replace("\r\n", "\n") else text if (normalized.length < 7) return@let null val lines = normalized.substring(4, normalized.length - 3).split('\n') val leadingSpaces = lines.filterIndexed { i, line -> i == lines.lastIndex || line.any { it != ' ' } }.minOfOrNull { line -> line.indexOfFirst { it != ' ' }.takeIf { it != -1 } ?: line.length } ?: 0 val trimmed = lines.joinToString("\n") { line -> line.let { if (line.length < leadingSpaces) line else line.substring(leadingSpaces) }.trimEnd(' ') } parseInnerText(trimmed) }.also { value = it parsed = true } override val reference by lazy { SmithyShapeReference(this) } override fun subtreeChanged() { parsed = false } } interface SmithyStructureExt : SmithyContainerShape { override val resource: SmithyShapeId? } abstract class SmithyStructureMixin(node: ASTNode) : SmithyContainerShapeImpl(node), SmithyStructure { override val resource get() = resourceReference?.shapeId } interface SmithyTraitExt : SmithyTraitDefinition { val target: SmithyDefinition? } abstract class SmithyTraitMixin(node: ASTNode) : SmithyPsiElement(node), SmithyTrait { private var parsed = false private var _value: SmithyValueDefinition = SmithySyntheticValue.Object().also { it.scope(this) } override val value: SmithyValueDefinition get() = if (parsed) _value else when (val body = body) { null -> SmithySyntheticValue.Object().also { it.scope(this) } else -> body.value ?: object : SmithySyntheticElement(), SmithyValueDefinition { override val type = SmithyValueType.OBJECT override val fields = body.entries.associate { it.name to it.value } override fun getParent() = this@SmithyTraitMixin } }.also { _value = it parsed = true } override val shapeName get() = shape.shapeName override val declaredNamespace get() = shape.declaredNamespace override val resolvedNamespace get() = shape.resolvedNamespace override val target: SmithyDefinition? get() = when (val parent = parent) { is SmithyAppliedTrait -> parent.target is SmithyAppliedTraitBody -> (parent.parent as? SmithyAppliedTrait)?.target is SmithyDefinition -> parent else -> null } override fun getName() = shapeName override fun setName(newName: String) = also { shape.setName(newName) } override fun getTextOffset() = shape.textOffset override fun getPresentation() = object : ItemPresentation { override fun getPresentableText(): String = shapeName override fun getLocationString() = parent.let { if (it is SmithyDefinition) it.name else containingFile.name } override fun getIcon(unused: Boolean) = getIcon(0) } override fun subtreeChanged() { parsed = false } } interface SmithyValueExt : SmithyElement, SmithyValueDefinition { val reference: SmithyReference } abstract class SmithyValueMixin(node: ASTNode) : SmithyPsiElement(node), SmithyValue { override val reference by lazy { SmithyShapeReference(this) } } private fun <T : SmithyNamedElement> setName(element: T, newName: String?): T { return setName(element, element.nameIdentifier, newName) } private fun <T : PsiNamedElement> setName(element: T, nameIdentifier: PsiElement, newName: String?): T { val textRange = nameIdentifier.textRange val document = FileDocumentManager.getInstance().getDocument(element.containingFile.virtualFile) document!!.replaceString(textRange.startOffset, textRange.endOffset, newName!!) PsiDocumentManager.getInstance(element.project).commitDocument(document) return element }
1
Kotlin
1
20
afe9cc9da3308d211cfa3fefb3c8c2a25eb9f85c
42,228
smithy-intellij-plugin
MIT License
src/commonTest/kotlin/fr/acinq/lightning/channel/states/WaitForFundingConfirmedTestsCommon.kt
ACINQ
243,326,972
false
null
package fr.acinq.lightning.channel.states import fr.acinq.bitcoin.* import fr.acinq.lightning.Feature import fr.acinq.lightning.Features import fr.acinq.lightning.Lightning.randomBytes32 import fr.acinq.lightning.Lightning.randomKey import fr.acinq.lightning.MilliSatoshi import fr.acinq.lightning.blockchain.* import fr.acinq.lightning.blockchain.electrum.UnspentItem import fr.acinq.lightning.blockchain.electrum.WalletState import fr.acinq.lightning.blockchain.fee.FeeratePerKw import fr.acinq.lightning.channel.* import fr.acinq.lightning.tests.TestConstants import fr.acinq.lightning.tests.utils.LightningTestSuite import fr.acinq.lightning.utils.msat import fr.acinq.lightning.utils.sat import fr.acinq.lightning.wire.* import kotlin.test.* class WaitForFundingConfirmedTestsCommon : LightningTestSuite() { @Test fun `recv TxSignatures -- duplicate`() { val (alice, bob, _) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (alice1, actionsAlice1) = alice.process(ChannelCommand.MessageReceived(bob.state.latestFundingTx.sharedTx.localSigs)) assertIs<WaitForFundingConfirmed>(alice1.state) assertEquals(alice1.state.rbfStatus, RbfStatus.RbfAborted) assertEquals(actionsAlice1.size, 1) actionsAlice1.hasOutgoingMessage<TxAbort>() } @Test fun `recv BITCOIN_FUNDING_DEPTHOK`() { val (alice, bob, fundingTx) = init(ChannelType.SupportedChannelType.AnchorOutputs) run { val (alice1, actionsAlice1) = alice.process(ChannelCommand.WatchReceived(WatchEventConfirmed(alice.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx))) assertIs<WaitForChannelReady>(alice1.state) assertEquals(3, actionsAlice1.size) actionsAlice1.hasOutgoingMessage<ChannelReady>() actionsAlice1.has<ChannelAction.Storage.StoreState>() val watch = actionsAlice1.hasWatch<WatchSpent>() assertEquals(watch.event, BITCOIN_FUNDING_SPENT) assertEquals(watch.txId, fundingTx.txid) assertEquals(watch.outputIndex.toLong(), alice.state.commitments.latest.commitInput.outPoint.index) } run { val (bob1, actionsBob1) = bob.process(ChannelCommand.WatchReceived(WatchEventConfirmed(bob.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx))) assertIs<WaitForChannelReady>(bob1.state) assertEquals(3, actionsBob1.size) actionsBob1.hasOutgoingMessage<ChannelReady>() actionsBob1.has<ChannelAction.Storage.StoreState>() val watch = actionsBob1.hasWatch<WatchSpent>() assertEquals(watch.event, BITCOIN_FUNDING_SPENT) assertEquals(watch.txId, fundingTx.txid) assertEquals(watch.outputIndex.toLong(), bob.state.commitments.latest.commitInput.outPoint.index) } } @Test fun `recv BITCOIN_FUNDING_DEPTHOK -- rbf in progress`() { val (alice, bob, fundingTx) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (bob1, actionsBob1) = bob.process(ChannelCommand.MessageReceived(TxInitRbf(alice.state.channelId, 0, FeeratePerKw(6000.sat), TestConstants.aliceFundingAmount))) assertIs<WaitForFundingConfirmed>(bob1.state) assertIs<RbfStatus.InProgress>(bob1.state.rbfStatus) assertEquals(actionsBob1.size, 1) actionsBob1.hasOutgoingMessage<TxAckRbf>() // The funding transaction confirms while the RBF attempt is in progress. val (bob2, actionsBob2) = bob1.process(ChannelCommand.WatchReceived(WatchEventConfirmed(bob.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx))) assertIs<WaitForChannelReady>(bob2.state) val watch = actionsBob2.hasWatch<WatchSpent>() assertEquals(watch.event, BITCOIN_FUNDING_SPENT) assertEquals(watch.txId, fundingTx.txid) assertEquals(watch.outputIndex.toLong(), bob.state.commitments.latest.commitInput.outPoint.index) } @Test fun `recv BITCOIN_FUNDING_DEPTHOK -- previous funding tx`() { val (alice, bob, previousFundingTx, walletAlice) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (alice1, bob1, fundingTx) = rbf(alice, bob, walletAlice) assertNotEquals(previousFundingTx.txid, fundingTx.txid) run { val (bob2, actionsBob2) = bob1.process(ChannelCommand.WatchReceived(WatchEventConfirmed(bob.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, previousFundingTx))) assertIs<WaitForChannelReady>(bob2.state) assertEquals(1, bob2.commitments.active.size) assertEquals(previousFundingTx.txid, bob2.commitments.latest.fundingTxId) assertIs<LocalFundingStatus.ConfirmedFundingTx>(bob2.commitments.latest.localFundingStatus) val watch = actionsBob2.hasWatch<WatchSpent>() assertEquals(watch.event, BITCOIN_FUNDING_SPENT) assertEquals(watch.txId, previousFundingTx.txid) assertEquals(watch.outputIndex.toLong(), bob.state.commitments.latest.commitInput.outPoint.index) } run { val (alice2, actionsAlice2) = alice1.process(ChannelCommand.WatchReceived(WatchEventConfirmed(alice.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, previousFundingTx))) assertIs<WaitForChannelReady>(alice2.state) assertEquals(1, alice2.commitments.active.size) assertEquals(previousFundingTx.txid, alice2.commitments.latest.fundingTxId) assertIs<LocalFundingStatus.ConfirmedFundingTx>(alice2.commitments.latest.localFundingStatus) val watch = actionsAlice2.hasWatch<WatchSpent>() assertEquals(watch.event, BITCOIN_FUNDING_SPENT) assertEquals(watch.txId, previousFundingTx.txid) assertEquals(watch.outputIndex.toLong(), bob.state.commitments.latest.commitInput.outPoint.index) } } @Test fun `recv BITCOIN_FUNDING_DEPTHOK -- after restart`() { val (alice, bob, fundingTx) = init(ChannelType.SupportedChannelType.AnchorOutputs) run { val (alice1, _) = LNChannel(alice.ctx, WaitForInit).process(ChannelCommand.Restore(alice.state)) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(actions.size, 2) actions.hasPublishTx(fundingTx) assertEquals(actions.findWatch<WatchConfirmed>().txId, fundingTx.txid) } val (_, _) = alice1.process(ChannelCommand.WatchReceived(WatchEventConfirmed(alice.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx))) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(actions.size, 2) actions.hasWatchFundingSpent(fundingTx.txid) actions.has<ChannelAction.Storage.StoreState>() } } run { val (bob1, _) = LNChannel(bob.ctx, WaitForInit).process(ChannelCommand.Restore(bob.state)) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(actions.size, 2) actions.hasPublishTx(fundingTx) assertEquals(actions.findWatch<WatchConfirmed>().txId, fundingTx.txid) } val (_, _) = bob1.process(ChannelCommand.WatchReceived(WatchEventConfirmed(bob.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx))) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(actions.size, 2) actions.hasWatchFundingSpent(fundingTx.txid) actions.has<ChannelAction.Storage.StoreState>() } } } @Test fun `recv BITCOIN_FUNDING_DEPTHOK -- after restart -- previous funding tx`() { val (alice, bob, fundingTx1, walletAlice) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (alice1, bob1, fundingTx2) = rbf(alice, bob, walletAlice) run { val (alice2, _) = LNChannel(alice.ctx, WaitForInit).process(ChannelCommand.Restore(alice1.state)) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(actions.size, 4) actions.hasPublishTx(fundingTx1) actions.hasPublishTx(fundingTx2) assertEquals(actions.findWatches<WatchConfirmed>().map { it.txId }.toSet(), setOf(fundingTx1.txid, fundingTx2.txid)) } val (_, _) = alice2.process(ChannelCommand.WatchReceived(WatchEventConfirmed(alice.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx1))) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(state.commitments.active.size, 1) assertTrue(state.commitments.inactive.isEmpty()) assertEquals(state.commitments.latest.fundingTxId, fundingTx1.txid) assertEquals(actions.size, 2) actions.hasWatchFundingSpent(fundingTx1.txid) actions.has<ChannelAction.Storage.StoreState>() } } run { val (bob2, _) = LNChannel(bob.ctx, WaitForInit).process(ChannelCommand.Restore(bob1.state)) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(actions.size, 4) actions.hasPublishTx(fundingTx1) actions.hasPublishTx(fundingTx2) assertEquals(actions.findWatches<WatchConfirmed>().map { it.txId }.toSet(), setOf(fundingTx1.txid, fundingTx2.txid)) } val (_, _) = bob2.process(ChannelCommand.WatchReceived(WatchEventConfirmed(bob.state.channelId, BITCOIN_FUNDING_DEPTHOK, 42, 0, fundingTx1))) .also { (state, actions) -> assertIs<Offline>(state.state) assertEquals(state.commitments.active.size, 1) assertTrue(state.commitments.inactive.isEmpty()) assertEquals(state.commitments.latest.fundingTxId, fundingTx1.txid) assertEquals(actions.size, 2) actions.hasWatchFundingSpent(fundingTx1.txid) actions.has<ChannelAction.Storage.StoreState>() } } } @Test fun `recv TxInitRbf`() { val (alice, bob, _, walletAlice) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (alice1, bob1) = rbf(alice, bob, walletAlice) assertEquals(alice1.state.previousFundingTxs.size, 1) assertEquals(bob1.state.previousFundingTxs.size, 1) assertTrue(alice1.state.commitments.latest.fundingTxId != alice.state.commitments.latest.fundingTxId) assertTrue(bob1.state.commitments.latest.fundingTxId != bob.state.commitments.latest.fundingTxId) assertEquals(alice1.state.commitments.latest.fundingTxId, bob1.state.commitments.latest.fundingTxId) } @Test fun `recv TxInitRbf -- invalid feerate`() { val (alice, bob, _) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (bob1, actions1) = bob.process(ChannelCommand.MessageReceived(TxInitRbf(alice.state.channelId, 0, TestConstants.feeratePerKw, alice.state.latestFundingTx.fundingParams.localContribution))) assertEquals(actions1.size, 1) assertEquals(actions1.hasOutgoingMessage<TxAbort>().toAscii(), InvalidRbfFeerate(alice.state.channelId, TestConstants.feeratePerKw, TestConstants.feeratePerKw * 25 / 24).message) val (bob2, actions2) = bob1.process(ChannelCommand.MessageReceived(TxAbort(alice.state.channelId, "acking tx_abort"))) assertEquals(bob2, bob) assertTrue(actions2.isEmpty()) } @Test fun `recv TxInitRbf -- invalid push amount`() { val (alice, bob, _) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (bob1, actions1) = bob.process(ChannelCommand.MessageReceived(TxInitRbf(alice.state.channelId, 0, TestConstants.feeratePerKw * 1.25, TestConstants.alicePushAmount.truncateToSatoshi() - 1.sat))) assertEquals(actions1.size, 1) assertEquals(actions1.hasOutgoingMessage<TxAbort>().toAscii(), InvalidPushAmount(alice.state.channelId, TestConstants.alicePushAmount, TestConstants.alicePushAmount - 1000.msat).message) val (bob2, actions2) = bob1.process(ChannelCommand.MessageReceived(TxAbort(alice.state.channelId, "acking tx_abort"))) assertEquals(bob2, bob) assertTrue(actions2.isEmpty()) } @Test fun `recv TxInitRbf -- failed rbf attempt`() { val (alice, bob, _) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (bob1, actions1) = bob.process(ChannelCommand.MessageReceived(TxInitRbf(alice.state.channelId, 0, TestConstants.feeratePerKw * 1.25, alice.state.latestFundingTx.fundingParams.localContribution))) assertIs<WaitForFundingConfirmed>(bob1.state) assertIs<RbfStatus.InProgress>(bob1.state.rbfStatus) assertEquals(actions1.size, 1) actions1.hasOutgoingMessage<TxAckRbf>() val txAddInput = alice.state.latestFundingTx.sharedTx.tx.localInputs.first().run { TxAddInput(alice.channelId, serialId, previousTx, previousTxOutput, sequence) } val (bob2, actions2) = bob1.process(ChannelCommand.MessageReceived(txAddInput)) assertEquals(actions2.size, 1) actions2.hasOutgoingMessage<TxAddInput>() val (bob3, actions3) = bob2.process(ChannelCommand.MessageReceived(TxAbort(alice.state.channelId, "changed my mind"))) assertIs<WaitForFundingConfirmed>(bob3.state) assertEquals(bob3.state.rbfStatus, RbfStatus.None) assertEquals(actions3.size, 1) actions3.hasOutgoingMessage<TxAbort>() } @Test fun `recv ChannelReady`() { val (alice, bob, _) = init(ChannelType.SupportedChannelType.AnchorOutputs) val channelReadyAlice = ChannelReady(alice.state.channelId, randomKey().publicKey()) val channelReadyBob = ChannelReady(bob.state.channelId, randomKey().publicKey()) val (alice1, actionsAlice1) = alice.process(ChannelCommand.MessageReceived(channelReadyBob)) assertIs<WaitForFundingConfirmed>(alice1.state) assertEquals(alice1.state.deferred, channelReadyBob) assertTrue(actionsAlice1.isEmpty()) val (bob1, actionsBob1) = bob.process(ChannelCommand.MessageReceived(channelReadyAlice)) assertIs<WaitForFundingConfirmed>(bob1.state) assertEquals(bob1.state.deferred, channelReadyAlice) assertTrue(actionsBob1.isEmpty()) } @Test fun `recv ChannelReady -- no remote contribution`() { val (alice, bob, _) = init(ChannelType.SupportedChannelType.AnchorOutputs, bobFundingAmount = 0.sat, alicePushAmount = 0.msat) val channelReadyAlice = ChannelReady(alice.state.channelId, randomKey().publicKey()) val channelReadyBob = ChannelReady(bob.state.channelId, randomKey().publicKey()) val (alice1, actionsAlice1) = alice.process(ChannelCommand.MessageReceived(channelReadyBob)) assertIs<WaitForFundingConfirmed>(alice1.state) assertEquals(alice1.state.deferred, channelReadyBob) assertTrue(actionsAlice1.isEmpty()) val (bob1, actionsBob1) = bob.process(ChannelCommand.MessageReceived(channelReadyAlice)) assertIs<WaitForFundingConfirmed>(bob1.state) assertEquals(bob1.state.deferred, channelReadyAlice) assertTrue(actionsBob1.isEmpty()) } @Test fun `recv Error`() { val (_, bob) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (bob1, actions1) = bob.process(ChannelCommand.MessageReceived(Error(bob.state.channelId, "oops"))) assertIs<Closing>(bob1.state) assertNotNull(bob1.state.localCommitPublished) actions1.hasPublishTx(bob.state.commitments.latest.localCommit.publishableTxs.commitTx.tx) assertEquals(2, actions1.findWatches<WatchConfirmed>().size) // commit tx + main output } @Test fun `recv Error -- previous funding tx confirms`() { val (alice, bob, previousFundingTx, walletAlice) = init(ChannelType.SupportedChannelType.AnchorOutputs) val commitTxAlice1 = alice.state.commitments.latest.localCommit.publishableTxs.commitTx.tx val commitTxBob1 = bob.state.commitments.latest.localCommit.publishableTxs.commitTx.tx val (alice1, bob1, fundingTx) = rbf(alice, bob, walletAlice) val commitTxAlice2 = alice1.state.commitments.latest.localCommit.publishableTxs.commitTx.tx val commitTxBob2 = bob1.state.commitments.latest.localCommit.publishableTxs.commitTx.tx assertNotEquals(previousFundingTx.txid, fundingTx.txid) assertNotEquals(commitTxAlice1.txid, commitTxAlice2.txid) assertNotEquals(commitTxBob1.txid, commitTxBob2.txid) run { // Bob receives an error and publishes his latest commitment. val (bob2, actions2) = bob1.process(ChannelCommand.MessageReceived(Error(bob.state.channelId, "oops"))) assertIs<Closing>(bob2.state) assertTrue(bob2.commitments.active.size > 1) actions2.hasPublishTx(commitTxBob2) val lcp1 = bob2.state.localCommitPublished assertNotNull(lcp1) assertTrue(lcp1.commitTx.txIn.map { it.outPoint.txid }.contains(fundingTx.txid)) // A previous funding transaction confirms, so Bob publishes the corresponding commit tx. val (bob3, actions3) = bob2.process(ChannelCommand.WatchReceived(WatchEventConfirmed(bob.state.channelId, BITCOIN_FUNDING_DEPTHOK, 50, 0, previousFundingTx))) assertIs<Closing>(bob3.state) assertEquals(bob3.state.commitments.active.size, 1) actions3.hasPublishTx(commitTxBob1) val lcp2 = bob3.state.localCommitPublished assertNotNull(lcp2) assertTrue(lcp2.commitTx.txIn.map { it.outPoint.txid }.contains(previousFundingTx.txid)) // Alice publishes her commit tx, Bob reacts by spending his remote main output. val (bob4, actions4) = bob3.process(ChannelCommand.WatchReceived(WatchEventSpent(bob.state.channelId, BITCOIN_FUNDING_SPENT, commitTxAlice1))) assertIs<Closing>(bob4.state) assertNotNull(bob4.state.localCommitPublished) assertNotNull(bob4.state.remoteCommitPublished) val claimMain = actions4.findPublishTxs().first() assertEquals(claimMain.txIn.first().outPoint.txid, commitTxAlice1.txid) } run { // Alice receives an error and publishes her latest commitment. val (alice2, actions2) = alice1.process(ChannelCommand.MessageReceived(Error(alice.state.channelId, "oops"))) assertIs<Closing>(alice2.state) assertTrue(alice2.commitments.active.size > 1) actions2.hasPublishTx(commitTxAlice2) val lcp1 = alice2.state.localCommitPublished assertNotNull(lcp1) assertTrue(lcp1.commitTx.txIn.map { it.outPoint.txid }.contains(fundingTx.txid)) // A previous funding transaction confirms, so Alice publishes the corresponding commit tx. val (alice3, actions3) = alice2.process(ChannelCommand.WatchReceived(WatchEventConfirmed(alice.state.channelId, BITCOIN_FUNDING_DEPTHOK, 50, 0, previousFundingTx))) assertIs<Closing>(alice3.state) assertEquals(alice3.commitments.active.size, 1) actions3.hasPublishTx(commitTxAlice1) val lcp2 = alice3.state.localCommitPublished assertNotNull(lcp2) assertTrue(lcp2.commitTx.txIn.map { it.outPoint.txid }.contains(previousFundingTx.txid)) // Bob publishes his commit tx, Alice reacts by spending her remote main output. val (alice4, actions4) = alice3.process(ChannelCommand.WatchReceived(WatchEventSpent(alice.state.channelId, BITCOIN_FUNDING_SPENT, commitTxBob1))) assertIs<Closing>(alice4.state) assertNotNull(alice4.state.localCommitPublished) assertNotNull(alice4.state.remoteCommitPublished) val claimMain = actions4.findPublishTxs().first() assertEquals(claimMain.txIn.first().outPoint.txid, commitTxBob1.txid) } } @Test fun `recv ChannelCommand_Close_MutualClose`() { val (alice, bob) = init(ChannelType.SupportedChannelType.AnchorOutputs) listOf(alice, bob).forEach { state -> val (state1, actions1) = state.process(ChannelCommand.Close.MutualClose(null, null)) assertEquals(state, state1) actions1.hasCommandError<CommandUnavailableInThisState>() } } @Test fun `recv ChannelCommand_Close_ForceClose`() { val (alice, bob) = init(ChannelType.SupportedChannelType.AnchorOutputs) listOf(alice, bob).forEach { state -> val (state1, actions1) = state.process(ChannelCommand.Close.ForceClose) assertIs<Closing>(state1.state) assertNotNull(state1.state.localCommitPublished) actions1.hasPublishTx(state1.state.localCommitPublished!!.commitTx) actions1.hasPublishTx(state1.state.localCommitPublished!!.claimMainDelayedOutputTx!!.tx) assertEquals(2, actions1.findWatches<WatchConfirmed>().size) // commit tx + main output } } @Test fun `recv ChannelCommand_Close_ForceClose -- nothing at stake`() { val (alice, bob) = init(ChannelType.SupportedChannelType.AnchorOutputs, bobFundingAmount = 0.sat, alicePushAmount = 0.msat) val (bob1, actions1) = bob.process(ChannelCommand.Close.ForceClose) assertIs<Aborted>(bob1.state) assertEquals(1, actions1.size) val error = actions1.hasOutgoingMessage<Error>() assertEquals(ForcedLocalCommit(alice.state.channelId).message, error.toAscii()) } @Test fun `recv CheckHtlcTimeout`() { val (alice, bob) = init(ChannelType.SupportedChannelType.AnchorOutputs) listOf(alice, bob).forEach { state -> run { val (state1, actions1) = state.process(ChannelCommand.CheckHtlcTimeout) assertEquals(state, state1) assertTrue(actions1.isEmpty()) } } } @Test fun `recv Disconnected`() { val (alice, bob) = init(ChannelType.SupportedChannelType.AnchorOutputs) val (alice1, actionsAlice1) = alice.process(ChannelCommand.Disconnected) assertIs<Offline>(alice1.state) assertTrue(actionsAlice1.isEmpty()) val (bob1, actionsBob1) = bob.process(ChannelCommand.Disconnected) assertIs<Offline>(bob1.state) assertTrue(actionsBob1.isEmpty()) } companion object { data class Fixture(val alice: LNChannel<WaitForFundingConfirmed>, val bob: LNChannel<WaitForFundingConfirmed>, val fundingTx: Transaction, val walletAlice: WalletState) fun init( channelType: ChannelType.SupportedChannelType = ChannelType.SupportedChannelType.AnchorOutputs, aliceFeatures: Features = TestConstants.Alice.nodeParams.features.initFeatures(), bobFeatures: Features = TestConstants.Bob.nodeParams.features.initFeatures(), currentHeight: Int = TestConstants.defaultBlockHeight, aliceFundingAmount: Satoshi = TestConstants.aliceFundingAmount, bobFundingAmount: Satoshi = TestConstants.bobFundingAmount, alicePushAmount: MilliSatoshi = TestConstants.alicePushAmount, bobPushAmount: MilliSatoshi = TestConstants.bobPushAmount, ): Fixture { val (alice, commitAlice, bob, commitBob, walletAlice) = WaitForFundingSignedTestsCommon.init( channelType, aliceFeatures, bobFeatures, currentHeight, aliceFundingAmount, bobFundingAmount, alicePushAmount, bobPushAmount, zeroConf = false ) val (alice1, actionsAlice1) = alice.process(ChannelCommand.MessageReceived(commitBob)) assertIs<WaitForFundingSigned>(alice1.state) assertTrue(actionsAlice1.isEmpty()) val (bob1, actionsBob1) = bob.process(ChannelCommand.MessageReceived(commitAlice)) assertIs<WaitForFundingConfirmed>(bob1.state) assertEquals(actionsBob1.findWatch<WatchConfirmed>().event, BITCOIN_FUNDING_DEPTHOK) val txSigsBob = actionsBob1.findOutgoingMessage<TxSignatures>() if (bob.staticParams.nodeParams.features.hasFeature(Feature.ChannelBackupClient)) { assertFalse(txSigsBob.channelData.isEmpty()) } val (alice2, actionsAlice2) = alice1.process(ChannelCommand.MessageReceived(txSigsBob)) assertIs<LNChannel<WaitForFundingConfirmed>>(alice2) val fundingTxAlice = alice2.state.latestFundingTx.signedTx assertNotNull(fundingTxAlice) val txSigsAlice = actionsAlice2.findOutgoingMessage<TxSignatures>() assertEquals(actionsAlice2.findWatch<WatchConfirmed>().event, BITCOIN_FUNDING_DEPTHOK) actionsAlice2.hasPublishTx(fundingTxAlice) actionsAlice2.has<ChannelAction.Storage.StoreState>() val (bob2, actionsBob2) = bob1.process(ChannelCommand.MessageReceived(txSigsAlice)) assertIs<LNChannel<WaitForFundingConfirmed>>(bob2) val fundingTxBob = bob2.state.latestFundingTx.signedTx assertNotNull(fundingTxBob) actionsBob2.hasPublishTx(fundingTxBob) actionsBob2.has<ChannelAction.Storage.StoreState>() assertEquals(fundingTxAlice.txid, fundingTxBob.txid) return Fixture(alice2, bob2, fundingTxAlice, walletAlice) } fun createRbfCommand(alice: LNChannel<WaitForFundingConfirmed>, wallet: WalletState): ChannelCommand.BumpFundingFee { val previousFundingParams = alice.state.latestFundingTx.fundingParams val previousFundingTx = alice.state.latestFundingTx.sharedTx assertIs<FullySignedSharedTransaction>(previousFundingTx) // Alice adds a new input that increases her contribution and covers the additional fees. val (address, script) = alice.staticParams.nodeParams.keyManager.swapInOnChainWallet.run { Pair(address(0), pubkeyScript(0)) } val parentTx = Transaction(2, listOf(TxIn(OutPoint(randomBytes32(), 1), 0)), listOf(TxOut(30_000.sat, script)), 0) val wallet1 = WalletState( wallet.addresses + (address to (wallet.addresses[address] ?: listOf()) + UnspentItem(parentTx.txid, 0, 30_000, 654321)), wallet.parentTxs + (parentTx.txid to parentTx), ) return ChannelCommand.BumpFundingFee(previousFundingTx.feerate * 1.1, previousFundingParams.localContribution + 20_000.sat, wallet1, previousFundingTx.tx.lockTime + 1) } fun rbf(alice: LNChannel<WaitForFundingConfirmed>, bob: LNChannel<WaitForFundingConfirmed>, walletAlice: WalletState): Triple<LNChannel<WaitForFundingConfirmed>, LNChannel<WaitForFundingConfirmed>, Transaction> { val previousFundingParams = alice.state.latestFundingTx.fundingParams val previousFundingTx = alice.state.latestFundingTx.sharedTx assertIs<FullySignedSharedTransaction>(previousFundingTx) val command = createRbfCommand(alice, walletAlice) val (alice1, actionsAlice1) = alice.process(command) assertEquals(actionsAlice1.size, 1) val txInitRbf = actionsAlice1.findOutgoingMessage<TxInitRbf>() assertEquals(txInitRbf.fundingContribution, previousFundingParams.localContribution + 20_000.sat) val (bob1, actionsBob1) = bob.process(ChannelCommand.MessageReceived(txInitRbf)) assertIs<LNChannel<WaitForFundingConfirmed>>(bob1) assertEquals(actionsBob1.size, 1) val txAckRbf = actionsBob1.findOutgoingMessage<TxAckRbf>() assertEquals(txAckRbf.fundingContribution, previousFundingParams.remoteContribution) // the non-initiator doesn't change its contribution val (alice2, actionsAlice2) = alice1.process(ChannelCommand.MessageReceived(txAckRbf)) assertIs<LNChannel<WaitForFundingConfirmed>>(alice2) assertEquals(actionsAlice2.size, 1) // Alice and Bob build the next funding transaction. val (alice3, bob2) = completeInteractiveTxRbf(alice2, bob1, actionsAlice2.findOutgoingMessage()) val fundingTx = alice3.state.latestFundingTx.sharedTx assertIs<FullySignedSharedTransaction>(fundingTx) assertNotEquals(previousFundingTx.txId, fundingTx.txId) assertEquals(fundingTx.signedTx.lockTime, previousFundingTx.tx.lockTime + 1) assertEquals(alice3.state.commitments.latest.fundingAmount, alice.state.commitments.latest.fundingAmount + 20_000.sat) assertEquals(alice3.state.rbfStatus, RbfStatus.None) assertEquals(bob2.state.rbfStatus, RbfStatus.None) return Triple(alice3, bob2, fundingTx.signedTx) } private fun completeInteractiveTxRbf( alice: LNChannel<WaitForFundingConfirmed>, bob: LNChannel<WaitForFundingConfirmed>, messageAlice: InteractiveTxMessage ): Pair<LNChannel<WaitForFundingConfirmed>, LNChannel<WaitForFundingConfirmed>> { val (bob1, actionsBob1) = bob.process(ChannelCommand.MessageReceived(messageAlice)) assertIs<LNChannel<WaitForFundingConfirmed>>(bob1) assertEquals(actionsBob1.size, 1) val messageBob = actionsBob1.findOutgoingMessage<InteractiveTxConstructionMessage>() val (alice1, actionsAlice1) = alice.process(ChannelCommand.MessageReceived(messageBob)) assertIs<LNChannel<WaitForFundingConfirmed>>(alice1) return when (val txComplete = actionsAlice1.findOutgoingMessageOpt<TxComplete>()) { null -> { assertEquals(actionsAlice1.size, 1) completeInteractiveTxRbf(alice1, bob1, actionsAlice1.findOutgoingMessage()) } else -> { assertEquals(actionsAlice1.size, 3) val commitSigAlice = actionsAlice1.findOutgoingMessage<CommitSig>() actionsAlice1.has<ChannelAction.Storage.StoreState>() val (bob2, actionsBob2) = bob1.process(ChannelCommand.MessageReceived(txComplete)) assertEquals(actionsBob2.size, 2) val commitSigBob = actionsBob2.findOutgoingMessage<CommitSig>() actionsBob2.has<ChannelAction.Storage.StoreState>() val (alice2, actionsAlice2) = alice1.process(ChannelCommand.MessageReceived(commitSigBob)) assertTrue(actionsAlice2.isEmpty()) val (bob3, actionsBob3) = bob2.process(ChannelCommand.MessageReceived(commitSigAlice)) assertIs<LNChannel<WaitForFundingConfirmed>>(bob3) assertEquals(actionsBob3.size, 3) actionsBob3.has<ChannelAction.Storage.StoreState>() val watchBob = actionsBob3.findWatch<WatchConfirmed>() val txSigsBob = actionsBob3.findOutgoingMessage<TxSignatures>() if (bob.staticParams.nodeParams.features.hasFeature(Feature.ChannelBackupClient)) { assertFalse(txSigsBob.channelData.isEmpty()) } val (alice3, actionsAlice3) = alice2.process(ChannelCommand.MessageReceived(txSigsBob)) assertIs<LNChannel<WaitForFundingConfirmed>>(alice3) assertEquals(actionsAlice3.size, 4) val txSigsAlice = actionsAlice3.hasOutgoingMessage<TxSignatures>() assertTrue(txSigsAlice.channelData.isEmpty()) val watchAlice = actionsAlice3.findWatch<WatchConfirmed>() actionsAlice3.has<ChannelAction.Storage.StoreState>() val fundingTxAlice = actionsAlice3.find<ChannelAction.Blockchain.PublishTx>().tx val (bob4, actionsBob4) = bob3.process(ChannelCommand.MessageReceived(txSigsAlice)) assertIs<LNChannel<WaitForFundingConfirmed>>(bob4) assertEquals(actionsBob4.size, 2) val fundingTxBob = actionsBob4.find<ChannelAction.Blockchain.PublishTx>().tx actionsBob4.has<ChannelAction.Storage.StoreState>() assertEquals(fundingTxAlice.txid, fundingTxBob.txid) assertEquals(watchAlice.txId, fundingTxAlice.txid) assertEquals(watchBob.txId, fundingTxBob.txid) Pair(alice3, bob4) } } } } }
41
null
22
94
f86fffe3032a16a3e55f2b4a8ab81e728f8310b1
33,279
lightning-kmp
Apache License 2.0
kotlin-eclipse-ui-test/testData/wordSelection/selectNext/TemplateStringLiteral/2.kt
bvfalcon
263,980,575
false
null
val v = "<selection>a<caret>aa ${x + y}</selection> bbb"
19
null
7
43
e6360b023e1e377325f1d10bda5755e3fc3af591
56
kotlin-eclipse
Apache License 2.0
app/src/main/java/id/asmith/someappclean/data/remote/ApiService.kt
bakode
115,181,489
false
null
package id.asmith.someappclean.data.remote import io.reactivex.Observable import okhttp3.ResponseBody import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST /** * Created by <NAME> on 27/12/2017. * https://asmith.my.id * <EMAIL> */ interface ApiService { @FormUrlEncoded @POST("auth/signin") fun signIn ( @Field("email") email: String, @Field("password") password: String ): Observable<ResponseBody> @FormUrlEncoded @POST("auth/signup") fun signUp ( @Field("full_name")reg_name: String, @Field("username")reg_username: String, @Field("phone")reg_phone: String, @Field("email")reg_email: String, @Field("password")reg_password: String ): Observable<ResponseBody> @FormUrlEncoded @POST("user/password/forgot") fun forgotPassword ( @Field("email") email: String ): Observable<ResponseBody> @FormUrlEncoded @POST("user/password/change") fun changePassword ( @Field("id") uid: String, @Field("password_old")password_old: String, @Field("password_new")password_new: String ): Observable<ResponseBody> @FormUrlEncoded @POST("user/detail") fun userDetail ( @Field("uid") uid: String, @Field("token") token: String ): Observable<ResponseBody> }
0
Kotlin
0
0
57d28a18cb98b6975ad92e929596c631803d0adf
1,421
a-droid-cc
Apache License 2.0
examples/user/readSession/readASessionByTheSessionId/main.kt
GWT-M3O-TEST
485,009,715
false
null
package examples.user.readSession import com.m3o.m3okotlin.M3O import com.m3o.m3okotlin.services.user suspend fun main() { M3O.initialize(System.getenv("M3O_API_TOKEN")) val req = UserReadSessionRequest() try { val response = UserServ.readSession(req) println(response) } catch (e: Exception) { println(e) } }
1
Kotlin
1
0
54158b584ba47bd7323a484804dcd78c55ef7f69
345
m3o-kotlin
Apache License 2.0
src/main/kotlin/me/chill/framework/CommandCategory.kt
woojiahao
145,920,296
false
null
package me.chill.framework @Target(AnnotationTarget.FUNCTION) annotation class CommandCategory
10
Kotlin
12
19
f55e6dc4897096b40c77580b5a4f3417ca563b34
95
Taiga
MIT License
library/src/androidTest/java/com/alexstyl/contactstore/ContactGroupsLookupTest.kt
alexstyl
408,189,357
false
{"Kotlin": 292914}
package com.alexstyl.contactstore import com.alexstyl.contactstore.GroupsPredicate.GroupLookup import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test internal class ContactGroupsLookupTest : ContactStoreTestBase() { private lateinit var groupA: ContactGroup private lateinit var groupB: ContactGroup override fun before(): Unit = runBlocking { super.before() groupA = buildStoreContactGroup { title = "GroupA" note = "Hi" } groupB = buildStoreContactGroup { title = "GroupB" } store.execute { insert { groupMembership(groupA.groupId) } } } @Test fun fetchContactGroup(): Unit = runBlocking { val actual = store.fetchContactGroups().first() val expected = listOf( ImmutableContactGroup( groupId = groupA.groupId, title = groupA.title, contactCount = 1, note = "Hi", ), ImmutableContactGroup( groupId = groupB.groupId, title = groupB.title, contactCount = 0, note = "", ) ) assertThat(actual, equalTo(expected)) } @Test fun lookupContactGroup(): Unit = runBlocking { val actual = store.fetchContactGroups( predicate = GroupLookup( listOf(groupA.groupId) ) ).first() val expected = listOf( ImmutableContactGroup( groupId = groupA.groupId, title = groupA.title, contactCount = 1, note = "Hi", ) ) assertThat(actual, equalTo(expected)) } }
3
Kotlin
15
429
ee2c5b0bc014b8191783e44e610315c1cc51d896
1,901
contactstore
Apache License 2.0
plugins/kotlin-serialization/kotlin-serialization-compiler/testData/diagnostics/SerializableIgnored.kt
walltz556
212,946,144
true
{"Markdown": 60, "Gradle": 598, "Gradle Kotlin DSL": 294, "Java Properties": 12, "Shell": 11, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 5, "Protocol Buffer": 11, "Java": 6356, "Kotlin": 48188, "Proguard": 8, "XML": 1560, "Text": 10288, "JavaScript": 266, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "INI": 115, "AsciiDoc": 1, "SVG": 31, "HTML": 463, "Groovy": 31, "JSON": 45, "JFlex": 3, "Maven POM": 95, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 25, "C": 1, "ANTLR": 1, "YAML": 2, "Ruby": 2, "OpenStep Property List": 2, "Swift": 2, "Objective-C": 2, "Scala": 1}
// !DIAGNOSTICS: -UNUSED_PARAMETER,-UNUSED_VARIABLE // FILE: test.kt import kotlinx.serialization.* <!PLUGIN_ERROR("@Serializable annotation is ignored because it is impossible to serialize automatically interfaces or enums. Provide serializer manually via e.g. companion object")!>@Serializable<!> interface INonSerializable <!PLUGIN_ERROR("@Serializable annotation is ignored because it is impossible to serialize automatically interfaces or enums. Provide serializer manually via e.g. companion object")!>@Serializable<!> enum class ENonSerializable { A, B }
0
null
0
1
f17e9ba9febdabcf7a5e0f17e4be02e0f9e87f13
565
kotlin
Apache License 2.0
updater-mapper-standard/src/main/java/org/runestar/client/updater/mapper/std/classes/IDKType.kt
Tachyon97
228,674,958
true
{"Markdown": 31, "Maven POM": 21, "Text": 2, "Kotlin": 587, "Java": 37, "XML": 2, "YAML": 1}
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.objectweb.asm.Type.VOID_TYPE import org.runestar.client.updater.mapper.* import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 @DependsOn(DualNode::class) class IDKType : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() } .and { it.interfaces.isEmpty() } .and { it.instanceFields.count { it.type == ShortArray::class.type } == 4 } .and { it.instanceFields.count { it.type == IntArray::class.type } == 2 } .and { it.instanceFields.count { it.type == BOOLEAN_TYPE } == 1 } class head : UniqueMapper.InConstructor.Field(IDKType::class) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class decode0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.any { it.opcode == Opcodes.BIPUSH && it.intOperand == 41 } } } @DependsOn(decode0::class) class decode : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it != method<decode0>() } } @DependsOn(decode0::class) class recol_s : OrderMapper.InMethod.Field(decode0::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class recol_d : OrderMapper.InMethod.Field(decode0::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class retex_s : OrderMapper.InMethod.Field(decode0::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class retex_d : OrderMapper.InMethod.Field(decode0::class, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class models : OrderMapper.InMethod.Field(decode0::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == ISTORE } .nextWithin(7) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class bodyPart : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE } } @DependsOn(UnlitModel::class, models::class) class getModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<UnlitModel>() } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<models>().id } } } @DependsOn(UnlitModel::class, head::class) class getChatHeadModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<UnlitModel>() } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<head>().id } } } @DependsOn(models::class) class loadModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<models>().id } } } @DependsOn(head::class) class loadChatHeadModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<head>().id } } } }
0
Kotlin
0
0
d02e7a382a34af117279be02f9f54a6a70fc012b
4,554
client
MIT License
updater-mapper-standard/src/main/java/org/runestar/client/updater/mapper/std/classes/IDKType.kt
Tachyon97
228,674,958
true
{"Markdown": 31, "Maven POM": 21, "Text": 2, "Kotlin": 587, "Java": 37, "XML": 2, "YAML": 1}
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.objectweb.asm.Type.VOID_TYPE import org.runestar.client.updater.mapper.* import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 @DependsOn(DualNode::class) class IDKType : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() } .and { it.interfaces.isEmpty() } .and { it.instanceFields.count { it.type == ShortArray::class.type } == 4 } .and { it.instanceFields.count { it.type == IntArray::class.type } == 2 } .and { it.instanceFields.count { it.type == BOOLEAN_TYPE } == 1 } class head : UniqueMapper.InConstructor.Field(IDKType::class) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class decode0 : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.any { it.opcode == Opcodes.BIPUSH && it.intOperand == 41 } } } @DependsOn(decode0::class) class decode : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it != method<decode0>() } } @DependsOn(decode0::class) class recol_s : OrderMapper.InMethod.Field(decode0::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class recol_d : OrderMapper.InMethod.Field(decode0::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class retex_s : OrderMapper.InMethod.Field(decode0::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class retex_d : OrderMapper.InMethod.Field(decode0::class, 3) { override val predicate = predicateOf<Instruction2> { it.opcode == SASTORE } .prevWithin(7) { it.opcode == GETFIELD && it.fieldType == ShortArray::class.type } } @DependsOn(decode0::class) class models : OrderMapper.InMethod.Field(decode0::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == ISTORE } .nextWithin(7) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class bodyPart : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE } } @DependsOn(UnlitModel::class, models::class) class getModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<UnlitModel>() } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<models>().id } } } @DependsOn(UnlitModel::class, head::class) class getChatHeadModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == type<UnlitModel>() } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<head>().id } } } @DependsOn(models::class) class loadModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<models>().id } } } @DependsOn(head::class) class loadChatHeadModel : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } .and { it.instructions.any { it.opcode == GETFIELD && it.fieldId == field<head>().id } } } }
0
Kotlin
0
0
d02e7a382a34af117279be02f9f54a6a70fc012b
4,554
client
MIT License
vk-sdk-api/src/main/java/com/vk/sdk/api/messages/dto/MessagesMessageAttachment.kt
wesshi-tiktok
358,352,248
true
{"Kotlin": 4764291, "Java": 37555}
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.messages.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.audio.dto.AudioAudio import com.vk.sdk.api.base.dto.BaseLink import com.vk.sdk.api.docs.dto.DocsDoc import com.vk.sdk.api.photos.dto.PhotosPhoto import com.vk.sdk.api.video.dto.VideoVideo /** * @param type no description * @param audio no description * @param audioMessage no description * @param doc no description * @param graffiti no description * @param link no description * @param market no description * @param photo no description * @param share no description * @param video no description * @param wall no description */ data class MessagesHistoryMessageAttachment( @SerializedName(value="type") val type: MessagesHistoryMessageAttachmentType, @SerializedName(value="audio") val audio: AudioAudio? = null, @SerializedName(value="audio_message") val audioMessage: MessagesAudioMessage? = null, @SerializedName(value="doc") val doc: DocsDoc? = null, @SerializedName(value="graffiti") val graffiti: MessagesGraffiti? = null, @SerializedName(value="link") val link: BaseLink? = null, @SerializedName(value="market") val market: BaseLink? = null, @SerializedName(value="photo") val photo: PhotosPhoto? = null, @SerializedName(value="share") val share: BaseLink? = null, @SerializedName(value="video") val video: VideoVideo? = null, @SerializedName(value="wall") val wall: BaseLink? = null )
0
null
0
0
32898fa706e4064118ae18327649e89a22fc6070
2,892
vk-android-sdk
MIT License
app/src/main/java/ozelentok/zcworker/KeepAliveService.kt
ozelentok
679,583,486
false
null
package ozelentok.zcworker import android.app.* import android.content.Intent import android.graphics.drawable.Drawable import android.os.IBinder import ozelentok.zcworker.Utils.showErrorToast import ozelentok.zcworker.Utils.toBitmap class KeepAliveService : Service() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager? if (notificationManager == null) { showErrorToast(this, "Failed to open NotificationManager") return START_NOT_STICKY } val contentIntent = PendingIntent.getActivity( this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val appIcon: Drawable = resources.getDrawable(R.mipmap.ic_launcher) val builder: Notification.Builder = Notification.Builder(this, CHANNEL_ID) .setContentTitle("ZCWorker Active") .setSmallIcon(R.drawable.ic_launcher_foreground) .setLargeIcon(toBitmap(appIcon)) .setContentIntent(contentIntent) val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT) channel.setSound(null, null) notificationManager.createNotificationChannel(channel) val notification: Notification = builder.build() notification.flags = notification.flags or Notification.FLAG_NO_CLEAR startForeground(NOTIFICATION_ID, notification) return START_NOT_STICKY } override fun onBind(intent: Intent?): IBinder? { return null } companion object { private const val NOTIFICATION_ID = 5142 private const val CHANNEL_ID = "zcworker" private const val CHANNEL_NAME = "ZCWorker" } }
0
Kotlin
0
0
c0789c9cd7222d3deffa1e1375f5863658b58966
1,897
ZCWorker
MIT License
signum-dynamodb/src/test/kotlin/com/sksamuel/signum/dynamodb/dynamo.kt
sksamuel
292,966,030
false
null
package com.sksamuel.signum.dynamodb import org.testcontainers.containers.GenericContainer import org.testcontainers.utility.DockerImageName val dockerImageName = DockerImageName.parse("amazon/dynamodb-local:1.20.0") val dynamo = GenericContainer(dockerImageName).withExposedPorts(8000)
0
Kotlin
0
6
319b18decc77a85bb3ddb6bfe44f9bccbebd0a9c
289
signum
Apache License 2.0
viewmodel/src/nonAndroidMain/kotlin/com/hoc081098/kmp/viewmodel/CreationExtras.nonAndroid.kt
hoc081098
593,616,264
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hoc081098.kmp.viewmodel import kotlin.jvm.JvmField public actual interface CreationExtrasKey<T> public actual abstract class CreationExtras internal actual constructor() { internal val map: MutableMap<Key<*>, Any?> = mutableMapOf() public actual abstract operator fun <T> get(key: Key<T>): T? } public actual object EmptyCreationExtras : CreationExtras() { override fun <T> get(key: Key<T>): T? = null } public actual class MutableCreationExtrasBuilder public actual constructor(initialExtras: CreationExtras) : CreationExtras() { init { map.putAll(initialExtras.map) } /** * Associates the given [key] with [t] */ public actual operator fun <T> set(key: Key<T>, t: T) { map[key] = t } public actual override fun <T> get(key: Key<T>): T? { @Suppress("UNCHECKED_CAST") return map[key] as T? } public actual fun asCreationExtras(): CreationExtras = this } @JvmField public actual val VIEW_MODEL_KEY: Key<String> = object : Key<String> {}
5
null
6
96
bd453f25c3054dbc5a309a097e889bf8865e9d18
1,621
kmp-viewmodel
MIT License
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedChangeDiff.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.actions.diff import com.intellij.diff.requests.DiffRequest import com.intellij.diff.tools.combined.* import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.ChangesUtil import com.intellij.openapi.vcs.changes.ui.ChangesComparator internal class CombinedChangeDiffVirtualFile(requestProducer: CombinedChangeDiffRequestProducer) : CombinedDiffVirtualFile<CombinedChangeDiffRequestProducer>(requestProducer) { override fun createProcessor(project: Project) = CombinedChangeDiffRequestProcessor(project, requestProducer) } internal class CombinedChangeDiffRequestProducer(val producers: List<ChangeDiffRequestProducer>) : CombinedDiffRequestProducer { override fun getFilesSize(): Int = producers.size override fun getName(): String = VcsBundle.message("changes.combined.diff") override fun process(context: UserDataHolder, indicator: ProgressIndicator): DiffRequest { val filePathComparator = ChangesComparator.getFilePathComparator(true) val requests = producers .asSequence() .map(::createChildRequest) .sortedWith { r1, r2 -> val id1 = r1.blockId val id2 = r2.blockId when { id1 is CombinedPathBlockId && id2 is CombinedPathBlockId -> filePathComparator.compare(id1.path, id2.path) else -> -1 } } .toList() return CombinedDiffRequest(name, requests) } private fun createChildRequest(producer: ChangeDiffRequestProducer): CombinedDiffRequest.ChildDiffRequest { val change = producer.change val blockId = CombinedPathBlockId(ChangesUtil.getFilePath(change), change.fileStatus) return CombinedDiffRequest.ChildDiffRequest(producer, blockId) } } internal class CombinedChangeDiffRequestProcessor(project: Project?, private val requestProducer: CombinedChangeDiffRequestProducer) : CombinedDiffRequestProcessor(project, requestProducer) { override fun createGoToChangeAction(): AnAction = MyGoToChangePopupAction() private inner class MyGoToChangePopupAction : PresentableGoToChangePopupAction.Default<ChangeDiffRequestProducer>() { override fun getChanges(): ListSelection<out ChangeDiffRequestProducer> { val changes = requestProducer.producers val selected = viewer?.getCurrentBlockId() as? CombinedPathBlockId val selectedIndex = when { selected != null -> changes.indexOfFirst { it.fileStatus == selected.fileStatus && it.filePath == selected.path } else -> -1 } return ListSelection.createAt(changes, selectedIndex) } override fun onSelected(change: ChangeDiffRequestProducer) { viewer?.selectDiffBlock(change.filePath, change.fileStatus, ScrollPolicy.DIFF_BLOCK) } } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
3,159
intellij-community
Apache License 2.0
src/main/kotlin/no/nav/dagpenger/iverksett/utbetaling/domene/Iverksettingsresultat.kt
navikt
611,752,955
false
{"Kotlin": 289131, "Gherkin": 44306, "Shell": 626, "Dockerfile": 121}
package no.nav.dagpenger.iverksett.utbetaling.domene import no.nav.dagpenger.kontrakter.felles.Fagsystem import no.nav.dagpenger.kontrakter.oppdrag.OppdragStatus import org.springframework.data.relational.core.mapping.Column import java.time.LocalDateTime import java.util.UUID data class Iverksettingsresultat( val fagsystem: Fagsystem, val behandlingId: UUID, val iverksettingId: String? = null, @Column("tilkjentytelseforutbetaling") val tilkjentYtelseForUtbetaling: TilkjentYtelse? = null, @Column("oppdragresultat") val oppdragResultat: OppdragResultat? = null, ) data class OppdragResultat( val oppdragStatus: OppdragStatus, val oppdragStatusOppdatert: LocalDateTime = LocalDateTime.now(), )
1
Kotlin
1
0
f35a87c6f3b1bc87e3edfe11c07670be677f8c3f
737
dp-iverksett
MIT License
plugins/compiler-plugin/src/main/kotlin/dev/ahmedmourad/nocopy/compiler/NoCopyPlugin.kt
AhmedMourad0
242,375,329
false
{"Kotlin": 24100}
package dev.ahmedmourad.nocopy.compiler import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.com.intellij.mock.MockProject import org.jetbrains.kotlin.com.intellij.openapi.extensions.Extensions import org.jetbrains.kotlin.com.intellij.openapi.extensions.impl.ExtensionPointImpl import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension class NoCopyPlugin : ComponentRegistrar { override fun registerProjectComponents( project: MockProject, configuration: CompilerConfiguration ) { val messageCollector = configuration.get( CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, MessageCollector.NONE ) SyntheticResolveExtension.registerExtensionAsFirst( project, NoCopySyntheticResolveExtension(messageCollector) ) } } private fun <T> ProjectExtensionDescriptor<T>.registerExtensionAsFirst(project: Project, extension: T) { Extensions.getArea(project) .getExtensionPoint(extensionPointName) .let { it as ExtensionPointImpl } .registerExtension(extension, project) }
1
Kotlin
4
150
e62c2564f114c0dcff9b09760601f651b21d6762
1,499
no-copy
Apache License 2.0
uicorek/src/main/java/com/mozhimen/uicorek/tabk/top/mos/TabKTopMo.kt
mozhimen
353,952,154
false
null
package com.mozhimen.uicorek.tabk.top.mos import androidx.fragment.app.Fragment import com.mozhimen.basick.extsk.asColorTone /** * @ClassName TabKTopInfo * @Description TODO * @Author mozhimen / <NAME> * @Date 2022/4/15 22:16 * @Version 1.0 */ class TabKTopMo { enum class TabKTopType { IMAGE, TEXT, IMAGE_TEXT } var name: String? = null var fragment: Class<out Fragment>? = null var bitmapDefault: Any? = null var bitmapSelected: Any? = null var colorDefault: Int? = null var colorSelected: Int? = null var colorIndicator: Int? = null var tabKType: TabKTopType? = null /** * 纯图片 * @param name String * @param bitmapDefault Any * @param bitmapSelected Any * @param colorIndicator Any * @constructor */ constructor( name: String, bitmapDefault: Any, bitmapSelected: Any, colorIndicator: Any, ) { this.name = name this.bitmapDefault = bitmapDefault this.bitmapSelected = bitmapSelected this.colorIndicator = colorIndicator.asColorTone() this.tabKType = TabKTopType.IMAGE } /** * 纯文本 * @param name String * @param colorDefault Any * @param colorSelected Any * @constructor */ constructor( name: String, colorDefault: Any, colorSelected: Any ) { this.name = name this.colorDefault = colorDefault.asColorTone() this.colorSelected = colorSelected.asColorTone() this.tabKType = TabKTopType.TEXT } /** * 图片文字 * @param name String * @param bitmapDefault Any * @param bitmapSelected Any * @param colorDefault Any * @param colorSelected Any * @constructor */ constructor( name: String, bitmapDefault: Any, bitmapSelected: Any, colorDefault: Any, colorSelected: Any ) { this.name = name this.bitmapDefault = bitmapDefault this.bitmapSelected = bitmapSelected this.colorDefault = colorDefault.asColorTone() this.colorSelected = colorSelected.asColorTone() this.tabKType = TabKTopType.IMAGE_TEXT } }
0
Kotlin
0
1
3dd109aff154bff96379cde86e6e4632967cca40
2,214
SwiftMK
Apache License 2.0
di/src/main/java/com/di/module/RemoteDataSourceModule.kt
Software-Meister-High-School-Community
452,152,042
false
null
package com.di.module abstract class RemoteDataSourceModule { }
8
Kotlin
0
4
9e2521871663805a4b50f23497dfee972bab1766
64
MOIZA_Android
MIT License
pensjon-brevbaker-api-model/src/main/kotlin/no/nav/pensjon/brev/api/model/maler/Brevkode.kt
navikt
375,334,697
false
null
package no.nav.pensjon.brev.api.model.maler object Brevkode { enum class AutoBrev(vararg koder: String) { PE_2023_FEIL_INFOBREV_AP_SENDT_BRUKER("ADHOC_2023_AP2"), PE_ADHOC_2023_04_GJENLEVENDEINFOETTER1970("ADHOC_2023_04_GJP1"), PE_ADHOC_2023_04_GJENLEVENDEINFOFOER1971("ADHOC_2023_04_GJP2"), PE_OMSORG_HJELPESTOENAD_AUTO("OMSORG_HJST_AUTO"), PE_OMSORG_EGEN_AUTO("OMSORG_EGEN_AUTO", "OMSORGP_EGENMLD"), UT_OMREGNING_ENSLIG_AUTO("UT_DOD_ENSLIG_AUTO", "TILST_DOD_UT"), UT_OPPHOER_BT_AUTO("PE_UT_07_200", "OPPHOR_ENDRING_UT_BT"), UT_UNG_UFOER_20_AAR_AUTO("PE_BA_04_505", "UP_FULLTT_BELOPENDR"), UT_EO_FORHAANDSVARSEL_FEILUTBETALING_AUTO("PE_UT_23_001", "UT_EO_VARSEL_FU"), UT_2023_INFO_REGLERENDRET_GJT_12_18 ("ADHOC_2023_UT1"), UT_2023_INFO_REGLERENDRET_GJT_KONVERTERT2015 ("ADHOC_2023_UT2") ; val brevkoder: Set<String> = koder.toSet() companion object { @Suppress("unused") fun findByKode(kode: String): AutoBrev? = AutoBrev.values().find { it.brevkoder.contains(kode) || it.name == kode } } } enum class Redigerbar(val kode: String) { INFORMASJON_OM_SAKSBEHANDLINGSTID("AP_INFO_STID_MAN"), ; companion object { @Suppress("unused") fun findByKode(kode: String): Redigerbar? = Redigerbar.values().firstOrNull { it.kode == kode || it.name == kode} } } }
8
Kotlin
3
0
f6279463e3a300492df8e7304a0063817b95273b
1,502
pensjonsbrev
MIT License
src/main/kotlin/org/kirinhorse/kbt/decorators/Force.kt
KirinHorse
674,049,029
false
null
package org.kirinhorse.kbt.decorators import org.kirinhorse.kbt.BehaviorTree import org.kirinhorse.kbt.Decorator import org.kirinhorse.kbt.KBTInput import org.kirinhorse.kbt.NodeConfig import org.kirinhorse.kbt.Types @KBTInput("status", Types.KBTType.Bool) class Force(tree: BehaviorTree, config: NodeConfig) : Decorator(tree, config) { override suspend fun onExecute(): Boolean { val status = getInput("status", Boolean::class) child?.execute() return status } }
0
Kotlin
0
1
9539293396e3a1bb5660d884ee93d97a00698732
497
KotlinBehaviors
MIT License
app/src/main/java/com/liuxe/energyweather/http/WeatherApi.kt
liuxe66
220,427,527
false
null
package com.liuxe.energyweather.http import com.liuxe.energyweather.base.BaseResponse import com.liuxe.energyweather.bean.WeatherBean import retrofit2.http.GET import retrofit2.http.Query interface WeatherApi { companion object { const val BASE_URL = "http://aider.meizu.com/app/weather/" } @GET("listWeather") suspend fun getWeatherInfo(@Query("cityIds")cityid: String):BaseResponse<WeatherBean> }
0
Kotlin
0
0
96c648b43dd07588e259dafc2dff14d6a14081c4
425
EneryWeather
Apache License 2.0
app/src/main/java/me/hufman/androidautoidrive/phoneui/PhoneUiUtils.kt
pshoey
320,626,857
true
{"Kotlin": 830646, "Java": 822}
package me.hufman.androidautoidrive.phoneui import android.content.Context import android.util.TypedValue import android.view.View import androidx.annotation.AttrRes import androidx.annotation.ColorInt /** Resolve a Color Attribute to a color int */ @ColorInt fun Context.getThemeColor( @AttrRes attrColor: Int ): Int { val typedValue = TypedValue() theme.resolveAttribute(attrColor, typedValue, true) val colorRes = typedValue.resourceId return resources.getColor(colorRes, theme) } /** Toggle a View's visibility by a boolean */ var View.visible: Boolean get() { return this.visibility == View.VISIBLE } set(value) {this.visibility = if (value) View.VISIBLE else View.GONE }
0
null
0
0
1eaea6771f11c0326e75cec6112ad26e717edbb7
687
AndroidAutoIdrive
MIT License
src/main/kotlin/org/joachimalaya/operators/Modifications.kt
Joachimalaya
144,450,090
false
null
package org.joachimalaya.operators /** * 'Multiply' a List by adding it to itself repeatedly. * If a List is multiplied with 0 the result is an empty List of the same type. * * This function will throw an [IllegalArgumentException] if given a multiplicand less than 0. */ operator fun <K> List<K>.times(times: Int) = multiplyByAddingWithNeutral({ a, b -> a + b }, this, times, emptyList()) /** * 'Multiply' a List by adding it to itself repeatedly. * If a List is multiplied with 0 the result is an empty List of the same type. * * This function will throw an [IllegalArgumentException] if given a multiplicand less than 0. */ operator fun <K> Int.times(toMultiply: List<K>) = multiplyByAddingWithNeutral({ a, b -> a + b }, toMultiply, this, emptyList()) /** * 'Multiply' a String by concatenating it to itself repeatedly. * If a String is multiplied with 0 the result is the empty String. * * This function will throw an [IllegalArgumentException] if given a multiplicand less than 0. */ operator fun String.times(times: Int) = multiplyByAddingWithNeutral(String::plus, this, times, "") /** * 'Multiply' a String by concatenating it to itself repeatedly. * If a String is multiplied with 0 the result is the empty String. * * This function will throw an [IllegalArgumentException] if given a multiplicand less than 0. */ operator fun Int.times(toMultiply: String) = multiplyByAddingWithNeutral(String::plus, toMultiply, this, "")
0
Kotlin
0
0
2e57304ab885b781407453a09fd4f74783c76527
1,454
operators
MIT License
plugins/kotlin/code-insight/intentions-shared/tests/testData/intentions/convertToForEachFunctionCall/blockBodyExpression.kt
ingokegel
72,937,917
true
null
// WITH_RUNTIME fun foo() { // check that original formatting of "x+1" and "1 .. 4" is preserved // AFTER-WARNING: The expression is unused <caret>for (x in 1 .. 4) { x x+1 } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
204
intellij-community
Apache License 2.0
rgpd/src/main/java/a/rgpd/rgpd/utils/utils.kt
Devid-Team
168,692,610
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 2, "XML": 22, "Kotlin": 19, "JSON": 1}
package a.rgpd.rgpd.utils import android.content.res.Resources import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.widget.Button import android.widget.RelativeLayout class ColorGenerator { fun getIntColors(colors: Array<String>): IntArray { val intColors = IntArray(colors.size) for (color in colors) { assert(color[0] == '#') { "Expected hex string of format #RRGGBB" } intColors[colors.indexOf(color)] = Color.parseColor(color) } return intColors } fun setImageGradient(resources: Resources, image: Int, colors: Array<String>): Drawable { val originalBitmap = BitmapFactory.decodeResource(resources, image) val updatedBitmap = Bitmap.createBitmap(originalBitmap.width, originalBitmap.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(updatedBitmap) canvas.drawBitmap(originalBitmap, 0f, 0f, null) val paint = Paint() val shader = LinearGradient(0f, 0f, originalBitmap.width.toFloat(), 0f, ColorGenerator().getIntColors(colors), null, Shader.TileMode.CLAMP) paint.shader = shader paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) canvas.drawRect(0f, 0f, originalBitmap.width.toFloat(), originalBitmap.height.toFloat(), paint) return BitmapDrawable(resources, updatedBitmap) } fun setColorButton(colors: Array<String>, button: RelativeLayout): Drawable { val drawable = GradientDrawable() if (colors.size == 1) { drawable.setColor(getIntColors(colors)[0]) } else { drawable.gradientType = GradientDrawable.LINEAR_GRADIENT drawable.orientation = GradientDrawable.Orientation.LEFT_RIGHT drawable.colors = getIntColors(colors) } drawable.cornerRadius = 10f drawable.setSize(button.width, button.height) return drawable } fun setColorAccountButton(colors: Array<String>, button: Button): Drawable { val drawable = GradientDrawable() if (colors.size == 1) { drawable.setColor(getIntColors(colors)[0]) } else { drawable.gradientType = GradientDrawable.LINEAR_GRADIENT drawable.orientation = GradientDrawable.Orientation.LEFT_RIGHT drawable.colors = getIntColors(colors) } drawable.cornerRadius = 70f drawable.setSize(button.width, button.height) return drawable } }
1
Kotlin
0
1
35fe799cd97764fef9158387b2b61e38a320a15e
2,617
RGPD-Android
Apache License 2.0
materialpreference/src/main/java/com/anggrayudi/materialpreference/PreferenceInflater.kt
anggrayudi
139,258,858
false
null
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.anggrayudi.materialpreference import android.content.Context import android.content.Intent import android.content.res.XmlResourceParser import android.util.AttributeSet import android.util.Xml import android.view.InflateException import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import java.io.IOException import java.lang.reflect.Constructor import java.util.* /** * The [PreferenceInflater] is used to inflate preference hierarchies from XML files. */ internal class PreferenceInflater(val context: Context, private val preferenceManager: PreferenceManager) { private val constructorArgs = arrayOfNulls<Any>(2) /** * Sets the default package that will be searched for classes to construct * for tag names that have no explicit package. * * @return Default package, or null if it is not set. */ var defaultPackages: Array<String>? = arrayOf("com.anggrayudi.materialpreference.") /** * Inflate a new item hierarchy from the specified xml resource. * Throws `InflaterException` if there is an error. * * @param resource ID for an XML resource to load (e.g., `R.layout.main_page`) * @param root Optional parent of the generated hierarchy. * @return The root of the inflated hierarchy. If root was supplied, * this is the root item; otherwise it is the root of the inflated XML file. */ fun inflate(resource: Int, root: PreferenceGroup?): Preference { // DO NOT USE "use" extension from Kotlin. It will cause this runtime error on some devices: // java.lang.ClassCastException: android.content.res.XmlBlock$Parser cannot be cast to java.lang.AutoCloseable // I don't know why. val parser = context.resources.getXml(resource) @Suppress("ConvertTryFinallyToUseCall") return try { inflate(parser, root) } finally { parser.close() } } /** * Inflate a new hierarchy from the specified XML node. Throws * `InflaterException` if there is an error. * * ***Important***&nbsp;&nbsp;&nbsp;For performance * reasons, inflation relies heavily on pre-processing of XML files * that is done at build time. Therefore, it is not currently possible to * use inflater with an XmlPullParser over a plain XML file at runtime. * * @param parser XML dom node containing the description of the hierarchy. * @param root Optional to be the parent of the generated hierarchy (if * *attachToRoot* is true), or else simply an object that * provides a set of values for root of the returned hierarchy (if *attachToRoot* is false.) * @return The root of the inflated hierarchy. If root was supplied, * this is root; otherwise it is the root of the inflated XML file. */ fun inflate(parser: XmlResourceParser, root: PreferenceGroup?): Preference { synchronized(constructorArgs) { val attrs = Xml.asAttributeSet(parser) constructorArgs[0] = context val result: Preference try { // Look for the root node. var type: Int do { type = parser.next() } while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) if (type != XmlPullParser.START_TAG) { throw InflateException(parser.positionDescription + ": No start tag found!") } // Temp is the root that was found in the xml val xmlRoot = createItemFromTag(parser.name, attrs) result = onMergeRoots(root, xmlRoot as PreferenceGroup) // Inflate all children under temp rInflate(parser, result, attrs) } catch (e: InflateException) { throw e } catch (e: XmlPullParserException) { val ex = InflateException(e.message) ex.initCause(e) throw ex } catch (e: IOException) { val ex = InflateException(parser.positionDescription + ": " + e.message) ex.initCause(e) throw ex } return result } } private fun onMergeRoots(givenRoot: PreferenceGroup?, xmlRoot: PreferenceGroup): PreferenceGroup { // If we were given a Preferences, use it as the root (ignoring the root // Preferences from the XML file). return if (givenRoot == null) { xmlRoot.onAttachedToHierarchy(preferenceManager) xmlRoot } else { givenRoot } } /** * Low-level function for instantiating by name. This attempts to * instantiate class of the given <var>name</var> found in this inflater's ClassLoader. * * There are two things that can happen in an error case: either the * exception describing the error will be thrown, or a null will be * returned. You must deal with both possibilities -- the former will happen * the first time createItem() is called for a class of a particular name, * the latter every time there-after for that class name. * * @param name The full name of the class to be instantiated. * @param attrs The XML attributes supplied for this instance. * @return The newly instantiated item, or null. */ @Throws(ClassNotFoundException::class, InflateException::class) private fun createItem(name: String, prefixes: Array<String>?, attrs: AttributeSet): Preference { var constructor: Constructor<*>? = CONSTRUCTOR_MAP[name] try { if (constructor == null) { // Class not found in the cache, see if it's real, // and try to add it val classLoader = context.classLoader var clazz: Class<*>? = null if (prefixes == null || prefixes.isEmpty()) { clazz = classLoader.loadClass(name) } else { var notFoundException: ClassNotFoundException? = null prefixes.forEach { try { clazz = classLoader.loadClass(it + name) return@forEach } catch (e: ClassNotFoundException) { notFoundException = e } } if (clazz == null) { if (notFoundException == null) { throw InflateException(attrs.positionDescription + ": Error inflating class $name") } else { throw notFoundException as ClassNotFoundException } } } constructor = clazz!!.getConstructor(*CONSTRUCTOR_SIGNATURE) constructor.isAccessible = true CONSTRUCTOR_MAP[name] = constructor } val args = constructorArgs args[1] = attrs return constructor!!.newInstance(*args) as Preference } catch (e: ClassNotFoundException) { // If loadClass fails, we should propagate the exception. throw e } catch (e: Exception) { val ie = InflateException(attrs.positionDescription + ": Error inflating class $name") ie.initCause(e) throw ie } } /** * This routine is responsible for creating the correct subclass of item * given the xml element name. Override it to handle custom item objects. If * you override this in your subclass be sure to call through to * `super.onCreateItem(name)` for names you do not recognize. * * @param name The fully qualified class name of the item to be create. * @param attrs An `AttributeSet` of attributes to apply to the item. * @return The item created. */ @Throws(ClassNotFoundException::class) protected fun onCreateItem(name: String, attrs: AttributeSet): Preference { return createItem(name, defaultPackages, attrs) } private fun createItemFromTag(name: String, attrs: AttributeSet): Preference { try { return if (-1 == name.indexOf('.')) { onCreateItem(name, attrs) } else { createItem(name, null, attrs) } } catch (e: InflateException) { throw e } catch (e: ClassNotFoundException) { val ie = InflateException(attrs.positionDescription + ": Error inflating class (not found) $name") ie.initCause(e) throw ie } catch (e: Exception) { val ie = InflateException(attrs.positionDescription + ": Error inflating class $name") ie.initCause(e) throw ie } } /** * Recursive method used to descend down the xml hierarchy and instantiate * items, instantiate their children, and then call `onFinishInflate()`. */ @Throws(XmlPullParserException::class, IOException::class) private fun rInflate(parser: XmlPullParser, parent: Preference, attrs: AttributeSet) { val depth = parser.depth var type = parser.next() while ((type != XmlPullParser.END_TAG || parser.depth > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { type = parser.next() continue } val name = parser.name when { INTENT_TAG_NAME == name -> { val intent: Intent try { intent = Intent.parseIntent(context.resources, parser, attrs) } catch (e: IOException) { val ex = XmlPullParserException("Error parsing preference") ex.initCause(e) throw ex } parent.intent = intent } EXTRA_TAG_NAME == name -> { context.resources.parseBundleExtra(EXTRA_TAG_NAME, attrs, parent.extras) try { skipCurrentTag(parser) } catch (e: IOException) { val ex = XmlPullParserException("Error parsing preference") ex.initCause(e) throw ex } } else -> { val item = createItemFromTag(name, attrs) (parent as PreferenceGroup).addItemFromInflater(item) rInflate(parser, item, attrs) } } type = parser.next() } } companion object { private const val TAG = "PreferenceInflater" private val CONSTRUCTOR_SIGNATURE = arrayOf(Context::class.java, AttributeSet::class.java) private val CONSTRUCTOR_MAP = HashMap<String, Constructor<*>>() private const val INTENT_TAG_NAME = "intent" private const val EXTRA_TAG_NAME = "extra" @Throws(XmlPullParserException::class, IOException::class) private fun skipCurrentTag(parser: XmlPullParser) { val outerDepth = parser.depth var type: Int do { type = parser.next() } while (type != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.depth > outerDepth)) } } }
0
Kotlin
19
92
34b2b884d8742a3cbd6c4f1c87604d77f15464d7
12,271
MaterialPreference
Apache License 2.0
stark-plugin-external/src/androidTest/java/com/hjhjw1991/stark/plugin/external/ExampleInstrumentedTest.kt
hjhjw1991
288,537,354
false
null
package com.hjhjw1991.stark.plugin.external import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.bytedance.ies.stark.plugin.external.test", appContext.packageName) } }
0
Kotlin
1
0
d22d05f5510b671b16a632411a3d03e76cc9e58b
696
stark
MIT License
app/src/main/java/br/com/schuster/androidunittests/domain/model/NoteItem.kt
cleberschuster
839,383,443
false
{"Kotlin": 12090}
package br.com.schuster.androidunittests.domain.model data class NoteItem( var title: String, var description: String, var imageUrl: String, val dateAdded: Long, val id: Int = 0, )
0
Kotlin
0
0
e51412c3c6cc645885fc388c56433c853eaf9026
204
android_unit_tests_app
Apache License 2.0
src/main/kotlin/org/jetbrains/plugins/bsp/jvm/JvmBspRunHandler.kt
JetBrains
521,228,542
false
{"Kotlin": 900996, "Java": 611}
package org.jetbrains.plugins.bsp.jvm import ch.epfl.scala.bsp4j.BuildTargetIdentifier import ch.epfl.scala.bsp4j.RunParams import com.intellij.execution.ExecutionException import com.intellij.execution.Executor import com.intellij.execution.configurations.RemoteConnection import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.executors.DefaultDebugExecutor import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.project.Project import org.jetbrains.bsp.protocol.BazelBuildServerCapabilities import org.jetbrains.bsp.protocol.RemoteDebugData import org.jetbrains.bsp.protocol.RunWithDebugParams import org.jetbrains.plugins.bsp.magicmetamodel.impl.workspacemodel.BuildTargetInfo import org.jetbrains.plugins.bsp.magicmetamodel.impl.workspacemodel.includesAndroid import org.jetbrains.plugins.bsp.magicmetamodel.impl.workspacemodel.isJvmTarget import org.jetbrains.plugins.bsp.server.connection.BspServer import org.jetbrains.plugins.bsp.services.BspTaskListener import org.jetbrains.plugins.bsp.services.OriginId import org.jetbrains.plugins.bsp.ui.configuration.BspProcessHandler import org.jetbrains.plugins.bsp.ui.configuration.BspRunConfiguration import org.jetbrains.plugins.bsp.ui.configuration.BspRunConfigurationBase import org.jetbrains.plugins.bsp.ui.configuration.BspTestConfiguration import org.jetbrains.plugins.bsp.ui.configuration.run.BspCommandLineStateBase import org.jetbrains.plugins.bsp.ui.configuration.run.BspRunCommandLineState import org.jetbrains.plugins.bsp.ui.configuration.run.BspRunHandler import org.jetbrains.plugins.bsp.ui.configuration.run.BspRunTaskListener import org.jetbrains.plugins.bsp.ui.configuration.run.BspTestCommandLineState import java.util.UUID import java.util.concurrent.CompletableFuture public class JvmBspRunHandler : BspRunHandler { // Explanation for this logic: // Because we have android_local_test with mocked Android classes, which should be run, well, locally, // as opposed to on-device like with android_binary // TODO: perhaps better solved by having a tag override fun canRun(targets: List<BuildTargetInfo>): Boolean = targets.all { it.languageIds.isJvmTarget() || it.languageIds.includesAndroid() && it.capabilities.canTest } override fun canDebug(targets: List<BuildTargetInfo>): Boolean = canRun(targets) override fun getRunProfileState( project: Project, executor: Executor, environment: ExecutionEnvironment, configuration: BspRunConfigurationBase, ): RunProfileState { return when { executor is DefaultDebugExecutor -> { JvmDebugHandlerState(project, environment, configuration, UUID.randomUUID().toString()) } configuration is BspTestConfiguration -> { BspTestCommandLineState(project, environment, configuration, UUID.randomUUID().toString()) } configuration is BspRunConfiguration -> { BspRunCommandLineState(project, environment, configuration, UUID.randomUUID().toString()) } else -> { throw ExecutionException("JvmBspRunHandler can run only JVM or generic BSP targets") } } } public class JvmDebugHandlerState( project: Project, environment: ExecutionEnvironment, private val configuration: BspRunConfigurationBase, private val originId: OriginId, ) : BspCommandLineStateBase(project, environment, configuration, originId) { public val remoteConnection: RemoteConnection = RemoteConnection(true, "localhost", "0", true) public val portForDebug: Int? get() = remoteConnection.debuggerAddress?.toInt() override fun checkRunCapabilities(capabilities: BazelBuildServerCapabilities) { if (!capabilities.runWithDebugProvider) { throw ExecutionException("BSP server does not support running") } if (configuration.targets.size != 1) { throw ExecutionException("Debugging only supports one target") } } override fun createAndAddTaskListener(handler: BspProcessHandler<out Any>): BspTaskListener = BspRunTaskListener(handler) override fun startBsp(server: BspServer): CompletableFuture<*> { // SAFETY: safe to unwrap because we checked in checkRunCapabilities val targetId = BuildTargetIdentifier(configuration.targets.single().id) val runParams = RunParams(targetId) runParams.originId = originId val remoteDebugData = RemoteDebugData("jdwp", portForDebug!!) val runWithDebugParams = RunWithDebugParams(originId, runParams, remoteDebugData) return server.buildTargetRunWithDebug(runWithDebugParams) } } }
2
Kotlin
12
27
0268f6b73e2c4cd0f8b37d28f983638b4843ee15
4,639
intellij-bsp
Apache License 2.0
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/XExecutableElement.kt
JetBrains
351,708,598
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing /** * Represents a method, constructor or initializer. * * @see [javax.lang.model.element.ExecutableElement] */ interface XExecutableElement : XHasModifiers, XParameterizable, XElement { /** * The element that declared this executable. * * For methods declared as top level functions in Kotlin: * * When running with KAPT, the value will be an [XTypeElement]. * * When running with KSP, if this function is coming from the classpath, the value will * be an [XTypeElement]. * * When running with KSP, if this function is in source, the value will **NOT** be an * [XTypeElement]. If you need the generated synthetic java class name, you can use * [XMemberContainer.asClassName] property. */ override val enclosingElement: XMemberContainer /** * The list of parameters that should be passed into this method. * * @see [isVarArgs] */ val parameters: List<XExecutableParameterElement> /** * The list of `Throwable`s that are declared in this executable's signature. */ val thrownTypes: List<XType> /** * Returns true if this method receives a vararg parameter. */ fun isVarArgs(): Boolean /** * The type representation of the method where more type parameters might be resolved. */ val executableType: XExecutableType /** * Returns the method as if it is declared in [other]. * * This is specifically useful if you have a method that has type arguments and there is a * subclass ([other]) where type arguments are specified to actual types. */ fun asMemberOf(other: XType): XExecutableType }
29
null
937
59
3fbd775007164912b34a1d59a923ad3387028b97
2,345
androidx
Apache License 2.0
app/src/main/java/in/surajsau/jisho/ui/home/HomeScreen.kt
surajsau
434,128,847
false
null
package `in`.surajsau.jisho.ui.home import `in`.surajsau.jisho.base.use import `in`.surajsau.jisho.data.model.Screen import `in`.surajsau.jisho.ui.Destinations import android.os.Build import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.ImageLoader import coil.compose.rememberImagePainter import coil.decode.GifDecoder import coil.decode.ImageDecoderDecoder @Composable fun HomeScreen( modifier: Modifier = Modifier, navigateToDestination: (Destinations) -> Unit ) { val (state, _) = use(LocalHomeViewModel.current, HomeViewModel.State()) Box(modifier = modifier) { LazyColumn( modifier = Modifier.fillMaxSize() .padding(horizontal = 16.dp) ) { itemsIndexed(state.screens) { index, screen -> ScreenCard( screen = screen, onClick = { navigateToDestination.invoke(it) }, modifier = Modifier.padding( top = if (index == 0) 16.dp else 0.dp, bottom = 16.dp ) ) } } } } @Composable fun ScreenCard( screen: Screen, modifier: Modifier = Modifier, onClick: (Destinations) -> Unit ) { val context = LocalContext.current val painter = rememberImagePainter( data = screen.previewImage, imageLoader = ImageLoader.invoke(context).newBuilder() .componentRegistry { val decoder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { ImageDecoderDecoder(LocalContext.current) } else { GifDecoder() } add(decoder) } .build() ) Row( modifier = modifier .clickable { onClick.invoke(screen.destinations) } .fillMaxWidth() .height(200.dp) .clip(RoundedCornerShape(4.dp)) .background(Color.White) ) { Image( painter = painter, contentDescription = null, modifier = Modifier .weight(1f) .fillMaxHeight() .clipToBounds() .height(200.dp), contentScale = ContentScale.Crop ) Column( modifier = Modifier.weight(2f) .padding(16.dp) ) { Text( text = screen.title, fontSize = 18.sp, fontWeight = FontWeight.Medium, modifier = Modifier .fillMaxWidth() ) Text( text = screen.description, modifier = Modifier.fillMaxWidth() .padding(top = 8.dp) ) } } }
2
null
5
15
66ca1373067c57257e7d26f9b922d2d0915b0f4a
3,614
ML-Android
Apache License 2.0
okhttp-sse/src/main/kotlin/okhttp3/sse/EventSources.kt
square
5,152,285
false
{"Kotlin": 3723581, "Java": 11377, "Shell": 3014}
/* * Copyright (C) 2018 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 okhttp3.sse import okhttp3.Call import okhttp3.ExperimentalOkHttpApi import okhttp3.OkHttpClient import okhttp3.Response import okhttp3.sse.internal.RealEventSource object EventSources { @Deprecated( message = "required for binary-compatibility!", level = DeprecationLevel.HIDDEN, ) @JvmStatic fun createFactory(client: OkHttpClient) = createFactory(client as Call.Factory) @JvmStatic @ExperimentalOkHttpApi fun createFactory(callFactory: Call.Factory): EventSource.Factory { return EventSource.Factory { request, listener -> val actualRequest = if (request.header("Accept") == null) { request.newBuilder().addHeader("Accept", "text/event-stream").build() } else { request } RealEventSource(actualRequest, listener).apply { connect(callFactory) } } } @JvmStatic fun processResponse( response: Response, listener: EventSourceListener, ) { val eventSource = RealEventSource(response.request, listener) eventSource.processResponse(response) } }
2
Kotlin
9281
45,832
dbedfd000c8e84bc914c619714b8c9bf7f3e06d4
1,682
okhttp
Apache License 2.0
example/write-endpoint/adapters/driving/http/src/test/kotlin/org/sollecitom/chassis/example/write_endpoint/adapters/driving/web/OpenApiComplianceTests.kt
sollecitom
669,483,842
false
null
package org.sollecitom.chassis.example.write_endpoint.adapters.driving.web import assertk.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS import org.sollecitom.chassis.logging.standard.configuration.configureLogging import org.sollecitom.chassis.openapi.checking.checker.sets.StandardOpenApiRules import org.sollecitom.chassis.openapi.checking.test.utils.isCompliantWith @TestInstance(PER_CLASS) private class OpenApiComplianceTests { init { configureLogging() } @Test fun `the declared OpenAPI specification complies with the standard OpenAPI guidelines`() { assertThat(openApi).isCompliantWith(StandardOpenApiRules) } }
0
null
0
2
e4e3403e46f7358a03c8ee3520b3b94be679792b
763
chassis
MIT License
deprecated/RxJavaTemplate/common-rx/src/main/java/co/nimblehq/rxjava/common/transformers/FlowableNeverErrorTransformer.kt
nimblehq
101,353,301
false
null
package co.nimblehq.smsforwarder.common.transformers import io.reactivex.Flowable import io.reactivex.FlowableTransformer import io.reactivex.functions.Consumer import org.reactivestreams.Publisher class FlowableNeverErrorTransformer<T>( private val errorConsumer: Consumer<Throwable>? = null ) : FlowableTransformer<T, T> { override fun apply(source: Flowable<T>): Publisher<T> { return source .doOnError { throwable -> errorConsumer?.accept(throwable) } .onErrorResumeNext(Flowable.empty()) // onComplete will be invoked } }
31
null
23
94
f07941499a70b6144f4280c233edba542ab3e516
602
android-templates
MIT License
src/main/kotlin/ee/deepmooc/model/GroupRegistrationEntity.kt
MTender
609,967,804
false
{"Kotlin": 70995, "Dockerfile": 133}
package ee.deepmooc.model import org.komapper.annotation.KomapperAutoIncrement import org.komapper.annotation.KomapperEntity import org.komapper.annotation.KomapperId import org.komapper.annotation.KomapperTable @KomapperEntity(aliases = ["groupRegistrations"]) @KomapperTable(name = "group_registrations") data class GroupRegistrationEntity( @KomapperId @KomapperAutoIncrement val id: Long = 0, val groupId: Long, val courseRegistrationId: Long )
0
Kotlin
0
0
28208b28d1db86efa0d7a391c3571443a4ab7297
472
deepmooc-backend
MIT License
app/src/main/kotlin/com/absinthe/libchecker/ui/fragment/detail/AppBundleBottomSheetDialogFragment.kt
allenymt
369,098,358
true
{"Kotlin": 580378, "Java": 96849, "Roff": 40506, "HTML": 125}
package com.absinthe.libchecker.ui.fragment.detail import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.absinthe.libchecker.bean.AppBundleItemBean import com.absinthe.libchecker.extensions.addSystemBarPadding import com.absinthe.libchecker.extensions.dp import com.absinthe.libchecker.recyclerview.VerticalSpacesItemDecoration import com.absinthe.libchecker.recyclerview.adapter.detail.AppBundleAdapter import com.absinthe.libchecker.ui.detail.EXTRA_PACKAGE_NAME import com.absinthe.libchecker.ui.fragment.BaseBottomSheetViewDialogFragment import com.absinthe.libchecker.utils.PackageUtils import com.absinthe.libchecker.view.app.BottomSheetHeaderView import com.absinthe.libchecker.view.detail.AppBundleBottomSheetView import com.absinthe.libchecker.view.detail.AppBundleItemView import java.io.File import java.util.* class AppBundleBottomSheetDialogFragment : BaseBottomSheetViewDialogFragment<AppBundleBottomSheetView>() { private val packageName by lazy { arguments?.getString(EXTRA_PACKAGE_NAME) } private val mAdapter = AppBundleAdapter() override fun initRootView(): AppBundleBottomSheetView = AppBundleBottomSheetView(requireContext()) override fun getHeaderView(): BottomSheetHeaderView = root.getHeaderView() override fun init() { root.apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) setPadding(24.dp, 16.dp, 24.dp, 0) } root.list.apply { adapter = mAdapter layoutManager = LinearLayoutManager(requireContext()) addItemDecoration(VerticalSpacesItemDecoration(4.dp)) addSystemBarPadding(addStatusBarPadding = false) } packageName?.let { val packageInfo = PackageUtils.getPackageInfo(it) val list = packageInfo.applicationInfo.splitSourceDirs val localeList by lazy { Locale.getISOLanguages() } val bundleList = list.map { split -> val name = split.substringAfterLast("/") val type = when { name.startsWith("split_config.arm") -> AppBundleItemView.IconType.TYPE_NATIVE_LIBS name.startsWith("split_config.x86") -> AppBundleItemView.IconType.TYPE_NATIVE_LIBS name.endsWith("dpi.apk") -> AppBundleItemView.IconType.TYPE_MATERIALS localeList.contains(name.removePrefix("split_config.").removeSuffix(".apk")) -> AppBundleItemView.IconType.TYPE_STRINGS else -> AppBundleItemView.IconType.TYPE_OTHERS } AppBundleItemBean(name = name, size = File(split).length(), type = type) } mAdapter.setList(bundleList) } } }
0
null
0
0
490de43cd33660491ab8ebb0f4a735dbb05d6913
2,861
LibChecker
Apache License 2.0
fallery/src/main/java/ir/mehdiyari/fallery/utils/MediaStoreObserver.kt
JojoStacy
349,338,456
true
{"Kotlin": 190004}
package ir.mehdiyari.fallery.utils import android.database.ContentObserver import android.net.Uri import android.os.Handler import android.provider.MediaStore import androidx.fragment.app.FragmentActivity import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LiveData import androidx.lifecycle.OnLifecycleEvent import kotlinx.coroutines.ExperimentalCoroutinesApi import java.lang.ref.WeakReference @OptIn(ExperimentalCoroutinesApi::class) internal class MediaStoreObserver constructor( handler: Handler, val context: WeakReference<FragmentActivity> ) : ContentObserver(handler), LifecycleObserver { private val _externalStorageChangeState = SingleLiveEvent<Uri?>() val externalStorageChangeState: LiveData<Uri?> = _externalStorageChangeState @OnLifecycleEvent(Lifecycle.Event.ON_START) fun registerObservers() { context.get()?.lifecycle?.addObserver(this) context.get()?.contentResolver?.registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, this ) context.get()?.contentResolver?.registerContentObserver( MediaStore.Images.Media.INTERNAL_CONTENT_URI, true, this ) context.get()?.contentResolver?.registerContentObserver( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, this ) context.get()?.contentResolver?.registerContentObserver( MediaStore.Video.Media.INTERNAL_CONTENT_URI, true, this ) } override fun onChange(selfChange: Boolean, uri: Uri?) { _externalStorageChangeState.value = uri } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onDestroy() { context.get()?.lifecycle?.removeObserver(this) context.get()?.contentResolver?.unregisterContentObserver(this) } }
0
null
0
0
cdda7c88f6ef84de1282d389a8b383765019b381
1,846
Fallery
Apache License 2.0
leic43d/ImageViewer/bin/main/pt/isel/leic/pc/imageviewer/filters/multi-threaded-filters.kt
isel-leic-pc
466,188,773
false
null
@file:Suppress("unused") package pt.isel.leic.pc.imageviewer.filters import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.luminance import androidx.compose.ui.graphics.toAwtImage import androidx.compose.ui.graphics.toComposeImageBitmap import java.awt.image.BufferedImage import java.util.concurrent.CountDownLatch import kotlin.system.measureTimeMillis /** * Converts the given image to its grayscale version (multithreaded version - MT) * (It uses the Luminosity method) * * Implementation notes: * - Multithreaded version that uses a fixed number of threads (EXPECTED_CORE_COUNT), regardless of the actual number * of cores in the target machine */ fun convertToGrayScaleMT(imageBitmap: ImageBitmap): ImageBitmap { val bufferedImage: BufferedImage = imageBitmap.toAwtImage() filtersLogger.info("Converting to gray scale (Single threaded approach)") filtersLogger.info("Image size is: width = ${bufferedImage.width}; height = ${bufferedImage.height}") val elapsed = measureTimeMillis { val latch = CountDownLatch(EXPECTED_CORE_COUNT) repeat(EXPECTED_CORE_COUNT) { Thread { val (xBounds, yBounds) = computePartitionBounds( width = bufferedImage.width, height = bufferedImage.height, partitionCount = EXPECTED_CORE_COUNT, partitionIndex = it ) bufferedImage.applyTransform(xBounds = xBounds, yBounds = yBounds) { val grayscaleValue = it.luminance() Color( red = grayscaleValue, green = grayscaleValue, blue = grayscaleValue, colorSpace = it.colorSpace, alpha = it.alpha ) } latch.countDown() }.start() } latch.await() } val result = bufferedImage.toComposeImageBitmap() filtersLogger.info("Converted to gray scale in $elapsed ms") return result } /** * Adjusts the brightness of the given image, producing the new image version (multithreaded version - MT) * * Implementation notes: * - Multithreaded version that uses a fixed number of threads (EXPECTED_CORE_COUNT), regardless of the actual number * of cores in the target machine * * @param imageBitmap the image to be processed * @param delta the brightness percentage variation in the interval [-1.0 ... 1.0] */ fun adjustBrightnessMT(imageBitmap: ImageBitmap, delta: Float): ImageBitmap { val bufferedImage: BufferedImage = imageBitmap.toAwtImage() filtersLogger.info("Adjusting brightness (Single threaded approach): ") filtersLogger.info("Image size is: width = ${bufferedImage.width}; height = ${bufferedImage.height}") val elapsedMillis = measureTimeMillis { val latch = CountDownLatch(EXPECTED_CORE_COUNT) repeat(EXPECTED_CORE_COUNT) { Thread { val (xBounds, yBounds) = computePartitionBounds( width = bufferedImage.width, height = bufferedImage.height, partitionCount = EXPECTED_CORE_COUNT, partitionIndex = it ) bufferedImage.applyTransform(xBounds = xBounds, yBounds = yBounds) { Color( red = (it.red + delta).coerceInRGB(), green = (it.green + delta).coerceInRGB(), blue = (it.blue + delta).coerceInRGB(), colorSpace = it.colorSpace, alpha = it.alpha ) } latch.countDown() }.start() } latch.await() } val result = bufferedImage.toComposeImageBitmap() filtersLogger.info("Adjusted brightness in $elapsedMillis ms") return result }
1
Kotlin
0
8
a9c586ee9563cf46340cdfd5de5a9981839a8af9
4,042
s2122v-li43d-li41n
MIT License
data/src/main/java/com/bottlerocketstudios/brarchitecture/data/crashreporting/ForceCrashLogic.kt
BottleRocketStudios
323,985,026
false
null
package com.bottlerocketstudios.brarchitecture.data.crashreporting /** Helper to force crashes in different scenarios. Intended to be used by DEV/QA to validate crash reporting library is configured properly. */ interface ForceCrashLogic { /** * Special logic for testing crash reports by throwing a [RuntimeException] on a matching [input] * * @throws RuntimeException */ fun forceCrashOnMatch(input: String?) /** * Only expected to be used by the dev options code! No-op if called on production release build. * * @throws RuntimeException */ fun forceCrashNow() }
1
Kotlin
1
9
e3014001732516e9feab58c862e0d84de9911c83
624
Android-ArchitectureDemo
Apache License 2.0
data/src/main/java/com/bottlerocketstudios/brarchitecture/data/crashreporting/ForceCrashLogic.kt
BottleRocketStudios
323,985,026
false
null
package com.bottlerocketstudios.brarchitecture.data.crashreporting /** Helper to force crashes in different scenarios. Intended to be used by DEV/QA to validate crash reporting library is configured properly. */ interface ForceCrashLogic { /** * Special logic for testing crash reports by throwing a [RuntimeException] on a matching [input] * * @throws RuntimeException */ fun forceCrashOnMatch(input: String?) /** * Only expected to be used by the dev options code! No-op if called on production release build. * * @throws RuntimeException */ fun forceCrashNow() }
1
Kotlin
1
9
e3014001732516e9feab58c862e0d84de9911c83
624
Android-ArchitectureDemo
Apache License 2.0
compiler/testData/diagnostics/testsWithStdLib/experimental/experimentalAfterRelease.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FIR_IDENTICAL // LANGUAGE: +OptInRelease @RequiresOptIn @Retention(AnnotationRetention.BINARY) annotation class Marker
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
123
kotlin
Apache License 2.0
krossbow-websocket-okhttp/src/test/kotlin/org/hildan/krossbow/websocket/okhttp/OkHttpWebSocketClientTest.kt
joffrey-bion
190,066,229
false
null
package org.hildan.krossbow.websocket.okhttp import org.hildan.krossbow.websocket.WebSocketClient import org.hildan.krossbow.websocket.test.WebSocketClientTestSuite class OkHttpWebSocketClientTest : WebSocketClientTestSuite() { override fun provideClient(): WebSocketClient = OkHttpWebSocketClient() }
12
Kotlin
7
82
e72a8d8254399e439c454b2d0a689011c297b22e
309
krossbow
MIT License
src/test/kotlin/com/cloudcontactai/smsreceiver/SmsProcessorApplicationTests.kt
CloudContactAI
373,336,471
false
null
/* Copyright 2021 Cloud Contact AI, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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.cloudcontactai.smstracker.model.message data class UpdateSmsStatusMessage( var id: Long? = null, var sid: String? = null, var status: String? = null, var errorCode: String? = null, var errorMessage: String? = null )
0
Kotlin
0
0
ffc0dce20fcd05a5d80389e1543d37ef8a014801
914
TwilioPolling
Apache License 2.0
apps/bekreftelse-api/src/main/kotlin/no/nav/paw/bekreftelse/api/topology/BekreftelseHendelseProcessor.kt
navikt
794,874,233
false
{"Kotlin": 929501, "Dockerfile": 143}
package no.nav.paw.bekreftelse.api.topology import io.micrometer.core.instrument.MeterRegistry import io.opentelemetry.api.trace.Span import io.opentelemetry.api.trace.SpanKind import io.opentelemetry.instrumentation.annotations.WithSpan import no.nav.paw.bekreftelse.api.model.InternState import no.nav.paw.bekreftelse.api.utils.buildStreamsLogger import no.nav.paw.bekreftelse.api.utils.ignorertBekreftelseHendeleCounter import no.nav.paw.bekreftelse.api.utils.lagreBekreftelseHendelseCounter import no.nav.paw.bekreftelse.api.utils.mottattBekreftelseHendelseKafkaCounter import no.nav.paw.bekreftelse.api.utils.slettetBekreftelseHendelseCounter import no.nav.paw.bekreftelse.internehendelser.BekreftelseHendelse import no.nav.paw.bekreftelse.internehendelser.BekreftelseMeldingMottatt import no.nav.paw.bekreftelse.internehendelser.BekreftelseTilgjengelig import no.nav.paw.bekreftelse.internehendelser.PeriodeAvsluttet import org.apache.kafka.streams.kstream.KStream import org.apache.kafka.streams.kstream.Named import org.apache.kafka.streams.processor.api.Processor import org.apache.kafka.streams.processor.api.ProcessorContext import org.apache.kafka.streams.processor.api.Record import org.apache.kafka.streams.state.KeyValueStore private val logger = buildStreamsLogger fun KStream<Long, BekreftelseHendelse>.oppdaterBekreftelseHendelseState( stateStoreName: String, meterRegistry: MeterRegistry ): KStream<Long, BekreftelseHendelse> { val processor = { BekreftelseHendelseProcessor(stateStoreName, meterRegistry) } return process(processor, Named.`as`("bekreftelseHendelseProcessor"), stateStoreName) } class BekreftelseHendelseProcessor( private val stateStoreName: String, private val meterRegistry: MeterRegistry ) : Processor<Long, BekreftelseHendelse, Long, BekreftelseHendelse> { private var stateStore: KeyValueStore<Long, InternState>? = null private var context: ProcessorContext<Long, BekreftelseHendelse>? = null override fun init(context: ProcessorContext<Long, BekreftelseHendelse>) { super.init(context) this.context = context stateStore = context.getStateStore(stateStoreName) } // TODO Legg til metrics @WithSpan override fun process(record: Record<Long, BekreftelseHendelse>?) { val hendelse = record?.value() ?: return val internStateStore = requireNotNull(stateStore) { "Intern state store er ikke initiert" } meterRegistry.mottattBekreftelseHendelseKafkaCounter(hendelse.hendelseType) logger.debug("Mottok hendelse av type {}", hendelse.hendelseType) when (hendelse) { is BekreftelseTilgjengelig -> { internStateStore.processBekreftelseTilgjengelig(meterRegistry, hendelse) } is BekreftelseMeldingMottatt -> { internStateStore.processBekreftelseMeldingMottatt(meterRegistry, hendelse) } is PeriodeAvsluttet -> { internStateStore.processPeriodeAvsluttet(meterRegistry, hendelse) } else -> { processAnnenHendelse(meterRegistry, hendelse) } } } } @WithSpan( value = "processBekreftelseTilgjengelig", kind = SpanKind.INTERNAL ) fun KeyValueStore<Long, InternState>.processBekreftelseTilgjengelig( meterRegistry: MeterRegistry, hendelse: BekreftelseTilgjengelig ) { val currentSpan = Span.current() currentSpan.setAttribute("paw.arbeidssoekerregisteret.hendelse.type", hendelse.hendelseType) currentSpan.setAttribute("paw.arbeidssoekerregisteret.aksjon", "lagrer_bekreftelse") meterRegistry.lagreBekreftelseHendelseCounter(hendelse.hendelseType) val internState = get(hendelse.arbeidssoekerId) if (internState != null) { val originalSize = internState.tilgjendeligeBekreftelser.size val tilgjengeligeBekreftelser = internState.tilgjendeligeBekreftelser + hendelse val nySize = tilgjengeligeBekreftelser.size logger.debug("Lagrer bekreftelse i eksisterende state ({} -> {})", originalSize, nySize) put(hendelse.arbeidssoekerId, InternState(tilgjengeligeBekreftelser)) } else { logger.debug("Lagrer bekreftelse i ny state ({} -> {})", 0, 1) put(hendelse.arbeidssoekerId, InternState(listOf(hendelse))) } } @WithSpan( value = "processBekreftelseMeldingMottatt", kind = SpanKind.INTERNAL ) fun KeyValueStore<Long, InternState>.processBekreftelseMeldingMottatt( meterRegistry: MeterRegistry, hendelse: BekreftelseMeldingMottatt ) { val currentSpan = Span.current() currentSpan.setAttribute("paw.arbeidssoekerregisteret.hendelse.type", hendelse.hendelseType) val internState = get(hendelse.arbeidssoekerId) if (internState != null) { val originalSize = internState.tilgjendeligeBekreftelser.size internState.tilgjendeligeBekreftelser .filterNot { it.bekreftelseId == hendelse.bekreftelseId } .let { bekreftelser -> if (bekreftelser.isEmpty()) { currentSpan.setAttribute("paw.arbeidssoekerregisteret.aksjon", "sletter_intern_state") meterRegistry.slettetBekreftelseHendelseCounter(hendelse.hendelseType) logger.debug("Sletter all state ({} -> {})", originalSize, 0) delete(hendelse.arbeidssoekerId) } else { val nySize = bekreftelser.size currentSpan.setAttribute("paw.arbeidssoekerregisteret.aksjon", "sletter_bekreftelser") meterRegistry.slettetBekreftelseHendelseCounter(hendelse.hendelseType, nySize.toLong()) logger.debug("Sletter bekreftelser ({} -> {})", originalSize, nySize) put(hendelse.arbeidssoekerId, InternState(bekreftelser)) } } } else { logger.warn("Mottok bekreftelsesmelding, men det finnes ingen state for arbeidssøker") } } @WithSpan( value = "processPeriodeAvsluttet", kind = SpanKind.INTERNAL ) fun KeyValueStore<Long, InternState>.processPeriodeAvsluttet( meterRegistry: MeterRegistry, hendelse: PeriodeAvsluttet ) { val currentSpan = Span.current() currentSpan.setAttribute("paw.arbeidssoekerregisteret.hendelse.type", hendelse.hendelseType) val internState = get(hendelse.arbeidssoekerId) if (internState != null) { val originalSize = internState.tilgjendeligeBekreftelser.size internState.tilgjendeligeBekreftelser .filterNot { it.periodeId == hendelse.periodeId } .let { bekreftelser -> if (bekreftelser.isEmpty()) { currentSpan.setAttribute("paw.arbeidssoekerregisteret.aksjon", "sletter_intern_state") meterRegistry.slettetBekreftelseHendelseCounter(hendelse.hendelseType) logger.debug("Sletter all state ({} -> {})", originalSize, 0) delete(hendelse.arbeidssoekerId) } else { val nySize = bekreftelser.size currentSpan.setAttribute("paw.arbeidssoekerregisteret.aksjon", "sletter_bekreftelser") meterRegistry.slettetBekreftelseHendelseCounter(hendelse.hendelseType, nySize.toLong()) logger.debug("Sletter bekreftelser for periode ({} -> {})", originalSize, nySize) put(hendelse.arbeidssoekerId, InternState(bekreftelser)) } } } else { logger.warn("Mottok melding om avsluttet periode, men det finnes ingen state for arbeidssøker") } } @WithSpan( value = "processAnnenHendelse", kind = SpanKind.INTERNAL ) fun processAnnenHendelse( meterRegistry: MeterRegistry, hendelse: BekreftelseHendelse ) { val currentSpan = Span.current() currentSpan.setAttribute("paw.arbeidssoekerregisteret.hendelse.type", hendelse.hendelseType) currentSpan.setAttribute("paw.arbeidssoekerregisteret.aksjon", "ignorerer_hendelse") meterRegistry.ignorertBekreftelseHendeleCounter(hendelse.hendelseType) logger.debug("Ignorerer hendelse av type {}", hendelse.hendelseType) }
4
Kotlin
0
1
fcf32a275c132d6190bb1fb8f36eb19a1fb6610c
8,212
paw-arbeidssoekerregisteret-monorepo-intern
MIT License
src/main/kotlin/org/audux/bgg/response/GeekList.kt
Bram--
716,669,280
false
null
/** * Copyright 2023-2024 Bram Wijnands * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.audux.bgg.response import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonRootName import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText import java.time.LocalDateTime import org.audux.bgg.common.Constants /** Encapsulates a geek list including its items and optionally its comments. */ @JsonRootName("geeklist") @JsonIgnoreProperties("postdate_timestamp", "editdate_timestamp") data class GeekList( /** Terms of use of the BGG API. */ @JacksonXmlProperty(isAttribute = true) val termsOfUse: String, /** Unique ID for the Geek list - same as in the request. */ @JacksonXmlProperty(isAttribute = true) val id: Int, /** The date and time the geek list was posted/published. */ @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val postDate: LocalDateTime, /** The date and time the geek list was last edited - the same as [postDate] if not edited. */ @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val editDate: LocalDateTime, /** The number of thumbs up/likes the geek list received. */ val thumbs: Int, /** The of number of items in the geek list. */ val numItems: Int, /** The username of the user that published this geek list. */ val username: String, /** The title of the geek list. */ val title: String, /** A more detailed description of the geek list. */ val description: String, /** The actual items in the geek list e.g. a list of board games. */ @JacksonXmlProperty(localName = "item") val items: List<GeekListItem> ) { /** The list of comments of this list. */ @JsonProperty("comment") var comments: List<GeekListComment> = mutableListOf() set(value) { field = field + value } } /** A single comment on either a Geek list or a Geek list item. */ data class GeekListComment( /** The username of the user that left the comment. */ @JacksonXmlProperty(isAttribute = true) val username: String, /** The date the comment was originally posted. */ @JacksonXmlProperty(isAttribute = true) @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val date: LocalDateTime, /** The date the comment was originally posted. */ @JacksonXmlProperty(isAttribute = true) @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val postDate: LocalDateTime, /** The date the comment was last edited - the same as [postDate] if not edited. */ @JacksonXmlProperty(isAttribute = true) @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val editDate: LocalDateTime, /** The number of thumbs up/likes on this item. */ @JacksonXmlProperty(isAttribute = true) val thumbs: Int, ) { /** The actual comment the user posted. */ // As this is the innerText of the XML element, using this in a (Kotlin) data class does // currently not work. See: https://github.com/FasterXML/jackson-module-kotlin/issues/138 @JsonDeserialize(using = TrimmedStringDeserializer::class) @JacksonXmlText var value: String? = null } /** An item in the geek list e.g. a board game including a description/[body] */ data class GeekListItem( /** The ID of the geek list item - NOT the id of the object. */ @JacksonXmlProperty(isAttribute = true) val id: Int, /** The type of object e.g. 'thing' or family. */ @JacksonXmlProperty(isAttribute = true) val objectType: String, /** The [org.audux.bgg.common.SubType] of the item e.g. a boardgame. */ @JsonDeserialize(using = SubTypeDeserializer::class) @JacksonXmlProperty(isAttribute = true) val subType: org.audux.bgg.common.SubType, /** The Name of the item/object e.g. the name of the game. */ @JacksonXmlProperty(isAttribute = true) val objectName: String, /** * The ID of the item/object which can be used in the [org.audux.bgg.request.familyItems] or * [org.audux.bgg.request.things] API. */ @JacksonXmlProperty(isAttribute = true) val objectId: Int, /** The username of the user that added this item to the geek list. */ @JacksonXmlProperty(isAttribute = true) val username: String, /** The original date this item was added/posted to the list. */ @JacksonXmlProperty(isAttribute = true) @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val postDate: LocalDateTime, /** The date this item was last edited/changed. */ @JacksonXmlProperty(isAttribute = true) @JsonFormat(pattern = Constants.DAY_FIRST_DATE_TIME_FORMAT) val editDate: LocalDateTime, /** The number of thumbs up/likes this item has received. */ @JacksonXmlProperty(isAttribute = true) val thumbs: Int, /** * The Image ID this item, these can be formatted as an URL as follows: `* * https://boardgamegeek.com/image/$imageId to display/look up the image. */ @JacksonXmlProperty(isAttribute = true) val imageId: Int? = null, @JsonDeserialize(using = TrimmedStringDeserializer::class) val body: String, ) { /** The list of comments of this list. */ @JsonProperty("comment") var comments: List<GeekListComment> = mutableListOf() set(value) { field = field + value } }
0
null
1
9
6d4f2425848fcc8ffe97419859b52b56d53fd142
6,114
bggclient
Apache License 2.0
shared/src/commonMain/kotlin/dev/efrenospino/kwtodo/models/Task.kt
efrenospino
752,048,783
false
{"Kotlin": 19613, "Dockerfile": 438, "HTML": 304}
package dev.efrenospino.kwtodo.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Task( @SerialName("id") val id: Int? = null, @SerialName("name") val name: String, @SerialName("completed") val completed: Boolean, @SerialName("created_at") val createdAt: String, @SerialName("updated_at") val updatedAt: String, )
0
Kotlin
0
0
d2b603fcc5b69016a43bb99fd6b3cddee082e092
398
kotlin-wasm-todo
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1010007.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position /* import xyz.qwewqa.relive.simulator.core.presets.condition.* import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress1010007 import xyz.qwewqa.relive.simulator.core.stage.Act import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory import xyz.qwewqa.relive.simulator.core.stage.autoskill.new import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint import xyz.qwewqa.relive.simulator.core.stage.buff.* import xyz.qwewqa.relive.simulator.core.stage.passive.* import xyz.qwewqa.relive.simulator.core.stage.stageeffect.* val dress = dress1010007( name = "ダ・ヴィンチ", acts = listOf( ActType.Act1.blueprint("斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [88, 92, 96, 101, 105] times1: 1 */ } }, ActType.Act2.blueprint("キラめきの斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [93, 98, 102, 107, 112] times1: 1 キラめき回復(%value%) target: 自身 hit_rate2: 100 values2: [20, 20, 20, 20, 20] times2: [0, 0, 0, 0, 0] */ } }, ActType.Act3.blueprint("回避の独奏") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [132, 138, 145, 151, 158] times1: 1 回避 target: 自身 hit_rate2: 100 values2: [0, 0, 0, 0, 0] times2: [1, 1, 1, 1, 1] */ } }, ActType.ClimaxAct.blueprint("ルネサンス方程式!") { Act { /* %attr%属性攻撃(威力%value%) target: 後ろから3体の敵役 hit_rate1: 100 values1: [164, 172, 181, 189, 197] times1: 3 混乱 target: 後ろから3体の敵役 hit_rate2: 66 values2: [0, 0, 0, 0, 0] times2: [2, 2, 2, 2, 2] */ } } ), autoSkills = listOf( listOf( /* auto skill 1: 被ダメージダウン(%value%) target: 自身 values: [4, 4, 5, 5, 6] */ ), listOf( /* auto skill 2: 回避 target: 自身 hit_rate: 100 value: 0 time: 1 */ ), listOf( /* auto skill 3: 不屈 target: 自身 hit_rate: 100 value: 0 time: 1 */ ), ), unitSkill = null /* 宙・星属性の舞台少女のACTパワーアップ %opt1_value%%(MAX15%) クリティカル威力アップ %opt2_value%%(MAX15%) */, multipleCA = false, categories = setOf(), ) */ val dress1010007 = PartialDressBlueprint( id = 1010007, name = "ダ・ヴィンチ", baseRarity = 4, cost = 12, character = Character.Karen, attribute = Attribute.Space, damageType = DamageType.Normal, position = Position.Back, positionValue = 32050, stats = StatData( hp = 1101, actPower = 167, normalDefense = 82, specialDefense = 75, agility = 152, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 36290, actPower = 2750, normalDefense = 1350, specialDefense = 1240, agility = 2500, ), actParameters = mapOf( ActType.Act1 to ActBlueprint( name = "斬撃", type = ActType.Act1, apCost = 1, icon = 1, parameters = listOf( actParameters0, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ActType.Act2 to ActBlueprint( name = "キラめきの斬撃", type = ActType.Act2, apCost = 2, icon = 89, parameters = listOf( actParameters2, actParameters3, actParameters1, actParameters1, actParameters1, ), ), ActType.Act3 to ActBlueprint( name = "回避の独奏", type = ActType.Act3, apCost = 3, icon = 34, parameters = listOf( actParameters7, actParameters25, actParameters1, actParameters1, actParameters1, ), ), ActType.ClimaxAct to ActBlueprint( name = "ルネサンス方程式!", type = ActType.ClimaxAct, apCost = 2, icon = 59, parameters = listOf( actParameters26, actParameters27, actParameters1, actParameters1, actParameters1, ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = growthBoard3, friendshipPanels = friendshipPattern0, remakeParameters = listOf( StatData( hp = 6300, actPower = 450, normalDefense = 300, specialDefense = 90, agility = 270, ), StatData( hp = 10500, actPower = 750, normalDefense = 500, specialDefense = 150, agility = 450, ), StatData( hp = 16800, actPower = 1200, normalDefense = 800, specialDefense = 240, agility = 720, ), StatData( hp = 21000, actPower = 1500, normalDefense = 1000, specialDefense = 300, agility = 900, ), ), )
0
Kotlin
11
7
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
6,485
relight
MIT License
src/jvmMain/kotlin/com/sdercolin/vlabeler/model/action/Action.kt
sdercolin
503,365,242
false
null
package com.sdercolin.vlabeler.model.action import com.sdercolin.vlabeler.ui.string.Language /** * An action that is registered in the keymaps. */ sealed interface Action { /** * The order of the action in the keymap list. */ val displayOrder: Int /** * The localized title of the action. */ fun getTitle(language: Language): String /** * A hash code to determine if key binds are in the same conflict group. */ val conflictGroupHash: Int get() = 0 }
1
Kotlin
13
96
3d6a884419d3946664763102ca4177858e1a5460
520
vlabeler
Apache License 2.0
app/src/main/java/com/example/flickerexample/core/extensions/SharedPref.kt
memorex386
197,053,869
false
null
package com.example.flickerexample.core.extensions import android.content.Context import com.example.flickerexample.core.app object SharedPref { val pref by lazy { app.getSharedPreferences(app.packageName, Context.MODE_PRIVATE) } }
1
null
1
1
98437677d8ed9d4f9f2305a774d37249dc076502
239
FlickrFindr
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/settings/SettingsFragment.kt
saletrak
102,412,247
true
{"Kotlin": 211185}
package io.github.feelfreelinux.wykopmobilny.ui.modules.settings import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.support.v7.preference.CheckBoxPreference import android.support.v7.preference.ListPreference import android.support.v7.preference.PreferenceFragmentCompat import android.view.MenuItem import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.WykopApp import io.github.feelfreelinux.wykopmobilny.base.BaseActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.NavigatorApi import io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice.WykopNotificationsJob import io.github.feelfreelinux.wykopmobilny.utils.SettingsPreferencesApi import kotlinx.android.synthetic.main.toolbar.* import javax.inject.Inject class SettingsActivity : BaseActivity() { companion object { val THEME_CHANGED_EXTRA = "THEME_CHANGED" val THEME_CHANGED_RESULT = 154 fun createIntent(context: Context): Intent { return Intent(context, SettingsActivity::class.java) } } @Inject lateinit var navigatorApi: NavigatorApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WykopApp.uiInjector.inject(this) setContentView(R.layout.activity_settings) setSupportActionBar(toolbar) supportActionBar?.title = "Ustawienia" supportActionBar?.setDisplayHomeAsUpEnabled(true) supportFragmentManager.beginTransaction() .replace(R.id.settings_fragment, SettingsFragment()) .commit() } class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { @Inject lateinit var settingsApi: SettingsPreferencesApi override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) WykopApp.uiInjector.inject(this) } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.app_preferences) (findPreference("notificationsSchedulerDelay") as ListPreference).apply { summary = entry } (findPreference("hotEntriesScreen") as ListPreference).apply { summary = entry } } override fun onSharedPreferenceChanged(sharedPrefs: SharedPreferences, key: String) { val pref = findPreference(key) if (pref is ListPreference) { pref.setSummary(pref.entry) } else if (pref is CheckBoxPreference) { when (pref.key) { "useDarkTheme" -> { restartActivity() } "showNotifications" -> { WykopNotificationsJob.schedule(settingsApi) } } } } override fun onResume() { super.onResume() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } private fun restartActivity() { val intent = Intent(context, SettingsActivity::class.java) intent.putExtra(THEME_CHANGED_EXTRA, true) startActivity(intent) activity.finish() } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> onBackPressed() } return true } override fun onBackPressed() { if (intent.hasExtra(THEME_CHANGED_EXTRA)) { setResult(THEME_CHANGED_RESULT) navigatorApi.openMainActivity(this) } finish() } }
0
Kotlin
0
0
0f2b65a46888e193134e8b94dacf5653ce5bb0ea
4,072
WykopMobilny
MIT License
rainbow-cake-channels/src/main/java/co/zsmb/rainbowcake/channels/SynchronizedChannelCollection.kt
xirt4m
220,315,206
true
{"Kotlin": 103043, "Shell": 1714, "Java": 601}
package co.zsmb.rainbowcake.channels import kotlinx.coroutines.channels.Channel /** * An implementation of the [ChannelCollection] interface that may be * safely used from multiple threads. * * When implementing a data source that produces events for multiple * channels, this helper class may be subclassed by the data source, * its callback, or be delegated to by either of them. */ class SynchronizedChannelCollection<T> : ChannelCollection<T> { private val channels = mutableListOf<Channel<T>>() override fun forEachChannel(actions: (Channel<T>) -> Unit) { synchronized(channels) { channels.forEach(actions) } } override fun clear() { synchronized(channels) { channels.clear() } } override fun addChannel(channel: Channel<T>): Boolean { synchronized(channels) { channels += channel return channels.size == 1 } } override fun removeChannel(channel: Channel<T>): Boolean { synchronized(channels) { channels -= channel return channels.isNotEmpty() } } }
0
null
0
0
a9442c5c437ce9f215df3134c4b50534bf56e19a
1,142
rainbowcake
Apache License 2.0
health/health-services-client/src/main/java/androidx/health/services/client/data/DataPoints.kt
RikkaW
389,105,112
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client.data import android.content.Intent import androidx.annotation.Keep import java.time.Duration import java.util.ArrayList /** Helper class to facilitate working with [DataPoint] s. */ // TODO(b/177504986): Remove all @Keep annotations once we figure out why this class gets stripped // away by proguard. @Keep public object DataPoints { /** * When using [DataType.LOCATION], the value is represented as `double[]`. The `double` value at * this index represents the latitude. */ public const val LOCATION_DATA_POINT_LATITUDE_INDEX: Int = 0 /** * When using [DataType.LOCATION], the value is represented as `double[]`. The `double` value at * this index represents the longitude. */ public const val LOCATION_DATA_POINT_LONGITUDE_INDEX: Int = 1 /** * When using [DataType.LOCATION], the value is represented as `double[]`. The `double` value at * this index represents the altitude. This is an optional index and there is no guarantee that * this index will be present. */ public const val LOCATION_DATA_POINT_ALTITUDE_INDEX: Int = 2 /** Name of intent extra containing the data points set on pending intent. */ private const val EXTRA_DATA_POINTS: String = "whs.data_points_list" /** Name of intent extra containing whether permissions are granted or not. */ private const val EXTRA_PERMISSIONS_GRANTED: String = "whs.data_points_has_permissions" /** Retrieves the [DataPoint] s that are contained in the given [Intent], if any. */ @JvmStatic @Keep public fun getDataPoints(intent: Intent): List<DataPoint> = intent.getParcelableArrayListExtra(EXTRA_DATA_POINTS) ?: listOf() /** Puts the given [DataPoint] s in the given [Intent]. */ @JvmStatic public fun putDataPoints(intent: Intent, dataPoints: Collection<DataPoint>) { val copy = ArrayList(dataPoints) intent.putParcelableArrayListExtra(EXTRA_DATA_POINTS, copy) } /** Sets whether [DataPoint] permissions are `granted` in the given [Intent]. */ @JvmStatic public fun putPermissionsGranted(intent: Intent, granted: Boolean) { intent.putExtra(EXTRA_PERMISSIONS_GRANTED, granted) } /** Retrieves whether permissions are granted in this [Intent]. */ @JvmStatic public fun getPermissionsGranted(intent: Intent): Boolean = intent.getBooleanExtra(EXTRA_PERMISSIONS_GRANTED, true) /** Creates a new [DataPoint] of type [DataType.STEPS] with the given `steps`. */ @JvmStatic public fun steps( steps: Long, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.STEPS, Value.ofLong(steps), startDurationFromBoot, endDurationFromBoot ) /** * Creates a new [DataPoint] of type [DataType.STEPS_PER_MINUTE] with the given * `stepsPerMinute`. */ @JvmStatic public fun stepsPerMinute(stepsPerMinute: Long, startDurationFromBoot: Duration): DataPoint = DataPoint.createSample( DataType.STEPS_PER_MINUTE, Value.ofLong(stepsPerMinute), startDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.DISTANCE] with the given `meters`. */ @JvmStatic public fun distance( meters: Double, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.DISTANCE, Value.ofDouble(meters), startDurationFromBoot, endDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.ELEVATION] with the given `meters`. */ @JvmStatic public fun elevation( meters: Double, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.ELEVATION, Value.ofDouble(meters), startDurationFromBoot, endDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.ALTITUDE] with the given `meters`. */ @JvmStatic public fun altitude(meters: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample(DataType.ALTITUDE, Value.ofDouble(meters), durationFromBoot) /** Creates a new [DataPoint] of type [DataType.FLOORS] with the given `floors`. */ @JvmStatic public fun floors( floors: Double, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.FLOORS, Value.ofDouble(floors), startDurationFromBoot, endDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.TOTAL_CALORIES] with the given `kcalories`. */ @JvmStatic public fun calories( kcalories: Double, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.TOTAL_CALORIES, Value.ofDouble(kcalories), startDurationFromBoot, endDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.SWIMMING_STROKES] with the given `kcalories`. */ @JvmStatic public fun swimmingStrokes( strokes: Long, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.SWIMMING_STROKES, Value.ofLong(strokes), startDurationFromBoot, endDurationFromBoot ) /** * Creates a new [DataPoint] of type [DataType.LOCATION] with the given `latitude` and * `longitude`. */ @JvmStatic public fun location( latitude: Double, longitude: Double, durationFromBoot: Duration ): DataPoint = DataPoint.createSample( DataType.LOCATION, Value.ofDoubleArray(latitude, longitude), durationFromBoot ) /** * Creates a new [DataPoint] of type [DataType.LOCATION] with the given `latitude`, `longitude` * and `altitude`. */ @JvmStatic public fun location( latitude: Double, longitude: Double, altitude: Double, durationFromBoot: Duration ): DataPoint = DataPoint.createSample( DataType.LOCATION, Value.ofDoubleArray(latitude, longitude, altitude), durationFromBoot ) /** Creates a new [DataPoint] of type [DataType.SPEED] with the given `metersPerSecond`. */ @JvmStatic public fun speed(metersPerSecond: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample(DataType.SPEED, Value.ofDouble(metersPerSecond), durationFromBoot) /** Creates a new [DataPoint] of type [DataType.PACE] with the given `millisPerKm`. */ @JvmStatic public fun pace(millisPerKm: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample(DataType.PACE, Value.ofDouble(millisPerKm), durationFromBoot) /** Creates a new [DataPoint] of type [DataType.HEART_RATE_BPM] with the given `bpm`. */ @JvmStatic public fun heartRate(bpm: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample(DataType.HEART_RATE_BPM, Value.ofDouble(bpm), durationFromBoot) /** Creates a new [DataPoint] of type [DataType.SPO2] with the given `percent`. */ @JvmStatic public fun spo2(percent: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample(DataType.SPO2, Value.ofDouble(percent), durationFromBoot) /** * Creates a new [DataPoint] of type [DataType.AGGREGATE_DISTANCE] with the given `distance`. */ @JvmStatic public fun aggregateDistance( distance: Double, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.AGGREGATE_DISTANCE, Value.ofDouble(distance), startDurationFromBoot, endDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.AGGREGATE_STEP_COUNT] with the given `steps`. */ @JvmStatic public fun aggregateSteps( steps: Long, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.AGGREGATE_STEP_COUNT, Value.ofLong(steps), startDurationFromBoot, endDurationFromBoot ) /** * Creates a new [DataPoint] of type [DataType.AGGREGATE_CALORIES_EXPENDED] with the given * `kcalories`. */ @JvmStatic public fun aggregateCalories( kcalories: Double, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.AGGREGATE_CALORIES_EXPENDED, Value.ofDouble(kcalories), startDurationFromBoot, endDurationFromBoot ) /** * Creates a new [DataPoint] of type [DataType.AGGREGATE_SWIMMING_STROKE_COUNT] with the given * `swimmingStrokes`. */ @JvmStatic public fun aggregateSwimmingStrokes( swimmingStrokes: Long, startDurationFromBoot: Duration, endDurationFromBoot: Duration ): DataPoint = DataPoint.createInterval( DataType.AGGREGATE_SWIMMING_STROKE_COUNT, Value.ofLong(swimmingStrokes), startDurationFromBoot, endDurationFromBoot ) /** Creates a new [DataPoint] of type [DataType.AVERAGE_PACE] with the given `millisPerKm`. */ @JvmStatic public fun averagePace(millisPerKm: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample(DataType.AVERAGE_PACE, Value.ofDouble(millisPerKm), durationFromBoot) /** * Creates a new [DataPoint] of type [DataType.AVERAGE_SPEED] with the given `metersPerSecond`. */ @JvmStatic public fun averageSpeed(metersPerSecond: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample( DataType.AVERAGE_SPEED, Value.ofDouble(metersPerSecond), durationFromBoot ) /** Creates a new [DataPoint] of type [DataType.MAX_SPEED] with the given `metersPerSecond`. */ @JvmStatic public fun maxSpeed(metersPerSecond: Double, durationFromBoot: Duration): DataPoint = DataPoint.createSample( DataType.MAX_SPEED, Value.ofDouble(metersPerSecond), durationFromBoot ) }
0
null
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
11,426
androidx
Apache License 2.0
src/jsMain/kotlin/baaahs/app/ui/ControlsPaletteView.kt
baaahs
174,897,412
false
{"Kotlin": 4815967, "C": 1529197, "C++": 661363, "GLSL": 412779, "JavaScript": 61944, "HTML": 56242, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.app.ui import baaahs.app.ui.layout.gridItem import baaahs.show.live.ControlProps import baaahs.show.live.ControlsInfo import baaahs.show.live.OpenShow import baaahs.ui.and import baaahs.ui.gridlayout.Layout import baaahs.ui.gridlayout.LayoutItem import baaahs.ui.gridlayout.gridLayout import baaahs.ui.unaryMinus import baaahs.ui.unaryPlus import baaahs.ui.xComponent import baaahs.util.useResizeListener import external.react_draggable.Draggable import external.react_resizable.Resizable import external.react_resizable.ResizeCallbackData import external.react_resizable.buildResizeHandle import materialui.icon import mui.material.Paper import org.w3c.dom.events.MouseEvent import react.Props import react.RBuilder import react.RHandler import react.dom.div import react.dom.header import react.useContext import web.html.HTMLElement private val ControlsPaletteView = xComponent<ControlsPaletteProps>("ControlsPalette") { props -> val appContext = useContext(appContext) val editMode = observe(appContext.showManager.editMode) val unplacedControlPaletteDiv = ref<HTMLElement>() val editModeStyle = if (editMode.isOn) Styles.editModeOn else Styles.editModeOff var layoutDimens by state { 100 to 100 } val containerDiv = ref<HTMLElement>() useResizeListener(containerDiv) { width, height -> layoutDimens = width to height } val handleResize by handler { e: MouseEvent, data: ResizeCallbackData -> unplacedControlPaletteDiv.current?.style?.width = "${data.size.width}px" unplacedControlPaletteDiv.current?.style?.height = "${data.size.height}px" } Draggable { val styleForDragHandle = "ControlsPaletteDragHandle" attrs.handle = ".$styleForDragHandle" Resizable { attrs.handle = ::buildResizeHandle attrs.width = unplacedControlPaletteDiv.current?.clientWidth ?: 0 attrs.height = unplacedControlPaletteDiv.current?.clientHeight ?: 0 attrs.onResize = handleResize div(+editModeStyle and Styles.unplacedControlsPalette) { ref = unplacedControlPaletteDiv div(+Styles.dragHandle and styleForDragHandle) { icon(mui.icons.material.DragIndicator) } Paper { attrs.className = -Styles.unplacedControlsPaper attrs.elevation = 3 header { +"Unplaced Controls" } div(+Styles.unplacedControlsDroppable) { ref = containerDiv if (editMode.isOn) { val styles = appContext.allStyles.layout val paletteWidth = layoutDimens.first val columns = if (paletteWidth > 200) paletteWidth / 100 else paletteWidth / 75 val controlsInfo = props.show.getSnapshot().controlsInfo val items = controlsInfo.relevantUnplacedControls val rows = items.size / columns + 1 val gridRowHeight = paletteWidth / columns val layout = Layout(items.mapIndexed { index, openControl -> LayoutItem(index % columns, index / columns, 1, 1, openControl.id) }, columns, rows) gridLayout { attrs.id = "_control_palette_" attrs.className = +styles.gridContainer attrs.width = paletteWidth.toDouble() attrs.autoSize = false attrs.cols = columns attrs.rowHeight = gridRowHeight.toDouble() attrs.maxRows = rows attrs.margin = 5 to 5 attrs.layout = layout // attrs.onLayoutChange = handleLayoutChange attrs.disableDrag = !editMode.isOn attrs.disableResize = true attrs.isDroppable = editMode.isOn // attrs.onDragStart = handleDragStart // attrs.onDragStop = handleDragStop items.forEachIndexed { index, item -> div(+styles.gridCell) { key = item.id gridItem { attrs.control = item attrs.controlProps = props.controlProps.withLayout(null, null, null) attrs.className = -styles.controlBox } } } } } } } } } } } external interface ControlsPaletteProps : Props { var controlsInfo: ControlsInfo var controlProps: ControlProps var show: OpenShow } fun RBuilder.controlsPalette(handler: RHandler<ControlsPaletteProps>) = child(ControlsPaletteView, handler = handler)
113
Kotlin
13
40
4dd92e5859d743ed7186caa55409f676d6408c95
5,410
sparklemotion
MIT License
app/src/androidTest/java/org/jdc/template/ui/activity/SmokeTest.kt
spach10
227,196,527
false
null
package org.jdc.template.ui.activity import android.view.View import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Espresso.pressBack import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withContentDescription import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withParent import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import org.hamcrest.Matchers.allOf import org.jdc.template.CustomMatchers.recyclerViewWithItemCount import org.jdc.template.R import org.jdc.template.ux.startup.StartupActivity import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SmokeTest { @Rule @JvmField var mActivityTestRule = ActivityTestRule(StartupActivity::class.java) @Test fun smokeTest() { val overflowMenuButton = onView(allOf<View>(withContentDescription("More options"), isDisplayed())) overflowMenuButton.perform(click()) val aboutMenuView = onView(allOf<View>(withId(R.id.title), withText("About"), isDisplayed())) aboutMenuView.perform(click()) val createDatabaseButton = onView(allOf<View>(withId(R.id.createDatabaseButton), withText("Create Database"), isDisplayed())) createDatabaseButton.perform(click()) pressBack() val directoryRecyclerView = onView(allOf<View>(withId(R.id.recyclerView), isDisplayed())) directoryRecyclerView.check(matches(recyclerViewWithItemCount(3))) directoryRecyclerView.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click())) val nameTextView = onView(allOf<View>(withId(R.id.nameTextView), withText("<NAME>"), isDisplayed())) nameTextView.check(matches(withText("<NAME>"))) val editMenuItemView = onView(allOf<View>(withId(R.id.menu_item_edit), withContentDescription("Edit"), isDisplayed())) editMenuItemView.perform(click()) val firstNameEditText = onView(allOf<View>(withId(R.id.firstNameEditText), withText("Jeff"), isDisplayed())) firstNameEditText.perform(click()) val firstNameEditText2 = onView(allOf<View>(withId(R.id.firstNameEditText), withText("Jeff"), isDisplayed())) firstNameEditText2.perform(replaceText("Jeffery")) val saveMenuItemView = onView(allOf<View>(withId(R.id.menu_item_save), withText("Save"), isDisplayed())) saveMenuItemView.perform(click()) val nameTextView2 = onView(allOf<View>(withId(R.id.nameTextView), withText("<NAME>"), isDisplayed())) nameTextView2.check(matches(withText("<NAME>"))) val imageButton = onView( allOf<View>(withContentDescription("Navigate up"), withParent(allOf<View>(withId(R.id.mainToolbar), isDisplayed())), isDisplayed())) imageButton.perform(click()) val listItemTextView = onView( allOf<View>(withId(R.id.listItemTextView), withText("<NAME>"), withParent(allOf<View>(withId(R.id.listItemLayout), withParent(withId(R.id.recyclerView)))), isDisplayed())) listItemTextView.check(matches(withText("<NAME>"))) val directoryRecyclerView2 = onView( allOf<View>(withId(R.id.recyclerView), isDisplayed())) directoryRecyclerView2.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(2, click())) val deleteMenuItemView = onView(allOf<View>(withId(R.id.menu_item_delete), withContentDescription("Delete"), isDisplayed())) deleteMenuItemView.perform(click()) val deleteDialogButton = onView(allOf<View>(withId(R.id.md_button_positive), withText("Delete"), isDisplayed())) deleteDialogButton.perform(click()) val directoryRecyclerView3 = onView(allOf<View>(withId(R.id.recyclerView), isDisplayed())) directoryRecyclerView3.check(matches(recyclerViewWithItemCount(2))) } }
0
Kotlin
0
1
28be446d63414cda728d06782fde7351082a0185
4,442
directory
Apache License 2.0
app/src/main/java/com/minew/wristbanddemo/OperationViewModel.kt
minewdevelop
316,447,891
false
{"Java": 26549, "Kotlin": 2255}
package com.minew.wristbanddemo import android.os.Parcel import android.os.Parcelable import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.minew.wristband.ble.bean.WristbandModule import com.minew.wristband.ble.manager.MinewWristbandManager class OperationViewModel : ViewModel() { private val manager = MinewWristbandManager.getInstance(DemoApp.getInstance()) val deviceInfoLiveData = MutableLiveData<ReadDeviceInfo>() fun readDeviceInfo(module:WristbandModule) { val readDeviceInfo = ReadDeviceInfo() if (module.firmwareVersionCode <= 2) { deviceInfoLiveData.value = readDeviceInfo return } manager.readAlarmGear(module) { gear -> readDeviceInfo.gear = gear if (module.hasTemperatureSensor()) { manager.readTempAlarmValue(module) {alarmValue -> readDeviceInfo.alarmValue = alarmValue manager.readTempeMeasureInterval(module) {interval -> readDeviceInfo.measureInterval = interval deviceInfoLiveData.value = readDeviceInfo } } } else { deviceInfoLiveData.value = readDeviceInfo } } } } data class ReadDeviceInfo( var gear:Int?= null, var alarmValue:Float?= null, var measureInterval:Int?= null) : Parcelable { constructor(parcel: Parcel) : this( parcel.readValue(Int::class.java.classLoader) as? Int, parcel.readValue(Float::class.java.classLoader) as? Float, parcel.readValue(Int::class.java.classLoader) as? Int) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(gear) parcel.writeValue(alarmValue) parcel.writeValue(measureInterval) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ReadDeviceInfo> { override fun createFromParcel(parcel: Parcel): ReadDeviceInfo { return ReadDeviceInfo(parcel) } override fun newArray(size: Int): Array<ReadDeviceInfo?> { return arrayOfNulls(size) } } }
1
null
1
1
da865e11c8d6259bb8c58850948827c5da8462ea
2,255
WristbandKit
MIT License
app/src/main/java/com/minew/wristbanddemo/OperationViewModel.kt
minewdevelop
316,447,891
false
{"Java": 26549, "Kotlin": 2255}
package com.minew.wristbanddemo import android.os.Parcel import android.os.Parcelable import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.minew.wristband.ble.bean.WristbandModule import com.minew.wristband.ble.manager.MinewWristbandManager class OperationViewModel : ViewModel() { private val manager = MinewWristbandManager.getInstance(DemoApp.getInstance()) val deviceInfoLiveData = MutableLiveData<ReadDeviceInfo>() fun readDeviceInfo(module:WristbandModule) { val readDeviceInfo = ReadDeviceInfo() if (module.firmwareVersionCode <= 2) { deviceInfoLiveData.value = readDeviceInfo return } manager.readAlarmGear(module) { gear -> readDeviceInfo.gear = gear if (module.hasTemperatureSensor()) { manager.readTempAlarmValue(module) {alarmValue -> readDeviceInfo.alarmValue = alarmValue manager.readTempeMeasureInterval(module) {interval -> readDeviceInfo.measureInterval = interval deviceInfoLiveData.value = readDeviceInfo } } } else { deviceInfoLiveData.value = readDeviceInfo } } } } data class ReadDeviceInfo( var gear:Int?= null, var alarmValue:Float?= null, var measureInterval:Int?= null) : Parcelable { constructor(parcel: Parcel) : this( parcel.readValue(Int::class.java.classLoader) as? Int, parcel.readValue(Float::class.java.classLoader) as? Float, parcel.readValue(Int::class.java.classLoader) as? Int) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(gear) parcel.writeValue(alarmValue) parcel.writeValue(measureInterval) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ReadDeviceInfo> { override fun createFromParcel(parcel: Parcel): ReadDeviceInfo { return ReadDeviceInfo(parcel) } override fun newArray(size: Int): Array<ReadDeviceInfo?> { return arrayOfNulls(size) } } }
1
null
1
1
da865e11c8d6259bb8c58850948827c5da8462ea
2,255
WristbandKit
MIT License
server/src/main/kotlin/com/github/tamasoszko/temp/DummyUserProvider.kt
tamasoszko
386,562,523
false
{"JavaScript": 44131, "Kotlin": 28083, "HTML": 1721, "Groovy": 1251, "CSS": 58}
package com.github.tamasoszko.temp import com.github.tamasoszko.dataprovider.UserProvider import com.github.tamasoszko.config.AppConfig import javax.inject.Inject import javax.inject.Singleton @Singleton class DummyUserProvider @Inject constructor(private val appConfig: AppConfig) : UserProvider { override fun getByUsername(username: String) = appConfig.dummyUsers?.firstOrNull { it.username == username } override fun getById(id: String) = appConfig.dummyUsers?.firstOrNull { it.id == id } override fun getAll() = appConfig.dummyUsers ?: emptyList() }
0
JavaScript
0
0
5a83999565180af57378614671c737622f37e3d5
595
ReactDemo
Apache License 2.0
music/commands/src/main/kotlin/dev/schlaubi/mikmusic/commands/RadioCommand.kt
DRSchlaubi
409,332,765
false
{"Kotlin": 343748, "Java": 5154, "Dockerfile": 201, "Shell": 197, "PowerShell": 96}
package dev.schlaubi.mikmusic.commands import com.kotlindiscord.kord.extensions.commands.Arguments import com.kotlindiscord.kord.extensions.commands.converters.impl.string class RadioArguments : Arguments() { val query by string { name = "query" description = "commands.radio.arguments.query.description" } } /* suspend fun MusicModule.radioCommand() { ephemeralSlashCommand(::RadioArguments) { name = "radio" description = "commands.radio.description" check { joinSameChannelCheck(bot) } action { val results = musicPlayer.loadItem("ytsearch: ${arguments.query}") val track = results.tracks.firstOrNull()?.toTrack() val videoId = track?.youtubeId if (track == null || videoId == null) { discordError(translate("commands.radio.invalid_vide")) } musicPlayer.enableAutoPlay(videoId, radioParam) musicPlayer.queueTrack(force = false, onTop = false, tracks = listOf(SimpleQueuedTrack(track, user.id))) respond { content = translate("commands.radio.queued") } } } } */
16
Kotlin
12
36
3f2f68bfdc5b6f9140c06d3d0d864ccf6f6bc963
1,203
mikbot
MIT License
app/src/main/java/net/yoedtos/intime/view/TasksActivity.kt
yoedtos
545,882,351
false
{"Kotlin": 102634}
package net.yoedtos.intime.view import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_tasks.* import net.yoedtos.intime.R import net.yoedtos.intime.model.Constants import net.yoedtos.intime.model.entity.Card import net.yoedtos.intime.model.entity.Task import net.yoedtos.intime.service.ResultListener import net.yoedtos.intime.service.TasksService import net.yoedtos.intime.view.ViewUtils.setupActionBar import net.yoedtos.intime.view.adapter.TaskItemsAdapter import net.yoedtos.intime.view.info.ErrorAlert import net.yoedtos.intime.view.info.Progress import net.yoedtos.intime.view.listener.ChangeListener import net.yoedtos.intime.view.listener.CardClickListener private val LOG_TAG = TasksActivity::class.java.simpleName class TasksActivity: AppCompatActivity(), CardClickListener, ChangeListener { private var taskIndex = 0 private var boardId: String = "0" private var taskItemsAdapter: TaskItemsAdapter? = null private var taskList: ArrayList<Task> = ArrayList() private lateinit var tasksService:TasksService private lateinit var progress: Progress override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tasks) setupActionBar(this, toolbar_task_list_activity) rv_task_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) rv_task_list.setHasFixedSize(true) initialize() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_members, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.action_members -> { startActivity(Intent(this, MembersActivity::class.java)) } } return super.onOptionsItemSelected(item) } override fun onStart() { Log.d(LOG_TAG, "On start") super.onStart() } override fun onResume() { Log.d(LOG_TAG, "On resume") taskItemsAdapter?.notifyDataSetChanged() super.onResume() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK && requestCode == RequestCode.CARD_VIEW) { if (data != null && data.hasExtra(IntentExtra.CARD_LIST)) { val cardList = data.getParcelableArrayListExtra<Card>(IntentExtra.CARD_LIST) as ArrayList<Card> tasksService.addCards(taskIndex, cardList) updateAndPersistData() } } super.onActivityResult(requestCode, resultCode, data) } override fun onClick(index: Int, position: Int, item: Any) { taskIndex = index callCardActivity(position, item as ArrayList<Card>) } override fun onAdd(index: Int, any: Any) { taskIndex = index tasksService.addTask(any as String) updateAndPersistData() } override fun onUpdate(index: Int, any: Any) { taskIndex = index if (any is Task) { tasksService.updateTask(index, any) } else { tasksService.addCardToTask(index, any as String) } updateAndPersistData() } override fun onDelete(index: Int) { taskIndex = index tasksService.deleteTask(index) updateAndPersistData() } private fun updateAndPersistData() { taskItemsAdapter?.notifyDataSetChanged() tasksService.updatePersist(object : ResultListener { override fun onSuccess(any: Any) { taskList = any as ArrayList<Task> loadTasksToUI(taskList) } override fun onFailure(message: String) { ErrorAlert(this@TasksActivity, message).show() } }) } private fun loadTasksToUI(taskList: ArrayList<Task>) { taskItemsAdapter = TaskItemsAdapter(this, taskList) rv_task_list.adapter = taskItemsAdapter taskItemsAdapter!!.setChangeListener(this) } private fun initialize() { progress = Progress(this) if (intent.hasExtra(IntentExtra.BOARD_ID)) { boardId = intent.getStringExtra(IntentExtra.BOARD_ID).toString() val boardName = intent.getStringExtra(IntentExtra.BOARD_NAME) supportActionBar?.title = boardName tasksService = TasksService(boardId) progress.showDefault() tasksService.loadTaskList(object : ResultListener { override fun onSuccess(any: Any) { progress.hideView() taskList = any as ArrayList<Task> taskList.add(Task("0", resources.getString(R.string.add_list), Constants.APPSYS)) loadTasksToUI(taskList) } override fun onFailure(message: String) { progress.hideView() ErrorAlert(this@TasksActivity, message).show() } }) } } private fun callCardActivity(position: Int, cards: ArrayList<Card>) { var cardIntent = Intent(this, CardActivity::class.java) cardIntent.putExtra(IntentExtra.CARD_INDEX, position) cardIntent.putParcelableArrayListExtra(IntentExtra.CARD_LIST, cards) startActivityForResult(cardIntent, RequestCode.CARD_VIEW) } }
0
Kotlin
0
0
381a00cf2a30c5937089f10e4a80e03fdde5c1f8
5,727
intime
MIT License
android-common/src/com/android/tools/idea/flags/IdeaIsInternalDefault.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.flags import com.android.flags.FlagDefault import com.intellij.openapi.application.ApplicationManager object IdeaIsInternalDefault : FlagDefault<Boolean>("Default enabled when idea.is.internal is true") { override fun get(): Boolean { val application = ApplicationManager.getApplication() return application != null && !application.isUnitTestMode && application.isInternal } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,041
android
Apache License 2.0
covpass-sdk/src/main/java/de/rki/covpass/sdk/cert/CovPassRulesValidator.kt
Digitaler-Impfnachweis
376,239,258
false
null
/* * (C) Copyright IBM Deutschland GmbH 2021 * (C) Copyright IBM Corp. 2021 */ package de.rki.covpass.sdk.cert import de.rki.covpass.sdk.cert.models.CovCertificate import de.rki.covpass.sdk.cert.models.Recovery import de.rki.covpass.sdk.cert.models.TestCert import de.rki.covpass.sdk.cert.models.Vaccination import de.rki.covpass.sdk.dependencies.defaultJson import de.rki.covpass.sdk.rules.CovPassValueSetsRepository import de.rki.covpass.sdk.rules.domain.rules.CovPassUseCase import de.rki.covpass.sdk.rules.domain.rules.CovPassValidationType import de.rki.covpass.sdk.rules.local.rules.eu.toRules import de.rki.covpass.sdk.rules.local.valuesets.toValueSets import de.rki.covpass.sdk.utils.toZonedDateTimeOrDefault import dgca.verifier.app.engine.CertLogicEngine import dgca.verifier.app.engine.ValidationResult import dgca.verifier.app.engine.data.CertificateType import dgca.verifier.app.engine.data.ExternalParameter import dgca.verifier.app.engine.data.Type import kotlinx.serialization.encodeToString import java.time.ZonedDateTime public class CovPassRulesValidator( private val rulesUseCase: CovPassUseCase, private val certLogicEngine: CertLogicEngine, private val valueSetsRepository: CovPassValueSetsRepository, ) { public suspend fun validate( cert: CovCertificate, countryIsoCode: String = "de", validationClock: ZonedDateTime = ZonedDateTime.now(), validationType: CovPassValidationType = CovPassValidationType.RULES, region: String? = null, ): List<ValidationResult> { val certificateType = cert.getCertificateType() val issuerCountryCode = cert.issuer.lowercase() val rules = rulesUseCase.invoke( countryIsoCode, issuerCountryCode, certificateType, validationClock, validationType, region, ) val valueSetsMap = valueSetsRepository.getAllCovPassValueSets().toValueSets().associate { valueSet -> valueSet.valueSetId to valueSet.valueSetValues.fieldNames().asSequence().toList() } val externalParameter = ExternalParameter( validationClock = validationClock.toOffsetDateTime().toZonedDateTime(), valueSets = valueSetsMap, countryCode = countryIsoCode, exp = cert.validUntil.toZonedDateTimeOrDefault(Long.MAX_VALUE), iat = cert.validFrom.toZonedDateTimeOrDefault(Long.MIN_VALUE), issuerCountryCode = issuerCountryCode, kid = "", region = region ?: "", ) val certString = defaultJson.encodeToString(cert) return certLogicEngine.validate( certificateType, cert.version, rules.toRules(), externalParameter, certString, ).filterNot { it.rule.type == Type.INVALIDATION } } private fun CovCertificate.getCertificateType(): CertificateType = when (dgcEntry) { is Vaccination -> CertificateType.VACCINATION is TestCert -> CertificateType.TEST is Recovery -> CertificateType.RECOVERY } }
33
Kotlin
60
185
7301f1500dab4a686aa40341500667cf4cc54d1e
3,169
covpass-android
Apache License 2.0
app/src/main/java/com/country/grocerystore/models/RandomDataCell.kt
ShivaniSoni22
534,943,179
false
{"Kotlin": 167065, "Java": 872}
package com.country.grocerystore.models import com.country.tableview.feature.filter.Filterable import com.country.tableview.feature.sort.Sortable class RandomDataCell( _data: Any, _id: String = _data.hashCode().toString(), _filter: String = _data.toString() ) : Filterable, Sortable { override var filterableKeyword: String = _filter override var id: String = _id override var content: Any = _data }
0
Kotlin
0
0
65e8f15d318fad1bae724341dddc668abec38e36
440
GroceryStore
MIT License
app/src/main/java/com/dariobrux/pokemon/app/ui/main/MainFragment.kt
dariobrux
307,843,590
false
null
package com.dariobrux.pokemon.app.ui.main import android.Manifest 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.NavHostFragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.dariobrux.pokemon.app.R import com.dariobrux.pokemon.app.data.models.ContactData import com.dariobrux.pokemon.app.data.models.Pokemon import com.dariobrux.pokemon.app.other.extensions.toMainActivity import com.dariobrux.pokemon.app.ui.MainActivity import com.dariobrux.pokemon.app.ui.utils.GridSpaceItemDecoration import com.dariobrux.pokemon.app.ui.utils.LinearSpaceItemDecoration import com.tbruyelle.rxpermissions3.RxPermissions import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.main_fragment.* import timber.log.Timber /** * * Created by <NAME> on 21/10/2020. * * This is the main fragment, where the layout shows * the list of all pokemon. It limits the items to display * each time. So, after having scrolled the list, an HTTP request must be * done to retrieve another group of pokemon. * * I declare this class with AndroidEntryPoint annotation, to tell the activity that * we will be injecting dependency here. Without this, the DI won't work. */ @AndroidEntryPoint class MainFragment : Fragment(), MainAdapter.OnItemSelectedListener { /** * The ViewModel */ private val viewModel: MainViewModel by viewModels() private var isContactPermissionGranted = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (viewModel.adapter == null) { viewModel.adapter = MainAdapter(requireContext(), viewModel.combinedItemsList, this) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.main_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { RxPermissions(this) .request(Manifest.permission.READ_CONTACTS) .subscribe { granted -> isContactPermissionGranted = granted // The permission is granted. This is always true for Android pre-M if (granted) { initFragmentViews() } else { // The permission is denied initFragmentViews() } } } /** * Initialize the views of this fragment. */ private fun initFragmentViews() { // Set the RecyclerView with its LayoutManager, ItemDecorator, Adapter and callbacks. recycler?.let { it.adapter = viewModel.adapter } // At this point, I must observe the ViewModel to get the updated list // of pokemon only if the current list is empty. I let do in this way // because, when I change the theme, the application is refreshed, and // I could incur in any bug. if (viewModel.combinedItemsList.isEmpty()) { getPokemonAndContactList() } // Observe the visualization to transform the list to grid and vice versa. requireActivity().toMainActivity()?.visualization?.observe(this.viewLifecycleOwner) { visualization -> visualization ?: return@observe recycler?.let { rec -> if (rec.itemDecorationCount != 0) rec.removeItemDecorationAt(0) if (rec.layoutManager as? GridLayoutManager == null) { rec.layoutManager = GridLayoutManager(requireContext(), 1, RecyclerView.VERTICAL, false) } } when (visualization) { MainActivity.Visualization.LIST -> { recycler?.let { (it.layoutManager as GridLayoutManager).spanCount = 1 it.addItemDecoration(LinearSpaceItemDecoration(requireContext().resources.getDimensionPixelSize(R.dimen.regular_space))) } } MainActivity.Visualization.GRID -> { recycler?.let { (it.layoutManager as GridLayoutManager).spanCount = 2 it.addItemDecoration(GridSpaceItemDecoration(requireContext().resources.getDimensionPixelSize(R.dimen.regular_space))) } } } viewModel.adapter?.notifyDataSetChanged() } } override fun onDestroy() { super.onDestroy() viewModel.resetOffset() } /** * Observe the ViewModel to get the list of the pokemon to show. */ private fun getPokemonAndContactList() { // Get the contact list val contactList = if (isContactPermissionGranted) { viewModel.getContactList() } else { emptyList() } viewModel.getPokemonList()?.observe(this.viewLifecycleOwner) { Timber.d("Observer the dataInfo object. It contains ${it.data?.pokemonList?.size ?: 0} pokemon") val items = viewModel.getSortedList(contactList, it.data?.pokemonList ?: emptyList()) viewModel.combinedItemsList.addAll(items) // Refresh the adapter. viewModel.adapter?.notifyDataSetChanged() } } /** * Invoke when a pokemon is selected. * @param pokemon the pokemon selected. */ override fun onPokemonSelected(pokemon: Pokemon) { NavHostFragment.findNavController(this).navigate(R.id.action_mainFragment_to_infoFragment, Bundle().apply { putSerializable("pokemon", pokemon) }) } /** * Invoke when a contact is selected. The contact received will be converted to a ContactData. * @param contact the contact selected. */ override fun onContactSelected(contact: ContactData) { NavHostFragment.findNavController(this).navigate(R.id.action_mainFragment_to_infoFragment, Bundle().apply { putSerializable("contact", contact) }) } }
0
Kotlin
0
0
268fb3534a954744238c705c1a473261bdc0ded2
6,298
PokemonContacts
Apache License 2.0
app/src/main/java/io/zoemeow/subjectnotifier/receiver/NewsBroadcastReceiver.kt
ZoeMeow5466
504,228,485
false
null
package io.zoemeow.subjectnotifier.receiver import android.content.Context import android.content.Intent import io.zoemeow.subjectnotifier.model.enums.ServiceBroadcastOptions abstract class NewsBroadcastReceiver : BaseBroadcastReceiver { constructor() constructor(packageFilter: String) : super(packageFilter) @Suppress("DEPRECATION") override fun onReceiveFilter(context: Context, intent: Intent) { intent.getStringExtra(ServiceBroadcastOptions.STATUS).also { if (it != null) { onStatusReceived( key = intent.action ?: "", value = it, ) } } intent.getSerializableExtra(ServiceBroadcastOptions.DATA).also { if (it != null) { onDataReceived( key = intent.action ?: "", data = it ) } } intent.getStringExtra(ServiceBroadcastOptions.ERRORMESSAGE).also { if (it != null) { onErrorReceived( key = intent.action ?: "", msg = it ) } } } abstract fun onStatusReceived(key: String, value: String) abstract fun onDataReceived(key: String, data: Any) abstract fun onErrorReceived(key: String, msg: String) }
0
Kotlin
0
0
d06999b85f03ccb7510987a2d5bbd12ab90bc981
1,368
SubjectNotifier
MIT License
app/src/main/java/com/karrar/movieapp/domain/models/Rated.kt
Salmon-family
540,624,429
false
{"Kotlin": 445900}
package com.karrar.movieapp.domain.models data class Rated( val id: Int, val title: String, val posterPath: String, val rating: Float, val releaseDate: String, var mediaType:String )
1
Kotlin
26
76
d8aa22e528208c42d89a3574f1da025a49f23aed
208
MovieApp
Apache License 2.0
client/app/src/main/java/com/example/healthc/data/local/Converters.kt
Solution-Challenge-HealthC
601,915,784
false
null
package com.example.healthc.data.local import androidx.room.ProvidedTypeConverter import androidx.room.TypeConverter import com.example.healthc.data.utils.GsonParser import com.google.gson.reflect.TypeToken @ProvidedTypeConverter class Converters( private val jsonParser: GsonParser ) { @TypeConverter fun fromUserInfoToJson(userInfo: List<String>) : String { return jsonParser.toJson( userInfo, object : TypeToken<List<String>>(){}.type ) ?: "[]" } @TypeConverter fun fromJsonToUserInfo(json : String): List<String> { return jsonParser.fromJson<List<String>>( json, object : TypeToken<List<String>>(){}.type ) ?: emptyList() } }
4
Kotlin
1
2
d74bff575502c4360e9735e8d558b907240ed4fe
740
HealthC_Android
MIT License
Pokemon/app/src/main/java/com/example/android/pokemon/retrofit/PokemonListEntity.kt
Savitar97
319,745,352
false
null
package com.example.android.pokemon.retrofit import com.example.android.pokemon.model.PokemonEntityList import retrofit2.Call import retrofit2.http.GET interface PokemonListEntity { @GET("pokedex.json") fun getAllPokemonList () : Call<PokemonEntityList> }
0
Kotlin
0
0
267d7c868dfecf39fbc5bd2b9b7ae5ae75def625
265
PokemonAndroid
MIT License
core/acorn-core/src/main/java/com/nhaarman/acorn/navigation/DisposableHandle.kt
nhaarman
137,459,947
false
null
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nhaarman.acorn.navigation /** * A handle that can be disposed of. */ interface DisposableHandle { /** * Disposes the resource. */ fun dispose() /** * @return true if this handle has been disposed of. */ fun isDisposed(): Boolean companion object { /** * Creates a non-thread-safe [DisposableHandle] that executes * given [dispose] function on dispose. */ operator fun invoke(dispose: () -> Unit): DisposableHandle { return object : DisposableHandle { private var isDisposed = false override fun dispose() { isDisposed = true dispose.invoke() } override fun isDisposed(): Boolean { return isDisposed } } } } }
17
Kotlin
6
182
bb4cd33a54103bb1a1cf4c0eecabfcc7b9c352d2
1,511
acorn
Apache License 2.0
VelocityX/src/main/java/dev/codepur/velocityx/compose/VxText.kt
iampawan
513,427,050
false
null
package dev.codepur.velocityx.compose import android.annotation.SuppressLint import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.sp import dev.codepur.velocityx.VxWidgetBuilder import dev.codepur.velocityx.mixin.IVxColorMixin import dev.codepur.velocityx.mixin.IVxModifierMixin import dev.codepur.velocityx.mixin.VxColorMixin import dev.codepur.velocityx.mixin.VxModifierMixin open class VxTextAddOn<T>( colorMixin: IVxColorMixin<T> = VxColorMixin<T>(), modifierMixin: IVxModifierMixin<T> = VxModifierMixin() ) : IVxColorMixin<T> by colorMixin, IVxModifierMixin<T> by modifierMixin class VxText(val text: String) : VxWidgetBuilder, VxTextAddOn<VxText>() { init { setChildToColor(this) setChildForModifier(this) } private var _text: String = text private var _fontFamily: FontFamily? = null private var _scaleFactor: Double = 1.0 private var _fontSize: Double? = null private var _letterSpacing: Double? = null private var _lineHeight: Double? = null private var _wordSpacing: Double? = null private var _maxLines: Int? = null private var _fontWeight: FontWeight? = null private var _textAlign: TextAlign? = null private var _overflow: TextOverflow? = null private var _fontStyle: FontStyle? = null private var _softWrap: Boolean = true private var _textStyle: TextStyle? = null private var _themedStyle: TextStyle? = null private var _textDecoration: TextDecoration? = null /// The text to display. /// /// This will be null if a [textSpan] is provided instead. fun text(text: String): VxText { _text = text return this } fun maxLines(lines: Int): VxText { _maxLines = lines return this } /// Sets [textScaleFactor] to extra small i.e. 0.75 val xs: VxText get() = fontSizedText(child = this, scaleFactor = 0.75) /// Sets [textScaleFactor] to small i.e. 0.875 val sm: VxText get() = fontSizedText(child = this, scaleFactor = 0.875) /// Sets [textScaleFactor] to base i.e. 1 or default val base: VxText get() = fontSizedText(child = this, scaleFactor = 1.0) /// Sets [textScaleFactor] to large i.e. 1.125 val lg: VxText get() = fontSizedText(child = this, scaleFactor = 1.125) /// Sets [textScaleFactor] to extra large i.e. 1.25 val xl: VxText get() = fontSizedText(child = this, scaleFactor = 1.25) /// Sets [textScaleFactor] to twice extra large i.e. 1.5 val xl2: VxText get() = fontSizedText(child = this, scaleFactor = 1.5) /// Sets [textScaleFactor] to thrice large i.e. 1.875 val xl3: VxText get() = fontSizedText(child = this, scaleFactor = 1.875) /// Sets [textScaleFactor] to four times extra large i.e. 2.25 val xl4: VxText get() = fontSizedText(child = this, scaleFactor = 2.25) /// Sets [textScaleFactor] to five times extra large i.e. 3 val xl5: VxText get() = fontSizedText(child = this, scaleFactor = 3.0) /// Sets [textScaleFactor] to six times extra large i.e. 4 val xl6: VxText get() = fontSizedText(child = this, scaleFactor = 4.0) /// Sets [textScaleFactor] to custom value fun scale(value: Double): VxText = fontSizedText(child = this, scaleFactor = value) /// To set fontSize of the text using [size] fun size(size: Double?): VxText { _fontSize = size return this } private fun fontSizedText( scaleFactor: Double, child: VxText ): VxText { _fontSize = (_fontSize ?: 14.0) * scaleFactor _scaleFactor = scaleFactor return child } // Give custom text alignment fun align(align: TextAlign): VxText { _textAlign = align return this } /// How the text should be aligned horizontally. /// /// To align text in [center] val center: VxText get() { _textAlign = TextAlign.Center return this } /// To align text in [start] val start: VxText get() { _textAlign = TextAlign.Start return this } /// To align text in [end] val end: VxText get() { _textAlign = TextAlign.End return this } /// To align text as [justify] val justify: VxText get() { _textAlign = TextAlign.Justify return this } /// Can be used to set overflow of a text. /// How visual overflow should be handled. fun overflow(overflow: TextOverflow): VxText { _overflow = overflow return this } /// To overflow text as [clip] val clip: VxText get() { _overflow = TextOverflow.Clip return this } /// To overflow text as [ellipsis] val ellipsis: VxText get() { _overflow = TextOverflow.Ellipsis return this } /// To overflow text as [visible] val visible: VxText get() { _overflow = TextOverflow.Visible return this } /// Set [FontWeight] for the text fun fontWeight(weight: FontWeight): VxText { _fontWeight = weight return this } /// Sets [FontWeight] to [FontWeight.w100] val hairLine: VxText get() = fontWeightedText(weight = FontWeight.W100) /// Sets [FontWeight] to [FontWeight.w200] val thin: VxText get() = fontWeightedText(weight = FontWeight.W200) /// Sets [FontWeight] to [FontWeight.w300] val light: VxText get() = fontWeightedText(weight = FontWeight.W300) /// Sets [FontWeight] to [FontWeight.w400] val normal: VxText get() = fontWeightedText(weight = FontWeight.W400) /// Sets [FontWeight] to [FontWeight.w500] val medium: VxText get() = fontWeightedText(weight = FontWeight.W500) /// Sets [FontWeight] to [FontWeight.w600] val semiBold: VxText get() = fontWeightedText(weight = FontWeight.W600) /// Sets [FontWeight] to [FontWeight.w700] val bold: VxText get() = fontWeightedText(weight = FontWeight.W700) /// Sets [FontWeight] to [FontWeight.w800] val extraBold: VxText get() = fontWeightedText(weight = FontWeight.W800) /// Sets [FontWeight] to [FontWeight.w900] val extraBlack: VxText get() = fontWeightedText(weight = FontWeight.W900) private fun fontWeightedText(weight: FontWeight): VxText { _fontWeight = weight return this } /// Sets [letterSpacing] to -3.0 val tightest: VxText get() = letterSpacing(-3.0) /// Sets [letterSpacing] to -2.0 val tighter: VxText get() = letterSpacing(-2.0) /// Sets [letterSpacing] to -1.0 val tight: VxText get() = letterSpacing(-1.0) /// Sets [letterSpacing] to 1.0 val wide: VxText get() = letterSpacing(1.0) /// Sets [letterSpacing] to 2.0 val wider: VxText get() = letterSpacing(2.0) /// Sets [letterSpacing] to 3.0 val widest: VxText get() = letterSpacing(3.0) fun letterSpacing(spacing: Double): VxText { _letterSpacing = spacing return this } /// Sets [FontStyle] to [FontStyle.italic] val italic: VxText get() { _fontStyle = FontStyle.Italic return this } /// Sets [lineHeight] to 0.75 val heightTight: VxText get() = lineHeight(0.75) /// Sets [lineHeight] to 0.875 val heightSnug: VxText get() = lineHeight(0.875) /// Sets [lineHeight] to 1.25 val heightRelaxed: VxText get() = lineHeight(1.25) /// Sets [lineHeight] to 1.5 val heightLoose: VxText get() = lineHeight(1.5) /// Sets custom [lineHeight] with [val] fun lineHeight(height: Double): VxText { _lineHeight = height return this } /// Set [fontFamily] for the text fun fontFamily(family: FontFamily): VxText { _fontFamily = family return this } /// Whether the text should break at soft line breaks. /// /// If false, the glyphs in the text will be positioned as if there was /// unlimited horizontal space. fun softWrap(wrapValue: Boolean): VxText { _softWrap = wrapValue return this } /// Use textStyle to provide custom or any theme style. /// /// If the style's 'inherit' property is true, the style will be merged with /// the closest enclosing [DefaultTextStyle]. Otherwise, the style will /// replace the closest enclosing [DefaultTextStyle]. fun textStyle(style: TextStyle): VxText { _textStyle = style return this } /// Sets [TextTheme] headline small @Composable fun headlineSmall(): VxText { _themedStyle = MaterialTheme.typography.headlineSmall return this } /// Sets [TextTheme] headline medium @Composable fun headlineMedium(): VxText { _themedStyle = MaterialTheme.typography.headlineMedium return this } /// Sets [TextTheme] headline large @Composable fun headlineLarge(): VxText { _themedStyle = MaterialTheme.typography.headlineLarge return this } /// Sets [TextTheme] title small @Composable fun titleSmall(): VxText { _themedStyle = MaterialTheme.typography.titleSmall return this } /// Sets [TextTheme] title medium @Composable fun titleMedium(): VxText { _themedStyle = MaterialTheme.typography.titleMedium return this } /// Sets [TextTheme] title large @Composable fun titleLarge(): VxText { _themedStyle = MaterialTheme.typography.titleLarge return this } /// Sets [TextTheme] body small @Composable fun bodySmall(): VxText { _themedStyle = MaterialTheme.typography.bodySmall return this } /// Sets [TextTheme] body medium @Composable fun bodyMedium(): VxText { _themedStyle = MaterialTheme.typography.bodyMedium return this } /// Sets [TextTheme] body large @Composable fun bodyLarge(): VxText { _themedStyle = MaterialTheme.typography.bodyLarge return this } /// Sets [TextTheme] display small @Composable fun displaySmall(): VxText { _themedStyle = MaterialTheme.typography.displaySmall return this } /// Sets [TextTheme] display medium @Composable fun displayMedium(): VxText { _themedStyle = MaterialTheme.typography.displayMedium return this } /// Sets [TextTheme] display large @Composable fun displayLarge(): VxText { _themedStyle = MaterialTheme.typography.displayLarge return this } /// Sets [TextTheme] label small @Composable fun labelSmall(): VxText { _themedStyle = MaterialTheme.typography.labelSmall return this } /// Sets [TextTheme] label medium @Composable fun labelMedium(): VxText { _themedStyle = MaterialTheme.typography.labelMedium return this } /// Sets [TextTheme] label large @Composable fun labelLarge(): VxText { _themedStyle = MaterialTheme.typography.labelLarge return this } /// Sets [TextDecoration] as [TextDecoration.underline] val underline get() = decoration(TextDecoration.Underline) /// Sets [TextDecoration] as [TextDecoration.lineThrough] val lineThrough get() = decoration(TextDecoration.LineThrough) /// Sets [TextDecoration] as [TextDecoration.None] val noneDecoration get() = decoration(TextDecoration.None) ///Sets TextDecoration fun decoration(decorator: TextDecoration): VxText { _textDecoration = decorator return this } /// Converts the text to fully uppercase. val uppercase: VxText get() = setText(_text.uppercase()) /// Converts the text to fully lowercase. val lowercase: VxText get() = setText(_text.lowercase()) ///Modifies Text private fun setText(newText: String): VxText { _text = newText return this } @SuppressLint("ComposableNaming") @Composable override fun make() { var currentModifier = velocityModifier ?: Modifier val currentContext = LocalTextStyle.current var newStyle = _themedStyle ?: _textStyle ?: currentContext val ts = TextStyle( color = velocityColor ?: newStyle.color, fontSize = _fontSize?.sp ?: newStyle.fontSize, fontWeight = _fontWeight ?: newStyle.fontWeight, textAlign = _textAlign ?: newStyle.textAlign, letterSpacing = _letterSpacing?.sp ?: newStyle.letterSpacing, fontStyle = _fontStyle ?: newStyle.fontStyle, lineHeight = _lineHeight?.sp ?: newStyle.lineHeight, fontFamily = _fontFamily ?: newStyle.fontFamily, textDecoration = _textDecoration ?: newStyle.textDecoration, ) newStyle = _themedStyle?.merge(ts) ?: _textStyle?.merge(ts) ?: ts Text( text = _text, color = newStyle.color, fontSize = newStyle.fontSize, fontWeight = newStyle.fontWeight, textAlign = newStyle.textAlign, maxLines = _maxLines ?: Int.MAX_VALUE, letterSpacing = newStyle.letterSpacing, fontStyle = newStyle.fontStyle, overflow = _overflow ?: TextOverflow.Clip, lineHeight = newStyle.lineHeight, softWrap = _softWrap, fontFamily = newStyle.fontFamily, style = newStyle, textDecoration = newStyle.textDecoration, modifier = currentModifier, ) } } val String.text get() = VxText(text = this)
0
Kotlin
3
25
59bfe8fdcbb36dc8a46bb2b5afaac7ae9b770ccd
14,453
VelocityXAndroidCompose
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/FaceExplode.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.FaceExplode: ImageVector get() { if (_faceExplode != null) { return _faceExplode!! } _faceExplode = Builder(name = "FaceExplode", 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(8.5f, 16.0f) curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f) close() moveTo(15.5f, 13.0f) curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f) reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f) reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f) close() moveTo(24.0f, 10.549f) verticalLineToRelative(1.086f) curveToRelative(0.0f, 6.698f, -5.283f, 12.245f, -11.776f, 12.363f) curveToRelative(-0.076f, 0.0f, -0.152f, 0.002f, -0.227f, 0.002f) curveToRelative(-3.165f, 0.0f, -6.141f, -1.215f, -8.403f, -3.437f) curveTo(1.276f, 18.288f, 0.0f, 15.247f, 0.0f, 12.0f) verticalLineToRelative(-1.499f) curveToRelative(0.0f, -0.599f, 0.358f, -1.138f, 0.912f, -1.372f) curveToRelative(0.545f, -0.23f, 1.169f, -0.116f, 1.59f, 0.292f) curveToRelative(0.572f, 0.555f, 1.489f, 0.579f, 1.498f, 0.579f) horizontalLineToRelative(4.5f) curveToRelative(0.276f, 0.0f, 0.5f, -0.225f, 0.5f, -0.5f) verticalLineToRelative(-1.5f) curveToRelative(0.0f, -0.523f, -0.154f, -0.774f, -0.316f, -0.894f) curveToRelative(-0.656f, 0.598f, -1.385f, 0.894f, -2.184f, 0.894f) curveToRelative(-1.064f, 0.0f, -2.059f, -0.476f, -2.727f, -1.306f) curveToRelative(-0.668f, -0.829f, -0.919f, -1.912f, -0.689f, -2.97f) curveToRelative(0.247f, -1.132f, 1.088f, -2.091f, 2.197f, -2.502f) curveToRelative(0.658f, -0.245f, 1.332f, -0.287f, 1.987f, -0.135f) curveTo(8.515f, -0.08f, 10.517f, -0.322f, 12.0f, 0.546f) curveToRelative(1.485f, -0.869f, 3.486f, -0.627f, 4.732f, 0.543f) curveToRelative(1.324f, -0.31f, 2.712f, 0.202f, 3.539f, 1.272f) curveToRelative(0.669f, 0.866f, 0.891f, 1.983f, 0.609f, 3.064f) curveToRelative(-0.294f, 1.128f, -1.167f, 2.047f, -2.277f, 2.399f) curveToRelative(-1.07f, 0.339f, -2.239f, 0.061f, -3.219f, -0.745f) curveToRelative(-0.255f, 0.136f, -0.384f, 0.444f, -0.384f, 0.92f) verticalLineToRelative(1.5f) curveToRelative(0.0f, 0.275f, 0.224f, 0.5f, 0.5f, 0.5f) horizontalLineToRelative(4.5f) reflectiveCurveToRelative(0.899f, -0.021f, 1.476f, -0.559f) curveToRelative(0.435f, -0.406f, 1.068f, -0.515f, 1.617f, -0.275f) curveToRelative(0.551f, 0.239f, 0.907f, 0.782f, 0.907f, 1.383f) close() moveTo(22.0f, 11.493f) curveToRelative(-0.941f, 0.488f, -1.869f, 0.507f, -2.0f, 0.507f) horizontalLineToRelative(-4.5f) curveToRelative(-1.378f, 0.0f, -2.5f, -1.121f, -2.5f, -2.5f) verticalLineToRelative(-1.5f) curveToRelative(0.0f, -1.241f, 0.511f, -1.951f, 0.939f, -2.328f) curveToRelative(0.733f, -0.646f, 1.624f, -0.693f, 1.878f, -0.664f) curveToRelative(0.227f, 0.029f, 0.438f, 0.136f, 0.596f, 0.302f) curveToRelative(0.245f, 0.257f, 0.886f, 0.834f, 1.583f, 0.609f) curveToRelative(0.456f, -0.145f, 0.827f, -0.536f, 0.948f, -0.999f) curveToRelative(0.126f, -0.483f, 0.036f, -0.958f, -0.256f, -1.336f) curveToRelative(-0.417f, -0.539f, -1.149f, -0.754f, -1.831f, -0.431f) curveToRelative(-0.435f, 0.207f, -0.958f, 0.074f, -1.24f, -0.317f) curveToRelative(-0.384f, -0.531f, -0.973f, -0.836f, -1.617f, -0.836f) curveToRelative(-0.621f, 0.0f, -1.066f, 0.283f, -1.331f, 0.521f) curveToRelative(-0.38f, 0.342f, -0.958f, 0.342f, -1.338f, 0.0f) curveToRelative(-0.265f, -0.238f, -0.71f, -0.521f, -1.331f, -0.521f) curveToRelative(-0.644f, 0.0f, -1.233f, 0.305f, -1.617f, 0.836f) curveToRelative(-0.283f, 0.393f, -0.806f, 0.526f, -1.242f, 0.316f) curveToRelative(-0.385f, -0.183f, -0.767f, -0.202f, -1.166f, -0.054f) curveToRelative(-0.467f, 0.173f, -0.835f, 0.586f, -0.937f, 1.052f) curveToRelative(-0.103f, 0.471f, 0.001f, 0.929f, 0.292f, 1.289f) curveToRelative(0.287f, 0.356f, 0.713f, 0.561f, 1.169f, 0.561f) curveToRelative(0.484f, 0.0f, 0.832f, -0.337f, 1.05f, -0.591f) curveToRelative(0.059f, -0.068f, 0.185f, -0.191f, 0.26f, -0.241f) curveToRelative(0.164f, -0.109f, 0.357f, -0.168f, 0.555f, -0.168f) curveToRelative(1.059f, 0.0f, 2.635f, 0.799f, 2.635f, 3.0f) verticalLineToRelative(1.5f) curveToRelative(0.0f, 1.379f, -1.122f, 2.5f, -2.5f, 2.5f) lineTo(4.0f, 12.0f) curveToRelative(-0.132f, 0.0f, -1.06f, -0.019f, -2.0f, -0.506f) verticalLineToRelative(0.506f) curveToRelative(0.0f, 2.706f, 1.063f, 5.24f, 2.995f, 7.137f) curveToRelative(1.93f, 1.895f, 4.487f, 2.903f, 7.193f, 2.861f) curveToRelative(5.411f, -0.099f, 9.812f, -4.747f, 9.812f, -10.363f) verticalLineToRelative(-0.142f) close() moveTo(12.0f, 17.0f) curveToRelative(-1.44f, 0.0f, -2.597f, 1.148f, -2.972f, 2.22f) curveToRelative(-0.134f, 0.383f, 0.168f, 0.78f, 0.573f, 0.78f) curveToRelative(1.158f, 0.0f, 3.638f, 0.0f, 4.788f, 0.0f) curveToRelative(0.403f, 0.0f, 0.706f, -0.393f, 0.576f, -0.775f) curveToRelative(-0.365f, -1.074f, -1.53f, -2.224f, -2.965f, -2.224f) close() } } .build() return _faceExplode!! } private var _faceExplode: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
7,419
icons
MIT License
src/main/kotlin/com/github/lizhikai38/toxo/services/MyApplicationService.kt
lizhikai38
517,637,781
false
null
package com.github.lizhikai38.toxo.services import com.github.lizhikai38.toxo.MyBundle class MyApplicationService { init { println(MyBundle.message("applicationService")) } }
0
Kotlin
0
0
b4645e68b2507f498be49f18130ce522f375e38d
194
toxo
Apache License 2.0
kafka/schemaregistry/client/src/main/kotlin/org/http4k/connect/kafka/schemaregistry/model/SchemaId.kt
http4k
295,641,058
false
{"Kotlin": 1624385, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.kafka.schemaregistry.model import dev.forkhandles.values.IntValue import dev.forkhandles.values.IntValueFactory import dev.forkhandles.values.minValue class SchemaId private constructor(value: Int) : IntValue(value) { companion object : IntValueFactory<SchemaId>(::SchemaId, 0.minValue) }
7
Kotlin
17
37
3522f4a2bf5e476b849ec367700544d89e006f71
322
http4k-connect
Apache License 2.0
tinbo-notes/src/main/kotlin/io/gitlab/arturbosch/tinbo/notes/NoteDataHolder.kt
arturbosch
66,214,435
false
null
package io.gitlab.arturbosch.tinbo.notes import io.gitlab.arturbosch.tinbo.api.config.ConfigDefaults import io.gitlab.arturbosch.tinbo.api.config.Defaults import io.gitlab.arturbosch.tinbo.api.config.TinboConfig import io.gitlab.arturbosch.tinbo.api.model.AbstractDataHolder import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component /** * @author artur */ @Component open class NoteDataHolder @Autowired constructor(persister: NotePersister, private val config: TinboConfig) : AbstractDataHolder<NoteEntry, NoteData>(persister) { override val lastUsedData: String get() = config.getKey(ConfigDefaults.NOTES) .getOrElse(ConfigDefaults.LAST_USED, { Defaults.NOTES_NAME }) override fun newData(name: String, entriesInMemory: List<NoteEntry>): NoteData { return NoteData(name, entriesInMemory) } override fun getEntriesFilteredBy(filter: String): List<NoteEntry> { return getEntries() } override fun changeCategory(oldName: String, newName: String) { throw UnsupportedOperationException() } }
1
null
1
6
85a74b80b081e374360475f4979e5adffbf91436
1,083
Tinbo
Apache License 2.0
backend/src/main/kotlin/no/nav/fo/forenkletdeploy/util/CorsFilter.kt
navikt
113,152,205
false
null
package no.nav.fo.mia.util import javax.servlet.* import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class CorsFilter: Filter { val ORIGIN = "Origin" val ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin" val ALLOWED_METHODS = arrayOf( "GET", "HEAD", "POST", "PATCH", "PUT", "DELETE", "OPTIONS" ).joinToString(", ") override fun init(filterConfig: FilterConfig?) { } override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) { val httpServletRequest = request as HttpServletRequest val originHeader = httpServletRequest.getHeader(ORIGIN) val httpServletResponse = response as HttpServletResponse httpServletResponse.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, originHeader) httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true") httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")) httpServletResponse.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS) chain.doFilter(request, response) } override fun destroy() { } }
5
null
2
4
591787a66690b1cf4b1f39a36facd4332ac837d9
1,294
forenklet-deploy
MIT License
omisego-core/src/main/java/co/omisego/omisego/model/Balance.kt
omgnetwork
116,833,092
false
null
package co.omisego.omisego.model /* * OmiseGO * * Created by <NAME> on 11/6/2017 AD. * Copyright © 2017-2018 OmiseGO. All rights reserved. */ import java.math.BigDecimal import java.math.RoundingMode /** * Represents a balance of a token * * @param token The token corresponding to the balance * @param amount The total amount of token available for the current user. */ data class Balance(val amount: BigDecimal, val token: Token) { /** * Helper method that returns an easily readable value of the amount * * @param precision The decimal precision to give to the formatter * for example, a number 0.123 with a precision 2 will be 0.12 * @return The formatted balance amount with thousand separator */ fun displayAmount(precision: Int = 2): String { return "%,.${precision}f".format(amount.divide(token.subunitToUnit, precision, RoundingMode.FLOOR)) } /** * Returns a [Balance] whose amount is (this.amount + augend.amount) * * @param augend balance to be added to this Balance * @return An added Balance whose amount is this.amount + augend.amount * @throws UnsupportedOperationException if [Token]'s compatWith is return false */ operator fun plus(augend: Balance): Balance { if (this.token compatWith augend.token) { val newAmount = this.amount.plus(augend.amount) return Balance(newAmount, this.token.copy()) } throw UnsupportedOperationException("Balances are not compatible. Make sure Tokens have the same symbol and subunitToUnit.") } /** * Returns a [Balance] whose amount is (this.amount - subtrahend.amount) * * @param subtrahend balance to be subracted to this Balance * @return An added Balance whose amount is this.amount - subtrahend.amount * @throws UnsupportedOperationException if [Token]'s compatWith is return false */ operator fun minus(subtrahend: Balance): Balance { if (this.token compatWith subtrahend.token) { val newAmount = this.amount.subtract(subtrahend.amount) return Balance(newAmount, this.token.copy()) } throw UnsupportedOperationException("Balances are not compatible. Make sure Tokens have the same symbol and subunitToUnit.") } }
0
Kotlin
8
18
de12e344d6437b9c23df35d158fb247bac6c8055
2,312
android-sdk
Apache License 2.0
shared/src/commonMain/kotlin/ru/blays/ficbookReader/shared/ui/mainScreenComponents/implemenatation/DefaultCollectionsComponent.kt
B1ays
710,470,973
false
{"Kotlin": 749323}
package ru.blays.ficbookReader.shared.ui.mainScreenComponents.implemenatation import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.value.MutableValue import com.arkivanov.decompose.value.Value import com.arkivanov.decompose.value.update import com.arkivanov.essenty.lifecycle.doOnDestroy import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import ru.blays.ficbookReader.shared.data.mappers.toStableModel import ru.blays.ficbookReader.shared.ui.mainScreenComponents.declaration.CollectionsComponent import ru.blays.ficbookReader.shared.ui.mainScreenComponents.declaration.CollectionsComponentInternal import ru.blays.ficbookapi.data.CollectionsTypes import ru.blays.ficbookapi.data.SectionWithQuery import ru.blays.ficbookapi.dataModels.CollectionModel import ru.blays.ficbookapi.ficbookConnection.IFicbookApi import ru.blays.ficbookapi.result.ApiResult class DefaultCollectionsComponent( componentContext: ComponentContext, private val ficbookApi: IFicbookApi, private val onOutput: (CollectionsComponent.Output) -> Unit ): CollectionsComponentInternal, ComponentContext by componentContext { private val _state: MutableValue<CollectionsComponent.State> = MutableValue( CollectionsComponent.State() ) override fun refresh() { getCollections(collectionSection) } override val state: Value<CollectionsComponent.State> get() = _state private val collectionSection = CollectionsTypes._personalCollections private val coroutineScope = CoroutineScope(Dispatchers.IO) init { getCollections(collectionSection) lifecycle.doOnDestroy { coroutineScope.cancel() } } override fun sendIntent(intent: CollectionsComponent.Intent) { when(intent) { CollectionsComponent.Intent.Refresh -> refresh() } } override fun onOutput(output: CollectionsComponent.Output) { onOutput.invoke(output) } private fun getCollections(section: SectionWithQuery) { coroutineScope.launch { _state.update { it.copy( isLoading = true ) } val apiResult = ficbookApi .getCollections(section) when(apiResult) { is ApiResult.Success -> { val collections = apiResult .value .map(CollectionModel::toStableModel) _state.update { it.copy( list = collections, isLoading = false ) } } is ApiResult.Error -> { _state.update { it.copy( isError = true ) } } } } } }
0
Kotlin
0
2
d311da576a35365bc72e1646e7ae8b946eac6690
3,047
ficbook-reader
MIT License
core-android/src/main/java/com/eventful/core/android/model/location/LocationState.kt
tosoba
542,691,274
false
{"Kotlin": 428063, "Java": 1125}
package com.eventful.core.android.model.location import android.os.Parcelable import com.google.android.gms.maps.model.LatLng import kotlinx.android.parcel.Parcelize @Parcelize data class LocationState( val latLng: LatLng? = null, val status: LocationStatus = LocationStatus.Initial ) : Parcelable
0
Kotlin
0
0
0ba84b32680768acd172dfd54d57f513ed2d1baa
308
Eventful
MIT License
app/src/main/java/com/ldept/restapidemo/ui/repoDetailsFragment/RepoFilesAdapter.kt
ldept
445,644,917
false
{"Kotlin": 23820}
package com.ldept.restapidemo.ui.repoDetailsFragment import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.ldept.restapidemo.R import com.ldept.restapidemo.data.models.GithubFile import com.ldept.restapidemo.databinding.FileItemBinding class RepoFilesAdapter : ListAdapter<GithubFile, RepoFilesAdapter.RepoFilesViewHolder>(DiffCallback()) { class RepoFilesViewHolder(private val binding: FileItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(githubFile: GithubFile) { binding.apply { textviewFileName.text = githubFile.name if (githubFile.type == "file") textviewFileName.setCompoundDrawablesWithIntrinsicBounds( R.drawable.ic_baseline_insert_drive_file_24, 0, 0, 0 ) else textviewFileName.setCompoundDrawablesWithIntrinsicBounds( R.drawable.ic_baseline_folder_24, 0, 0, 0 ) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepoFilesViewHolder { val binding = FileItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return RepoFilesViewHolder(binding) } override fun onBindViewHolder(holder: RepoFilesViewHolder, position: Int) { val item = getItem(position) if (item != null) holder.bind(item) } class DiffCallback : DiffUtil.ItemCallback<GithubFile>() { override fun areItemsTheSame(oldItem: GithubFile, newItem: GithubFile): Boolean = oldItem.sha == newItem.sha override fun areContentsTheSame(oldItem: GithubFile, newItem: GithubFile): Boolean = oldItem == newItem } }
0
Kotlin
1
0
90972e528446b527c376e33039a97d0bbf237211
2,095
REST-API-Demo
MIT License
klutter-annotations/annotations-jvm/src/main/kotlin/dev/buijs/klutter/annotations/jvm/KlutterAnnotations.kt
buijs-dev
436,644,099
false
null
package dev.buijs.klutter.annotations.jvm @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.FUNCTION) annotation class KlutterAdaptee(val name: String) @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.CLASS) annotation class KlutterAdapter @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.CLASS) annotation class KlutterResponse
0
Kotlin
2
86
8c7128d96b32461177468c6216a69c2f0dabec78
375
klutter
MIT License
library-merminal/src/main/java/cn/mucute/merminal/view/TermSessionCallback.kt
CaiMuCheng
714,178,682
false
null
package cn.mucute.merminal.view import cn.mucute.merminal.core.TerminalSession open class TermSessionCallback(private var terminalView: TerminalView) : TerminalSession.SessionChangedCallback { override fun onTextChanged(changedSession: TerminalSession?) { terminalView.onScreenUpdated() } override fun onTitleChanged(changedSession: TerminalSession?) { } override fun onSessionFinished(finishedSession: TerminalSession?) { } override fun onClipboardText(session: TerminalSession?, text: String?) { } override fun onColorsChanged(session: TerminalSession?) { terminalView.onScreenUpdated() } }
5
null
5
12
4072b9f90dfcc03576731871ad3fd10a69463008
663
LeafIDE
Apache License 2.0
Oxygen/core/src/main/kotlin/cc/fyre/stark/core/profile/ProfileHandler.kt
AndyReckt
364,514,997
false
{"Java": 12055418, "Kotlin": 766337, "Shell": 5518}
/* * Copyright (c) 2020. * Created by YoloSanta * Created On 10/22/20, 1:23 AM */ package cc.fyre.stark.core.profile import cc.fyre.stark.core.StarkCore import cc.fyre.stark.core.profile.punishment.ProfilePunishment import cc.fyre.stark.core.profile.punishment.ProfilePunishmentSerializer import cc.fyre.stark.core.profile.punishment.ProfilePunishmentType import cc.fyre.stark.core.util.mojanguser.MojangUser import com.google.gson.JsonParser import com.mongodb.client.MongoCollection import com.mongodb.client.model.ReplaceOptions import com.squareup.okhttp.OkHttpClient import com.squareup.okhttp.Request import org.bson.Document import java.util.* import java.util.stream.Collectors abstract class ProfileHandler<T : Profile> { lateinit var collection: MongoCollection<Document> val profiles = HashMap<UUID, T>() fun load() { collection = StarkCore.instance.mongo.database.getCollection("profiles") collection.createIndex(Document("uuid", 1)) collection.createIndex(Document("ipAddress", 1)) } abstract fun createProfileInstance(uuid: UUID): T fun getByUUID(uuid: UUID): T? { return this.profiles[uuid] } fun loadProfile(uuid: UUID): T { return loadProfile(uuid, null) } fun loadProfile(uuid: UUID, ipAddress: String?): T { if (StarkCore.instance.isPrimaryThread()) { throw IllegalStateException("Cannot query mongo on primary thread") } if (this.profiles.containsKey(uuid)) { return this.profiles[uuid]!! } val profile = createProfileInstance(uuid) var save = false val document = collection.find(Document("uuid", uuid.toString())).first() if (document != null) { profile.update(document) } else { save = true } if (ipAddress != null) { // add ip to ip history if (!profile.ipAddresses.contains(ipAddress)) { save = true profile.ipAddresses.add(ipAddress) } } if (save) { saveProfile(profile) } return profile } fun pullProfileUpdates(uuid: UUID): T { val profile: Profile if (profiles.containsKey(uuid)) { profile = profiles[uuid]!! profile.update(collection.find(Document("uuid", uuid.toString())).first()!!) } else { profile = loadProfile(uuid) } profile.apply() return profile } fun saveProfile(profile: T) { val grants = profile.grants.stream().map<Document> { it.toDocument() }.collect(Collectors.toList()) val punishments = profile.punishments.stream().map<Document> { it.toDocument() }.collect(Collectors.toList()) val document = Document() document["uuid"] = profile.uuid.toString() document["userName"] = profile.getClearedDisplayName() document["grants"] = grants document["punishments"] = punishments document["dateJoined"] = profile.dateJoined.time document["ipAddresses"] = profile.ipAddresses document["playerperms"] = profile.playerPerms if (profile.tag != null) { document["tag"] = profile.tag!!.name } else { document["tag"] = null } collection.replaceOne(Document("uuid", profile.uuid.toString()), document, ReplaceOptions().upsert(true)) } fun findActivePunishment(uuid: UUID, ipAddress: String): Pair<UUID, ProfilePunishment>? { val orExpressions = listOf( Document("uuid", uuid.toString()), Document("ipAddresses", ipAddress) ) for (profileDocument in collection.find(Document("\$or", orExpressions))) { val punishments = profileDocument.getList("punishments", Document::class.java) .stream() .map { ProfilePunishmentSerializer.deserialize(it) } .filter { Objects.nonNull(it) } .collect(Collectors.toList()) for (punishment in punishments) { if (punishment.type == ProfilePunishmentType.BLACKLIST || punishment.type == ProfilePunishmentType.BAN) { if (punishment.isActive()) { return Pair(UUID.fromString(profileDocument.getString("uuid")), punishment) } } } } return null } fun findAlts(target: T): List<UUID> { if (target.ipAddresses.isEmpty()) { return emptyList() } val query = Document("ipAddresses", target.ipAddresses) val results = arrayListOf<UUID>() for (profileDocument in collection.find(query)) { val uuid = UUID.fromString(profileDocument.getString("uuid")) if (uuid != null && !results.contains(uuid) && target.uuid != uuid) { results.add(uuid) } } return results } fun fetchProfileByUsername(username: String): T? { val uuid = StarkCore.instance.uuidCache.uuid(username) if (uuid != null && this.profiles.containsKey(uuid)) { return this.profiles[uuid]!! } val mojangUser = fetchMojangUser(username) return if (mojangUser != null) { loadProfile(mojangUser.uuid) } else null } fun fetchMojangUser(username: String): MojangUser? { return fetchMojangUserFromRedis(username) ?: fetchMojangUserFromMojang(username) } private fun fetchMojangUserFromRedis(username: String): MojangUser? { val uuid = StarkCore.instance.uuidCache.uuid(username) return if (uuid != null) { MojangUser(uuid, username) } else null } private fun fetchMojangUserFromMojang(username: String): MojangUser? { StarkCore.instance.logger.info("Fetching username from Mojang API: $username") try { val request = Request.Builder().url("https://api.mojang.com/users/profiles/minecraft/$username").build() val response = client.newCall(request).execute() if (response.isSuccessful) { val json = parser.parse(response.body().string()).asJsonObject val uuid = UUID.fromString(json.get("id").asString.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})".toRegex(), "$1-$2-$3-$4-$5")) val name = json.get("name").asString // update uuid cache StarkCore.instance.uuidCache.update(uuid, name) return MojangUser(uuid, name) } } catch (e: Exception) { StarkCore.instance.logger.info("Failed to retrieve user info from Mojang API: $username") } return null } companion object { private val client = OkHttpClient() private val parser = JsonParser() } }
1
null
1
1
200501c7eb4aaf5709b4adceb053fee6707173fa
6,957
Old-Code
Apache License 2.0
ComposeAnimationKit/src/main/java/com/lie/composeanimationkit/animation/LoadingButton.kt
LiePy
568,339,579
false
null
/* * Copyright (c) 2022. * @username: LiePy * @file: LoadingButton.kt * @project: ComposeAnimationKit * @model: ComposeAnimationKit.ComposeAnimationKit.main * @date: 2022/12/28 下午1:36 */ package com.lie.composeanimationkit.animation import android.util.Size import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.lie.composeanimationkit.AnimationKit import com.lie.composeanimationkit.utils.view.CircularProgressIndicator import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.min /** * @desc 带加载状态的按钮 * @param modifier 修饰符 * @param state 定义按钮状态,一般使用[rememberLoadingButtonState]创建 * @param colors 定义按钮颜色,@see [defaultLoadingButtonColors] * @param size 定义按钮大小 * @param durationMillis 动画时长,该值越小动画越快 * @param readyContent 初始显示的内容 * @param successContent 成功时显示的内容 * @param errorContent 失败时显示的内容 * @param onClicked 点击事件处理 * @author LiePy * @date 2022/12/28 */ @Composable fun LA.LoadingButton( modifier: Modifier = Modifier, state: LoadingButtonState = rememberLoadingButtonState(), colors: LoadingButtonColors = defaultLoadingButtonColors, size: Size = Size(120, 58), durationMillis: Int = 300, readyContent: @Composable () -> Unit = { defaultReadyContent() }, successContent: @Composable () -> Unit = { defaultSuccessContent() }, errorContent: @Composable () -> Unit = { defaultErrorContent() }, onClicked: (LoadingState) -> Unit = {} ) { val sizeMin = min(size.height, size.width) val buttonSize2 = Size(sizeMin, sizeMin) val contentAlpha1 = ContentAlpha(1f, 0f, 0f, 0f) val contentAlpha2 = ContentAlpha(0f, 1f, 0f, 0f) val contentAlpha3 = ContentAlpha(0f, 0f, 1f, 0f) val contentAlpha4 = ContentAlpha(0f, 0f, 0f, 1f) //按钮尺寸动画,自定义animate Value val buttonState by animateValueAsState( targetValue = when (state.currentState) { LoadingState.Loading -> buttonSize2 else -> size }, typeConverter = TwoWayConverter(convertToVector = { bs: Size -> AnimationVector2D( bs.width.toFloat(), bs.height.toFloat() ) }, convertFromVector = { vector: AnimationVector2D -> Size(vector.v1.toInt(), vector.v2.toInt()) }), animationSpec = tween(durationMillis, 0, LinearEasing), label = "buttonSize" ) //内容透明度动画,自定义animate Value val contentAlpha by animateValueAsState( targetValue = when (state.currentState) { LoadingState.Ready -> contentAlpha1 LoadingState.Loading -> contentAlpha2 LoadingState.Success -> contentAlpha3 LoadingState.Error -> contentAlpha4 }, typeConverter = TwoWayConverter(convertToVector = { ca: ContentAlpha -> AnimationVector4D( ca.content1, ca.content2, ca.content3, ca.content4 ) }, convertFromVector = { vector: AnimationVector4D -> ContentAlpha(vector.v1, vector.v2, vector.v3, vector.v4) }), animationSpec = tween(durationMillis, 0, LinearEasing), label = "contentAlpha" ) //背景色动画 val bgColor by animateColorAsState( targetValue = when (state.currentState) { LoadingState.Ready -> colors.onReadyBackgroundColor LoadingState.Loading -> colors.onLoadingBackgroundColor LoadingState.Success -> colors.onSuccessBackGroundColor LoadingState.Error -> colors.onErrorBackgroundColor }, animationSpec = tween(durationMillis, 0, LinearEasing), label = "backgroundColor" ) //边框动画 val borderWidth by animateDpAsState( targetValue = when (state.currentState) { LoadingState.Loading -> 4.dp else -> 0.dp }, animationSpec = tween(durationMillis, 0, LinearEasing), label = "borderWidth" ) Box( modifier, contentAlignment = Alignment.Center ) { Box( modifier = modifier .size(buttonState.width.dp, buttonState.height.dp) .clip(RoundedCornerShape(100.dp)) .clickable { onClicked(state.currentState) } .background(bgColor) .border(borderWidth, Color(0xBBFFFFFF), RoundedCornerShape(100.dp)), ) //初始时显示 Box( modifier = Modifier.alpha(contentAlpha.content1), contentAlignment = Alignment.Center ) { readyContent() } //加载时显示 CircularProgressIndicator( modifier = Modifier .alpha(contentAlpha.content2) .size(sizeMin.dp) ) //成功时显示 Box(modifier = Modifier.alpha(contentAlpha.content3)) { successContent() } //错误或失败时显示 Box(modifier = Modifier.alpha(contentAlpha.content4)) { errorContent() } } } @Composable fun defaultReadyContent() { Text(text = "Upload", color = defaultLoadingButtonColors.onReadyContentColor) } @Composable fun defaultSuccessContent() { Icon( imageVector = Icons.Default.Check, contentDescription = "success", tint = defaultLoadingButtonColors.onSuccessContentColor ) } @Composable fun defaultErrorContent() { Icon( imageVector = Icons.Default.Delete, contentDescription = "error", tint = defaultLoadingButtonColors.onErrorContentColor ) } /** * 主要内容的透明度 */ data class ContentAlpha( val content1: Float, val content2: Float, val content3: Float, val content4: Float ) /** * 加载按钮的颜色 */ data class LoadingButtonColors( val onReadyBackgroundColor: Color = Color.Cyan, val onLoadingBackgroundColor: Color = Color.White, val onSuccessBackGroundColor: Color = Color.Green, val onErrorBackgroundColor: Color = Color.Red, val onReadyContentColor: Color = Color.White, val onLoadingContentColor: Color = Color.Blue, val onSuccessContentColor: Color = Color.White, val onErrorContentColor: Color = Color.White ) /** * 默认颜色 */ val defaultLoadingButtonColors = LoadingButtonColors() /** * 一般使用该方法初始化创建加载按钮状态 * @see LoadingButtonState */ @Composable fun rememberLoadingButtonState( initialState: LoadingState = LoadingState.Ready, ): LoadingButtonState = rememberSaveable(saver = LoadingButtonState.Saver) { LoadingButtonState(initialState) } /** * 加载按钮状态容器 * @see rememberLoadingButtonState */ class LoadingButtonState(currentState: LoadingState = LoadingState.Ready) { private var _currentState by mutableStateOf(currentState) companion object { /** * The default [Saver] implementation for [currentState]. */ val Saver: Saver<LoadingButtonState, *> = listSaver( save = { listOf<Any>( it.currentState.code, ) }, restore = { LoadingButtonState( currentState = LoadingState.getState(it[0] as Int), ) } ) } var currentState: LoadingState get() = _currentState internal set(value) { if (value != _currentState) { _currentState = value } } fun changeToState(newState: LoadingState) { _currentState = newState } fun nextState(isSuccess: Boolean) { _currentState = if (isSuccess) { when (_currentState) { is LoadingState.Ready -> LoadingState.Loading is LoadingState.Loading -> LoadingState.Success else -> LoadingState.Ready } } else { when (_currentState) { is LoadingState.Ready -> LoadingState.Loading is LoadingState.Loading -> LoadingState.Error else -> LoadingState.Ready } } } } /** * 加载状态密封类,定义具体的加载状态 */ sealed class LoadingState(val code: Int) { object Ready : LoadingState(0) object Loading : LoadingState(1) object Success : LoadingState(2) object Error : LoadingState(3) companion object { fun getState(code: Int): LoadingState { return when (code) { 0 -> Ready 1 -> Loading 2 -> Success else -> Error } } } } @Preview @Composable fun LoadingButtonPreview() { val state = rememberLoadingButtonState() AnimationKit.LoadingAnimation.LoadingButton(state = state) { //点击切换到下一状态 // state.nextState(true) //一般使用以下用法,根据具体当前状态来分发点击事件 when (it) { is LoadingState.Ready -> state.changeToState(LoadingState.Loading) is LoadingState.Loading -> state.changeToState(LoadingState.Success) else -> state.changeToState(LoadingState.Ready) } } //这里是为了展示切换效果,使其自动切换 LaunchedEffect(key1 = null, block = { launch { var success = true while (true) { delay(3000) state.nextState(success) success = !success } } }) }
0
null
0
7
4a0e95c396dcd751895dabdecdb706eedf241a05
10,269
ComposeAnimationKit
Apache License 2.0
app/src/main/java/com/myth/ticketmasterapp/data/eventdatamodels/Last.kt
MichaelGift
634,539,469
false
{"Kotlin": 89192}
package com.myth.ticketmasterapp.data.eventdatamodels data class Last( val href: String )
0
Kotlin
1
0
5bae5c47ec44500dc85165275d43914775de6f44
94
Event-Finder-App
MIT License
Kotlinlang/src/examples/problems/Index_of_MaximumTests.kt
why168
118,225,102
false
null
package examples.problems import org.junit.Test import java.util.* import kotlin.test.assertEquals /** * * * @author Edwin.Wu * @version 2018/2/5 下午4:45 * @since JDK1.8 */ class Index_of_MaximumTests { @Test fun testNull() { test(null) } @Test fun testIndexOfMaximum1() { test(0, 0) } @Test fun testIndexOfMaximum2() { test(1, -1, 0) } @Test fun testIndexOfMaximum3() { test(0, -1, -2) } @Test fun testIndexOfMaximum4() { test(1, 1, 3, 2, 1) } @Test fun testIndexOfMaximum5() { test(2, 1, 3, 4, 1) } @Test fun testIndexOfMaximum6() { test(2, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE) } @Test fun testIndexOfMaximum7() { test(2, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE) } } fun test(expected: Int?, vararg data: Int) { assertEquals(expected, indexOfMax(data), "\ndata = ${Arrays.toString(data)}") }
1
Kotlin
1
4
c642d97a605ef09355b86c39c1c522e3181d65e2
981
JavaProjects
Apache License 2.0
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/domain/model/StakeSummary.kt
soramitsu
278,060,397
false
null
package com.edgeverse.wallet.feature_staking_impl.domain.model import java.math.BigDecimal class StakeSummary<S>( val status: S, val totalStaked: BigDecimal, ) sealed class NominatorStatus { object Active : NominatorStatus() class Waiting(val timeLeft: Long) : NominatorStatus() class Inactive(val reason: Reason) : NominatorStatus() { enum class Reason { MIN_STAKE, NO_ACTIVE_VALIDATOR } } } enum class StashNoneStatus { INACTIVE } enum class ValidatorStatus { ACTIVE, INACTIVE }
9
null
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
549
fearless-Android
Apache License 2.0
reactiveandroid/src/main/kotlin/com/github/kittinunf/reactiveandroid/reactive/DisposableExt.kt
kittinunf
50,813,818
false
null
package com.github.kittinunf.reactiveandroid.reactive import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable fun Disposable.addTo(composite: CompositeDisposable) { composite.add(this) }
5
null
12
79
117cb3e9738df17bb4c8b9f73d2a21bc5b97f6f5
232
ReactiveAndroid
MIT License
android/app/src/main/kotlin/com/example/flutterui/MainActivity.kt
yunweneric
837,057,016
false
{"Dart": 442146, "C++": 24213, "CMake": 19464, "HTML": 7961, "Ruby": 3217, "JavaScript": 3211, "CSS": 2800, "Swift": 1949, "C": 1425, "Shell": 698, "Kotlin": 122, "Objective-C": 38}
package com.flutterwidget.hub import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
4
Dart
4
32
d1fad9d8ca23000159786c27aaf4f3df656983fc
122
flutter-widgethub
MIT License
mvvm-dagger/src/main/java/com/nphau/android/shared/libs/CommonUtils.kt
ThanhHuong98
432,947,065
false
null
package com.imstudio.android.shared.libs import android.annotation.SuppressLint import android.app.Activity import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.media.AudioManager import android.media.ToneGenerator import android.net.Uri import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.provider.Settings import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.content.pm.PackageInfoCompat import com.imstudio.android.shared.R import java.util.* object CommonUtils { private const val URL_GOOGLE_PLAY_URI = "market://details?id=com.google.android.gms&hl=en" private const val URL_GOOGLE_PLAY = "https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en" private const val ACTION_VIEW = Intent.ACTION_VIEW private val toneG = ToneGenerator(AudioManager.STREAM_ALARM, 100) @JvmStatic fun playTone() { if (toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD)) { toneG.stopTone() } } @JvmStatic fun playToneAndVibrate(context: Context, milliseconds: Int) { if (toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD)) toneG.stopTone() val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator vibrator?.let { if (it.hasVibrator()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) it.vibrate( VibrationEffect.createOneShot( milliseconds.toLong(), VibrationEffect.DEFAULT_AMPLITUDE ) ) else it.vibrate(milliseconds.toLong()) } } } @JvmStatic fun getAppFullVersion(context: Context): String { return String.format( "%s (%s)A", getAppVersionName(context), getAppVersionCode(context) ) } @JvmStatic fun getAppVersionName(context: Context): String { var versionName = "" try { val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) versionName = packageInfo.versionName } catch (e: Exception) { e.printStackTrace() } return versionName } @JvmStatic fun getAppVersionCode(context: Context): String { var versionCode = "" try { val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) versionCode = PackageInfoCompat.getLongVersionCode(packageInfo).toString() } catch (e: Exception) { e.printStackTrace() } return versionCode } @JvmStatic @SuppressLint("HardwareIds") fun getDeviceId(context: Context): String { return Settings.Secure.getString( context.contentResolver, Settings.Secure.ANDROID_ID ) } @JvmStatic fun formatWithFont(content: String, fontName: String, fontExt: String): String { val addBodyEnd: Boolean = content.toLowerCase(Locale.getDefault()).contains("</body") val addBodyStart: Boolean = content.toLowerCase(Locale.getDefault()).contains("<body>") val font = "$fontName.$fontExt" return "<style type=\"text/css\">@font-face {font-family: $fontName;" + "src: url(\"file:///android_asset/fonts/$font\")}" + "body {font-family: $fontName;text-align: justify;}</style>" + (if (addBodyStart) "<body>" else "") + content + if (addBodyEnd) "</body>" else "" } @JvmStatic fun makeVibrator(context: Context) { val v = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v?.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE)) } else { v?.vibrate(200) } } @JvmStatic fun openGpsSetting(activity: Activity, requestCode: Int) { try { activity.startActivityForResult( Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), requestCode ) } catch (e: Exception) { e.printStackTrace() } } @JvmStatic fun openAppSetting(activity: Activity, requestCode: Int) { try { activity.startActivityForResult(Intent().apply { action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS addCategory(Intent.CATEGORY_DEFAULT) data = Uri.parse("package:" + activity.packageName) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) }, requestCode) } catch (e: Exception) { activity.startActivityForResult( Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS), requestCode ) } } @JvmStatic fun makeVibrator(context: Context, pattern: LongArray) { val v = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { v?.vibrate(VibrationEffect.createWaveform(pattern, VibrationEffect.DEFAULT_AMPLITUDE)) } else { v?.vibrate(1000) } } fun isChromeOs(context: Context): Boolean { return context.packageManager.hasSystemFeature("org.chromium.arc.device_management") } fun hasTelephony(context: Context): Boolean { return context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) } fun hasMicrophone(context: Context): Boolean { return context.packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE) } @RequiresApi(Build.VERSION_CODES.M) fun hasFingerprint(context: Context): Boolean { return context.packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT) } fun hasBluetooth(context: Context): Boolean { return context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH) } @JvmStatic fun copyTextToClipboard(context: Context, text: String?) { (context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager) ?.setPrimaryClip(ClipData.newPlainText("code", text)) Toast.makeText(context, R.string.common_copied, Toast.LENGTH_LONG).show() } @JvmStatic fun openApp(activity: Activity, packageClass: String) { if (isAppInstalled(activity, packageClass)) { activity.startActivity(activity.packageManager.getLaunchIntentForPackage(packageClass)) } else { openGooglePlayIfAppNotBeInstalled(activity, packageClass) } } @JvmStatic fun openGooglePlayIfAppNotBeInstalled(activity: Activity, packageClass: String) { try { activity.startActivity( Intent( ACTION_VIEW, Uri.parse("market://details?id=$packageClass") ) ) } catch (e: Exception) { activity.startActivity( Intent( ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=$packageClass") ) ) } } @JvmStatic fun isAppInstalled(mActivity: Activity, packageClass: String): Boolean { val pm = mActivity.packageManager var isInstalled = false try { pm.getPackageInfo(packageClass, PackageManager.GET_ACTIVITIES) isInstalled = true } catch (e: Exception) { } return isInstalled } fun openNetworkSetting(activity: Activity) { activity.startActivity(Intent(Settings.ACTION_SETTINGS)) } @JvmStatic fun updateGooglePlayServicesIfOutDated(context: Context) { try { context.startActivity( Intent(Intent.ACTION_VIEW, Uri.parse(URL_GOOGLE_PLAY_URI)) ) } catch (e: Exception) { context.startActivity( Intent(Intent.ACTION_VIEW, Uri.parse(URL_GOOGLE_PLAY)) ) } } @JvmStatic fun getFullAction(context: Context, name: String): String { return context.packageName + ".action.$name" } fun isIntentAvailable(i: Intent, ctx: Context): Boolean { return ctx.packageManager.queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size > 0 } }
0
null
0
1
ac0402ae4734285ef5e647d1f53a1f9f4a8d98cd
8,839
android.clean-architecture.mvvm
Apache License 2.0